@gencode/agents 0.13.0 → 0.14.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,164 +1,161 @@
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(`
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 F,x as I,y as L,z as R}from"./session-CvZsdTZJ.js";import{n as z,t as ee}from"./goal-events-BtFriEK5.js";import{c as B,i as V,l as H,n as U,o as te,r as ne,s as W,t as re,u as G}from"./goal-store-CmMXXTIZ.js";import{A as ie,C as ae,D as K,E as oe,F as se,M as ce,N as le,O as ue,P as de,S as fe,T as pe,_ as me,a as he,b as ge,c as _e,d as ve,f as ye,g as be,h as xe,i as Se,j as Ce,k as we,l as Te,m as Ee,n as De,o as Oe,p as ke,r as Ae,s as je,t as Me,u as Ne,v as Pe,w as Fe,x as Ie,y as Le}from"./system-runtime-DfAhRq2L.js";import{a as Re,c as ze,i as Be,l as Ve,o as He,r as Ue,s as We,t as Ge,u as Ke}from"./default-provider-DchVtHkL.js";import{a as qe,i as Je,n as Ye,o as Xe,r as Ze,t as Qe}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as $e}from"./host-BC9sAhdH.js";import{a as et,i as tt,l as nt,n as rt,o as it,r as at,s as ot,t as st}from"./session-store-BaH2Dvmo.js";import{_ as ct,a as lt,c as ut,d as dt,f as ft,g as pt,h as mt,i as ht,l as gt,m as _t,n as vt,o as yt,p as bt,s as xt,t as St,u as Ct,v as wt,y as Tt}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Et,formatTaskForDisplay as Dt,isHitlExpired as Ot,isHitlTool as kt}from"@gencode/shared";import q,{readFile as At}from"node:fs/promises";import J,{join as jt}from"node:path";import{createHash as Mt,randomBytes as Nt,randomUUID as Pt}from"node:crypto";import Ft from"node:os";import{spawn as It}from"node:child_process";import{TextDecoder as Lt}from"node:util";import Rt from"gray-matter";import{Agent as zt}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Bt}from"node:async_hooks";import Vt from"node:fs";import Ht from"openai";import{Type as Y,calculateCost as Ut,clampThinkingLevel as Wt,createAssistantMessageEventStream as Gt,getEnvApiKey as Kt,parseStreamingJson as qt,registerApiProvider as Jt,registerBuiltInApiProviders as Yt,streamSimple as Xt}from"@earendil-works/pi-ai";import{fileURLToPath as Zt}from"node:url";import{isBinaryFile as Qt}from"isbinaryfile";var $t=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 en(e,t,n,r,i){let a=await W(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await H(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const tn=`clarify plan and acceptance`,nn=`补齐后续 task list、每个 task 的验收项和当前下一步`,rn={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},an=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function on(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function sn(e,t){let n=on(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function cn(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 ln(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(rn))sn(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?cn(t.steps):[],acceptance:t.acceptance?cn(t.acceptance):[],raw:e.trim()}}function un(e){let t=e.toLowerCase();return an.some(e=>t.includes(e.toLowerCase()))}function dn(e){return e.some(un)}function fn(e,t){return{id:e,text:t,required:!0}}function pn(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 mn(e){return pn({id:`task-1`,kind:`clarify`,title:tn,status:`doing`,acceptanceCriteria:[fn(`ac-1`,nn)],updatedAt:e})}function hn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>fn(`ac-${t+1}`,e)):[fn(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>pn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[fn(`ac-1`,`完成:${e}`)],updatedAt:n}))}function gn(e){let t=new Date().toISOString(),n=ln(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:hn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&dn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:hn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&dn(cn(n.raw))){let e=cn(n.raw).filter(un);return{interpretation:r,assumptions:i,openQuestions:a,tasks:hn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[mn(t)]}}function _n(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function vn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>_n(n.has(e.id),e)),``].join(`
2
+ `)}function yn(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[vn(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 bn=process.platform===`win32`;function xn(e){return bn?{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 Sn(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(bn&&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 Cn=2e5;function wn(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Tn(e,t){let n=e+t;return n.length<=Cn?{text:n,truncated:!1}:{text:n.slice(-Cn),truncated:!0}}function En(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Tn(e.output,r);e.output=i.text;let a=Tn(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Dn(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:wn(e.output),stdoutTail:wn(e.stdout),stderrTail:wn(e.stderr),outputTruncated:e.outputTruncated}}function On(e,t){return t?e.scopeKey===t:!0}function kn(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function An(e){return e?e.split(/\r?\n/):[]}function jn(e){let t=An(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=kn(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 Mn(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),Mn(e))};return{start(t){let{file:n,args:r,shell:a}=xn(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:!bn}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Pt(),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=>En(l,`stdout`,e)),o.stderr.on(`data`,e=>En(l,`stderr`,e));let u=e=>t=>{En(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=kn(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,En(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Sn(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Sn(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),En(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`)})}),Dn(l)},get(e,t){let n=r(e);return!n||!On(n,t)?null:Dn(n)},list(n){return[...e.values(),...t.values()].filter(e=>On(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Dn(e))},async wait(e,t,n){let i=r(e);if(!i||!On(i,t))return null;if(i.status!==`running`)return Dn(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||!On(a,t)?null:Dn(a)},readLog(e){let t=r(e.sessionId);return!t||!On(t,e.scopeKey)?null:jn({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!On(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||!On(n,t))return null;if(n.status!==`running`)return Dn(n);n.status=`killed`,Sn(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Sn(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?Dn(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Sn(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Sn(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const Pn=1;var Fn=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},In=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 Rn=new Map;function zn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function Bn(e,t,n,r){let i=zn(e,t,n),a=Rn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});Rn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function Vn(e,t,n){return J.join(U(e,t,n),`state.json`)}function Hn(e,t,n){return J.join(U(e,t,n),`plan.md`)}function Un(e,t,n){return J.join(U(e,t,n),`artifacts`)}async function Wn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${Nt(4).toString(`hex`)}.tmp`;try{await q.writeFile(n,t,`utf-8`),await q.rename(n,e)}finally{await q.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function Gn(e){if(e.version!==1)throw new Fn(e.version)}function Kn(e){let t=e.currentTaskId?e.tasks.find(t=>t.id===e.currentTaskId)??null:null,n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`done`).length,i=n.filter(e=>e.status!==`done`).length;return{workflowStatus:e.status,currentTaskId:e.currentTaskId,currentTaskTitle:t?.title??null,currentTaskStatus:t?.status??null,blockedReason:e.blockedReason,openRequiredTasks:i,doneRequiredTasks:r,finalEvidenceRefs:[...e.finalEvidenceRefs]}}async function qn(e,t,n){let r=Vn(e,t,n);try{let e=await q.readFile(r,`utf-8`);try{let t=JSON.parse(e);return Gn(t),t}catch(t){throw t instanceof Fn?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 Fn?e:new Ln(`corrupt_goal_workflow_state`,{cause:e})}}async function Jn(e,t,n){let r=Vn(e,t,n),i;try{i=await q.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return Gn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof Fn)throw e}let a=await W(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await B(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await q.writeFile(s,i,`utf-8`),c=s}catch{}return await Qn(e,t,{goalId:a.goalId,objective:o},n),await Er(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 qn(e,t,n);return r?Kn(r):null}async function Xn(e,t,n){let r=await qn(e,t,n);return r?{goalState:Kn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function Zn(e,t,n){let r=Vn(e,t,n),i=Hn(e,t,n),a=Un(e,t,n);await Promise.all([q.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),q.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),q.rm(a,{recursive:!0,force:!0})])}async function Qn(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await Zn(e,t,r);let a=gn(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=U(e,t,r);await q.mkdir(l,{recursive:!0}),await Wn(Vn(e,t,r),JSON.stringify(c,null,2));let u=yn(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await Wn(Hn(e,t,r),u),c}const $n=1048576,er=/KEY|TOKEN|SECRET|PASSWORD|COOKIE|AUTH/i,tr=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g],nr=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.pdf`]);function rr(e,t,n){return J.join(Un(e,t,n),`registry.jsonl`)}function ir(e,t,n){return J.join(Un(e,t,n),`notes`)}function ar(e,t,n){return J.join(Un(e,t,n),`commands`)}function or(e,t,n){return J.join(Un(e,t,n),`snapshots`)}function sr(e,t,n){return J.join(U(e,t,n),`plan-meta.json`)}function cr(e){let t=e,n=!1;for(let e of tr)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function lr(e){return`sha256:${Mt(`sha256`).update(e).digest(`hex`)}`}async function ur(e){return lr(await q.readFile(e))}function dr(e,t){let n=J.normalize(e);return t.some(e=>{let t=J.normalize(e);return n===t||n.startsWith(t+J.sep)})}function fr(e){let t=[J.normalize(e.workspaceDir),J.normalize(Ft.tmpdir())],n=e.projectDir?.trim();n&&t.push(J.normalize(n));let r=J.join(e.dataDir,`workspace`);return t.includes(J.normalize(r))||t.push(J.normalize(r)),t}function pr(e,t){return t?.trim()?J.isAbsolute(t)?J.normalize(t):J.normalize(J.join(e,t)):e}function mr(e,t){return e.byteLength<=t?{data:e,truncated:!1,originalBytes:e.byteLength}:{data:e.subarray(0,t),truncated:!0,originalBytes:e.byteLength}}function hr(e){return`${e}-${Date.now().toString(36)}-${Nt(3).toString(`hex`)}`}async function gr(e,t,n,r){let i=await _r(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${hr(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function _r(e,t,n){let r=rr(e,t,n);try{let e=await q.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 In(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function vr(e,t,n,r){let i=rr(e,t,r);await q.mkdir(J.dirname(i),{recursive:!0}),await q.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function yr(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 _r(e,t,r),o=new Map(a.map(e=>[e.id,e])),s=[],c=br(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?J.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 q.readFile(n);if(t.hash&&lr(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?J.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 q.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 ur(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?J.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 q.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 br(e,t,n){return J.dirname(U(e,t,n))}async function xr(e,t,n,r){Gn(n),await Wn(Vn(e,t,r),JSON.stringify(n,null,2))}async function Sr(e,t,n){let r=sr(e,t,n);try{let e=await q.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function Cr(e,t,n,r){await Wn(sr(e,t,r),JSON.stringify(n,null,2))}async function wr(e,t,n,r){let i=await Sr(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 Cr(e,t,a,r),a}async function Tr(e,t,n,r){try{let i=yn(n,await Sr(e,t,r));return await Wn(Hn(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 Er(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=z(e,t,r);await q.mkdir(J.dirname(s),{recursive:!0}),await q.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}function Dr(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 Or(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 kr(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 gr(e,t,n.kind,r),a=i.split(`:`)[1]??hr(n.kind),o=ir(e,t,r);await q.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=J.join(ir(e,t,r),`${a}.md`),l=cr(n.content);await q.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 vr(e,t,u,r)}catch{return await q.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}async function Ar(e,t,n,r){let i=pr(n.workspaceDir,n.cwd);if(!dr(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=mr(d,$n),m=mr(f,$n),h=cr(p.data.toString(`utf-8`)),g=cr(m.data.toString(`utf-8`)),_=h.redactionIncomplete||g.redactionIncomplete,v=await gr(e,t,`command`,r),y=v.split(`:`)[1]??hr(`command`),b=ar(e,t,r);await q.mkdir(b,{recursive:!0});let x=`goal/artifacts/commands/${y}.out.txt`,S=`goal/artifacts/commands/${y}.err.txt`,C=J.join(b,`${y}.out.txt`),w=J.join(b,`${y}.err.txt`);await q.writeFile(C,h.text,`utf-8`),await q.writeFile(w,g.text,`utf-8`);let T=Object.keys({...process.env,...n.baseEnv}).filter(e=>er.test(e)),E={id:v,kind:`command`,command:cr(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:lr(h.text),createdAt:new Date().toISOString()};try{await vr(e,t,E,r)}catch{return await Promise.all([q.unlink(C).catch(()=>{}),q.unlink(w).catch(()=>{})]),{error:`registry_write_failed`}}return{evidenceRef:v,exitCode:l.exitCode??1}}function jr(e,t){let n=J.normalize(e),r=n.split(J.sep).filter(Boolean);if(r.includes(`.aimax`)||r.includes(`.ssh`)||r.includes(`.gnupg`))return!0;let i=J.normalize(t);return n.startsWith(J.join(i,`.aimax`)+J.sep)||n===J.join(i,`.aimax`)}async function Mr(e,t,n,r){let i=J.isAbsolute(n.path)?J.normalize(n.path):J.normalize(J.join(n.workspaceDir,n.path));if(!dr(i,n.allowedRoots))return{error:`snapshot_path_outside_allowed_roots`};if(jr(i,e))return{error:`snapshot_sensitive_path_not_allowed`};let a;try{a=await q.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=J.extname(i).toLowerCase(),s=o.length>0&&nr.has(o),c;try{c=await q.readFile(i)}catch{return{error:`snapshot_read_failed`}}if(!s){let e=cr(c.toString(`utf-8`));c=Buffer.from(e.text,`utf-8`)}else if(!nr.has(o))return{error:`snapshot_binary_type_not_allowed`};let l=await gr(e,t,`snapshot`,r),u=l.split(`:`)[1]??hr(`snapshot`),d=or(e,t,r);await q.mkdir(d,{recursive:!0});let f=`${u}${o||J.extname(i)}`,p=`goal/artifacts/snapshots/${f}`,m=J.join(d,f);await q.writeFile(m,c);let h={id:l,kind:`snapshot`,summary:n.summary,path:i,hash:lr(c),sizeBytes:c.byteLength,snapshotPath:p,createdAt:new Date().toISOString()};try{await vr(e,t,h,r)}catch{return await q.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 Pr(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 Fr(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===tn)&&t.unshift(`- Current task is "${tn}": 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 Ir(){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 Rr(e,t,n){return zr(e,t,n,{introLine:Lr})}function zr(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>`,...Pr(n),`</workflow>`,``,`Rules:`,...Fr(n)):l.push(`Rules:`,...Ir()),l.push(``,`</goal_context>`),l.join(`
5
+ `)}function Br(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 Vr(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 Hr(e){return{role:`user`,content:e}}function Ur(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Wr=`AIMAX_GOAL_CONTINUATION`;var Gr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function Kr(e,t,n){let r=await qn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await Sr(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 qr(){let e=process.env[Wr];return e===void 0||e===``||e!==`0`}async function Jr(e,t,n,r){if(!qr()||n.continuationCount>=Et)return!1;let i=await W(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-BaH2Dvmo.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Yr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Xr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Jr(n,r,a,{storeName:i}))return!1;let u=await W(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await B(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await Kr(n,r,{storeName:i}),h=Hr(p?Br(u,f):zr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Yr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=Et){let e=await W(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-CmMXXTIZ.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-BtFriEK5.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${Et}), goal paused`)}}return!0}async function Zr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function Qr(e,t,n){let r=await qn(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await xr(e,t,c,{storeName:n?.storeName}),await Er(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await Sr(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await wr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await Tr(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function $r(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await Kr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=Hr(Rr(i,await B(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function ei(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Hr(Vr(i,await B(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function ti(e,t,n){(await W(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await H(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const ni=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function ri(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===tn}function ii(e){return ni.has(e)}function ai(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 oi(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())&&ii(n.toolName))return{block:!0,blockReason:ai(n.toolName)}}}),()=>{t=!1}}function si(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 ci(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(gi(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}_i(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 li(e,t={}){let n=mi(t.limit,`limit`),r=hi(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!_i(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:pi(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function ui(e,t){let n=hi(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 di(e,t=80){let n=hi(e,`totalEntryCount`),r=hi(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function fi(e,t){return e.slice(t.startIndex,t.endIndex)}function pi(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function mi(e,t){return e===void 0?1/0:hi(e,t)}function hi(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function gi(e){return e.role===`assistant`}function _i(e){return e.role===`tool_result`}const vi=24e3;async function yi(e){return Di({params:e,kind:`current_run`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function bi(e){return Di({params:e,kind:`recent_conversation`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function xi(e){return Di({params:e,kind:`transcript_range`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Si(e){let t=Fi(e),n=await wi(e),r=await ji(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:Ti(e.dataDir,e.sessionId,e.sessionOptions)}}function Ci(e){return{maxEntries:Ii(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Ii(e?.maxBytes??vi,`limits.maxBytes`)}}async function wi(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Oi(await ki(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 Ai({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Ti(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function Ei(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 Di(e){let t=Fi(e.params),n=Ei(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=Mi(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:Ti(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Oi(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 ki(e,t,n){let[r,i]=await Promise.all([I(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)Bi(e)&&e.toolResultRef?.sessionId===t&&a.set(Vi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Vi(e),e);return Array.from(a.values())}async function Ai(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(J.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=J.resolve(e.dataDir,e.reference.storagePath);if(!zi(J.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!zi(J.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([Ri(t),Ri(n),Ri(i)]);if(!zi(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!zi(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function ji(e,t){let n=await q.stat(e),r=await q.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:Pi(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function Mi(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:Pi(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function Pi(e){let t=new Lt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Fi(e){return Ci(e.limits)}function Ii(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 Ri(e){try{return await q.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Hi(e)}`)}}function zi(e,t){let n=J.relative(e,t);return n===``||!n.startsWith(`..`)&&!J.isAbsolute(n)}function Bi(e){return e.role===`tool_result`}function Vi(e){return`${e.toolCallId}\n${e.storagePath}`}function Hi(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ui(e){return J.join(e,`.aimax`,`auto-skills`)}function Wi(e){return J.join(e,`categories.json`)}function Gi(e){return J.join(e,`.auto_skills_prompt_snapshot.json`)}const Ki=/^[a-z0-9][a-z0-9-]*$/,qi=/^[a-z0-9][a-z0-9-]*$/;function Ji(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(`\\`)||J.win32.isAbsolute(t)||J.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Ki.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Yi(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(`.`)||!qi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Xi(e,t){return`auto:${Ji(e)}/${Yi(t)}`}function Zi(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=Ji(n.slice(0,r)),a=Yi(n.slice(r+1));return{skillId:Xi(i,a),categoryPath:i,skillName:a}}function Qi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function $i(e,t,n){let r=J.resolve(e),i=J.resolve(r,...Ji(t).split(`/`),Yi(n));return ta(r,i),i}function ea(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||J.win32.isAbsolute(n)||J.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=J.resolve(e),a=J.resolve(i,...r);return ta(i,a),a}function ta(e,t){let n=J.resolve(e),r=J.resolve(t),i=J.relative(n,r);if(i.startsWith(`..`)||J.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function na(e){let t=Wi(e),n;try{n=await q.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=Ji(e),r=ia(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 ra(e){return new Map(e.map(e=>[e.path,e]))}function ia(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 aa=32*1024,oa=new Map;function sa(e){return new la(e)}async function ca(e){let t=J.resolve(e);for(let e of Array.from(oa.keys()))e.startsWith(`${t}|`)&&oa.delete(e);await q.rm(Gi(t),{force:!0}).catch(()=>{})}var la=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=J.resolve(e.rootDir??Ui(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return da(ra((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Ji(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>fa(e.categoryPath,t)).map(ua)}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:pa(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})=>({...ua(e),score:t}))}async autoSkillView(e){let t=Zi(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=ea(n.skillDir,e.filePath),r=await Sa(t,this.maxResourceBytes);return{...ua(n),status:n.status,content:r,path:Ta(J.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Ta(J.relative(n.skillDir,t))}}let r=await Sa(n.skillFile,this.maxSkillBytes);return{...ua(n),status:n.status,content:r,path:Ta(J.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 ma(this.rootDir),i=oa.get(n);if(!e&&i&&ya(i.manifest,r))return i;let a=e?void 0:await _a(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return oa.set(n,e),e}let o=await na(this.rootDir),s=ra(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return oa.set(n,c),await va(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 Oa({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:aa})}async loadEntry(e){try{let t=J.dirname(e),n=Yi(J.basename(t)),r=Ta(J.relative(this.rootDir,t)),i=Ji(J.posix.dirname(r)),a=Xi(i,n),o=J.join(t,`metadata.json`),s=await ba(o);if(s?.skillId&&Zi(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Ji(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=Qi(s?.status);return{skillId:a,name:n,description:Ca(await xa(e,aa)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:wa(s?.tags),relatedSkills:wa(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}: ${Ea(t)}\n`);return}}};function ua(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function da(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function fa(e,t){return t?e===t:!0}function pa(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 ma(e){let t;try{t=await q.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await ga(J.join(e,`categories.json`),`categories`,n),await ha(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function ha(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=J.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await ga(t,`skill`,n),await ga(J.join(e,`metadata.json`),`metadata`,n),await ga(J.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await q.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await ha(t,i,n)}}async function ga(e,t,n){try{let r=await q.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 _a(e,t,n){let r;try{r=await q.readFile(Gi(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)||!ya(e.manifest,n)?void 0:e}catch{return}}async function va(e,t){if(!await Da(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await q.writeFile(Gi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function ya(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 ba(e){try{let t=await q.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 xa(e,t){let n=await q.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 Sa(e,t){if((await q.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return q.readFile(e,`utf-8`)}function Ca(e){let t=Rt(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 wa(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Ta(e){return e.split(J.sep).join(`/`)}function Ea(e){return e instanceof Error?e.message:String(e)}async function Da(e){try{return await q.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Oa(e){return Mt(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function ka(e,t,n,r){return de(se(e.apiFormat)).createModel(e,t,n,r)}const Aa=`/aimax/agents`,ja=/^[a-z]+(?:-[a-z]+)*$/;function Ma(e){let t=[{dir:e.systemAgentsDir??Aa,source:`system`},{dir:J.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:J.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Na(e){let t=new Map;for(let n of Ma(e)){let e=await La(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Pa(e={}){let t=e.allAgents??e.availableAgents??[],n=Va(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>za(n,e),findAny:e=>za(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function Fa(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 Ia(e){return Fa(e.agentPolicy)?e.agentPolicy:Pa({allAgents:await Na(e)})}async function La(e,t){let n;try{n=await q.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=J.join(e,i.name),a=Ra(await q.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Ra(e,t){let n=Rt(e),r=Ka(n.data.name)?.trim(),i=Ka(n.data.description)?.trim();if(!r||!ja.test(r)||!i)return;let a=Ka(n.data.model)?.trim(),o=Ka(n.data.initPrompt)?.trim()??Ka(n.data.initialPrompt)?.trim(),s=qa(n.data.maxTurns),c=Ja(n.data.tools),l=Ja(n.data.disallowedTools),u=Ja(n.data.skills),d=Ya(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 za(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Ba(e)===`public`))}function Ba(e){return e.visibility??`public`}function Va(e){return e.filter(e=>Ba(e)===`public`)}function Ha(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Ua(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Xa)):void 0,r=new Set((t.disallowedTools??[]).map(Xa));return e.filter(e=>{let t=typeof e.name==`string`?Xa(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Wa(e){let t=Va(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
9
  `),``].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(`
10
+ `)}function Ga(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 qa(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 Ya(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Xa(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}var Za=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){K.warn(`progress handler failed; event dropped`,{sessionId:e,eventType:t.type,error:n instanceof Error?n.message:String(n)})}}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const Qa=`<aimax_artifacts>`,$a=`</aimax_artifacts>`;function eo(e,t={}){let n=[];if(!e.includes(Qa))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf(Qa);if(e===-1)break;let o=r.indexOf($a,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(...to(s,{warnings:n,timestamp:i,workspaceDir:t.workspaceDir}))),r=[r.slice(0,e).trimEnd(),r.slice(o+18).trimStart()].filter(e=>e.length>0).join(`
11
+ `).trimEnd()}return{cleanedText:r,artifacts:a,warnings:n}}function to(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=no(t,{index:e,warnings:n,timestamp:r,workspaceDir:i});s&&o.push(s)}return o}function no(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=io(t,a);return o?{kind:`file`,file:o,timestamp:i,label:ro(e.label,J.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 ao(s)?{kind:`url`,url:s,timestamp:i,label:ro(e.label,c,n,r)}:(r.push(`Artifact at index ${n}: url is invalid, skipping`),null)}function ro(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 io(e,t){return J.isAbsolute(e)?J.normalize(e):t?.trim()?J.normalize(J.join(t,e)):null}function ao(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 so=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($a);if(e===-1){let e=co(this.buffer,$a);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(Qa);if(e!==-1){t+=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e+17),this.suppressing=!0;continue}let n=co(this.buffer,Qa);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 co(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 lo(e){if(e.isError)return[];let t=(e.now??(()=>new Date))().toISOString(),n=_o(e.result),r=[];if(e.toolName===`write_file`){let i=yo(Oo(n.details?.path),e.workspaceDir);return i&&r.push(So(i,t,To(i))),wo(r)}if(e.toolName===`edit_file`){let i=ko(n.details?.occurrences),a=yo(Oo(n.details?.path),e.workspaceDir);return a&&i!==0&&r.push(So(a,t,To(a))),wo(r)}if(e.toolName===`apply_patch`)return r.push(...uo(n.details,e.workspaceDir,t)),wo(r);if(e.toolName===`exec`||e.toolName===`bash`||e.toolName===`process`){if(xo(n.details))return[];let i=Oo(e.input?.command),a=vo(Oo(n.details?.cwd),e.workspaceDir);return r.push(...fo({command:i,output:n.content,cwd:a,workspaceDir:e.workspaceDir,timestamp:t})),r}let i=bo(n.content);return i?[Co(i,t,Eo(i))]:[]}function uo(e,t,n){let r=e?.summary&&typeof e.summary==`object`?e.summary:void 0;return r?[...Do(r.added),...Do(r.modified)].flatMap(e=>{let r=yo(e,t);return r?[So(r,n,To(r))]:[]}):[]}function fo(e){let t=[],n=e.cwd??e.workspaceDir,r=r=>{let i=yo(r,n);i&&t.push(So(i,e.timestamp,To(i)))};if(e.command)for(let t of po(e.command))r(t);for(let t of go(e.output))r(t);let i=bo(e.output);return i&&t.push(Co(i,e.timestamp,Eo(i))),wo(t)}function po(e){let t=mo(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 mo(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(...ho(r))}return t.join(`
12
+ `)}function ho(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 go(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(jo(a.trim()))}return t}function _o(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 vo(e,t){return e?.trim()?J.normalize(e):t}function yo(e,t){let n=Ao(e?.trim()??``);return!n||n.startsWith(`-`)||n===`/dev/null`||n.startsWith(`/dev/`)||Mo(n)?null:J.isAbsolute(n)?J.normalize(n):t?.trim()?J.normalize(J.join(t,n)):null}function bo(e){let t=e.trim();return!t||/\s/.test(t)?null:No(t)?new URL(t).toString():null}function xo(e){let t=Oo(e?.status);return t===`running`||t===`failed`||t===`killed`||t===`timeout`}function So(e,t,n){return{kind:`file`,file:e,timestamp:t,label:n}}function Co(e,t,n){return{kind:`url`,url:e,timestamp:t,label:n}}function wo(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 To(e){return J.basename(e)||`File artifact`}function Eo(e){try{return new URL(e).host||`URL artifact`}catch{return`URL artifact`}}function Do(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function Oo(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function ko(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Ao(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function jo(e){return e.replace(/[),.;,。;)]+$/u,``)}function Mo(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)}function No(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}var Po=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 Fo(e){return!!(e instanceof Po||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const Io=new Bt;function Lo(){return{}}async function Ro(e,t){return await Io.run(e,t)}function zo(e){let t=Io.getStore();!t||t.signal||(t.signal=e)}function Bo(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function Vo(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 Ho(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 Uo(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:Ho(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:Ho(e.content,`(tool image omitted: model does not support images)`)}:e)}function Wo(e,t,n){let r=new Map,i=Uo(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 Go(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Ko(e){if(!Go(e))return null;let t=e,n=qo(t.message),r=Yo(n?.code)??Yo(t.code),i=Yo(n?.type)??Yo(t.type),a=Yo(n?.message)??Jo(t.error)??Yo(t.message)??`Unknown upstream error`;return{message:Xo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Zo(r,i),raw:e}}function qo(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 Jo(e){if(!(!e||typeof e!=`object`))return Yo(e.message)}function Yo(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Xo(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Zo(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 Qo(e,t=`error`){let n={};$o(n,t,e);let r=is(e);return r!==void 0&&$o(n,`${t}Cause`,r),n}function $o(e,t,n){e[`${t}Type`]=es(n),e[`${t}Name`]=ns(n,`name`),e[`${t}Message`]=ts(n),e[`${t}Code`]=rs(n,`code`),e[`${t}Status`]=rs(n,`status`),e[`${t}StatusCode`]=rs(n,`statusCode`)}function es(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 ts(e){if(e instanceof Error)return as(e.message);if(typeof e==`string`)return as(e);let t=ns(e,`message`);return t?as(t):void 0}function ns(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 rs(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 is(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function as(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const os=(e,t,n)=>{let r=Gt();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=ls(e,t,n?.apiKey||Kt(e.provider)||``,n?.headers),c=us(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=qt(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=Ko(t);if(n)throw new pe({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}},Ut(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=qt(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){K.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,...Qo(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 pe&&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},ss=(e,t,n)=>{let r=n?.apiKey||Kt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Vo(e,n,r),a=n?.reasoning?Wt(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return os(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function cs(e,t,n){return us(e,t,n)}function ls(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 Ht({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function us(e,t,n){let r=_s(e),i=ps(e,t,r);fs(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=ms(t.tools,r):ds(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 ds(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 fs(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 ps(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=Wo(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Bo(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:Bo(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Bo(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=>Bo(e.text)).join(``):a.map(e=>({type:`text`,text:Bo(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
16
13
 
17
14
  `);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
18
15
  `))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
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(`
16
+ `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:Bo(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 ms(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 gs(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 _s(e){let t=gs(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 vs=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),ys=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),bs=[`llmrequesterror`];function xs(e){let t=Ts(e?.maxAttempts,3),n=Es(e?.initialDelayMs,250),r=Es(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Ss(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Cs(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 ws(e){if(ks(e))return!1;let t=Ds(e),n=Os(e);if(t?.statusCode!==void 0)return js(t.statusCode);if(t?.providerCode!==void 0)return As(t.providerCode);let r=t?.message??n,i=Ms(r);if(i!==void 0)return js(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(vs.has(e))return!0;if(ys.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=Ns(r);return a===void 0?Ps(r)?!0:t?.retryable===!0:a}function Ts(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Es(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Ds(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 Os(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 ks(e){return Ds(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function As(e){return/^\d+$/.test(e)?js(Number(e)):!1}function js(e){return e===408||e===409||e===425||e===429||e>=500}function Ms(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function Ns(e){if(!e)return;let t=Fs(e);for(let e of ys)if(t.includes(e))return!1;for(let e of vs)if(t.includes(e))return!0}function Ps(e){if(!e)return!1;let t=Fs(e);return bs.some(e=>t.includes(e))}function Fs(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const Is=Symbol(`omit-json-value`);function Ls(e,t=new WeakSet){if(e===void 0)return Is;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=Ls(r,t);e!==Is&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=Ls(i,t);e!==Is&&(n[r]=e)}return n}finally{t.delete(e)}}function Rs(e,t,n){return J.join(J.dirname(C(e,t,n)),`session-tools.json`)}function zs(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:Ls(e.parameters??{})}))}async function Bs(e,t,n){let r=await o(Rs(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 Vs(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:zs(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([R(C(e,t,r),n.systemPrompt,r?.encryptSessions),R(Rs(e,t,r),a,r?.encryptSessions)])}async function Hs(e,t,n){let[r,i]=await Promise.all([g(e,t,n),Bs(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function Us(e){return Math.ceil(e.length/4*1.2)}function Ws(e){if(e.role===`user`)return Us(e.content);if(e.role===`assistant`){let t=Us(e.content),n=e.thinking?.trim();n&&(t+=Us(n)),e.errorMessage&&(t+=Us(e.errorMessage));for(let n of e.toolCalls??[])t+=Us(n.name)+Us(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
17
+ `):e.content;return Us(e.toolName)+Us(t)}function X(e){return e.reduce((e,t)=>e+Ws(t),0)}function Gs(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 Ks(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 qs=[`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.`],Js={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Ys(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function Xs(e,t,n){return e.map(e=>Zs(e,t,n))}function Zs(e,t,n){let r=new Date(e.timestamp).getTime();if(Qs(e))return{role:`user`,content:e.content,timestamp:r};if($s(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:Js,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:ec(i)}],isError:i.isError,timestamp:r}}function Qs(e){return e.role===`user`}function $s(e){return e.role===`assistant`}function ec(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:`,...qs];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
18
+ `)}const tc=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
19
+ `);async function nc(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=ic(t,r,i,a),u=ac(a),d,f=oe({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:tc,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 rc(500*e)}throw d}function rc(e){return new Promise(t=>setTimeout(t,e))}function ic(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${lc(t.trim(),oc(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=sc(e,t,n,r),o=cc(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: ${lc(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(`, `)}]`:``} ${lc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?uc(n):n.toolResultRef?[`[tool result persisted] ${n.toolResultRef.toolName} (${n.toolResultRef.originalChars} chars).`,`Full output: ${n.toolResultRef.storagePath}`,n.toolResultRef.preview.trim()?`Preview:\n${n.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
20
+ `):n.content;r=`Tool(${n.toolName})[${e}]: ${lc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
21
+ `)}function ac(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function oc(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function sc(e,t,n,r){let i=cc(t,n,r);if(!r||r<=0)return 2e3;let a=ac(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=tc.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 cc(e,t,n){if(!n||n<=0)return 1/0;let r=ac(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=tc.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function lc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function uc(e){let t=dc(e),n=t.name??`<skill-name>`,r=t.path,i=r?`skill_load(name="${n}", skillPath="${r}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,r?`Original path: ${r}`:``,`If this skill is needed later, call ${i} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].filter(Boolean).join(`
22
+ `)}function dc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=fc(t);if(e.name||e.path)return e}return{}}function fc(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 pc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Ws(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function mc(e){return gc((await oe({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:yc,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 _c((await oe({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:bc,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 gc(e){let t=vc(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 _c(e){let t=vc(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 vc(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
23
+ `);const yc=[`You select relevant conversation segments for an IM assistant before final turn-level topic classification.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedSegmentIds":["..."],"reason":"...","confidence":"high|medium|low"}`,`Task: choose which prior segments are relevant to the current user message.`,`Relevant includes same task continuation, explicit topic return, reuse of prior artifact, correction, or combining multiple earlier topics.`,`Prefer recall over over-pruning when the user explicitly refers to older topics by name.`,`Do not answer the user.`].join(`
24
+ `),bc=[`You select relevant historical conversation turns for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurns":[{"turnId":"...","summary":"...","topicLabel":"optional","keywords":["..."]}],"reason":"...","confidence":"high|medium|low"}`,`Task: from the provided turns, select any turn that may be relevant to the current user message.`,`This is recall-first. It is better to include possibly relevant turns than to miss a relevant one.`,`Select turns for same task continuation, explicit old-topic return, reuse of prior artifact, corrections, or combinations of multiple earlier topics.`,`For every selected turn, provide a concise reusable summary, an optional topicLabel, and short keywords.`,`Prefer the provided summary/topicLabel fields when they exist; use raw user/assistant content only when needed.`,`Do not answer the user.`].join(`
25
+ `);async function xc(e){let t=Ec(e);if(t)try{let e=await q.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(Hc);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function Sc(e){let t=Ec(e);t&&(await q.mkdir(J.dirname(t),{recursive:!0}),await q.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function Cc(e){let t=Dc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||Oc(t,e)){r.push(e);continue}n.push(Ac(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(Ac(r,n.length+1,!0)),n}function wc(e,t){let n=Dc(t);if(n.length===0)return[];if(!e||e.length===0)return Cc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return Cc(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&&kc(t,e)){a[a.length-1]=Fc(t,e);continue}t&&(t.status=`closed`),a.push(Ac([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 Tc(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 Ec(e){if(!(!e.dataDir||!e.sessionId))return J.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function Dc(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 Oc(e,t){return Rc(Lc(e.user,e.assistant),Lc(t.user,t.assistant))>0}function kc(e,t){return Rc(Lc(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),Lc(t.user,t.assistant,t.toolNames.join(` `)))>0}function Ac(e,t,n){return jc(e,t,n)}function jc(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=Mc(e,o),c=Vc(r?.summary||s),l=Ic(r?.keywords,c,o),u=Vc(r?.compressedSummary||Pc(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(`
29
26
  `),assistantSummary:e.map(e=>e.assistant).filter(Boolean).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(`
27
+ `)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function Mc(e,t){return Nc(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 Nc(e,t,n){let r=Bc(e,220),i=t?Bc(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return Vc(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function Pc(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return Vc(`Relevant prior segment: ${Bc(e,280)}${n}`)}function Fc(e,t,n){let r=[...new Set([...e.toolNames,...t.toolNames])].sort(),i=`${e.userSummary}\n${t.user}`.trim(),a=[e.assistantSummary,t.assistant].filter(Boolean).join(`
28
+ `)||void 0,o=Nc(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Vc(n?.summary||o),compressedSummary:Vc(n?.compressedSummary||Pc(n?.summary||o,r)),keywords:Ic(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Ic(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:zc(t,n)}function Lc(...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 Rc(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function zc(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 Lc(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 Bc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Vc(e){return e.replace(/\s+/g,` `).trim()}function Hc(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 Uc(e){let t=qc(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Jc(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 Wc(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Gc(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:Kc(i.compressedSummary),timestamp:e.timestamp})}return r}function Kc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function qc(...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 Jc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=qc(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 Yc=`Xenova/bge-small-zh-v1.5`;let Xc,Zc;const Qc=new Map;async function $c(e,t){if(e.length===0)return K.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=il(t),i=r.path;K.info(`topic segmentation embedding started`,{provider:`transformers`,model:Yc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await nl({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=Qc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Qc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return K.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Yc,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 K.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Yc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function el(e,t){let[n]=await $c([e],t);return n??[]}function tl(){return Yc}async function nl(e){let t=il(e).path;return(!Xc||Zc!==t)&&(Zc=t,Xc=rl(t)),Xc}async function rl(e){let t=Date.now();K.info(`topic segmentation embedding extractor load started`,{model:Yc,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`,Yc,{dtype:`q8`});return K.info(`topic segmentation embedding extractor load completed`,{model:Yc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw K.warn(`topic segmentation embedding extractor load failed`,{model:Yc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function il(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=J.dirname(Zt(import.meta.url)),i=J.resolve(r,`../../../../../model`);if(Vt.existsSync(i))return{path:i,source:`repo_candidate`};let a=J.resolve(process.cwd(),`model`);return Vt.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const al=`topic_segments_vec`,ol=`topic_segments_meta`,sl=`topic_segment_embedding_cache`;async function cl(e){let t=Date.now(),n=ul(e);if(!n){K.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}K.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await q.mkdir(J.dirname(n),{recursive:!0});let r=We(n,{allowExtension:!0});try{let i=await fl(r);K.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 ${ol}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=tl(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=Ve(dl(e));return o.get(e.segmentId)!==t});K.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 $c(l.map(e=>dl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=dl(t),n=Ve(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:_l(r,t.segmentId);hl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(gl(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(ml(r,i,o.length),r.prepare(`DELETE FROM ${al} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${al} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,Cl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${al} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${ol} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${sl} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${al} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),K.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 K.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 ll(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return K.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=ul(e);if(!n)return K.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 q.access(n)}catch{return K.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}K.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await bl(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return K.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=We(n,{allowExtension:!0});try{let a=await fl(i),o=tl(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?vl(i,o,r,e.limit):yl(i,o,r,e.limit);return K.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 K.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 ul(e){if(!(!e.dataDir||!e.sessionId))return J.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function dl(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
29
+ `)}async function fl(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${ol} (\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 ${sl} (\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_${ol}_hash ON ${ol}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${sl}_hash ON ${sl}(content_hash)`),{vectorAvailable:(await ze({db:e})).ok,vectorDims:pl(e)}}function pl(e){let t=e.prepare(`SELECT dims FROM ${sl} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function ml(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${al}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${al} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function hl(e,t){e.prepare(`INSERT INTO ${ol} (\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 gl(e,t){e.prepare(`INSERT INTO ${sl} (\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 _l(e,t){let n=e.prepare(`SELECT embedding FROM ${sl} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function vl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${al} v\n JOIN ${ol} 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(Cl(n),t,Cl(n),r)}function yl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${sl} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:Sl(n,xl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function bl(e,t){try{return await el(e,t)}catch(e){return K.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function xl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Sl(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 Cl(e){return Buffer.from(new Float32Array(e).buffer)}const wl=8e3,Tl=new Map;function El(e){return{enabled:e?.enabled!==!1,embeddingModelDir:Hl(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 Dl(e){let t=Nl(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(Ll(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?Gc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function Ol(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Ul(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:Gl(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 kl(e){let t=El(e.config),n=()=>Jl({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){K.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){K.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){K.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Nl(e.entries),i=X(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){K.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>Pl(e,t)),o=e.llm.flashModel||e.llm.model,s=await Al({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();K.info(`topic segmentation classify started`,Jl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Il({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=Dl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Fl({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:X(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await zl(e,g),K.info(`topic segmentation classify succeeded`,{...Jl({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 Al(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await jl({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 ll({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=Uc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=Xl(l,e.config.maxShortlistSegments),d=Ml({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:wl});if(d&&nu({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await au({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=Wc({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Zl({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:wl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await Sc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),ou({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=tu(a,l.selectedCandidates),d=Ol({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 jl(e){K.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await xc(e);if(!t){let t=Cc(e.entries);if(t.length===0){K.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await Sc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),ou({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),K.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}K.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=wc(t,e.entries);return n.length>0&&(await Sc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),ou({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),K.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function Ml(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 Nl(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 Pl(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}ql(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:Bl(e.user,t.maxCandidateUserChars),assistant:n?Bl((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Fl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:Bl(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 Il(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=Ul(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Gl(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 Ll(e,t){let n=t?.assistant??Rl(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Vl(t?.user??e.user,50),assistantPreview:n?Vl(n,50):void 0}}function Rl(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 zl(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await q.mkdir(n,{recursive:!0}),await q.appendFile(J.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function Bl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Vl(e,t){return[...e].slice(0,t).join(``)}function Hl(e){return e?.trim()||void 0}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)||t.add(n)}return t}function Wl(e){return[...Ul(e)].slice(0,8)}function Gl(e,t,n,r){let i=Kl(e,Ul(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Kl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function ql(e){return e.role===`tool_result`}function Jl(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Yl(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 Yl(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function Xl(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 Zl(e){if(!Ql(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=$l(eu(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=Ml({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??Wl(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Tc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Ql(e){let t=e.selectedSegments.filter(e=>!e.forced);return ru(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:iu(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function $l(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 eu(e,t,n){let r=Math.max(n.length,1),i=Ul(t);return e.map(e=>({candidate:e,score:Gl(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function tu(...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 nu(e){if(e.retrieved.length<2||!ru(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 ru(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function iu(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 au(e){try{let t=await mc({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 ou(e){let t=su(e);if(!t||Tl.has(t)){K.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}K.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=cl(e).catch(t=>{K.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(()=>{Tl.delete(t)});Tl.set(t,n)}function su(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
30
+ `);const cu=[`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 lu(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 mu(t);for(let e of p.readStates)n.set(uu(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 q.mkdir(J.dirname(t),{recursive:!0});let p=e.encryptSessions??!1;await R(t,JSON.stringify(s,null,2),p)};return{async findReusableRead(e,t,r){let i=uu(e,t,r),a=n.get(i);if(!a)return null;let o=await fu(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:pu(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await fu(e.path)??Date.now()};return n.set(uu(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())du(i.path)===du(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=J.join(o,c);await q.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await R(l,t.content,u);let p=J.relative(e.dataDir,l).split(J.sep).join(`/`),h=vu(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:_u(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 yu(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 uu(e,t,n){return`${du(e)}::${t??``}::${n??``}`}function du(e){return J.normalize(e)}async function fu(e){try{return(await q.stat(e)).mtimeMs}catch{return null}}function pu(e){return Mt(`sha1`).update(e).digest(`hex`)}async function mu(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:gu(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 gu(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 _u(e){let t=e.preview.length<e.originalChars?`
31
+ ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...cu,`Preview:`,e.preview+t].join(`
32
+ `)}function vu(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
33
+ `),r=n>t*.5?n:t;return e.slice(0,r)}async function yu(e,t,n,r){let i=l(e,t,r);await q.mkdir(J.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await R(i,JSON.stringify(n,null,2),a)}const bu=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function xu(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=Fu(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=Ks(Gs(S,a)),T=[],E=(await kl({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=>{K.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 Cu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await wu({entries:E,contextStore:f,compactionEvents:T});let D=await Tu({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g});if(E=D.entries,b=Du(b,D.summaries),f&&(b=await Su({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:Xs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let O=f?.getSnapshot(),k=Math.max(1e3,Math.floor(r*.7)),A=Iu({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:O?.compaction.modelUsage}).projectedInputTokens>=k,j=O?.compaction.consecutiveAutocompactFailures??0;if(!A||j>=3)return{messages:Xs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let{toKeep:M,toSummarise:N}=pc(E,r);if(N.length===0)return{messages:Xs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let P=new Date().toISOString();try{let e=O?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await nc({entries:N,llm:i,previousSummary:b,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d}),a={role:`compaction`,content:t,keptCount:M.length,droppedCount:N.length,timestamp:P};return await f?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:P}),T.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${N.length} entries with session memory`:`Autocompact summarised ${N.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,X(N)),affectedEntries:N.length,snapshotVersion:2}),{messages:Xs(Ks(M),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:M.length,estimatedTokens:X(M),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:P}),{messages:Xs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:[...T,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function Su(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=X(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&Pu(t)>=3;if(!d&&!f)return Ou(n,u?.summary);let p=await nc({entries:t,llm:r,previousSummary:Ou(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 Cu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(ku).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(!ku(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=Au(n)?ju(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
34
+ `);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),Ks(l.reverse())}async function wu(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(!ku(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=Au(r)?ju(r):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${r.toolName}`,`Preview:\n${r.toolResultRef?.preview?.trim()||r.content.slice(0,400).trim()}`].join(`
35
+ `);a!==r.content&&(s+=1,c+=Math.max(0,Math.floor((r.content.length-a.length)/4)),await n?.recordSnip({toolCallId:r.toolCallId,toolName:r.toolName,originalChars:r.content.length,retainedChars:a.length,reason:`microcompact`,createdAt:new Date().toISOString()})),l.push({...r,content:a})}return s===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${s} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:c,affectedEntries:s,snapshotVersion:2}),Cu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Tu(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(ku).filter(e=>bu.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=Eu(r,o),g=new Date().toISOString();f.push(l),m+=r.length,h+=Math.max(0,Math.floor(X(r)-Math.ceil(l.length/4)));let _={id:Pt(),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 Lu(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 Eu(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(`
39
36
  `),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
40
37
  `);return[`Historical tool activity summary: ${t.length} tool results across ${n.join(`, `)}.`,i?`Assistant notes:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
41
38
 
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,`
39
+ `)}function Du(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
40
  `)}`)].join(`
44
41
  `);return[e?.trim(),r].filter(Boolean).join(`
45
42
 
46
- `)}function td(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
43
+ `)}function Ou(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
47
44
 
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(`
45
+ `)||void 0}function ku(e){return e.role===`tool_result`}function Au(e){return e.toolName===`skill_load`}function ju(e){let t=Mu(e),n=t.name||`<skill-name>`,r=t.path?`skill_load(name="${n}", skillPath="${t.path}")`:`skill_load(name="${n}")`;return[`[skill content folded] The previous skill_load result for "${n}" was folded out of model-visible context.`,`The complete SKILL.md content is no longer available in the current prompt.`,`Before using this skill again, call ${r} again. Do not infer or reconstruct the skill instructions from memory or summaries.`,t.path?`Original path: ${t.path}`:``].filter(Boolean).join(`
46
+ `)}function Mu(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Nu(t);if(e.name||e.path)return e}return{}}function Nu(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 Pu(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Fu(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Iu(e){let t=e.pendingUserMessage?.trim()?X([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=X(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=X(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function Lu(e,t,n,r){let i=j(e,t,r);await q.mkdir(J.dirname(i),{recursive:!0}),await q.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Ru(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await lu({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 xu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function zu(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}):xu({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 Bu=Y.Object({command:Y.String({description:`Shell command to execute`}),workdir:Y.Optional(Y.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:Y.Optional(Y.Record(Y.String(),Y.String())),timeout:Y.Optional(Y.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:Y.Optional(Y.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:Y.Optional(Y.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),Vu=6e4;function Hu(e,t,n){return Math.max(t,Math.min(n,e))}function Uu(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Wu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?Vu:Hu(Math.floor(e),0,12e4)}function Gu(e,t){if(!t?.trim())return e;let n=J.isAbsolute(t)?J.normalize(t):J.normalize(J.join(e,t));if(!n.startsWith(e+J.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Ku(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 qu(e){return Yu({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
47
+ `)}function Ju(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Yu(e){let t=Ju(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 Xu(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:Bu,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=Gu(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Uu(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?Wu(n.yieldMs):Vu,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:Ku(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?Yu({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[qu(l)],p=Ju(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
48
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Zu=Y.Object({action:Y.String({description:`Process action: list | poll | log | kill`}),sessionId:Y.Optional(Y.String({description:`Session id for non-list actions`})),offset:Y.Optional(Y.Number({description:`Log line offset (0-based)`})),limit:Y.Optional(Y.Number({description:`Maximum lines to return`})),timeout:Y.Optional(Y.Number({description:`Poll wait time in milliseconds`}))});function Qu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function $u(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function ed(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:Zu,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
49
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return $u(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Qu(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`}}:$u(`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}}:$u(`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}}:$u(`No session found for ${i}`)}return $u(`Unsupported action: ${n.action}`)}}}function td(e){return Xu({workspaceDir:e,registry:Nn(),scopeKey:e})}const nd=5*1024*1024,rd=2e3;async function id(e,t){e&&await e(t).catch(()=>{})}function ad(e,t){return J.isAbsolute(e)?J.normalize(e):J.normalize(J.join(t,e))}const od=Y.Object({path:Y.String({description:`File path (relative to workspace or absolute)`}),offset:Y.Optional(Y.Number({description:`Line offset (1-based, default: 1)`})),limit:Y.Optional(Y.Number({description:`Maximum lines to read (default: 2000)`}))});function sd(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:od,async execute(n,r){let i;try{i=ad(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 q.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 Qt(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>nd){let e=o.slice(0,nd).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${nd} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
50
+ `),l=Math.max(1,r.offset??1),u=Math.min(rd,r.limit??rd),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(`
54
51
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
55
52
  `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
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(`
53
+ `),lines:d.length,truncated:f}}}}}const cd=Y.Object({path:Y.String({description:`File path (relative to workspace or absolute)`}),content:Y.String({description:`File content to write`})});function ld(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:cd,async execute(r,i){let a;try{a=ad(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await q.mkdir(J.dirname(a),{recursive:!0}),await q.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await id(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 ud=Y.Object({path:Y.String({description:`File path (relative to workspace or absolute)`}),old_string:Y.String({description:`Exact text to replace`}),new_string:Y.String({description:`Replacement text`})});function dd(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:ud,async execute(r,i){let a;try{a=ad(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 q.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 q.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await id(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 fd=Y.Object({path:Y.Optional(Y.String({description:`Directory path (default: workspace root)`}))});function pd(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:fd,async execute(t,n){let r=n.path??`.`,i;try{i=ad(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await q.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
54
+ `)||`(empty directory)`}],details:{entries:a}}}}}const md=Y.Object({input:Y.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function hd(e,t){let n=J.isAbsolute(e)?J.normalize(e):J.normalize(J.join(t,e));if(!n.startsWith(t+J.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function gd(e,t){let n=J.relative(t,e);return!n||n===``?J.basename(e):n.startsWith(`..`)||J.isAbsolute(n)?e:n}async function _d(e){await q.mkdir(J.dirname(e),{recursive:!0})}async function vd(e,t){e&&await e(t).catch(()=>{})}function yd(e){let t=[`Success. Updated the following files:`];for(let n of e.added)t.push(`A ${n}`);for(let n of e.modified)t.push(`M ${n}`);for(let n of e.deleted)t.push(`D ${n}`);return t.join(`
55
+ `)}function bd(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:md,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=Sd(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 _d(i),await q.writeFile(i,r.contents,`utf-8`),await vd(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),xd(o,s,`added`,gd(i,e));continue}if(r.kind===`delete`){let i=hd(r.path,e);await q.rm(i,{force:!0,recursive:!1}),await vd(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),xd(o,s,`deleted`,gd(i,e));continue}let i=hd(r.path,e),a=await Ed(i,r.chunks);if(r.movePath){let c=hd(r.movePath,e);await _d(c),await q.writeFile(c,a,`utf-8`),await q.rm(i,{force:!0,recursive:!1}),await vd(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),xd(o,s,`modified`,gd(c,e))}else await q.writeFile(i,a,`utf-8`),await vd(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),xd(o,s,`modified`,gd(i,e))}return{content:[{type:`text`,text:yd(o)}],details:{summary:o}}}catch(e){if(Fo(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function xd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Sd(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Cd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=wd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Cd(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 wd(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}=Td(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 Td(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 Ed(e,t){let n=(await q.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
56
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Od(n,Dd(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
57
+ `)}function Dd(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=kd(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=kd(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=kd(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
58
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Od(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 kd(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(Ad(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Ad(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Ad(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Ad(e,t,n,e=>jd(e.trim())))return n;return null}function Ad(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 jd(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 Md(e){return J.join(e,`.aimax`)}function Nd(e){return J.join(Md(e),`MEMORY.md`)}async function Pd(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function Fd(e,t){let n=Md(e),r=Ue({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 Id(e){return Ke(Md(e))}async function Ld(e){try{return await q.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Rd(e){return Ld(Nd(e))}async function zd(e,t,n){let{provider:r}=Fd(e,n);return await r.search(t)}async function Bd(e,t,n,r,i){try{let{provider:a}=Fd(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Vd(e,t,n){let{provider:r,resolvedProviderId:i}=Fd(e,n);await r.append(t),await Pd(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 Hd(e,t,n,r){let{provider:i,resolvedProviderId:a}=Fd(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 Pd(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Pd(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 Pd(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 Pd(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Pd(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 Ud(e,t,n,r){let{provider:i,resolvedProviderId:a}=Fd(e,r);await i.updateFile(t,n),await Pd(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Wd(e,t,n){let{provider:r,resolvedProviderId:i}=Fd(e,n);await r.deleteFile(t),await Pd(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Gd=Y.Object({query:Y.String({description:`Search query (case-insensitive substring match)`})});function Kd(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:Gd,async execute(n,r){let i=(await zd(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({id:e.id,file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.id?`[${e.id}] `:``}${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
59
+ `)}],details:{matches:i}}}}}const qd=Y.Object({file:Y.String({description:`Memory file path (from memory_search results)`}),start_line:Y.Number({description:`Start line number (1-based)`}),end_line:Y.Number({description:`End line number (1-based)`})});function Jd(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:qd,async execute(n,r){let i=await Bd(e,r.file,r.start_line,r.end_line,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});return i===null?{content:[{type:`text`,text:`File not found: ${r.file}`}],details:{lines:null}}:{content:[{type:`text`,text:i.map((e,t)=>`${(r.start_line+t).toString().padStart(4)} ${e}`).join(`
60
+ `)||`(empty)`}],details:{lines:i}}}}}const Yd=Y.Object({content:Y.String({description:`Content to write to memory`})});function Xd(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:Yd,async execute(n,r){try{return await Vd(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 Zd=Y.Object({section:Y.Optional(Y.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:Y.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:Y.Union([Y.Literal(`append`),Y.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Qd(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:Zd,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Vd(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 Ud(e,`MEMORY.md`,$d(await Rd(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Vd(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 $d(e,t,n){let r=e.split(`
64
61
  `),i=`## ${t}`,a=`${i}\n${n.trimEnd()}`.trimEnd(),o=-1;for(let e=0;e<r.length;e+=1)if(r[e]?.trim()===i){o=e;break}if(o===-1){let t=e.trimEnd();return`${t?`${t}\n`:``}${a}\n`}let s=r.length;for(let e=o+1;e<r.length;e+=1)if(/^##\s+/.test(r[e]??``)){s=e;break}return`${[r.slice(0,o).join(`
65
62
  `).trimEnd(),a,r.slice(s).join(`
66
63
  `).trimStart()].filter(e=>e.length>0).join(`
67
- `)}\n`}function Of(e,t){let n=e.split(`
64
+ `)}\n`}function ef(e,t){let n=e.split(`
68
65
  `),r=`## ${t}`,i=-1;for(let e=0;e<n.length;e+=1)if(n[e]?.trim()===r){i=e;break}if(i===-1)return null;let a=n.length;for(let e=i+1;e<n.length;e+=1)if(/^##\s+/.test(n[e]??``)){a=e;break}let o=[n.slice(0,i).join(`
69
66
  `).trimEnd(),n.slice(a).join(`
70
67
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
71
- `)}\n`:``}function kf(e,t){let n=e.split(`
68
+ `)}\n`:``}function tf(e,t){let n=e.split(`
72
69
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
73
- `)}\n`:``)}function Af(e,t,n){let r=e.split(`
70
+ `)}\n`:``)}function nf(e,t,n){let r=e.split(`
74
71
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.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(`
72
+ `)}\n`)}function rf(e){let t=e.indexOf(`#`);if(t===-1)return{filePath:e};let n=e.slice(0,t),r=e.slice(t+1),i=r.match(/^L(\d+)$/);return i?{filePath:n,line:Number(i[1])}:{filePath:n,section:r}}function af(e,t){let n=[],r=t.split(`
73
+ `);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const of=Y.Object({content:Y.String({description:`Note to append to today's daily log`}),scope:Y.Optional(Y.Union([Y.Literal(`daily`),Y.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function sf(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:of,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Hd(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 cf=Y.Object({scope:Y.Optional(Y.Union([Y.Literal(`long-term`),Y.Literal(`recent`),Y.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function lf(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:cf,async execute(n,r){try{let n=r.scope??`all`,i=await Id(e),a=[];for(let n of i.slice(0,30)){let r=await Bd(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
74
+ `),t=af(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(`
78
75
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
79
76
 
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(`
77
+ `)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const uf=Y.Object({id:Y.Optional(Y.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:Y.Optional(Y.String({description:`Search query used to find memories to delete`})),limit:Y.Optional(Y.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:Y.Optional(Y.Union([Y.Literal(`long-term`),Y.Literal(`recent`),Y.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function df(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:uf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=rf(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=ef(await Rd(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 Ud(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 Bd(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=ef(n.join(`
78
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Ud(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 Bd(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=tf(n.join(`
79
+ `),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Ud(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 Wd(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 zd(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Wd(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 ff=Y.Object({id:Y.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:Y.String({description:`New content to replace the existing memory with`})});function pf(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:ff,async execute(n,r){try{let n=rf(r.id);if(n.section){let i=$d(await Rd(e)??``,n.section,r.content);return await Ud(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 Bd(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=nf(i.join(`
80
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Ud(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 Ud(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 mf=Y.Object({query:Y.Optional(Y.String({description:`Search query; omit to browse recent sessions.`})),role_filter:Y.Optional(Y.Union([Y.Literal(`user`),Y.Literal(`assistant`),Y.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:Y.Optional(Y.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:Y.Optional(Y.Union([Y.Literal(`llm`),Y.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:mf,async execute(n,r){let i=gf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await _f(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 vf({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=jf(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 nc({entries:Of(Df(await I(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Af({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 gf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function _f(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 L(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 vf(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Sf(e.query),i=(await Mf(n,6,async t=>yf({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Ef).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 L(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 yf(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
81
+ `);for(let t of r){let r=t.trim();if(!r||!bf(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!xf(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=wf(i.content,e.terms,i.role);if(a<=0)continue;let o=Tf(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(Ef),n.length=20)}return n.sort(Ef),n}function bf(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function xf(e){return e===`user`||e===`assistant`||e===`tool_result`}function Sf(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=>Cf(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 Cf(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 wf(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 Tf(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Ef(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Df(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Of(e,t,n){if(e.length===0)return e;let r=Sf(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 kf(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 kf(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 Af(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
82
+ `)}function jf(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
83
+ `)}`}async function Mf(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 Nf(e){return J.join(e,`.aimax`,`skills`)}function Pf(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ff(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${Pf(n)}\n`)}function If(e){let t=Rt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
84
+ `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}function Lf(e){let t=Rt(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 Rf(e){return(await q.stat(e)).mtime.toISOString()}async function zf(e){return Vf([Nf(e)])}async function Bf(e,t,n=[]){return Vf([...n,...t,Nf(e)])}async function Vf(e){let t=new Map;for(let n of e){let e;try{e=await q.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=J.join(n,e,`SKILL.md`),i;try{i=await q.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=If(i),o=Lf(i),s=await Rf(r)}catch(t){Ff(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 Hf(e,t){let n=t.trim();if(!n)return;let r=(await Vf(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:J.dirname(r.location)}}async function Uf(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=J.resolve(r),a=J.basename(i)===`SKILL.md`?i:J.join(i,`SKILL.md`);if(J.basename(a)!==`SKILL.md`)return;let o;try{o=await q.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=If(o),c=Lf(o),l=await Rf(a)}catch(e){Ff(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:J.dirname(a)}}async function Wf(e,t,n){let r=n?.trim()?await Uf(t,n):await Hf(e,t);if(!r)return;let i=await q.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Gf(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(`
88
85
  `)).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(`
86
+ `)}\n</available_skills>`}const Kf=Y.Object({category:Y.Optional(Y.String({description:`Reserved category filter field. Not used yet.`}))}),qf=Y.Object({name:Y.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:Y.Optional(Y.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Jf(e,t,n=[]){return[...n,...t,Nf(e)]}function Yf(e,t,n=[]){let r=Jf(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Kf,async execute(e,t){let n=await Vf(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 Xf(e){let t=Jf(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:qf,async execute(r,i){let a=await Wf(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 Zf=Y.Object({});function Qf(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:Zf,async execute(r,i){let a=await W(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,goalState:null,workflowWarning:null})}],details:{}};let o=await B(e,t,a,{storeName:n}),s=await Xn(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:{}}}}}Y.Object({status:Y.String({description:`Status to set. Only 'complete' is allowed.`})});function $f(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 ep(e){let t=$f(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=J.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 tp(e){let t=e.watchFactory??((e,t,n)=>Vt.watch(e,t,n)),n=J.join(e.dataDir,`.aimax`),r=[{target:J.join(n,`MEMORY.md`),kind:`memory-file`},{target:J.join(n,`memory.md`),kind:`memory-file-lower`},{target:J.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=ep({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 Z(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function np(e){return e.projectDir?.trim()||J.join(e.dataDir,`workspace`)}async function rp(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=np(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=sp(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=J.join(t.dataDir,`.aimax`),m=Ze({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=Ge({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName},{includeSessions:!0})}catch(e){if(!He(e))throw e;x=e instanceof Error?e.message:String(e),g=ip(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=tp({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,op({sessionOptions:Z(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 ip(e,t){return{id:`builtin-memory`,name:`Builtin Memory Provider (degraded)`,status:()=>({backend:`builtin`,provider:`builtin-memory`,workspaceDir:e,dbPath:J.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 ap(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function op(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 sp(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 Q(e){return{storeName:e.sessionStoreName}}function cp(e){return np({dataDir:e.dataDir,projectDir:e.projectDir})}function lp(e){return fr({dataDir:e.dataDir,workspaceDir:cp(e),projectDir:e.projectDir})}function up(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function $(e,t){return up({ok:!1,error:e,...t})}function dp(e,t){return Bn(e.dataDir,e.sessionId,Q(e),t)}async function fp(e){try{return await qn(e.dataDir,e.sessionId,Q(e))}catch(e){if(e instanceof Ln)return{corrupt:!0};throw e}}function pp(){return $(`workflow_corrupt`,{repairTool:`goal_repair_workflow_state`})}const mp={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,gp=/[/\\]|\.(?:html|css|js|ts|tsx|jsx|json|md|txt|py|go|rs|yaml|yml|sh)\b|\bexists\b/i,_p=/\b(npm|pnpm|yarn|cargo|go test|pytest|vitest|jest|exit code|stdout|stderr|command output|test pass|tests pass)\b/i;function vp(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 yp(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 bp(e){let t=e.trim();return hp.test(t)?{reason:`the ref describes planning state`}:gp.test(t)?{reason:yp(t)?`the ref describes a file artifact`:`the ref describes a file artifact but no reliable path could be extracted`}:_p.test(t)?{reason:`the ref describes command output`}:{reason:`the ref is natural language and must be registered as evidence`}}function xp(e){let t=e.trim();if(hp.test(t))return{kind:`manual`,source:`goal/state.json`,summary:t.slice(0,120),content:t};if(gp.test(t)){let e=yp(t);if(e)return{kind:`snapshot`,path:e,summary:t.slice(0,120)}}return _p.test(t)?{kind:`exec`,command:t.includes(`npm test`)?`npm test`:`<command>`,cwd:`<workspace>`,timeoutMs:12e4}:{kind:`manual`,source:vp(t,t),summary:t.slice(0,120),content:t}}function Sp(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=bp(e);n.push({tool:`goal_record_evidence`,reason:i.reason,args:xp(e)})}return n}function Cp(e){let t=e.errors[0]?.code??`invalid_evidence`;return t===`unregistered_evidence_ref`?$(t,{errors:e.errors,repairPlan:Sp(e.errors),...mp}):$(t,{errors:e.errors})}function wp(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:vp(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 Tp(e){let t=Or(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 Ep(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 Dp(e,t){return e.tasks.find(e=>e.id===t)}function Op(e){return e.tasks.some(e=>e.kind===`execution`&&e.required!==!1)}function kp(e){return e.ok===!1?e.warning:null}async function Ap(e,t){await xr(e.dataDir,e.sessionId,t,Q(e));let n=kp(await Tr(e.dataDir,e.sessionId,t,Q(e)));return n?{planWarning:n}:{}}function jp(e){return{name:`goal_plan_update`,label:`Goal Plan Update`,description:`Update controlled sections of goal/plan.md without changing task workflow state.`,parameters:Y.Object({interpretation:Y.Optional(Y.String()),assumptions:Y.Optional(Y.Array(Y.String())),openQuestions:Y.Optional(Y.Array(Y.String())),taskPlanNotes:Y.Optional(Y.String())}),async execute(t,n){return dp(e,async()=>{let t=await fp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return pp();let r=t;await Er(e.dataDir,e.sessionId,{type:`goal_plan_updated`,goalId:r.goalId,interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Q(e));let i=await wr(e.dataDir,e.sessionId,{interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Q(e)),a=await Tr(e.dataDir,e.sessionId,r,Q(e));return up({ok:!0,goalId:r.goalId,planMeta:i,warning:kp(a),hint:`Use goal_add_task to project executable tasks into goal/state.json.`})})}}}function Mp(e){return{name:`goal_task_done`,label:`Goal Task Done`,description:`Mark the current doing task done with evidence covering required acceptance criteria.`,parameters:Y.Object({taskId:Y.String(),summary:Y.Optional(Y.String()),evidenceRefs:Y.Optional(Y.Array(Y.String())),acceptanceEvidence:Y.Optional(Y.Array(Y.Object({criterionId:Y.String(),evidenceRefs:Y.Array(Y.String())})))}),async execute(t,n){return dp(e,async()=>{let t=await fp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return pp();let r=t,i=Dp(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=Ep(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 yr(e.dataDir,e.sessionId,a,Q(e));if(!c.valid)return Cp(c);if(i.kind===`clarify`){if(!Op(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 Er(e.dataDir,e.sessionId,{type:`goal_task_done`,goalId:r.goalId,taskId:i.id,summary:n.summary,acceptanceEvidence:n.acceptanceEvidence,evidenceRefs:a},Q(e));let h=await Sr(e.dataDir,e.sessionId,Q(e));await wr(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},Q(e));let{planWarning:g}=await Ap(e,m);return up({ok:!0,currentTaskId:m.currentTaskId,hint:m.currentTaskId?null:`All tasks done. Call goal_complete with finalEvidenceRefs.`,warning:g??null})})}}}function Np(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:Y.Object({taskId:Y.String(),reason:Y.String(),neededInput:Y.Optional(Y.String()),evidenceRefs:Y.Optional(Y.Array(Y.String()))}),async execute(t,n){return dp(e,async()=>{let t=await fp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return pp();let r=t,i=Dp(r,n.taskId);if(!i)return $(`task_not_found`);let a=n.evidenceRefs??[];if(a.length>0){let t=await yr(e.dataDir,e.sessionId,a,{...Q(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 Er(e.dataDir,e.sessionId,{type:`goal_task_blocked`,goalId:r.goalId,taskId:i.id,reason:n.reason,neededInput:n.neededInput,evidenceRefs:a},Q(e)),await wr(e.dataDir,e.sessionId,{risks:[s]},Q(e));let{planWarning:u}=await Ap(e,l);return up({ok:!0,workflowStatus:`blocked`,warning:u??null})})}}}function Pp(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:Y.Object({title:Y.String(),kind:Y.Optional(Y.Literal(`execution`)),required:Y.Optional(Y.Boolean()),acceptanceCriteria:Y.Array(Y.Union([Y.String(),Y.Object({text:Y.String(),required:Y.Optional(Y.Boolean())})])),afterTaskId:Y.Optional(Y.String()),startNow:Y.Optional(Y.Boolean())}),async execute(t,n){return dp(e,async()=>{let t=await fp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return pp();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=Dr(r.tasks),o=Tp(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 Er(e.dataDir,e.sessionId,{type:`goal_task_added`,goalId:r.goalId,taskId:a,kind:`execution`,required:s.required,acceptanceCriteria:o},Q(e));let{planWarning:u}=await Ap(e,l);return up({ok:!0,taskId:a,warning:u??null})})}}}function Fp(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:Y.Object({kind:Y.Union([Y.Literal(`note`),Y.Literal(`manual`),Y.Literal(`exec`),Y.Literal(`snapshot`)]),summary:Y.Optional(Y.String()),content:Y.Optional(Y.String()),taskId:Y.Optional(Y.String()),source:Y.Optional(Y.String()),command:Y.Optional(Y.String()),cwd:Y.Optional(Y.String()),timeoutMs:Y.Optional(Y.Number()),path:Y.Optional(Y.String())}),async execute(t,n){let r=await fp(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return pp();let i=r;if(n.kind===`note`||n.kind===`manual`){if(!n.summary?.trim())return $(`missing_summary`);if(!n.content?.trim())return $(`missing_content`);let t=await kr(e.dataDir,e.sessionId,{kind:n.kind,summary:n.summary,content:n.content,source:n.source},Q(e));return`error`in t?t.error===`manual evidence requires source`?wp(n.summary,n.content):$(t.error):(await Er(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`},Q(e)),up({ok:!0,evidenceRef:t.evidenceRef}))}if(n.kind===`exec`){if(!n.command?.trim())return $(`missing_command`);let t=await Ar(e.dataDir,e.sessionId,{command:n.command,cwd:n.cwd,timeoutMs:n.timeoutMs,workspaceDir:cp(e),allowedRoots:lp(e),baseEnv:e.baseEnv},Q(e));return`error`in t?$(t.error):(await Er(e.dataDir,e.sessionId,{type:`goal_command_recorded`,goalId:i.goalId,evidenceRef:t.evidenceRef,command:n.command,cwd:n.cwd??cp(e),exitCode:t.exitCode},Q(e)),up({ok:!0,evidenceRef:t.evidenceRef,exitCode:t.exitCode}))}if(!n.path?.trim())return $(`missing_path`);let a=await Mr(e.dataDir,e.sessionId,{path:n.path,summary:n.summary,workspaceDir:cp(e),allowedRoots:lp(e)},Q(e));return`error`in a?$(a.error):(await Er(e.dataDir,e.sessionId,{type:`goal_snapshot_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,path:n.path},Q(e)),up({ok:!0,evidenceRef:a.evidenceRef}))}}}function Ip(e){return{name:`goal_complete`,label:`Goal Complete`,description:`Complete the goal after all required tasks are done and final evidence is recorded.`,parameters:Y.Object({summary:Y.String(),finalEvidenceRefs:Y.Array(Y.String()),risks:Y.Optional(Y.Array(Y.String()))}),async execute(t,n){return dp(e,async()=>{let t=await fp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return pp();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 yr(e.dataDir,e.sessionId,n.finalEvidenceRefs,Q(e));if(!o.valid)return Cp(o);let s=new Date().toISOString(),c={...r,status:`complete`,finalEvidenceRefs:n.finalEvidenceRefs,completedAt:s,currentTaskId:null,updatedAt:s};if(!await W(e.dataDir,e.sessionId,Q(e)))return $(`goal_not_found`);await xr(e.dataDir,e.sessionId,c,Q(e));try{await H(e.dataDir,e.sessionId,{status:`complete`},{...Q(e),eventSource:`tool`})}catch(t){throw await xr(e.dataDir,e.sessionId,r,Q(e)),t}return await Er(e.dataDir,e.sessionId,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:n.finalEvidenceRefs,summary:n.summary,risks:n.risks??[]},Q(e)),await wr(e.dataDir,e.sessionId,{finalSummary:n.summary,evidence:n.finalEvidenceRefs,risks:n.risks},Q(e)),up({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,warning:kp(await Tr(e.dataDir,e.sessionId,c,Q(e)))})})}}}function Lp(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:Y.Object({confirm:Y.Literal(!0)}),async execute(t,n){return up(await dp(e,()=>Jn(e.dataDir,e.sessionId,Q(e))))}}}function Rp(e){return[jp(e),Pp(e),Fp(e),Mp(e),Np(e),Lp(e),Ip(e)]}var zp=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=J.resolve(e.rootDir??Ui(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=Ji(e.path),n=Gp(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 ca(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:Wi(this.rootDir)}}async createSkill(e){let t=Yi(e.name),n=Ji(e.categoryPath),r=Gp(e.description,`auto-skill description`),i=Kp(e.body);await this.assertCategoryExists(n);let a=Xi(n,t),o=$i(this.rootDir,n,t);if(await Up(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=J.join(o,`SKILL.md`),l=J.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:qp(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:Jp(e.evidence,s)};return await q.mkdir(o,{recursive:!0}),await q.writeFile(c,Bp(t,r,i),`utf-8`),await Wp(l,u),await ca(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Zi(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=$i(this.rootDir,t.categoryPath,t.skillName),r=J.join(n,`SKILL.md`),i=J.join(n,`metadata.json`),a=await Vp(r),o=await Hp(i),s=e.description===void 0?a.description:Gp(e.description,`auto-skill description`),c=e.body===void 0?a.body:Kp(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?qp(o.tags):qp(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:{},...Jp(e.evidence,l)}};return await q.writeFile(r,Bp(t.skillName,s,c),`utf-8`),await Wp(i,u),await ca(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Zi(e.skillId),n=$i(this.rootDir,t.categoryPath,t.skillName),r=J.join(n,`metadata.json`),i=J.join(n,`SKILL.md`);await q.access(i);let a=await Hp(r),o=this.now().toISOString();return await Wp(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...Jp(e.evidence,o)}}),await ca(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=Wi(this.rootDir),t;try{t=await q.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=Ji(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 q.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await Wp(Wi(this.rootDir),t)}};function Bp(e,t,n){return[`---`,`name: ${Yp(e)}`,`description: ${Yp(t)}`,`---`,``,n.trim(),``].join(`
87
+ `)}async function Vp(e){let t=Rt(await q.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Hp(e){let t;try{t=await q.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 Up(e){try{return await q.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Wp(e,t){await q.mkdir(J.dirname(e),{recursive:!0}),await q.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Gp(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function Kp(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 qp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Jp(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Yp(e){return JSON.stringify(e)}const Xp=[`create`,`update`,`archive`,`create_category`],Zp=Y.Object({}),Qp=Y.Object({categoryPath:Y.Optional(Y.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:Y.Optional(Y.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),$p=Y.Object({query:Y.String({description:`Search query for learned auto-skills.`}),limit:Y.Optional(Y.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),em=Y.Object({skillId:Y.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:Y.Optional(Y.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),tm=Y.Object({action:Y.Union(Xp.map(e=>Y.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:Y.Optional(Y.String({description:`Exact auto-skill id for update/archive.`})),name:Y.Optional(Y.String({description:`Auto-skill slug for create.`})),categoryPath:Y.Optional(Y.String({description:`Existing single-level category slug for create.`})),newCategory:Y.Optional(Y.Object({path:Y.String({description:`New single-level category slug to create.`}),description:Y.String({description:`New category description.`})})),description:Y.Optional(Y.String({description:`Auto-skill description for create/update.`})),tags:Y.Optional(Y.Array(Y.String({description:`Auto-skill tag.`}))),confidence:Y.Optional(Y.Number({description:`Optional confidence score from 0 to 1.`})),body:Y.Optional(Y.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:Y.Optional(Y.Object({sessionId:Y.String({description:`Source session id.`}),reason:Y.String({description:`Why this auto-skill write is justified.`}),toolCallCount:Y.Optional(Y.Number({description:`Tool calls observed in source run.`})),loadedSkills:Y.Optional(Y.Array(Y.String({description:`Skill loaded during source run.`})))}))});function nm(e){let t=new la({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:Zp,async execute(){try{let e=await t.autoSkillCategories();return cm({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return cm({categories:[],count:0,error:lm(e)})}}}}function rm(e){let t=new la({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:Qp,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return cm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return cm({skills:[],count:0,error:lm(e)})}}}}function im(e){let t=new la({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:$p,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return cm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return cm({skills:[],count:0,error:lm(e)})}}}}function am(e){let t=new la({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:em,async execute(e,n){try{return cm({...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 cm({skillId:n.skillId,error:lm(e)})}}}}function om(e){let t=new zp({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:tm,async execute(e,n){try{return cm(await sm(t,n))}catch(e){return cm({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:lm(e)})}}}}async function sm(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 cm(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function lm(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const um=2,dm=5;var fm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),K.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:we(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&&K.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`){K.info(`subagent status changed`,t);return}if(e.status===`killed`){K.warn(`subagent status changed`,t);return}K.error(`subagent status changed`,t)}};const pm=Y.Object({task:Y.String({description:`The task description for the subagent to execute`}),label:Y.Optional(Y.String({description:`Optional short label to identify this subagent`})),agent:Y.Optional(Y.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.`}))}),mm=Y.Object({task:Y.String({description:`The task description for the subagent to execute`}),label:Y.Optional(Y.String({description:`Optional short label to identify this subagent`})),agent:Y.Optional(Y.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.`}))}),hm=Y.Object({tasks:Y.Array(pm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function gm(e){let t=e.label?`"${e.label}"`:`task: ${Dt(e.task)}`;return e.status===`done`?`${t}\n\n${_m(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function _m(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 vm(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(K.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:we(p)}),!p){let e={status:`error`,error:`task must not be empty`};return K.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 K.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Pt(),v=new AbortController,y=t,b=za(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return K.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 K.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}K.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?Ga(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),K.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,K.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=gm({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 K.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 K.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 ym(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:mm,async execute(e,t){return vm(u,e,t)}}}function bm(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:hm,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}}K.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 vm(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${_m(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
91
88
 
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(`
89
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const xm=Y.Object({action:Y.Union([`list`,`kill`].map(e=>Y.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:Y.Optional(Y.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Sm(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 Cm(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 wm(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:xm,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} (${Sm(e.runtimeMs)})${n}`})).join(`
90
+ `)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Cm(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 Tm=Y.Object({image:Y.String({description:`Image path or URL`}),prompt:Y.Optional(Y.String({description:`Prompt for image analysis`})),model:Y.Optional(Y.String({description:`Optional model override`})),maxBytesMb:Y.Optional(Y.Number({description:`Optional size cap in MB`}))});function Em(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Tm,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}function Dm(e,t){let n=np({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=[Xu({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),ed({registry:i,scopeKey:n}),sd(n,t?.contextManager),ld(n,t?.contextManager,s),dd(n,t?.contextManager,s),pd(n),bd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[Qf(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),...Rp({dataDir:e,sessionId:t.sessionId,sessionStoreName:t.inheritedRunParams?.sessionStoreName,projectDir:t.inheritedRunParams?.projectDir,baseEnv:t.baseEnv})]:[],Kd(e,r),hf(e,r),Jd(e,r),Qd(e,r),sf(e,r),lf(e,r),df(e,r),pf(e,r),Yf(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Xf({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(nm(e),rm(e),im(e),am(e)),t&&c.push(ym(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),bm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),wm(t.registry,t.parentSessionId)),c}function Om(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(`
94
91
  `),`</auto_skill_categories>`,``].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(`
92
+ `)}const km={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`},Am=`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 jm(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...Am.filter(e=>t.has(e)),...n.filter(e=>!Am.includes(e)).sort()],displayName:t}}function Mm(e){let{ordered:t,displayName:n}=jm(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??km[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
96
93
  `),``].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
+ `)}function Nm(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Use `get_goal` to view the current goal, its status, budget, usage, and V2-lite workflow summary (`goalState`).",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,"- When V2-lite workflow is active, complete tasks with `goal_task_done` and finish the goal with `goal_complete` (with evidence refs).","- Use `goal_record_evidence` to create evidence refs before filling `evidenceRefs`, `acceptanceEvidence`, or `finalEvidenceRefs`.","- Do NOT call `goal_complete` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and goal workflow tools report an error.",``].join(`
95
+ `)}function Pm(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
96
+ `)}function Fm(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
97
+ `)}function Im(e){return e?``:[`## Tool Call Style`,`Default: call routine low-risk tools directly without narrating every step.`,`Narrate briefly when actions are sensitive, long-running, or likely surprising.`,`When approvals are required, keep the command text exact and complete.`,``].join(`
98
+ `)}function Lm(){return[`## Artifact Declaration`,"Before your final answer, always run an internal artifact audit for the current turn. If the turn produced, modified, returned, exported, downloaded, or made available any user-relevant persistent artifact, declare it at the very end of the assistant message using exactly one `<aimax_artifacts>` block.",`A user-relevant artifact is a deliverable the user or backend may want to open, inspect, download, or display, including files and user-openable URLs.`,`Maintain a private artifact list while working: after every successful tool result, add produced or modified file/URL candidates; before the final answer, serialize the distinct list into the block.`,`Normal answer text does not count as artifact reporting: mentioning a file path or URL in prose is not enough. Every reportable artifact must appear in the block.`,``,`Mandatory artifact sources to audit:`,"- `write_file`: every file written after success.","- `edit_file`: every successfully edited file when the tool says `File edited` or reports occurrences greater than 0. If you changed file contents, declare the edited file even if the final answer only says it was modified.","- `apply_patch`: every added, updated, or moved resulting file; include all files touched by a multi-file patch.","- `exec` / bash / `process`: files generated, exported, downloaded, converted, overwritten, or modified by commands and scripts. Use command arguments, stdout/stderr, path parameters, and follow-up confirmations. If a bash command creates a user deliverable, declare it even when no file-writing tool was used or the result is `(no output)`.",`- Skills, plugin tools, and UI tools: files or URLs produced or returned by tool execution. If a skill returns a user-openable URL as the deliverable, declare that URL even if the visible final answer is only the URL.`,"- `subagent_spawn` / `batch_subagent_spawn`: artifacts returned from child agents; include all child artifacts in the parent block.",`- Assistant-only output: durable URLs or newly created file paths mentioned without a tool call when they are user deliverables.`,``,`Bash/exec detection checklist:`,"- Treat command arguments as evidence; successful `(no output)` does not cancel reporting when the command names a write/edit target.","- Declare files named by redirection or output patterns such as `> file`, `>> file`, `cat > file`, heredoc writers, `tee`, `cp`, `mv`, `curl -o`, `wget -O`, `--output`, `saved to`, `generated file`, `file created`, `file written`, or `文件已生成:<path>`.","- Declare files mutated by commands such as `sed -i`, `perl -pi`, append redirections, `tee -a`, scripts that open/write files, or temp-file replacement patterns like `command > file.tmp && mv file.tmp file`.",`- For heredocs that write a script template, declare the outer script file. Do not declare paths inside the heredoc body until that generated script runs or a later result confirms creation.`,"- Ignore metadata-only lines such as `Generated at:`, file size, byte counts, timestamps, row counts, and column counts; they are not artifact paths.",``,`Do not declare deleted files, failed or rolled-back outputs, files that were only read/listed/searched, temporary/cache files unless explicitly presented as user deliverables, or internal AIMax files such as transcript.jsonl, artifacts.json, session metadata, logs, memory files, context snapshots, and tool-result spill files.`,``,`The block format is a JSON array. Each item must include:`,'- `kind`: `"file"` or `"url"`.','- `file`: file path, required when kind is `"file"`; prefer absolute paths, but use a workspace-relative path if that is what the tool reported.','- `url`: URL value, required when kind is `"url"`.',"- `timestamp`: ISO 8601 timestamp.","- `label`: short human-readable description in the user's language.",``,`Example:`,`<aimax_artifacts>`,`[{"kind":"file","file":"/data/user/workspace/report.md","timestamp":"2026-06-15T10:30:00.000Z","label":"分析报告"},{"kind":"url","url":"https://artifact.example.test/report","timestamp":"2026-06-15T10:31:00.000Z","label":"在线报告"}]`,`</aimax_artifacts>`,``,`Common cases:`,'- After a successful `edit_file` on `src/app.ts`: `[{"kind":"file","file":"src/app.ts","timestamp":"2026-06-15T10:30:00.000Z","label":"已编辑的应用源码"}]`.','- After a bash command writes `dist/report.html`: `[{"kind":"file","file":"dist/report.html","timestamp":"2026-06-15T10:30:00.000Z","label":"生成的 HTML 报告"}]`.','- After a skill returns `https://artifact.example.test/share/abc`: `[{"kind":"url","url":"https://artifact.example.test/share/abc","timestamp":"2026-06-15T10:30:00.000Z","label":"技能生成的在线结果"}]`.',``,`High-risk scenarios:`,"- After `cat > hello.py << 'EOF' ... EOF`, declare `hello.py` even if the command returns `(no output)`.","- After `sed -i '' 's/old/new/' test123.md`, declare `test123.md` even if a later read merely verifies the contents.","- After one turn edits `hello.md` and a subagent returns `test.md`, include both items in the same block. Reporting only one artifact violates the protocol.",`- If a child result text or child task explicitly names a user deliverable path/URL that was created or modified, include it in the parent block even when the child did not emit its own block.`,'- If a skill or command returns a single user-openable URL such as `https://artifact.example.test/result`, declare it as `kind: "url"`; do not return only the visible URL.',``,`Bad outputs that violate the protocol:`,"- Saying `已编辑 test123.md` after `edit_file` or `sed -i` without an `<aimax_artifacts>` block.","- Saying `已创建 hello.py` after `cat > hello.py` without an `<aimax_artifacts>` block.",`- Reporting only one artifact after multiple successful tool calls changed multiple user files.`,``,`Rules:`,`- If no artifacts were produced this turn, do not include the block.`,`- The block must be the last thing in the assistant message.`,"- There must be no text after `</aimax_artifacts>`.",`- The block is for the runtime parser, not for the user.`,`- Do not duplicate the same file or URL inside the block.`,``].join(`
99
+ `)}function Rm(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(`
103
100
  `)).join(`
104
101
  `)}\n</available_skills>`,``].join(`
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
102
+ `)}function zm(e=[]){let t=Om(e).trim();return t?`${t}\n`:``}function Bm(){return[`## Scenes`,'If the user message contains a `<scenes category="..." type="..." items="...">...</scenes>` tag, treat it as an explicit scene activation request.',"In this tag, `category` means the scene category, `type` means the scene name, and `items` means the item list required by that scene.","The `category`, `type`, and `items` attributes may each contain one or more comma-separated values. You must split them on commas, trim whitespace, and use every requested value.","Before executing the task, you must enumerate every requested `<category, scene, item>` combination derived from those attributes.","For each requested item, you must call `skill_load(name=<item>, skillPath=/aimax_pvc/scenes/<category>/<scene>/<item>)` to load that item's `SKILL.md`.","If one `<scenes ...>` tag requests multiple items for the same scene, you must load them one by one. Do not stop after the first matching item.","Do not start implementation, analysis, tool execution, or user-facing conclusions until all required scene skills have been loaded with `skill_load`.","After loading those scene `SKILL.md` files through `skill_load`, you must follow their instructions as mandatory task-specific guidance unless a higher-priority instruction overrides them.","For scene skills, if the exact scene SKILL.md is not visible, reload it again with the original `skillPath`.","Scene skills are not loaded by default. Only load them when the user explicitly includes the `<scenes ...>` tag.","Outside explicit scene activation, normal shared skills from `<available_skills>` must still be loaded with `skill_load(name=<skill-name>)` rather than direct file reads.","When a scene is activated, you must load scene instructions only through `skill_load` with `skillPath` pointing at `/aimax_pvc/scenes/<category>/<scene>/<item>` or that directory's `SKILL.md`.","Do not load, match, or fall back to scene instructions from `<dataDir>/.aimax/skills`.","Do not load, match, or fall back to scene instructions from `/aimax/extensions/`.","Do not load, match, or fall back to scene instructions from any path declared in `<available_skills>`.",`Do not ignore, rewrite, or drop the scene tag semantics even if the natural-language request looks answerable without scene skills.`,``].join(`
103
+ `)}function Vm(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
104
+ `)}function Hm(e){return[`## Memory & session recall`,`Choose the right recall surface:`,"- **Durable memory (Markdown / MEMORY.md / memory/ logs)**: stable facts, preferences, policies, decisions. Prefer `memory_search`, then `memory_get` when you need the full passage. Do not guess entry IDs or file paths.","- **Past chat transcripts across sessions** (what was said or done in earlier conversations): use `session_search`. Omit `query` to browse recent sessions; include `query` to search transcripts. Do not use `memory_search` alone to reconstruct a cross-session chat timeline.",'- **Ambiguous** ("last time" could mean chat or written notes): run `session_search` first for conversational evidence, then `memory_search` for durable notes; merge and attribute each source.',"If a listed memory tool call fails, report the failure; do not claim the tool is unavailable. Use `memory_list` before update/delete when needed.","Short tool chains: `memory_search` → `memory_get`; `memory_list` → `memory_update`; `memory_search` → `memory_forget`.",`Routing examples (intent → tool):`,'1) "上次聊天我们怎么修的" → `session_search` with keywords from the bug/symptom.','2) "团队对 release 的硬性规范是什么" → `memory_search` (durable policy).','3) "最近几个会话在忙什么" → `session_search` with no query (recent mode).','4) "把这条写进长期记忆" → `memory_write` (default), not `memory_log` or `session_search`.','5) "昨天日志里有没有记过 X" → `memory_search` on daily logs / `memory_list`.','6) "上次口头结论 vs 正式文档" → `session_search` then `memory_search`.',e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
105
+ `)}function Um(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`,o=e.projectDir?.trim(),s=o?[`Current project directory: ${o}`,`Treat this project directory as the default cwd for repository/code work unless the user specifies another directory.`]:[];return[`## Workspace`,`Your cloud working directory is: ${r}`,...s,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,`Use the workspace temp directories for temporary or intermediate files:`,`- ${r}/temp/daily/ for short-lived files that can be cleaned daily.`,`- ${r}/temp/weekly/ for files that should remain available for about a week.`,`- ${r}/temp/monthly/ for files that should remain available for about a month.`,`Do not pre-initialize these directories; create them only when you actually need to write temporary files.`,``].join(`
106
+ `)}function Wm(e){if(!e?.enabled)return``;let t=[`## Sandbox`,`You are running in a containerized cloud CLI runtime.`];return e.containerWorkspaceDir?.trim()&&t.push(`Container workdir: ${e.containerWorkspaceDir.trim()}`),e.hostWorkspaceDir?.trim()&&t.push(`Host-mounted workspace: ${e.hostWorkspaceDir.trim()}`),t.push(``),t.join(`
107
+ `)}function Gm(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Km(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
108
+ `)}function Km(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 qm(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools only when the user or system instructions explicitly require subagents, delegation, or parallel agent execution; otherwise stay in the current agent.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
109
+ `)}function Jm(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
110
+ `)}function Ym(e){return e.isMinimal?``:[`## Silent Replies`,`Do not send empty or filler replies.`,`If a tool already delivered the user-visible output, keep your final reply minimal and avoid duplication.`,``].join(`
111
+ `)}function Xm(e){let t=e.contextFiles,n=(e.bootstrapWarnings??[]).map(e=>e.trim()).filter(Boolean);if(t.length===0&&n.length===0)return``;let r=t.some(e=>(e.path.split(`/`).pop()?.toLowerCase()??``)===`soul.md`),i=[`# Project Context`,``];if(n.length>0){i.push(`⚠ Bootstrap truncation warning:`);for(let e of n)i.push(`- ${e}`);i.push(``)}t.length>0&&(i.push(`The following project context files have been loaded:`),i.push(`These are source-of-truth cloud files at their shown paths. If you update them, use the exact path shown in the heading, especially for files under .aimax.`)),r&&i.push(`If SOUL.md is present, embody its persona and tone. Avoid stiff, generic replies; follow its guidance unless higher-priority instructions override it.`),i.push(``);for(let e of t)i.push(`## ${e.path}`,``,e.content,``);return i.join(`
112
+ `)}function Zm(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
113
+ `)}function Qm(e){return e?.trim()?[`## Prior Conversation Summary`,`The following is a summary of the conversation history that occurred before the current context window.`,`Use it to maintain continuity with earlier work.`,``,e.trim(),``].join(`
114
+ `):``}function $m(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:[...Am],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Zm(e.subagentDepth??0),Mm({toolNames:i,toolSummaries:e.toolSummaries}),Lm(),Im(n),Nm(),Pm(),Wa(e.availableAgents??[]),Rm(a),zm(e.autoSkillCategories),Bm(),Vm(),Hm(e.memoryCitationsMode??`off`),Um({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Wm(e.sandboxInfo),Gm({currentDate:e.currentDate,timezone:e.timezone}),Fm(),qm({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Ym({isMinimal:n}),Jm(e.runtimeInfo),Xm({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Qm(e.priorConversationSummary)].filter(Boolean).join(`
115
+ `)}function eh(e,t,n){return e.map(e=>{let r=e,i=Pe(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await le({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(Fo(e))return zo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function th(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=oh(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=rh(n,e.content)),e.details!==void 0){let t=oh(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function rh(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?ih(e,t)?t:[...e,...t]:t}function ih(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!ah(e[n],t[n]))return!1;return!0}function ah(e,t){return JSON.stringify(e)===JSON.stringify(t)}function oh(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function sh(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),Fo(t))return zo(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=th(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(Fo(e))return zo(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?ch(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 ch(e){if(typeof e==`string`&&e.trim())return e;if(!Array.isArray(e))return;let t=e.map(e=>e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`?e.text.trim():``).filter(Boolean);return t.length>0?t.join(`
116
+ `):void 0}var lh=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 uh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function dh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function fh(e){let t=dh(e?.warningThreshold,uh.warningThreshold),n=dh(e?.criticalThreshold,uh.criticalThreshold),r=dh(e?.globalCircuitBreakerThreshold,uh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??uh.enabled,historySize:dh(e?.historySize,uh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??uh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??uh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??uh.detectors.pingPong}}}function ph(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function mh(e,t){return`${e}:${_h(t)}`}function hh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(hh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${hh(t[e])}`).join(`,`)}}`}function gh(e){try{return hh(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 _h(e){let t=gh(e);return Mt(`sha256`).update(t).digest(`hex`)}function vh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!ph(t))return!1;let n=t.action;return n===`poll`||n===`log`}function yh(e){return!ph(e)||!Array.isArray(e.content)?``:e.content.filter(e=>ph(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
117
+ `).trim()}function bh(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:hh(e)}function xh(e,t,n,r){if(r!==void 0)return`error:${_h(bh(r))}`;if(!ph(n))return n===void 0?void 0:_h(n);let i=ph(n.details)?n.details:{},a=yh(n);if(vh(e,t)&&e===`process`&&ph(t)){let e=t.action;if(e===`poll`)return _h({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return _h({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 _h({details:i,text:a})}function Sh(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 Ch(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 wh(e,t){return[e,t].toSorted().join(`|`)}function Th(e,t,n,r){let i=fh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=mh(t,n),s=Sh(a,t,o),c=s.count,l=vh(t,n),u=Ch(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:${wh(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function Eh(e,t,n,r,i){let a=fh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:mh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Dh(e,t){let n=fh(t.config),r=xh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=mh(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 Oh(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 kh(e){return e&&e.trim()||`tool`}function Ah(e,t,n){if(!e.execute)return e;let r=kh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Th(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Oh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Eh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Dh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Dh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function jh(e,t,n){return e.map(e=>Ah(e,t,n))}const Mh=new Map;function Nh(e){let t=Mh.get(e);return t||(t={},Mh.set(e,t)),t}function Ph(e){Mh.delete(e)}function Fh(e){let t=e.streamFn??Xt;return(e,n,r)=>(e.api===`anthropic-messages`&&Ih(e),t(e,n,{...r,...Uh(e,r)}))}function Ih(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>zh(Hh(e),n)?(globalThis.fetch=t,Lh(await t(e,Bh(e,r)))):t(e,r))}function Lh(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
118
+
119
+ `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Rh))),a.enqueue(r.encode(e+`
120
+
121
+ `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Rh=`event: message_start
125
122
  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}}}
126
123
 
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(`
124
+ `;function zh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Bh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Vh(e)&&n.delete(e);return{...t,headers:n}}function Vh(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 Hh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Uh(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}function Wh(e,t=.3){return e.length===0?!0:e.every(e=>e.score<t)}function Gh(e){return Math.ceil(e.length/4)}function Kh(e,t){if(Gh(e)<=t)return e;let n=t*4;return`${e.slice(0,Math.max(0,n-3)).trimEnd()}...`}async function qh(e){let t=e.query.trim();if(!t)return{};let n=await e.provider.search(t),r=e.coreConfig?.knowledgeController?.scoreThreshold,i=Wh(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:Kh(o.join(`
125
+ `),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function Jh(e,t){return`${t.trim()}\n\n${e}`}function Yh(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const Xh=`<!-- AIMax compaction memory recall -->`;async function Zh(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await qh({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?`${Xh}\n\n${n.block.replace(`${Xh}\n\n`,``).trim()}`:void 0}catch{return}}async function Qh(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 I(t.dataDir,n,Z(t)),T={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},E=Ys(t.llm),D=await Ru({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 zu({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 tg({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,Z(t)),j=Nn(),M=Ua([...Dm(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 F=t.messaging?.enabled??t.channel!==`CRON`,L=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],R=$m({dataDir:t.dataDir,projectDir:t.projectDir,skills:Ha(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:F,channels:L},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Ft.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});R=await eg({systemPrompt:R,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let z,ee=t.memory?.core,B=ee?.recall?.enabled===!0,V=!!t.subagentContext,H=o.memoryProviderSource===`plugin`&&ee?.recall?.forceWithPluginProvider!==!0;if(B&&!V&&!H&&!o.recallState.recallProvided)try{let e=await qh({provider:o.memoryProvider,query:f,coreConfig:ee}),t=ee?.knowledgeController;if(t?.enabled===!0&&t?.searchMode===`fallback`&&(e.isWeakLocalRecall===!0||!e.block))try{let e=await(await import(`./kc-Omw-bmtO.js`)).runKcFallbackSearch({config:t,query:f});e.block&&(z&&(R=Yh(R,z)),z=e.block,R=Jh(R,z),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&&(z=e.block,R=Jh(R,z),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 U={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},te=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:R,systemPromptOptions:U,recallState:o.recallState},a,{eventDispatcher:s}),ne=await i.dispatchWithMetadata(`before_prompt_build`,{prompt:f,recallState:o.recallState},a,{eventDispatcher:s});ne.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 W=[];for(let e of te){if(!e)continue;let t=e;if(t.recall?.block?.trim()){z&&=(R=Yh(R,z),void 0),R=Jh(R,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}t.systemPrompt&&(R=t.systemPrompt),t.prependContext&&(R=`${t.prependContext}\n\n${R}`),t.message&&W.push(t.message)}for(let e of ne){if(!e.result)continue;let t=e.result;if(t.recall?.block?.trim()){z&&=(R=Yh(R,z),void 0),R=Jh(R,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}if(t.systemPrompt&&(R=t.systemPrompt),t.prependContext){if((e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&o.recallState.recallProvided)continue;R=`${t.prependContext}\n\n${R}`,(e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&(o.recallState={recallProvided:!0,source:`plugin`})}}await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:R},a,{eventDispatcher:s});let re=jh(eh(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},Nh),G=S?.model??t.llm.model,ie=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of ie)e&&e.modelOverride&&(G=e.modelOverride);let ae=y({...t.llm,model:G},n,t.messageId,t.channel);try{await Vs(t.dataDir,n,{systemPrompt:R,tools:re},Z(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let K=new zt({initialState:{systemPrompt:R,model:ae,tools:re,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:Fh({})}),oe={eventDispatcher:s};a.signal=b;let se=new lh;return a.toolParamOverrides=se,sh({agent:K,hookRegistry:i,hookContext:a,pluginRuntime:oe,overrideStore:se}),O.messages.length>0&&(K.state.messages=O.messages),W.length>0&&(K.state.messages=[...W,...K.state.messages]),{agent:K,resolvedModelId:G,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function $h(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 eg(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 tg(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 Zh({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(`
129
126
 
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(`
127
+ `):void 0,pluginRecallProvided:r}}function rg(e){return e.some(e=>og(e.message)!==null||e.toolResults.length>0)}function ig(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 ag(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 og(e){let t=fg(e),n=sg(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 sg(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function cg(e){return e.map(e=>sg(e.message)).filter(e=>e.trim().length>0).join(`
131
128
 
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(`
129
+ `)}function lg(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function ug(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 dg(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:pg(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function fg(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function pg(e){let t=e.indexOf(`
133
130
  Preview:
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(`
131
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function mg(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=Lo(),O=Ie(),k=new so,A={workspaceDir:l.workspaceDir},j=new Set,M=Promise.resolve(),N,P=0,F=0,I={eventDispatcher:s},L=e=>{j.add(e),e.catch(e=>{N??=e}).finally(()=>{j.delete(e)})},R=async()=>{for(;j.size>0;)await Promise.allSettled([...j]);if(N)throw N},z=t.subscribe(e=>{let t=M.then(()=>ee(e));M=t.catch(()=>{}),L(t)});async function ee(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`agent_start`){c.dispatch(`agent_start`,{turnIndex:P},l,I).catch(()=>{});return}if(e.type===`turn_start`){F=P,P+=1,c.dispatch(`turn_start`,{turnIndex:F,timestamp:Date.now()},l,I).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=kg(`partial`in t?t.partial:void 0)??kg(`message`in t?t.message:void 0)??kg(`message`in e?e.message:void 0),a=Ag(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=fg(e);let r=Ag(``,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=fg(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=bg(t));let r=eo(fg(t),A);n||(r.artifacts.length>0&&p?.addOwn(r.artifacts),await ie(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:dg(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=lg(og(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(ug);(i||o.length>0)&&await f(i,o)}if(e||n)return}await c.dispatch(`turn_end`,{turnIndex:F,message:t,toolResults:a},l,I);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=Og(e.result),r=Dg(e.result);p?.addChild(hg(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:dg(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(lo({toolName:e.toolName,input:c,result:e.result,isError:!!e.isError,workspaceDir:l.workspaceDir})),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_completed`,message:`tool call completed`,details:{toolCallId:e.toolCallId,toolName:e.toolName,input:c,output:n,isError:e.isError,...o?{toolResultRef:o}:{}}}),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let B=xs(d),V=B.enabled?B.maxAttempts:1;try{gg({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=V;e++){let d=C.length;b=void 0,y=void 0,P=0,F=0;try{await $h({agent:t,hookRegistry:c,hookContext:l,pluginRuntime:I});let f=await c.dispatch(`before_provider_request`,{model:a,messages:t.state.messages,tools:t.state.tools},l,I);for(let e of f)if(e){if(e.abort)return await R(),{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`);K.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await Ro(D,async()=>{await fe(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await R();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&&(K.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let S=t.state,w=typeof S.error==`string`?S.error:typeof S.errorMessage==`string`?S.errorMessage:void 0,T=b??w;if(T){let t=b?`sdk`:`agent_state`;if(y=jg(T),K.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...Qo(T,`providerError`)}),await U(T,y,e,d))continue;await te(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||K.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await R(),Fo(t)||Fe(t))throw t;if(y=jg(t),K.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,error:y}),await U(t,y,e,d))continue;await te(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{z()}function H(){m=``,h=``,g=``}async function U(e,n,r,a){if(!yg({error:e,attempt:r,maxAttempts:V,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g}))return!1;let o=Ss(r,B);return K.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:V,delayMs:o,error:n}),await Cg({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:V,message:n,delayMs:o}),C.length=a,H(),wg(t),await Cs(o,u),!0}async function te(e,t){f&&await f(ig(e,t),[])}let ne=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:ne,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let W=O.signal?``:C.length>0?eo(fg(C[C.length-1].message),A).cleanedText:``,re=eo(m,A).cleanedText,G=W||re||ag(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!rg(C)&&!y&&m.trim().length>0){let e=eo(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await ie(e.warnings);let t=cg(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:G,inputTokens:_,outputTokens:v,error:y,turnRecords:C};async function ie(e){for(let t of e)await s.dispatchDiagnostic(i,{level:`warn`,scope:`runner`,phase:`artifact_parse`,message:t})}}function hg(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 gg(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:_g(a,e.message),s=vg(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=cs(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 _g(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function vg(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 yg(e){return e.attempt>=e.maxAttempts||!ws(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&&fg(e.message).trim().length===0)}function bg(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:xg(t.errorCode),statusCode:Sg(t.statusCode),providerCode:xg(t.providerCode),providerType:xg(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function xg(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Sg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Cg(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 wg(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&Tg(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function Tg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:Eg(t.content):!1}function Eg(e){return e==null?!0:typeof e==`string`?e.trim().length===0:Array.isArray(e)?e.every(e=>{if(!e||typeof e!=`object`)return!0;let t=e;return t.type===`toolCall`?!1:t.type===`text`?typeof t.text!=`string`||t.text.trim().length===0:!0}):!1}function Dg(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return Og(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):Og(e)}function Og(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function kg(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 Ag(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function jg(e){let t=Mg(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 Mg(e){if(e instanceof pe)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:xg(t.code),statusCode:Sg(t.statusCode),statusText:xg(t.statusText),providerMessage:xg(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 Ng(e){let t=zg(e.toolResultPreviewChars),n=Bg(e.systemPrompt,e.agentDefinition),r=Hg(e.model,e.agentDefinition),i=Ua(e.tools??[],e.agentDefinition),a=Vg(e.message,e.agentDefinition),o=await mg({agent:new zt({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:Pg({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new Ce,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:Ig(o.turnRecords),toolResults:Lg(o.turnRecords,t)}}function Pg(e){let t=e.phasePrefix??`silent_agent`;return new Za({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await Fg(e.diagnosticDispatcher,t,n)}})}async function Fg(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 Ig(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 Lg(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Rg(e.content,t)})))}function Rg(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function zg(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 Bg(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
135
132
 
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(`
133
+ `)}function Vg(e,t){return!t?.initPrompt||typeof e!=`string`?e:Ga(t,e)}function Hg(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const Ug=Y.Object({kind:Y.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>Y.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:Y.Optional(Y.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:Y.Optional(Y.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:Y.Optional(Y.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:Y.Optional(Y.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function Wg(e){let t=Ci({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??vi}),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:Ug,async execute(r,i){try{return i.kind===`tool_result`?Kg(await Si({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?Kg(await yi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?Kg(await bi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?Kg({...await xi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):Kg(await xi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:Gg(i),limits:t}))}catch(r){return Kg({kind:i.kind,error:qg(r),limits:t,contextFiles:Ti(e.dataDir,e.sessionId,n)})}}}}function Gg(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 Kg(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function qg(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Jg(e){let t=[rm(e.dataDir),im(e.dataDir),am(e.dataDir),Wg({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(om(e.dataDir)),t}const Yg=`auto-skill-reviewer`;async function Xg(e){let t=e.createModel??ka,n=e.tools??Jg({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 Ng({sessionId:e.sessionId,systemPrompt:Zg(e.mode),message:Qg(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=$g(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 Zg(e){let t=e===`write`?"Write mode is active. `auto_skill_manage` is exposed for this run.":"Dry-run mode is active. `auto_skill_manage` is not exposed for this run.",n=[`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`auto_skill_review_context_view`,...e===`write`?[`auto_skill_manage`]:[]];return[`Run the configured auto-skill reviewer agent against the review packet for this invocation.`,`Apply the durable reviewer policy from the selected AgentDefinition together with the mode and tool boundaries below.`,``,`Current review mode: ${e}`,`Tools exposed for this run:`,...n.map(e=>`- ${e}`),``,t].join(`
134
+ `)}function Qg(e,t){return[`Review mode: ${t}`,`Use the following auto-skill review packet as the source input for this invocation.`,``,`<auto_skill_review_packet>`,JSON.stringify(e,null,2),`</auto_skill_review_packet>`].join(`
135
+ `)}function $g(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=e_(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 e_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const t_=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],n_=t_,r_={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}},i_=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function a_(e){let t=s_(e.gates),n={session:l_(`session`,e.sessionTranscript,t.session),currentRun:l_(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:l_(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=p_(e.reviewState?.reviewCount,0),i=p_(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return h_(n,a,r,i,o,`run_error`);if(e.result?.paused)return h_(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return h_(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return h_(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 o_(e,t={}){let n=ci(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??t_),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(g_(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}__(t)&&v_(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 s_(e){return{session:c_(e?e.session:r_.session),currentRun:c_(e?e.currentRun:r_.currentRun),reviewWindow:c_(e?e.reviewWindow:r_.reviewWindow)}}function c_(e){let t={};for(let n of i_){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?n_:void 0;if(typeof r==`number`){let e=f_(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=f_(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:m_(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:m_(r.toolNames,i)})}return t}function l_(e,t,n){let r=o_(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=i_.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];u_(t,o,r)?i.push({code:t,description:d_(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 u_(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 d_(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 f_(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function p_(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function m_(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function h_(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 g_(e){return e.role===`assistant`}function __(e){return e.role===`tool_result`}function v_(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:y_(e.content)?.success===!1}function y_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function b_(e){let t=ui(e.transcript.length,e.transcriptStartIndex),n=di(e.transcript.length,e.recentEntryLimit),r=ui(e.transcript.length,e.reviewWindowStartIndex??void 0),i=ui(e.transcript.length,0),a=fi(e.transcript,t),o=fi(e.transcript,r),s=o_(e.transcript),c=o_(a),l=o_(o),u=si(e.transcript),d=si(a),f=si(o),p=a.filter(S_),m=a.filter(C_);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:x_(p[0]?.content??``,800),finalResponse:x_(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:li(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 x_(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 w_(e,t,n){return J.join(r(e,t,n),`auto-skill-review-state.json`)}function T_(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function E_(e,t,n){let r=w_(e,t,n),i;try{i=await q.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return T_(t);throw e}return j_(JSON.parse(i),t)}async function D_(e,t,n){let r=w_(e,t.sessionId,n);await q.mkdir(J.dirname(r),{recursive:!0}),await q.writeFile(r,`${JSON.stringify(j_(t,t.sessionId),null,2)}\n`,`utf-8`)}async function O_(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await D_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function k_(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 D_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function A_(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await D_(e.dataDir,t,{storeName:e.sessionStoreName}),t}function j_(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:P_(n.reviewCount,0),lastAttemptedReviewAt:M_(n.lastAttemptedReviewAt),lastCompletedReviewAt:M_(n.lastCompletedReviewAt),lastFailedReviewAt:M_(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:N_(n.lastReviewedTranscriptEndIndex)}}function M_(e){return typeof e==`string`&&e.trim()?e:null}function N_(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function P_(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function F_(e){return J.join(Ui(e),`.reviews`,`run-log.jsonl`)}async function I_(e,t){let n=F_(e);await q.mkdir(J.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await q.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const L_=`write`,R_=new Set([`off`,`gate`,`dry_run`,`write`]);async function z_(e){let t=B_(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=H_(e);if(n){await K_(e,t,n);return}let r,i;try{let n=await I(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=U_(n,e.transcriptStartIndex),o=await E_(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=W_(o.lastReviewedTranscriptEndIndex,n.length),c=U_(n,s);await q_(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=a_({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await q_(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 J_(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await q_(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new la({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=b_({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:Ti(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await q_(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await J_(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(Yg);if(!p){K.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:Yg}),await K_(e,t,`reviewer_agent_missing`,{reviewerAgentName:Yg});return}i={mode:f,decision:l,packet:d},r=await O_({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??Xg,h=Jg({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 A_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await Y_(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await G_(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:X_(g.toolCalls),toolResults:rv(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await k_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await Y_(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:X_(g.toolCalls),toolResults:rv(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 A_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await Y_(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await G_(e,n,a?{reviewRunLogPath:a}:void 0)}}function B_(e){return{mode:V_(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function V_(e){if(e==null)return L_;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?R_.has(t)?t:`off`:L_}function H_(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 U_(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function W_(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function G_(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 K_(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 q_(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function J_(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:tv(n),...i.packet?{packet:i.packet}:{}}})}async function Y_(e,t,n){return I_(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?Q_(n.curatorResult.text):void 0,conclusionText:n.curatorResult?$_(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?X_(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?rv(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 X_(e){return e.map(e=>({...e,arguments:Z_(e.name,e.arguments)}))}function Z_(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 Q_(e){let t=ev(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function $_(e){return Q_(e)?void 0:nv(e,8e3)}function ev(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 tv(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 rv(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let iv=!1;function av(){iv||=(Yt(),Jt({api:`openai-completions`,stream:os,streamSimple:ss}),!0)}const ov=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`,`- As the user role, summarize the title based on the conversation content`,`- The principle of title generation is to describe the behavioral characteristics of the user in the conversation, rather than answering based on the content of the conversation`].join(`
136
+ `);async function sv(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 fv(c);let l=fv(c),u=r.flashModel,d=oe({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=lv(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await d.chat({system:ov,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(uv(t)){if(p.didTimeout())return s?.(`timeout`),l;throw t}e<3&&await cv(500*e,p.signal)}}catch(e){if(uv(e)&&p.didTimeout())return s?.(`timeout`),l;throw e}finally{p.clear()}return s?.(`error`),l}function cv(e,t){return t?t.aborted?Promise.reject(dv()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(dv())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function lv(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 uv(e){return e instanceof Error&&e.name===`AbortError`}function dv(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function fv(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 pv(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 mv(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await _v(await I(r.dataDir,t,{...Z(r)}),r);await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs,messages:o},a,{eventDispatcher:e.eventDispatcher})}async function hv(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await I(r.dataDir,t,{...Z(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 gv(e){await mv(e),await hv(e)}async function _v(e,t){return e.map(e=>({...e}))}function vv(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(`
140
137
 
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
138
+ `).slice(0,4e3)}async function yv(e){if(e.coreConfig?.capture?.enabled!==!0)return;let t=vv(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 bv(e){if(!(!e.runContext||e.runParams.memory?.core?.capture?.enabled!==!0||e.runParams.subagentContext))try{let t=await I(e.runParams.dataDir,e.sessionId,Z(e.runParams));await yv({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 xv(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=Z(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 wv({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,Z(o)),toolResultsDir:s(o.dataDir,n,Z(o))}};return K.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 bv({sessionId:n,runParams:o,runContext:e.runContext,eventDispatcher:p}),await gv({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function Sv(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=Z(i),s=await wv({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,Z(i)),toolResultsDir:s(i.dataDir,t,Z(i))}};h&&h.length>0&&e.transcriptStartIndex!==void 0&&!p&&!m&&await Cv({dataDir:i.dataDir,sessionId:t,pathOptions:Z(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?K.warn(`agent run finalized with error`,b):K.info(`agent run finalized`,b),await bv({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 hv(x):await gv(x),y}async function Cv(e){let t=await I(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 F(e.dataDir,e.sessionId,t=>t.map((t,n)=>n!==o||t.role!==`assistant`?t:{...t,artifacts:e.artifacts}),e.pathOptions)}async function wv(e){let t=fv(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&K.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await sv({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,onFallback:e=>{n=e}});return n?K.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&K.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return K.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const Tv=new Set([`pause`,`resume`,`clear`,`help`]),Ev=`/goal
142
139
  【目标】:把 src/auth 目录下重复的参数校验逻辑抽离成公共函数。
143
140
  【范围】:只处理 src/auth 目录,不扩散到用户模块或订单模块。
144
141
  【约束】:保持现有 API 兼容,不引入新依赖,不要改变数据库结构。
145
142
  【验证】:每次改动后请自主运行 npm test auth 以及 npm run typecheck。如果测试失败,请定位原因并修复。
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(`
143
+ 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function Dv(){return[`/goal 命令`,` /goal <目标内容> 设置或替换 /goal 目标(设为进行中)`,` /goal --token-budget <n> <目标内容> 设置带 Token 预算的 /goal 目标(0 表示不限)`,` /goal 查看当前 /goal 目标摘要`,` /goal pause 暂停 /goal 目标继续执行`,` /goal resume 恢复已暂停的 /goal 目标`,` /goal clear 清除 /goal 目标`,``,`多行结构化示例(/goal 后换行;Console 用 Shift+Enter 换行,Enter 发送):`,Ev].join(`
144
+ `)}function Ov(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,Ev,``,`正文(写入 objective.txt 供 --goal-file):`,Ev.replace(/^\/goal\s+/,``)].join(`
145
+ `)}async function kv(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await W(e.dataDir,e.sessionId,t);if(!r){let r=await G(e.dataDir,e.sessionId,{goalId:Pt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await Qn(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await B(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await G(e.dataDir,e.sessionId,{goalId:Pt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await Qn(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`replaced`,goal:r}}if(r.status===`complete`)return{action:`unchanged`,goal:r};let i={};if(r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0)return{action:`unchanged`,goal:r};let a=await H(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function Av(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(Tv.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 jv(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function Mv(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function Nv(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${jv(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:`,` 状态:${Mv(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,Fv(e.status)),a.join(`
146
+ `)}async function Pv(e,t,n){let r=await Xn(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return Nv(t,n,r.goalState,r.workflowWarning)}function Fv(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 Iv(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:Dv()};if(e.action===`get`){let e=await W(t.dataDir,t.sessionId,n);return e?{replyText:await Pv(t,e,await B(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
147
+ `)}}if(e.action===`set`){let r=await kv({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await B(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await Pv(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 Pv(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await W(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await H(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await Pv(t,r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await W(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 Pv(t,e,await B(t.dataDir,t.sessionId,e,n))}`};let r=await H(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await Pv(t,r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await re(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const Lv=[{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 Rv(){return Lv.map(e=>({...e}))}function zv(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Bv(e){let t=new Set,n=[];for(let r of e){let e=zv(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Vv(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function Hv(e,t){let n=Rv(),r=Bv(e),i=t?Vv(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function Uv(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 Wv(e){let t=Uv(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 Gv(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 Kv(e,t){let n=Wv(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=Av(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:zv(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Bv(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 qv=new Set([`/new`,`/reset`,`/compact`]),Jv=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Yv=new Set([`/help`]);function Xv(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function Zv(e){if(e.length===0)return[];let t=e.map(Xv),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Qv(e){let t=Hv(e.skills),n=t.builtin.filter(e=>qv.has(e.name)),r=t.builtin.filter(e=>Jv.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Yv.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...Zv(n)),s.push(``),s.push(`目标命令`),s.push(...Zv(r)),s.push(``),s.push(`技能命令`),s.push(...Zv(i)),o.length>0?(s.push(...Zv(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...Zv(a)),{kind:`reply`,text:s.join(`
148
+ `)}}function $v(e,t){let n=t.trim().toLowerCase();return n&&Bv(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function ey(e){let t=$v(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(`
152
149
 
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(`
150
+ `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function ty(e){let t=Kv(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Qv(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?ey({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=ry(t),l=c>=0?t[c].content:void 0,u=Ks(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}=pc(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:X(u)}:{status:`compacted`,entry:{role:`compaction`,content:await nc({entries:f,llm:r,previousSummary:l,instructions:i,contextWindowTokens:n,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:X(d)}}function ry(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const iy=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
151
+ `),ay=[`.aimax/new.txt`];async function oy(e){try{return(await At(e,`utf-8`)).trim()||null}catch{return null}}async function sy(e){for(let t of ay){let n=await oy(jt(e,t));if(n)return n}return await oy(`/aimax_pvc/new.txt`)||iy}async function cy(e){return{kind:`reply`,text:await sy(e)}}function ly(){return{kind:`reply`,text:`✅ Session reset.`}}async function uy(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function dy(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 uy(e,t,{action:n.action,goal:n.after??null})}function fy(e){let t=hy(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?gy(r):null,a=n??i?.text,o=a?Gv(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?_y(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:vy(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function py(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=Kv(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=ty({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:_y(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:vy(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function my(e){let t=py(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 xv({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 xv({replyText:(t.action===`reset`?ly():await cy(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 xv({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 Iv({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 uy(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),yy(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await B(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await xv({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 I(e.runParams.dataDir,e.sessionId,Z(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await xv({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 hy(e){return typeof e.message==`string`}function gy(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 _y(e,t){let n=gy(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 vy(e){return typeof e==`string`?e:JSON.stringify(e)}function yy(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function by(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++,K.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){K.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}K.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 _=xy(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await mg({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?K.warn(`subagent announce round completed with error`,y):K.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&K.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function xy(e){if(e.length===1){let t=e[0];return gm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>gm({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
155
152
 
156
153
  ---
157
154
 
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(`
155
+ `)}`}async function Sy(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?Se({...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 Ce,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=Oe(c.normalizedConfig),d;if(u.length>0){let e=await De(c.normalizedConfig);if(e.length>0){d=new $e(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 Cy=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 wy(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=np(t),o=n,s=!o,c=Z(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:()=>I(t.dataDir,o,c)}},u=new Cy,d=await Sy({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await rp({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=>pv({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function Ty(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Ey(e){if(!(e instanceof Error))return{errorValue:Ty(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]=Ty(n[e]));return t}async function Dy(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Ey(e.error)}})}function Oy(e,t,n){return J.join(r(e,t,n),`pending-ui-tool.json`)}async function ky(e,t,n,i){let a=r(e,t,i);await q.mkdir(a,{recursive:!0}),await R(Oy(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function Ay(e,t,n){let r=await o(Oy(e,t,n));return r===null?null:JSON.parse(r)}async function jy(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await ky(e,t,a,r),a}async function My(e,t,n,r,i){let a=await Ay(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 ky(e,t,o,i),o}async function Ny(e,t,n){try{await q.unlink(Oy(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Py(e,t,n,r){let i=await W(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 Fy(e,t,n,r,i,a){let o=await W(e,t,{storeName:a?.storeName});await Py(e,t,n,a);let s=await en(e,t,n,r,a);return s.goal&&await dy(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function Iy(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!kt(t))}async function Ly(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=Lo();if(i=await Ro(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Fo(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Ry(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 Ry(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 zy=2e4,By=15e4,Vy=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Hy(e){return J.join(e,`.aimax`)}async function Uy(e){let t=Hy(e),n=[];for(let e of Vy){let r=J.join(t,e);try{let t=await q.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await q.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 Wy(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(`
159
156
  `),s].join(`
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":`---
157
+ `),truncated:!0,originalLength:r.length}}function Gy(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Ky(e,t){let n=t?.maxChars??zy,r=Math.max(1,t?.totalMaxChars??Math.max(n,By)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Gy(`[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}=Wy(a.content??``,a.name,e),l=Gy(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 qy=`You are a personal assistant running inside AiMax.`;async function Jy(e){try{return{presetSystemPrompt:Rt(await q.readFile(e,`utf-8`)).content.trim()||qy}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:qy};throw e}}async function Yy(){return Jy(`/aimax_pvc/system_prompt.md`)}async function Xy(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await Uy(t.dataDir),o=[],s=Ky(a,{warn:e=>o.push(e)}),c=await Yy();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}}),K.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await Bf(t.dataDir,r.pluginSkillDirs,l),d=await Ia({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}))}}),K.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}))}}),K.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 Zy({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function Zy(e){if(!e.enabled)return[];try{let t=await new la({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 Qy=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 $y={Inferred:1,Child:2,Own:3};var eb=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=nb(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,$y.Own)}addInferred(e){this.add(e,$y.Inferred)}addChild(e){e&&e.length>0&&this.add(e,$y.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=tb(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=rb(e.url);return t?this.urlWhitelist.has(t):!1}};function tb(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function nb(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function rb(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const ib=`crons`;function ab(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:we(e.message)}}async function ob(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 mg({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 by({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 I(e.runParams.dataDir,e.sessionId,Z(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 sb(e,t){av();let n=Date.now(),i=new Za(e),a=new eb({urlWhitelist:e.artifactsUrlWhitelist}),o=fy(e);K.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 wy({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;ue(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,Z(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 I(e.dataDir,d,{storeName:e.sessionStoreName})).length;if(K.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}}),K.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,ap({sessionId:d,title:fv(s),channel:e.channel}),Z(e)),e.pendingGoal){let t=await G(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await Qn(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 Xy({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await my({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 K.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}}),K.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await Qh({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=>sb(e,new fm),createModel:ka,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}}),K.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=pb(e.timeoutMs),P=!1,F=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}}),K.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let L=new Qy,R=``,z,ee=!1,B=new $t;await Py(e.dataDir,d,B,{storeName:e.sessionStoreName}),w.signal;try{if(Iy(e)){let t=await Ly({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return R=t.text,S(),Sv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:R,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await v.persistInitialUserEntry(s);ee=t,c=t||c;try{await Bn(e.dataDir,d,{storeName:e.sessionStoreName},()=>Qr(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 W(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await Kr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof Ln)o=!0;else throw e}let u=!!(o||l&&ri(l)),p=oi({hookRegistry:g,isGateActive:()=>u}),m=await ei(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Call goal_repair_workflow_state with confirm:true to reinitialize from the saved objective before other goal workflow tools.`,`</goal_context>`,``].join(`
158
+ `);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await $r(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});K.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await mg({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(),R=x.text,L.add(x.inputTokens,x.outputTokens),x.error&&(z=x.error),m.hadObjectiveUpdatedSteering&&!x.error&&await ti(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?K.warn(`first agent turn completed with error`,C):K.info(`first agent turn completed`,C);let T=await Fy(e.dataDir,d,B,L.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`}),K.info(`announce loop started`,{sessionId:d});let D=await by({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&&(R=D.text),L.add(D.inputTokens,D.outputTokens),D.error&&!z&&(z=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 Fy(e.dataDir,d,B,L.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`}),qr()){let n=new Gr;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=Et;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Xr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:B,abortSignal:w.signal,executeTurn:async t=>{let n=await mg({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 Zr(E,e,t)}});L.add(n.inputTokens,n.outputTokens),R=n.text||R,n.error&&!z&&(z=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 Fy(e.dataDir,d,B,L.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 by({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,artifactAccumulator:a,appendEntry:E});L.add(e.inputTokens,e.outputTokens),e.text&&(R=e.text),e.error&&!z&&(z=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 mv({sessionId:d,result:{sessionId:d,text:R??``,usage:L.snapshot(),durationMs:Date.now()-n,error:z},runParams:e,hookRegistry:g,hookContext:h,eventDispatcher:i});let r=await ob({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});L.add(r.inputTokens,r.outputTokens),r.lastResponseText&&(R=r.lastResponseText),r.error&&!z&&(z=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?K.warn(`announce loop completed with error`,k):K.info(`announce loop completed`,k)}catch(t){if(Fo(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await rt(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}}),K.info(`agent paused for HITL`,{sessionId:d,requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let l={...L.snapshot()};return await cb({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:ee}),S(),Sv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:R||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:l,error:void 0,paused:{requestId:c.requestId,kind:c.kind,title:c.title}})}if(Fe(t)){let r=t,o=r.request.outputSchema.properties??{};await jy(e.dataDir,d,r.request,Z(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}}),K.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={...L.snapshot()};return await cb({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:ee}),S(),Sv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:R||``,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&&mb(t))z=`Run timed out after ${N}ms`;else throw await Dy({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),K.error(`agent run failed`,{sessionId:d,channel:e.channel,isNewSession:f,error:t instanceof Error?t.message:String(t)}),t}finally{F!==void 0&&clearTimeout(F);try{await Fy(e.dataDir,d,B,L.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}B.clearActiveGoal(),Ph(d);try{A.processRegistry.disposeAll()}catch{}try{Re.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let V=L.snapshot();P&&(z=`Run timed out after ${N}ms`),await i.dispatchDiagnostic(d,{level:z?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!z,error:z}});let H={sessionId:d,durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!z,error:z};return z?K.warn(`agent run completed with error`,H):K.info(`agent run completed`,H),await cb({runtime:A,resolvedModelId:M,usage:V,currentUserEntryCoveredByUsage:ee}),await z_({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:R,usage:V,durationMs:Date.now()-n,error:z}}),Sv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),transcriptStartIndex:C,text:R,usage:V,error:z,sessionEndOnly:b>0})}async function cb(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 lb(e){let t=Date.now(),i=new Za(e),a=fy(e),o=a.transcriptMessage.trim()||`CRON task`,c=e.sessionStoreName;K.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...ab(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,ap({sessionId:l,title:fv(o),channel:e.channel}),{storeName:c});let f=await T(e.dataDir,e.channel,{storeName:ib});ue(e.dataDir,{messageId:e.messageId,sessionId:f,sessionStoreName:ib,sessionDir:r(e.dataDir,f,{storeName:ib})}),await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:f,task:o}),K.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:f,taskLength:o.length,taskPreview:we(o)});let m={...e,sessionId:f,sessionStoreName:ib,subagentContext:{depth:1,parentSessionId:l}},g,y=`done`;try{g=await sb(m,new fm),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:ib}),toolResultsDir:s(e.dataDir,f,{storeName:ib})}},y=`error`,K.error(`cron child run failed`,{parentSessionId:l,childSessionId:f,error:r})}await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:f,task:o,status:y}),K.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:f,status:y,durationMs:Date.now()-t,hasError:!!g.error});let b=gm({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 F(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=>!db(e));let n=e.reduce((e,t,n)=>(db(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!db(e)||r.has(t))}function db(e){return`source`in e&&e.source===`cron`}async function fb(e,t){let n=async()=>{if(K.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,...ab(e)}),e.channel===`CRON`&&!e.subagentContext)return lb(e);let n=t??new fm;try{return await sb(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:Ey(t)}),K.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?ie(e.onLog,n):n()}function pb(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function mb(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 hb={"AGENTS.md":`---
162
159
  title: "AGENTS.md Template"
163
160
  summary: ".aimax template for AGENTS.md"
164
161
  read_when:
@@ -451,7 +448,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
451
448
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
452
449
 
453
450
  Add whatever helps you do your job. This is your cheat sheet.
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(`
451
+ `},gb=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function _b(e,t){try{if(!(await q.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 q.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function vb(e,t,n){try{if(!(await q.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 q.mkdir(J.dirname(e),{recursive:!0});try{await q.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 yb(e){let t=Hy(e);return[e,t,J.join(t,`skills`),J.join(t,`sessions`),J.join(t,`memory`),J.join(e,`workspace`)]}function bb(e){let t=Hy(e);return[...gb.filter(e=>e!==`BOOTSTRAP.md`).map(e=>J.join(t,e)),J.join(t,`MEMORY.md`)]}function xb(e){return J.join(Hy(e),`.bootstrapped`)}async function Sb(e){try{return(await q.stat(xb(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Cb(e){let t=xb(e);await q.mkdir(J.dirname(t),{recursive:!0}),await q.writeFile(t,``,{encoding:`utf-8`})}async function wb(e){let t=[],n=[];for(let n of yb(e))try{(await q.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of bb(e))try{(await q.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 Tb(e){return(await wb(e)).ready}async function Eb(e){if(await Sb(e))return{ready:!0,performedBootstrap:!1};if((await wb(e)).ready)return await Cb(e),{ready:!0,performedBootstrap:!1};let t=await Db(e);return await Cb(e),{ready:!0,performedBootstrap:!0,result:t}}async function Db(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Hy(e),r=J.join(e,`workspace`),i=J.join(n,`skills`),a=J.join(n,`sessions`),o=J.join(n,`memory`);await _b(e,t),await _b(n,t),await _b(i,t),await _b(a,t),await _b(o,t),await _b(r,t);for(let e of gb){let r=hb[e]??``;await vb(J.join(n,e),r,t)}return await vb(J.join(n,`MEMORY.md`),``,t),t}async function Ob(e){let t=J.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await q.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 kb(e,t){let n=J.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 q.mkdir(J.dirname(n),{recursive:!0}),await q.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Ab(e,t){let n=await Ob(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 jb(e,t=7){let n=await Ob(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 kb(e,n),i}var Mb=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function Nb(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function Pb(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 W(t,n,s);if(!l){let e=await G(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await Qn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await B(t,n,l,s)).trim();if(u!==c){if(!a)throw new Mb(`A different goal already exists for this session. Use --force to replace it.`,Nb(u));let e=await G(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await Qn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new Mb(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,Nb(u));if(a){let e=await G(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await Qn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await H(t,n,d,{storeName:o,eventSource:`cli`})}}async function Fb(e,t,n,r){let i=await ot(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ot(i.request)?(await nt(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 Ib(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await at(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 Fb(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await nt(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 Lb={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 Rb(e){return e.action===`timeout`?Lb.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Lb.approval.summary.approved:Lb.approval.summary.denied}function zb(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Rb(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Bb(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 Vb(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 Hb(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
455
452
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
456
453
  `)):(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(`
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};
454
+ `))}export{la as AutoSkillsLoader,Vy as BOOTSTRAP_FILE_NAMES,zy as BOOTSTRAP_MAX_CHARS,By as BOOTSTRAP_TOTAL_MAX_CHARS,nn as CLARIFY_ACCEPTANCE_TEXT,ni as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,tn as CLARIFY_TASK_TITLE,Gr as ContinuationState,Ln as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,Wr as ENV_GOAL_CONTINUATION,Lr as FIRST_TURN_GOAL_WORKFLOW_INTRO,Ev as GOAL_MULTILINE_TEMPLATE_EXAMPLE,Pn as GOAL_WORKFLOW_STATE_VERSION,$t as GoalAccounting,Mb as GoalConflictError,Lb as HITL_MESSAGES,Po as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,dm as MAX_CHILDREN_PER_SESSION,um as MAX_SUBAGENT_DEPTH,Re as MemoryIndexManager,Ne as PLUGIN_MANIFEST_FILENAME,ve as PLUGIN_MANIFEST_FILENAMES,Ce as PluginHookRegistry,me as PluginToolRegistry,Aa as SYSTEM_AGENTS_DIR,fm as SubagentRegistry,ae as UiToolPauseSignal,St as addAgent,vt as addBinding,Ma as agentDirCandidates,Ba as agentVisibility,Hy as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,ee as appendGoalEvent,Hd as appendRecentToMemory,i as appendSessionFile,Vd as appendToMemory,h as appendTranscriptEntry,Pb as applyCliGoalBeforeRun,Rb as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,Ui as autoSkillsDir,Db as bootstrapMountLayout,Wa as buildAgentDelegationPrompt,Ga as buildAgentTaskPrompt,Ov as buildAimaxGoalCliHelpExtra,Ky as buildBootstrapContextFiles,Br as buildBudgetLimitPrompt,zr as buildContinuationPrompt,Rr as buildFirstTurnGoalWorkflowPrompt,Hr as buildGoalContextItem,Dv as buildGoalSlashHelpText,Vr as buildObjectiveUpdatedPrompt,Hb as buildResumeNarration,Gf as buildSkillsPrompt,gm as buildSubagentAnnounceMessage,$m as buildSystemPrompt,jb as cleanupOldSubagentRecords,st as clearPendingHitl,Ny as clearPendingUiTool,j as collapseLogPath,ti as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,Yr as continuationTurnHadMeaningfulOutput,Pa as createAgentDefinitionsContext,Dm as createAgentTools,bd as createApplyPatchTool,nm as createAutoSkillCategoriesTool,rm as createAutoSkillListTool,im as createAutoSkillSearchTool,am as createAutoSkillViewTool,sa as createAutoSkillsLoader,td as createBashTool,bm as createBatchSubagentSpawnTool,Be as createBuiltinMemoryProvider,Ru as createContextManager,Ge as createDefaultMemoryProvider,dd as createEditFileTool,Xu as createExecTool,Em as createImageTool,pd as createListDirTool,Xd as createMemoryAppendTool,df as createMemoryForgetTool,Jd as createMemoryGetTool,lf as createMemoryListTool,sf as createMemoryLogTool,Kd as createMemorySearchTool,pf as createMemoryUpdateTool,Qd as createMemoryWriteTool,rt as createPendingHitl,jy as createPendingUiTool,ce as createPluginProgressEmitter,_e as createPluginRuntime,ed as createProcessTool,sd as createReadFileTool,T as createSession,lu as createSessionContextStore,hf as createSessionSearchTool,Yf as createSkillListTool,Xf as createSkillLoadTool,ym as createSubagentSpawnTool,wm as createSubagentsTool,Le as createUiTool,ld as createWriteFileTool,N as cronExecutionsPath,ge as defaultUiToolInputSchema,re as deleteGoal,Zn as deleteGoalWorkflow,Wd as deleteMemoryFile,Ee as discoverAIMaxPlugins,uy as emitGoalUpdatedProgress,Eb as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,gn as extractWorkflowPlanFromObjective,Ha as filterSkillsForAgent,Ua as filterToolsForAgent,za as findAgentDefinition,Hf as findSkillByName,en as flushAccounting,zb as formatApprovalResolution,Bb as formatClarifyResolution,Vb as formatReviewResolution,sv as generateSessionTitle,ht as getAgentConfig,Bd as getMemoryLines,Ae as getPluginSystem,Un as goalArtifactsDir,U as goalDir,z as goalEventsPath,ne as goalObjectiveMdPath,V as goalPath,Hn as goalWorkflowPlanPath,Vn as goalWorkflowStatePath,Sb as hasBootstrapSentinel,tt as hitlHistoryPath,Qn as initializeGoalWorkflow,Se as initializePluginSystem,wb as inspectBootstrapMountLayout,k as inspectSession,oi as installClarifyFirstTurnGate,Tb as isBootstrapMountLayoutReady,ii as isClarifyFirstTurnBlockedTool,ri as isClarifyWorkflowTask,qr as isContinuationEnabled,Ur as isGoalContext,Fo as isHitlPauseSignal,Fe as isUiToolPauseSignal,lt as listAgents,Hv as listAvailableSlashCommands,yt as listBindings,Id as listMemoryFiles,E as listSessionSummaries,x as listSessions,Ab as listSubagentRunsFromDisk,La as loadAgentDefinitionsFromDir,xt as loadAgentsConfig,b as loadArtifactOperations,Uy as loadBootstrapFiles,m as loadCronExecutionRecords,ot as loadPendingHitl,ot as readPendingHitl,Ay as loadPendingUiTool,Ay as readPendingUiTool,ye as loadPluginManifest,Te as loadPluginManifestRegistry,je as loadPlugins,P as loadSessionContextSnapshot,Hs as loadSessionExportSnapshots,L as loadSessionMetadata,Wf as loadSkillView,zf as loadSkills,Vf as loadSkillsFromDirs,Bf as loadSkillsWithPluginDirs,Ob as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,I as loadTranscript,Kr as loadWorkflowPromptContext,Xr as maybeContinueGoalIfIdle,Md as memoryDir,f as metadataPath,te as mirrorGoalStatusToSession,ut as normalizeAgentId,xe as normalizePluginsConfig,t as normalizeSessionStoreName,Ra as parseAgentDefinition,et as pendingHitlPath,Oy as pendingUiToolPath,Vs as persistSessionExportSnapshots,he as preloadPluginSystem,Me as prepareSystemRuntime,$r as prependFirstGoalWorkflowSteeringIfNeeded,ei as prependObjectiveUpdatedSteeringIfNeeded,Nd as primaryMemoryPath,Va as publicAgentDefinitions,W as readGoal,qn as readGoalWorkflowState,Yn as readGoalWorkflowSummary,it as readHitlHistory,Ld as readMemoryFile,Rd as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,Qr as recoverBlockedWorkflowOnUserTurn,Je as registerEmbeddingProvider,Qe as registerMemoryProvider,gt as removeAgent,Ct as removeBindings,yn as renderGoalPlanMarkdown,Jn as repairGoalWorkflowState,Ud as replaceMemoryFile,qe as resetEmbeddingProviderRegistryForTests,Ye as resetMemoryProviderRegistryForTests,Ia as resolveAgentDefinitionsContext,dt as resolveAgentDir,ft as resolveAgentIdByBinding,bt as resolveAgentsConfigPath,_t as resolveDefaultAgentId,Xe as resolveEmbeddingProvider,B as resolveGoalObjective,Xn as resolveGoalToolWorkflowView,Ib as resolveHitlRequest,Ib as resolvePendingHitl,Ze as resolveMemoryProvider,Ue as resolveMemoryProviderOrDefault,mt as resolveModelFallbacks,pt as resolveModelString,My as resolvePendingUiTool,ke as resolvePluginManifestPath,F as rewriteTranscript,fb as runAgent,ct as saveAgentsConfig,p as saveSessionMetadata,kb as saveSubagentRegistryToDisk,Na as scanAgentDefinitions,zd as searchMemory,zs as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,Rs as sessionToolsSnapshotPath,e as sessionsDir,Jr as shouldContinueGoal,Nf as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,nt as transitionHitlStatus,wt as updateAgent,Tt as updateAgentIdentity,H as updateGoal,u as updateSessionMetadata,be as validatePluginsConfig,Fb as validateResume,Bn as withGoalWorkflowLock,eh as wrapToolsWithHooks,G as writeGoal,R as writeSessionFile};