@gencode/agents 0.16.3 → 0.17.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/CHANGELOG.md +26 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +119 -116
- package/dist/system-runtime-BwN5oJYF.js +4 -0
- package/dist/{system-runtime-CbHrwg94.d.ts → system-runtime-CEaCYWXK.d.ts} +6 -0
- package/dist/system-runtime.d.ts +1 -1
- package/dist/system-runtime.js +1 -1
- package/package.json +3 -2
- package/dist/system-runtime-CpWEW04p.js +0 -4
package/dist/index.js
CHANGED
|
@@ -1,89 +1,92 @@
|
|
|
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
|
|
2
|
-
`)}function
|
|
3
|
-
`)}const
|
|
4
|
-
`);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Nn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Pn(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Nn(e))};return{start(t){let{file:n,args:r,shell:a}=Sn(t.command),o=Lt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!xn}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Ft(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:o,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:c,resolveDone:s};e.set(l.sessionId,l),o.stdout.on(`data`,e=>Dn(l,`stdout`,e)),o.stderr.on(`data`,e=>Dn(l,`stderr`,e));let u=e=>t=>{Dn(l,`stderr`,Buffer.from(`\n[${e} stream error: ${t.message}]\n`))};o.stdout.on(`error`,u(`stdout`)),o.stderr.on(`error`,u(`stderr`)),o.stdin.on(`error`,u(`stdin`));try{o.stdin.end()}catch{}let d=An(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Dn(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Cn(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Cn(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Dn(l,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),o.on(`close`,(e,t)=>{i(l,()=>{l.exitCode=e,l.exitSignal=t,l.status===`running`?l.status=e===0?`completed`:`failed`:l.status===`killed`&&e===0&&(l.status=`completed`)})}),On(l)},get(e,t){let n=r(e);return!n||!kn(n,t)?null:On(n)},list(n){return[...e.values(),...t.values()].filter(e=>kn(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>On(e))},async wait(e,t,n){let i=r(e);if(!i||!kn(i,t))return null;if(i.status!==`running`)return On(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!kn(a,t)?null:On(a)},readLog(e){let t=r(e.sessionId);return!t||!kn(t,e.scopeKey)?null:Mn({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!kn(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!kn(n,t))return null;if(n.status!==`running`)return On(n);n.status=`killed`,Cn(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Cn(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?On(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Cn(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Cn(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const Fn=1;var In=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},Ln=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},Rn=class extends Error{rawContentPreview;constructor(e,t){super(e),this.name=`CorruptGoalWorkflowStateError`,t?.cause!==void 0&&(this.cause=t.cause),this.rawContentPreview=t?.rawContentPreview}};const zn=new Map;function Bn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function Vn(e,t,n,r){let i=Bn(e,t,n),a=zn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});zn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function Hn(e,t,n){return J.join(ee(e,t,n),`state.json`)}function Un(e,t,n){return J.join(ee(e,t,n),`plan.md`)}function Wn(e,t,n){return J.join(ee(e,t,n),`artifacts`)}async function Gn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${Pt(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 Kn(e){if(e.version!==1)throw new In(e.version)}function qn(e){let t=e.currentTaskId?e.tasks.find(t=>t.id===e.currentTaskId)??null:null,n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`done`).length,i=n.filter(e=>e.status!==`done`).length;return{workflowStatus:e.status,currentTaskId:e.currentTaskId,currentTaskTitle:t?.title??null,currentTaskStatus:t?.status??null,blockedReason:e.blockedReason,openRequiredTasks:i,doneRequiredTasks:r,finalEvidenceRefs:[...e.finalEvidenceRefs]}}async function Jn(e,t,n){let r=Hn(e,t,n);try{let e=await q.readFile(r,`utf-8`);try{let t=JSON.parse(e);return Kn(t),t}catch(t){throw t instanceof In?t:new Rn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof Rn||e instanceof In?e:new Rn(`corrupt_goal_workflow_state`,{cause:e})}}async function Yn(e,t,n){let r=Hn(e,t,n),i;try{i=await q.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return Kn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof In)throw e}let a=await W(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await V(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 $n(e,t,{goalId:a.goalId,objective:o},n),await mr(e,t,{type:`goal_workflow_repaired`,goalId:a.goalId,mode:`reinitialized`,backupPath:c},n),{ok:!0,mode:`reinitialized`,goalId:a.goalId,backedUpState:c}}async function Xn(e,t,n){let r=await Jn(e,t,n);return r?qn(r):null}async function Zn(e,t,n){let r=await Jn(e,t,n);return r?{goalState:qn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function Qn(e,t,n){let r=Hn(e,t,n),i=Un(e,t,n),a=Wn(e,t,n);await Promise.all([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 $n(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await Qn(e,t,r);let a=_n(i),o=new Date().toISOString(),s=a.tasks.find(e=>e.status===`doing`)?.id??a.tasks[0]?.id??null,c={version:1,goalId:n.goalId,status:`active`,objective:i,currentTaskId:s,tasks:a.tasks,blockedReason:null,finalEvidenceRefs:[],completedAt:null,updatedAt:o},l=ee(e,t,r);await q.mkdir(l,{recursive:!0}),await Gn(Hn(e,t,r),JSON.stringify(c,null,2));let u=bn(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await Gn(Un(e,t,r),u),c}const er=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g];function tr(e,t,n){return J.join(Wn(e,t,n),`registry.jsonl`)}function nr(e,t,n){return J.join(Wn(e,t,n),`notes`)}function rr(e,t,n){return J.join(ee(e,t,n),`plan-meta.json`)}function ir(e){let t=e,n=!1;for(let e of er)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function ar(e){return`${e}-${Date.now().toString(36)}-${Pt(3).toString(`hex`)}`}async function or(e,t,n,r){let i=await sr(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${ar(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function sr(e,t,n){let r=tr(e,t,n);try{let e=await 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 Ln(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function cr(e,t,n,r){let i=tr(e,t,r);await q.mkdir(J.dirname(i),{recursive:!0}),await q.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function lr(e,t,n,r){Kn(n),await Gn(Hn(e,t,r),JSON.stringify(n,null,2))}async function ur(e,t,n){let r=rr(e,t,n);try{let e=await q.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function dr(e,t,n,r){await Gn(rr(e,t,r),JSON.stringify(n,null,2))}async function fr(e,t,n,r){let i=await ur(e,t,r),a={...i,...n,assumptions:n.assumptions??i.assumptions,openQuestions:n.openQuestions??i.openQuestions,progressLog:n.progressLog??i.progressLog,evidence:n.evidence??i.evidence,risks:n.risks??i.risks,criterionEvidence:{...i.criterionEvidence,...n.criterionEvidence}};return await dr(e,t,a,r),a}async function pr(e,t,n,r){try{let i=bn(n,await ur(e,t,r));return await Gn(Un(e,t,r),i),{ok:!0}}catch(e){return{ok:!1,warning:`plan_update_failed`,message:e instanceof Error?e.message:String(e)}}}async function mr(e,t,n,r){let{type:i,...a}=n,o={timestamp:new Date().toISOString(),sessionId:t,goalId:n.goalId??null,action:i,detail:a},s=z(e,t,r);await q.mkdir(J.dirname(s),{recursive:!0}),await q.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}async function hr(e,t,n,r){if(n.kind===`manual`&&!n.source?.trim())return{error:`manual evidence requires source`};if(Buffer.byteLength(n.content,`utf-8`)>65536)return{error:`note_content_too_large`};let i=await or(e,t,n.kind,r),a=i.split(`:`)[1]??ar(n.kind),o=nr(e,t,r);await q.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=J.join(nr(e,t,r),`${a}.md`),l=ir(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 cr(e,t,u,r)}catch{return await q.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}function gr(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function _r(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${gr(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${gr(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${gr(e.taskBlockedReason)}`),e.acceptanceCriteria.length>0){t.push(``,`Acceptance criteria (current task):`);for(let n of e.acceptanceCriteria){let e=n.required===!1?``:` [required]`;t.push(`- ${n.id}${e}: ${gr(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${gr(n)}`)}return t}function vr(e){let t=[`- Treat goal/state.json as the only task workflow machine state; use goal/plan.md for human-readable context.`,`- Work on the current task and acceptance criteria shown in this context.`,`- Do not expose internal workflow files or task mechanics to the user unless they ask for implementation details.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary }).`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- Use the current worktree, files, command output, and test results as authoritative evidence.`,`- Do not rely solely on conversation memory to assess completion.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress on the current task.`,`- Do not inform the user about this continuation context; treat it as internal steering.`];return(e.currentTaskKind===`clarify`||e.currentTaskTitle===nn)&&t.unshift(`- Current task is "${nn}": explore, clarify, and refine the plan and acceptance criteria.`,`- Do NOT implement deliverables yet; use normal conversation to clarify scope and acceptance before execution work.`),t}function yr(){return[`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary }).`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`]}const br=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function xr(e,t,n){return Sr(e,t,n,{introLine:br})}function Sr(e,t,n,r){let i=gr(t),a=e.tokenBudget===null?`none`:String(e.tokenBudget),o=String(e.tokensUsed),s=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed)),c=n?`The user's thread goal is still active. Continue working on the current workflow task below.`:`The user's thread goal is still active. Continue working toward the objective below.`,l=[`<goal_context>`,``,r?.introLine??c,``,`<objective>`,i,`</objective>`,``,`Token budget: ${a}`,`Tokens used: ${o}`,`Tokens remaining: ${s}`,`Time used: ${e.timeUsedSeconds}s`,``];return n?l.push(`<workflow>`,..._r(n),`</workflow>`,``,`Rules:`,...vr(n)):l.push(`Rules:`,...yr()),l.push(``,`</goal_context>`),l.join(`
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
7
|
-
`)}function Tr(e){return{role:`user`,content:e}}function Er(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Dr=`AIMAX_GOAL_CONTINUATION`;var Or=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function kr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await ur(e,t,{storeName:n?.storeName}),a=r.currentTaskId?r.tasks.find(e=>e.id===r.currentTaskId)??null:null;return{workflowStatus:r.status,currentTaskId:r.currentTaskId,currentTaskTitle:a?.title??null,currentTaskKind:a?.kind??null,currentTaskStatus:a?.status??null,blockedReason:r.blockedReason,taskBlockedReason:a?.blockedReason??null,acceptanceCriteria:a?.acceptanceCriteria??[],openQuestions:i.openQuestions??[]}}function Ar(){let e=process.env[Dr];return e===void 0||e===``||e!==`0`}async function jr(e,t,n,r){if(!Ar()||n.continuationCount>=Dt)return!1;let i=await 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-BwYOp-2K.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Mr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Nr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await jr(n,r,a,{storeName:i}))return!1;let u=await 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 V(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await kr(n,r,{storeName:i}),h=Tr(p?Cr(u,f):Sr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Mr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=Dt){let e=await W(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-M3_Nx3ky.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-CocRykqc.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${Dt}), goal paused`)}}return!0}async function Pr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function Fr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await lr(e,t,c,{storeName:n?.storeName}),await mr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await ur(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await fr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await pr(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Ir(e,t,n,r){let i=await 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=Tr(xr(i,await V(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Lr(e,t,n,r){let i=await W(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Tr(wr(i,await V(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Rr(e,t,n){(await W(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await U(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const zr=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Br(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===nn}function Vr(e){return zr.has(e)}function Hr(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before running commands.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before executing deliverables directly.`].join(` `)}function Ur(e){let t=!0;return e.hookRegistry.register({pluginId:`goal-clarify-first-turn-gate`,hookName:`before_tool_call`,source:`agents/goal/clarify-first-turn-gate`,priority:100,handler:n=>{if(!(!t||!e.isGateActive())&&Vr(n.toolName))return{block:!0,blockReason:Hr(n.toolName)}}}),()=>{t=!1}}function Wr(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e)o.role===`user`?t+=1:o.role===`assistant`?n+=1:o.role===`tool_result`?r+=1:o.role===`compaction`?i+=1:a+=1;return{userTurnCount:t,assistantTurnCount:n,toolResultCount:r,compactionCount:i,otherEntryCount:a,totalEntryCount:e.length}}function Gr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if($r(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}ei(a)&&(r+=1,a.isError&&(i+=1))}let a=Array.from(t).sort();return{toolCallCount:n,distinctToolCount:a.length,toolNames:a,toolResultCount:r,failedToolResultCount:i}}function Kr(e,t={}){let n=Zr(t.limit,`limit`),r=Qr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!ei(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Xr(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function qr(e,t){let n=Qr(e,`totalEntryCount`);return typeof t!=`number`||!Number.isFinite(t)?{startIndex:0,endIndex:n}:{startIndex:Math.min(n,Math.max(0,Math.floor(t))),endIndex:n}}function Jr(e,t=80){let n=Qr(e,`totalEntryCount`),r=Qr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Yr(e,t){return e.slice(t.startIndex,t.endIndex)}function Xr(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Zr(e,t){return e===void 0?1/0:Qr(e,t)}function Qr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function $r(e){return e.role===`assistant`}function ei(e){return e.role===`tool_result`}const ti=24e3;async function ni(e){return ui({params:e,kind:`current_run`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ri(e){return ui({params:e,kind:`recent_conversation`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ii(e){return ui({params:e,kind:`transcript_range`,transcript:await I(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ai(e){let t=vi(e),n=await si(e),r=await mi(n.filePath,t.maxBytes);return{kind:`tool_result`,toolCallId:n.reference.toolCallId,toolName:n.reference.toolName,storagePath:n.reference.storagePath,content:r.content,originalBytes:r.originalBytes,returnedBytes:Buffer.byteLength(r.content,`utf-8`),truncated:r.truncated,limits:t,contextFiles:ci(e.dataDir,e.sessionId,e.sessionOptions)}}function oi(e){return{maxEntries:yi(e?.maxEntries??80,`limits.maxEntries`),maxBytes:yi(e?.maxBytes??ti,`limits.maxBytes`)}}async function si(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=di(await fi(e.dataDir,e.sessionId,e.sessionOptions),{toolCallId:e.toolCallId,storagePath:e.storagePath});if(!t)throw Error(`Requested tool result is not referenced by this session transcript or context.`);return{reference:t,filePath:await pi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function ci(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function li(e,t,n){let r=bi(e.startIndex,`startIndex`),i=bi(e.endIndex,`endIndex`);if(r<0||i<r||i>t)throw Error(`Requested transcript range is outside transcript bounds 0..${t}.`);if(i-r>n)throw Error(`Requested transcript range exceeds maximum of ${n} entries.`);return{startIndex:r,endIndex:i}}function ui(e){let t=vi(e.params),n=li(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=hi(r,t.maxBytes);return{kind:e.kind,range:n,entries:i.entries,entryCount:i.entries.length,rangeEntryCount:r.length,totalEntryCount:e.transcript.length,returnedBytes:i.returnedBytes,truncated:i.truncated,limits:t,contextFiles:ci(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function di(e,t){if(t.toolCallId&&t.storagePath){let n=e.find(e=>e.toolCallId===t.toolCallId&&e.storagePath===t.storagePath);if(n)return n;let r=e.some(e=>e.toolCallId===t.toolCallId),i=e.some(e=>e.storagePath===t.storagePath);if(r&&i)throw Error(`Requested toolCallId and storagePath do not reference the same tool result.`);return}return e.find(e=>t.toolCallId?e.toolCallId===t.toolCallId:e.storagePath===t.storagePath)}async function fi(e,t,n){let[r,i]=await Promise.all([I(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)Ci(e)&&e.toolResultRef?.sessionId===t&&a.set(wi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(wi(e),e);return Array.from(a.values())}async function pi(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(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(!Si(J.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Si(J.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([xi(t),xi(n),xi(i)]);if(!Si(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Si(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function mi(e,t){let n=await 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:_i(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function hi(e,t){let n=[],r=0,i=!1;for(let a of e){let e={...a,content:``},o=Buffer.byteLength(JSON.stringify(e),`utf-8`);if(r+o>=t){i=!0;break}let s=t-r-o,c=gi(a.content,s);c.truncated&&(i=!0);let l={...a,content:c.value},u=Buffer.byteLength(JSON.stringify(l),`utf-8`);if(n.push(l),r+=u,c.truncated)break}return n.length<e.length&&(i=!0),{entries:n,returnedBytes:r,truncated:i}}function gi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:_i(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function _i(e){let t=new Rt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function vi(e){return oi(e.limits)}function yi(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function bi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function xi(e){try{return await q.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Ti(e)}`)}}function Si(e,t){let n=J.relative(e,t);return n===``||!n.startsWith(`..`)&&!J.isAbsolute(n)}function Ci(e){return e.role===`tool_result`}function wi(e){return`${e.toolCallId}\n${e.storagePath}`}function Ti(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ei(e){return J.join(e,`.aimax`,`auto-skills`)}function Di(e){return J.join(e,`categories.json`)}function Oi(e){return J.join(e,`.auto_skills_prompt_snapshot.json`)}const ki=/^[a-z0-9][a-z0-9-]*$/,Ai=/^[a-z0-9][a-z0-9-]*$/;function X(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 ji(e){let t=e.trim();if(!t)throw Error(`Auto-skill name cannot be empty.`);if(t.length>80)throw Error(`Auto-skill name is too long.`);if(t.includes(`/`)||t.includes(`\\`)||t===`.`||t===`..`||t.startsWith(`.`)||!Ai.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Mi(e,t){return`auto:${X(e)}/${ji(t)}`}function Ni(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=X(n.slice(0,r)),a=ji(n.slice(r+1));return{skillId:Mi(i,a),categoryPath:i,skillName:a}}function Pi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Fi(e,t,n){let r=J.resolve(e),i=J.resolve(r,...X(t).split(`/`),ji(n));return Li(r,i),i}function Ii(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||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 Li(i,a),a}function Li(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 Ri(e){let t=Di(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=X(e),r=Bi(t);return{path:n,name:n.split(`/`).at(-1)??n,description:r.description,createdBy:r.createdBy}}).sort((e,t)=>e.path.localeCompare(t.path))}function zi(e){return new Map(e.map(e=>[e.path,e]))}function Bi(e){return typeof e==`string`?{description:e.trim()}:!e||typeof e!=`object`||Array.isArray(e)?{description:``}:{description:typeof e.description==`string`?e.description.trim():``,createdBy:typeof e.createdBy==`string`?e.createdBy.trim():void 0}}const Vi=32*1024,Hi=new Map;function Ui(e){return new Gi(e)}async function Wi(e){let t=J.resolve(e);for(let e of Array.from(Hi.keys()))e.startsWith(`${t}|`)&&Hi.delete(e);await q.rm(Oi(t),{force:!0}).catch(()=>{})}var Gi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=J.resolve(e.rootDir??Ei(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return qi(zi((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?X(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Ji(e.categoryPath,t)).map(Ki)}async autoSkillSearch(e){let t=e.query.trim().toLowerCase();if(!t)return[];let n=Math.max(1,e.limit??5);return(await this.visibleEntries()).map(e=>({entry:e,score:Yi(e,t)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||e.entry.skillId.localeCompare(t.entry.skillId)).slice(0,n).map(({entry:e,score:t})=>({...Ki(e),score:t}))}async autoSkillView(e){let t=Ni(e.skillId),n=(await this.visibleEntries()).find(e=>e.skillId===t.skillId);if(!n)throw Error(`Unknown auto-skill: ${e.skillId}`);if(e.filePath?.trim()){let t=Ii(n.skillDir,e.filePath),r=await ia(t,this.maxResourceBytes);return{...Ki(n),status:n.status,content:r,path:sa(J.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:sa(J.relative(n.skillDir,t))}}let r=await ia(n.skillFile,this.maxSkillBytes);return{...Ki(n),status:n.status,content:r,path:sa(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 Xi(this.rootDir),i=Hi.get(n);if(!e&&i&&ta(i.manifest,r))return i;let a=e?void 0:await $i(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return Hi.set(n,e),e}let o=await Ri(this.rootDir),s=zi(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return Hi.set(n,c),await ea(this.rootDir,c).catch(()=>{}),c}async parseEntriesFromManifest(e){let t=e.filter(e=>e.kind===`skill`).map(e=>e.filePath),n=[];for(let e of t){let t=await this.loadEntry(e);t&&n.push(t)}return n.sort((e,t)=>e.skillId.localeCompare(t.skillId))}async visibleEntries(){let e=await this.loadIndex();return this.visibleEntriesFrom(e)}visibleEntriesFrom(e){return this.includeArchived?e:e.filter(e=>e.status===`active`)}optionsHash(){return ua({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Vi})}async loadEntry(e){try{let t=J.dirname(e),n=ji(J.basename(t)),r=sa(J.relative(this.rootDir,t)),i=X(J.posix.dirname(r)),a=Mi(i,n),o=J.join(t,`metadata.json`),s=await na(o);if(s?.skillId&&Ni(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&X(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=Pi(s?.status);return{skillId:a,name:n,description:aa(await ra(e,Vi)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:oa(s?.tags),relatedSkills:oa(s?.relatedSkills),confidence:typeof s?.confidence==`number`?s.confidence:void 0,createdAt:typeof s?.createdAt==`string`?s.createdAt:void 0,updatedAt:typeof s?.updatedAt==`string`?s.updatedAt:void 0}}catch(t){process.stderr.write(`[auto-skills] skipped ${e}: ${ca(t)}\n`);return}}};function Ki(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function qi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Ji(e,t){return t?e===t:!0}function Yi(e,t){let n=t.split(/\s+/).filter(Boolean),r=e.name.toLowerCase(),i=e.description.toLowerCase(),a=e.categoryPath.toLowerCase(),o=e.tags.join(` `).toLowerCase(),s=0;r===t&&(s+=80),r.includes(t)&&(s+=30),i.includes(t)&&(s+=20),a.includes(t)&&(s+=10),o.includes(t)&&(s+=10);for(let e of n)r.includes(e)&&(s+=8),i.includes(e)&&(s+=5),a.includes(e)&&(s+=3),o.includes(e)&&(s+=3);return s}async function Xi(e){let t;try{t=await q.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await Qi(J.join(e,`categories.json`),`categories`,n),await Zi(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Zi(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=J.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await Qi(t,`skill`,n),await Qi(J.join(e,`metadata.json`),`metadata`,n),await Qi(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 Zi(t,i,n)}}async function Qi(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 $i(e,t,n){let r;try{r=await q.readFile(Oi(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!ta(e.manifest,n)?void 0:e}catch{return}}async function ea(e,t){if(!await la(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await q.writeFile(Oi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function ta(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.filePath!==i.filePath||r.kind!==i.kind||r.size!==i.size||r.mtimeMs!==i.mtimeMs)return!1}return!0}async function na(e){try{let t=await 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 ra(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 ia(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 aa(e){let t=zt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
|
|
8
|
-
`)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function
|
|
1
|
+
import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,R as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as P,w as ee,x as F,y as I,z as L}from"./session-BpKaF-Gk.js";import{n as R,t as te}from"./goal-events-CocRykqc.js";import{c as z,i as B,l as V,n as ne,o as re,r as ie,s as H,t as ae,u as U}from"./goal-store-M3_Nx3ky.js";import{A as oe,C as se,D as W,E as ce,F as le,I as ue,M as de,N as fe,O as pe,P as me,S as he,T as ge,_ as _e,a as ve,b as ye,c as be,d as xe,f as Se,g as Ce,h as we,i as Te,j as Ee,k as De,l as Oe,m as ke,n as Ae,o as je,p as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./system-runtime-BwN5oJYF.js";import{a as Ve,c as He,i as Ue,l as We,o as Ge,r as Ke,s as qe,t as Je,u as Ye}from"./default-provider-BV9gmV00.js";import{a as Xe,i as Ze,n as Qe,o as $e,r as et,t as tt}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as nt}from"./host-BC9sAhdH.js";import{a as rt,i as it,l as at,n as ot,o as st,r as ct,s as lt,t as ut}from"./session-store-BwYOp-2K.js";import{_ as dt,a as ft,c as pt,d as mt,f as ht,g as gt,h as _t,i as vt,l as yt,m as bt,n as xt,o as St,p as Ct,s as wt,t as Tt,u as Et,v as Dt,y as Ot}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as kt,formatTaskForDisplay as At,isHitlExpired as jt,isHitlTool as Mt}from"@gencode/shared";import G,{readFile as Nt}from"node:fs/promises";import K,{join as Pt}from"node:path";import{createHash as Ft,randomBytes as It,randomUUID as Lt}from"node:crypto";import Rt from"node:os";import{spawn as zt}from"node:child_process";import{TextDecoder as Bt}from"node:util";import Vt from"gray-matter";import{Agent as Ht}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Ut}from"node:async_hooks";import Wt from"node:fs";import Gt from"openai";import{Type as q,calculateCost as Kt,clampThinkingLevel as qt,createAssistantMessageEventStream as Jt,getEnvApiKey as Yt,parseStreamingJson as Xt,registerApiProvider as Zt,registerBuiltInApiProviders as Qt,streamSimple as $t}from"@earendil-works/pi-ai";import{fileURLToPath as en}from"node:url";import{isBinaryFile as tn}from"isbinaryfile";import{parse as nn}from"yaml";import rn from"ajv";var an=class{turn=null;wallClock={activeGoalId:null,lastAccountedAt:Date.now()};resetWallClock(){this.wallClock.lastAccountedAt=Date.now()}markActiveGoal(e,t,n){e&&(this.turn&&this.turn.turnId===e?(this.turn.activeGoalId=t,this.turn.lastTokenUsage=n):this.turn={turnId:e,activeGoalId:t,lastTokenUsage:n}),this.wallClock.activeGoalId!==t&&this.resetWallClock(),this.wallClock.activeGoalId=t}clearActiveGoal(){this.turn&&(this.turn.activeGoalId=null),this.wallClock.activeGoalId=null,this.resetWallClock()}tokenDeltaSinceLastAccounting(e){if(!this.turn||!this.turn.activeGoalId)return 0;let t=this.turn.lastTokenUsage;return Math.max(0,e.input-t.input)+Math.max(0,e.output-t.output)}timeDeltaSecondsSinceLastAccounting(){if(!this.wallClock.activeGoalId)return 0;let e=Date.now()-this.wallClock.lastAccountedAt;return Math.floor(e/1e3)}markAccounted(e,t){this.turn&&(this.turn.lastTokenUsage=e),t>0&&(this.wallClock.lastAccountedAt+=t*1e3),this.wallClock.lastAccountedAt>Date.now()&&(this.wallClock.lastAccountedAt=Date.now())}};async function on(e,t,n,r,i){let a=await H(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await V(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const sn=`clarify plan and acceptance`,cn=`补齐后续 task list、每个 task 的验收项和当前下一步`,ln={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},un=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function dn(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function fn(e,t){let n=dn(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function pn(e){let t=e.split(/\r?\n/),n=[];for(let e of t){let t=e.trim();if(!t)continue;let r=t.match(/^(?:[-*•]|\d+[.)])\s+(.+)$/);if(r?.[1]){n.push(r[1].trim());continue}t.length>=8&&n.push(t)}return n.filter(e=>e.length>=4)}function mn(e){let t={raw:e.trim()},n=/(?:^|\n)\s*(?:【([^】]+)】|(?:#{1,3}\s*)?([A-Za-z\u4e00-\u9fff][^:\n]{0,30}))\s*[::]\s*/g,r=[],i;for(;(i=n.exec(e))!==null;){let e=(i[1]??i[2]??``).trim();e&&r.push({label:e,start:i.index,contentStart:i.index+i[0].length})}for(let n=0;n<r.length;n+=1){let i=r[n],a=r[n+1],o=e.slice(i.contentStart,a?.start??e.length).trim();for(let[e,n]of Object.entries(ln))fn(i.label,n)&&(t[e]=t[e]?`${t[e]}\n${o}`:o)}return{goal:t.goal?.trim()||e.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>=8)||e.trim(),scope:t.scope?.trim()??``,steps:t.steps?pn(t.steps):[],acceptance:t.acceptance?pn(t.acceptance):[],raw:e.trim()}}function hn(e){let t=e.toLowerCase();return un.some(e=>t.includes(e.toLowerCase()))}function gn(e){return e.some(hn)}function _n(e,t){return{id:e,text:t,required:!0}}function vn(e){return{id:e.id,kind:e.kind,title:e.title,required:!0,status:e.status,acceptanceCriteria:e.acceptanceCriteria,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:e.updatedAt}}function yn(e){return vn({id:`task-1`,kind:`clarify`,title:sn,status:`doing`,acceptanceCriteria:[_n(`ac-1`,cn)],updatedAt:e})}function bn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>_n(`ac-${t+1}`,e)):[_n(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>vn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[_n(`ac-1`,`完成:${e}`)],updatedAt:n}))}function xn(e){let t=new Date().toISOString(),n=mn(e),r=n.goal||n.raw,i=n.scope?[n.scope]:[],a=[];if(n.steps.length>=2)return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&gn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&gn(pn(n.raw))){let e=pn(n.raw).filter(hn);return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[yn(t)]}}function Sn(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function Cn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>Sn(n.has(e.id),e)),``].join(`
|
|
2
|
+
`)}function wn(e,t){let n=e.tasks.find(t=>t.id===e.currentTaskId),r=t?.interpretation?.trim()||e.objective,i=t?.assumptions??[],a=t?.openQuestions??[],o=t?.progressLog??[`${new Date(e.updatedAt).toISOString().slice(0,16).replace(`T`,` `)}: 创建目标并生成初始任务。`],s=t?.evidence?.length?t.evidence:e.finalEvidenceRefs.length>0?e.finalEvidenceRefs:[],c=t?.risks??(e.blockedReason?[e.blockedReason]:[]),l=[`# Goal Plan`,``,`## Objective`,``,e.objective,``,`## Interpretation`,``,r,``,`## Assumptions`,``,...i.length>0?i.map(e=>`- ${e}`):[`- 暂无`],``];return t?.taskPlanNotes?.trim()&&l.push(`## Task Plan Notes`,``,t.taskPlanNotes.trim(),``),l.push(`## Current Focus`,``,`- Current task: ${e.currentTaskId??`none`}`,`- Status: ${e.status}`,`- Next step: ${n?.title??`无当前任务`}`,...e.blockedReason?[`- Blocked: ${e.blockedReason}`]:[],``,`## Task List`,``,...e.tasks.flatMap(e=>{let n=new Set,r=t?.criterionEvidence?.[e.id];if(r)for(let t of e.acceptanceCriteria)r.includes(t.id)&&n.add(t.id);else if(e.status===`done`)for(let t of e.acceptanceCriteria)n.add(t.id);return[Cn(e,n)]}),`## Progress Log`,``,...o.map(e=>`- ${e}`),``,`## Open Questions`,``,...a.length>0?a.map(e=>`- ${e}`):[`- 暂无`],``,`## Evidence`,``,...s.length>0?s.map(e=>`- ${e}`):[`- 暂无`],``,`## Risks`,``,...c.length>0?c.map(e=>`- ${e}`):[`- 暂无`],``),t?.finalSummary?.trim()&&l.push(`## Final Summary`,``,t.finalSummary.trim(),``),l.join(`
|
|
3
|
+
`)}const Tn=process.platform===`win32`;function En(e){return Tn?{shell:!0,file:process.env.ComSpec||process.env.COMSPEC||`cmd.exe`,args:[`/d`,`/s`,`/c`,`chcp 65001>nul & ${e}`]}:{file:`bash`,args:[`-lc`,e],shell:void 0}}function Dn(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(Tn&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{zt(`taskkill`,n,{windowsHide:!0,stdio:`ignore`})}catch{try{e.kill()}catch{}}return}try{if(typeof e.pid==`number`){process.kill(-e.pid,t);return}e.kill(t)}catch{try{e.kill(t)}catch{}}}}const On=2e5;function kn(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function An(e,t){let n=e+t;return n.length<=On?{text:n,truncated:!1}:{text:n.slice(-On),truncated:!0}}function jn(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=An(e.output,r);e.output=i.text;let a=An(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Mn(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:kn(e.output),stdoutTail:kn(e.stdout),stderrTail:kn(e.stderr),outputTruncated:e.outputTruncated}}function Nn(e,t){return t?e.scopeKey===t:!0}function Pn(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Fn(e){return e?e.split(/\r?\n/):[]}function In(e){let t=Fn(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Pn(e.limit,n?200:Math.max(1,t.length-r)),a=(n&&t.length>200?t.slice(t.length-200):t.slice(r,r+i)).join(`
|
|
4
|
+
`);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Ln(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Rn(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Ln(e))};return{start(t){let{file:n,args:r,shell:a}=En(t.command),o=zt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!Tn}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Lt(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:o,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:c,resolveDone:s};e.set(l.sessionId,l),o.stdout.on(`data`,e=>jn(l,`stdout`,e)),o.stderr.on(`data`,e=>jn(l,`stderr`,e));let u=e=>t=>{jn(l,`stderr`,Buffer.from(`\n[${e} stream error: ${t.message}]\n`))};o.stdout.on(`error`,u(`stdout`)),o.stderr.on(`error`,u(`stderr`)),o.stdin.on(`error`,u(`stdin`));try{o.stdin.end()}catch{}let d=Pn(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,jn(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Dn(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Dn(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),jn(l,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),o.on(`close`,(e,t)=>{i(l,()=>{l.exitCode=e,l.exitSignal=t,l.status===`running`?l.status=e===0?`completed`:`failed`:l.status===`killed`&&e===0&&(l.status=`completed`)})}),Mn(l)},get(e,t){let n=r(e);return!n||!Nn(n,t)?null:Mn(n)},list(n){return[...e.values(),...t.values()].filter(e=>Nn(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Mn(e))},async wait(e,t,n){let i=r(e);if(!i||!Nn(i,t))return null;if(i.status!==`running`)return Mn(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!Nn(a,t)?null:Mn(a)},readLog(e){let t=r(e.sessionId);return!t||!Nn(t,e.scopeKey)?null:In({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Nn(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!Nn(n,t))return null;if(n.status!==`running`)return Mn(n);n.status=`killed`,Dn(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Dn(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?Mn(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Dn(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Dn(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const zn=1;var Bn=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},Vn=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},Hn=class extends Error{rawContentPreview;constructor(e,t){super(e),this.name=`CorruptGoalWorkflowStateError`,t?.cause!==void 0&&(this.cause=t.cause),this.rawContentPreview=t?.rawContentPreview}};const Un=new Map;function Wn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function Gn(e,t,n,r){let i=Wn(e,t,n),a=Un.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});Un.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function Kn(e,t,n){return K.join(ne(e,t,n),`state.json`)}function qn(e,t,n){return K.join(ne(e,t,n),`plan.md`)}function Jn(e,t,n){return K.join(ne(e,t,n),`artifacts`)}async function Yn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${It(4).toString(`hex`)}.tmp`;try{await G.writeFile(n,t,`utf-8`),await G.rename(n,e)}finally{await G.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function Xn(e){if(e.version!==1)throw new Bn(e.version)}function Zn(e){let t=e.currentTaskId?e.tasks.find(t=>t.id===e.currentTaskId)??null:null,n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`done`).length,i=n.filter(e=>e.status!==`done`).length;return{workflowStatus:e.status,currentTaskId:e.currentTaskId,currentTaskTitle:t?.title??null,currentTaskStatus:t?.status??null,blockedReason:e.blockedReason,openRequiredTasks:i,doneRequiredTasks:r,finalEvidenceRefs:[...e.finalEvidenceRefs]}}async function Qn(e,t,n){let r=Kn(e,t,n);try{let e=await G.readFile(r,`utf-8`);try{let t=JSON.parse(e);return Xn(t),t}catch(t){throw t instanceof Bn?t:new Hn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof Hn||e instanceof Bn?e:new Hn(`corrupt_goal_workflow_state`,{cause:e})}}async function $n(e,t,n){let r=Kn(e,t,n),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return Xn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof Bn)throw e}let a=await H(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await z(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await G.writeFile(s,i,`utf-8`),c=s}catch{}return await rr(e,t,{goalId:a.goalId,objective:o},n),await vr(e,t,{type:`goal_workflow_repaired`,goalId:a.goalId,mode:`reinitialized`,backupPath:c},n),{ok:!0,mode:`reinitialized`,goalId:a.goalId,backedUpState:c}}async function er(e,t,n){let r=await Qn(e,t,n);return r?Zn(r):null}async function tr(e,t,n){let r=await Qn(e,t,n);return r?{goalState:Zn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function nr(e,t,n){let r=Kn(e,t,n),i=qn(e,t,n),a=Jn(e,t,n);await Promise.all([G.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),G.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),G.rm(a,{recursive:!0,force:!0})])}async function rr(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await nr(e,t,r);let a=xn(i),o=new Date().toISOString(),s=a.tasks.find(e=>e.status===`doing`)?.id??a.tasks[0]?.id??null,c={version:1,goalId:n.goalId,status:`active`,objective:i,currentTaskId:s,tasks:a.tasks,blockedReason:null,finalEvidenceRefs:[],completedAt:null,updatedAt:o},l=ne(e,t,r);await G.mkdir(l,{recursive:!0}),await Yn(Kn(e,t,r),JSON.stringify(c,null,2));let u=wn(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await Yn(qn(e,t,r),u),c}const ir=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g];function ar(e,t,n){return K.join(Jn(e,t,n),`registry.jsonl`)}function or(e,t,n){return K.join(Jn(e,t,n),`notes`)}function sr(e,t,n){return K.join(ne(e,t,n),`plan-meta.json`)}function cr(e){let t=e,n=!1;for(let e of ir)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function lr(e){return`${e}-${Date.now().toString(36)}-${It(3).toString(`hex`)}`}async function ur(e,t,n,r){let i=await dr(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${lr(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function dr(e,t,n){let r=ar(e,t,n);try{let e=await G.readFile(r,`utf-8`),t=[],n=e.split(/\r?\n/).map((e,t)=>({line:e,index:t})).filter(e=>e.line.trim().length>0);for(let[e,r]of n.entries())try{t.push(JSON.parse(r.line))}catch{if(e===n.length-1)continue;throw new Vn(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function fr(e,t,n,r){let i=ar(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0}),await G.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function pr(e,t,n,r){Xn(n),await Yn(Kn(e,t,r),JSON.stringify(n,null,2))}async function mr(e,t,n){let r=sr(e,t,n);try{let e=await G.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function hr(e,t,n,r){await Yn(sr(e,t,r),JSON.stringify(n,null,2))}async function gr(e,t,n,r){let i=await mr(e,t,r),a={...i,...n,assumptions:n.assumptions??i.assumptions,openQuestions:n.openQuestions??i.openQuestions,progressLog:n.progressLog??i.progressLog,evidence:n.evidence??i.evidence,risks:n.risks??i.risks,criterionEvidence:{...i.criterionEvidence,...n.criterionEvidence}};return await hr(e,t,a,r),a}async function _r(e,t,n,r){try{let i=wn(n,await mr(e,t,r));return await Yn(qn(e,t,r),i),{ok:!0}}catch(e){return{ok:!1,warning:`plan_update_failed`,message:e instanceof Error?e.message:String(e)}}}async function vr(e,t,n,r){let{type:i,...a}=n,o={timestamp:new Date().toISOString(),sessionId:t,goalId:n.goalId??null,action:i,detail:a},s=R(e,t,r);await G.mkdir(K.dirname(s),{recursive:!0}),await G.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}async function yr(e,t,n,r){if(n.kind===`manual`&&!n.source?.trim())return{error:`manual evidence requires source`};if(Buffer.byteLength(n.content,`utf-8`)>65536)return{error:`note_content_too_large`};let i=await ur(e,t,n.kind,r),a=i.split(`:`)[1]??lr(n.kind),o=or(e,t,r);await G.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=K.join(or(e,t,r),`${a}.md`),l=cr(n.content);await G.writeFile(c,l.text,`utf-8`);let u={id:i,kind:n.kind,summary:n.summary,source:n.source??`model`,createdAt:new Date().toISOString(),notePath:s,contentBytes:Buffer.byteLength(l.text,`utf-8`),redactionIncomplete:l.redactionIncomplete};try{await fr(e,t,u,r)}catch{return await G.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}function br(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function xr(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${br(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${br(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${br(e.taskBlockedReason)}`),e.acceptanceCriteria.length>0){t.push(``,`Acceptance criteria (current task):`);for(let n of e.acceptanceCriteria){let e=n.required===!1?``:` [required]`;t.push(`- ${n.id}${e}: ${br(n.text)}`)}}if(e.requiredTasks.length>0){t.push(``,`Completion report required tasks:`);for(let n of e.requiredTasks){t.push(`- ${n.taskId} [${n.status}]: ${br(n.title)}`);for(let e of n.acceptanceCriteria)e.required!==!1&&t.push(` - ${e.id} [required]: ${br(e.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${br(n)}`)}return t}function Sr(e){let t=[`- Treat goal/state.json as the only task workflow machine state; use goal/plan.md for human-readable context.`,`- Work on the current task and acceptance criteria shown in this context.`,`- Do not expose internal workflow files or task mechanics to the user unless they ask for implementation details.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary, completedTasks }) with every required task and acceptance criterion covered by evidence summaries and sources.`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- Use the current worktree, files, command output, and test results as authoritative evidence.`,`- Do not rely solely on conversation memory to assess completion.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress on the current task.`,`- Do not inform the user about this continuation context; treat it as internal steering.`];return(e.currentTaskKind===`clarify`||e.currentTaskTitle===sn)&&t.unshift(`- Current task is "${sn}": explore, clarify, and refine the plan and acceptance criteria.`,`- Do NOT implement deliverables yet; use normal conversation to clarify scope and acceptance before execution work.`),t}function Cr(){return[`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary, completedTasks }) with every required task and acceptance criterion covered by evidence summaries and sources.`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`]}const wr=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function Tr(e,t,n){return Er(e,t,n,{introLine:wr})}function Er(e,t,n,r){let i=br(t),a=e.tokenBudget===null?`none`:String(e.tokenBudget),o=String(e.tokensUsed),s=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed)),c=n?`The user's thread goal is still active. Continue working on the current workflow task below.`:`The user's thread goal is still active. Continue working toward the objective below.`,l=[`<goal_context>`,``,r?.introLine??c,``,`<objective>`,i,`</objective>`,``,`Token budget: ${a}`,`Tokens used: ${o}`,`Tokens remaining: ${s}`,`Time used: ${e.timeUsedSeconds}s`,``];return n?l.push(`<workflow>`,...xr(n),`</workflow>`,``,`Rules:`,...Sr(n)):l.push(`Rules:`,...Cr()),l.push(``,`</goal_context>`),l.join(`
|
|
5
|
+
`)}function Dr(e,t){let n=br(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed);return[`<goal_context>`,``,`The token budget for the current thread goal has been exhausted.`,`The goal status has been set to "budget_limited" automatically.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Instructions:`,`- Wrap up the current turn soon. Do not start new substantive work.`,`- Summarize progress made, any blockers, and what would be needed next.`,`- Do NOT submit goal complete unless the objective is truly achieved.`,`- The user can increase the budget or resume the goal later via the CLI.`,``,`</goal_context>`].join(`
|
|
6
|
+
`)}function Or(e,t){let n=br(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The thread goal objective has been edited by the user.`,`The following objective supersedes any previous thread goal objective.`,`Adjust your work direction accordingly.`,``,`<untrusted_objective>`,n,`</untrusted_objective>`,``,`Token budget: ${r}`,`Tokens remaining: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Use the goal tool only for terminal complete or blocked status; do not use it for routine progress notes.`,``,`</goal_context>`].join(`
|
|
7
|
+
`)}function kr(e){return{role:`user`,content:e}}function Ar(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const jr=`AIMAX_GOAL_CONTINUATION`;var Mr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function Nr(e,t,n){let r=await Qn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await mr(e,t,{storeName:n?.storeName}),a=r.currentTaskId?r.tasks.find(e=>e.id===r.currentTaskId)??null:null;return{workflowStatus:r.status,currentTaskId:r.currentTaskId,currentTaskTitle:a?.title??null,currentTaskKind:a?.kind??null,currentTaskStatus:a?.status??null,blockedReason:r.blockedReason,taskBlockedReason:a?.blockedReason??null,acceptanceCriteria:a?.acceptanceCriteria??[],requiredTasks:r.tasks.filter(e=>e.required!==!1).map(e=>({taskId:e.id,title:e.title,status:e.status,acceptanceCriteria:e.acceptanceCriteria})),openQuestions:i.openQuestions??[]}}function Pr(){let e=process.env[jr];return e===void 0||e===``||e!==`0`}async function Fr(e,t,n,r){if(!Pr()||n.continuationCount>=kt)return!1;let i=await H(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-BwYOp-2K.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Ir(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Lr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Fr(n,r,a,{storeName:i}))return!1;let u=await H(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await z(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await Nr(n,r,{storeName:i}),h=kr(p?Dr(u,f):Er(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Ir(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=kt){let e=await H(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-M3_Nx3ky.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-CocRykqc.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${kt}), goal paused`)}}return!0}async function Rr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function zr(e,t,n){let r=await Qn(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await pr(e,t,c,{storeName:n?.storeName}),await vr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await mr(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await gr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await _r(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Br(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await Nr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=kr(Tr(i,await z(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Vr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=kr(Or(i,await z(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Hr(e,t,n){(await H(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await V(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const Ur=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Wr(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===sn}function Gr(e){return Ur.has(e)}function Kr(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before running commands.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before executing deliverables directly.`].join(` `)}function qr(e){let t=!0;return e.hookRegistry.register({pluginId:`goal-clarify-first-turn-gate`,hookName:`before_tool_call`,source:`agents/goal/clarify-first-turn-gate`,priority:100,handler:n=>{if(!(!t||!e.isGateActive())&&Gr(n.toolName))return{block:!0,blockReason:Kr(n.toolName)}}}),()=>{t=!1}}function Jr(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e)o.role===`user`?t+=1:o.role===`assistant`?n+=1:o.role===`tool_result`?r+=1:o.role===`compaction`?i+=1:a+=1;return{userTurnCount:t,assistantTurnCount:n,toolResultCount:r,compactionCount:i,otherEntryCount:a,totalEntryCount:e.length}}function Yr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(ri(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}ii(a)&&(r+=1,a.isError&&(i+=1))}let a=Array.from(t).sort();return{toolCallCount:n,distinctToolCount:a.length,toolNames:a,toolResultCount:r,failedToolResultCount:i}}function Xr(e,t={}){let n=ti(t.limit,`limit`),r=ni(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!ii(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:ei(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Zr(e,t){let n=ni(e,`totalEntryCount`);return typeof t!=`number`||!Number.isFinite(t)?{startIndex:0,endIndex:n}:{startIndex:Math.min(n,Math.max(0,Math.floor(t))),endIndex:n}}function Qr(e,t=80){let n=ni(e,`totalEntryCount`),r=ni(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function $r(e,t){return e.slice(t.startIndex,t.endIndex)}function ei(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function ti(e,t){return e===void 0?1/0:ni(e,t)}function ni(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function ri(e){return e.role===`assistant`}function ii(e){return e.role===`tool_result`}const ai=24e3;async function oi(e){return mi({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function si(e){return mi({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ci(e){return mi({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function li(e){let t=Si(e),n=await di(e),r=await vi(n.filePath,t.maxBytes);return{kind:`tool_result`,toolCallId:n.reference.toolCallId,toolName:n.reference.toolName,storagePath:n.reference.storagePath,content:r.content,originalBytes:r.originalBytes,returnedBytes:Buffer.byteLength(r.content,`utf-8`),truncated:r.truncated,limits:t,contextFiles:fi(e.dataDir,e.sessionId,e.sessionOptions)}}function ui(e){return{maxEntries:Ci(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Ci(e?.maxBytes??ai,`limits.maxBytes`)}}async function di(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=hi(await gi(e.dataDir,e.sessionId,e.sessionOptions),{toolCallId:e.toolCallId,storagePath:e.storagePath});if(!t)throw Error(`Requested tool result is not referenced by this session transcript or context.`);return{reference:t,filePath:await _i({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function fi(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function pi(e,t,n){let r=wi(e.startIndex,`startIndex`),i=wi(e.endIndex,`endIndex`);if(r<0||i<r||i>t)throw Error(`Requested transcript range is outside transcript bounds 0..${t}.`);if(i-r>n)throw Error(`Requested transcript range exceeds maximum of ${n} entries.`);return{startIndex:r,endIndex:i}}function mi(e){let t=Si(e.params),n=pi(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=yi(r,t.maxBytes);return{kind:e.kind,range:n,entries:i.entries,entryCount:i.entries.length,rangeEntryCount:r.length,totalEntryCount:e.transcript.length,returnedBytes:i.returnedBytes,truncated:i.truncated,limits:t,contextFiles:fi(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function hi(e,t){if(t.toolCallId&&t.storagePath){let n=e.find(e=>e.toolCallId===t.toolCallId&&e.storagePath===t.storagePath);if(n)return n;let r=e.some(e=>e.toolCallId===t.toolCallId),i=e.some(e=>e.storagePath===t.storagePath);if(r&&i)throw Error(`Requested toolCallId and storagePath do not reference the same tool result.`);return}return e.find(e=>t.toolCallId?e.toolCallId===t.toolCallId:e.storagePath===t.storagePath)}async function gi(e,t,n){let[r,i]=await Promise.all([F(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)Di(e)&&e.toolResultRef?.sessionId===t&&a.set(Oi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Oi(e),e);return Array.from(a.values())}async function _i(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(K.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=K.resolve(e.dataDir,e.reference.storagePath);if(!Ei(K.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Ei(K.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([Ti(t),Ti(n),Ti(i)]);if(!Ei(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Ei(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function vi(e,t){let n=await G.stat(e),r=await G.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:xi(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function yi(e,t){let n=[],r=0,i=!1;for(let a of e){let e={...a,content:``},o=Buffer.byteLength(JSON.stringify(e),`utf-8`);if(r+o>=t){i=!0;break}let s=t-r-o,c=bi(a.content,s);c.truncated&&(i=!0);let l={...a,content:c.value},u=Buffer.byteLength(JSON.stringify(l),`utf-8`);if(n.push(l),r+=u,c.truncated)break}return n.length<e.length&&(i=!0),{entries:n,returnedBytes:r,truncated:i}}function bi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:xi(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function xi(e){let t=new Bt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Si(e){return ui(e.limits)}function Ci(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function wi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Ti(e){try{return await G.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${ki(e)}`)}}function Ei(e,t){let n=K.relative(e,t);return n===``||!n.startsWith(`..`)&&!K.isAbsolute(n)}function Di(e){return e.role===`tool_result`}function Oi(e){return`${e.toolCallId}\n${e.storagePath}`}function ki(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ai(e){return K.join(e,`.aimax`,`auto-skills`)}function ji(e){return K.join(e,`categories.json`)}function Mi(e){return K.join(e,`.auto_skills_prompt_snapshot.json`)}const Ni=/^[a-z0-9][a-z0-9-]*$/,Pi=/^[a-z0-9][a-z0-9-]*$/;function Fi(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||K.win32.isAbsolute(t)||K.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Ni.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Ii(e){let t=e.trim();if(!t)throw Error(`Auto-skill name cannot be empty.`);if(t.length>80)throw Error(`Auto-skill name is too long.`);if(t.includes(`/`)||t.includes(`\\`)||t===`.`||t===`..`||t.startsWith(`.`)||!Pi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Li(e,t){return`auto:${Fi(e)}/${Ii(t)}`}function Ri(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=Fi(n.slice(0,r)),a=Ii(n.slice(r+1));return{skillId:Li(i,a),categoryPath:i,skillName:a}}function zi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Bi(e,t,n){let r=K.resolve(e),i=K.resolve(r,...Fi(t).split(`/`),Ii(n));return Hi(r,i),i}function Vi(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||K.win32.isAbsolute(n)||K.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=K.resolve(e),a=K.resolve(i,...r);return Hi(i,a),a}function Hi(e,t){let n=K.resolve(e),r=K.resolve(t),i=K.relative(n,r);if(i.startsWith(`..`)||K.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ui(e){let t=ji(e),n;try{n=await G.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=Fi(e),r=Gi(t);return{path:n,name:n.split(`/`).at(-1)??n,description:r.description,createdBy:r.createdBy}}).sort((e,t)=>e.path.localeCompare(t.path))}function Wi(e){return new Map(e.map(e=>[e.path,e]))}function Gi(e){return typeof e==`string`?{description:e.trim()}:!e||typeof e!=`object`||Array.isArray(e)?{description:``}:{description:typeof e.description==`string`?e.description.trim():``,createdBy:typeof e.createdBy==`string`?e.createdBy.trim():void 0}}const Ki=32*1024,qi=new Map;function Ji(e){return new Xi(e)}async function Yi(e){let t=K.resolve(e);for(let e of Array.from(qi.keys()))e.startsWith(`${t}|`)&&qi.delete(e);await G.rm(Mi(t),{force:!0}).catch(()=>{})}var Xi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Ai(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Qi(Wi((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Fi(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>$i(e.categoryPath,t)).map(Zi)}async autoSkillSearch(e){let t=e.query.trim().toLowerCase();if(!t)return[];let n=Math.max(1,e.limit??5);return(await this.visibleEntries()).map(e=>({entry:e,score:ea(e,t)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||e.entry.skillId.localeCompare(t.entry.skillId)).slice(0,n).map(({entry:e,score:t})=>({...Zi(e),score:t}))}async autoSkillView(e){let t=Ri(e.skillId),n=(await this.visibleEntries()).find(e=>e.skillId===t.skillId);if(!n)throw Error(`Unknown auto-skill: ${e.skillId}`);if(e.filePath?.trim()){let t=Vi(n.skillDir,e.filePath),r=await la(t,this.maxResourceBytes);return{...Zi(n),status:n.status,content:r,path:fa(K.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:fa(K.relative(n.skillDir,t))}}let r=await la(n.skillFile,this.maxSkillBytes);return{...Zi(n),status:n.status,content:r,path:fa(K.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await ta(this.rootDir),i=qi.get(n);if(!e&&i&&oa(i.manifest,r))return i;let a=e?void 0:await ia(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return qi.set(n,e),e}let o=await Ui(this.rootDir),s=Wi(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return qi.set(n,c),await aa(this.rootDir,c).catch(()=>{}),c}async parseEntriesFromManifest(e){let t=e.filter(e=>e.kind===`skill`).map(e=>e.filePath),n=[];for(let e of t){let t=await this.loadEntry(e);t&&n.push(t)}return n.sort((e,t)=>e.skillId.localeCompare(t.skillId))}async visibleEntries(){let e=await this.loadIndex();return this.visibleEntriesFrom(e)}visibleEntriesFrom(e){return this.includeArchived?e:e.filter(e=>e.status===`active`)}optionsHash(){return ha({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Ki})}async loadEntry(e){try{let t=K.dirname(e),n=Ii(K.basename(t)),r=fa(K.relative(this.rootDir,t)),i=Fi(K.posix.dirname(r)),a=Li(i,n),o=K.join(t,`metadata.json`),s=await sa(o);if(s?.skillId&&Ri(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Fi(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=zi(s?.status);return{skillId:a,name:n,description:ua(await ca(e,Ki)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:da(s?.tags),relatedSkills:da(s?.relatedSkills),confidence:typeof s?.confidence==`number`?s.confidence:void 0,createdAt:typeof s?.createdAt==`string`?s.createdAt:void 0,updatedAt:typeof s?.updatedAt==`string`?s.updatedAt:void 0}}catch(t){process.stderr.write(`[auto-skills] skipped ${e}: ${pa(t)}\n`);return}}};function Zi(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Qi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function $i(e,t){return t?e===t:!0}function ea(e,t){let n=t.split(/\s+/).filter(Boolean),r=e.name.toLowerCase(),i=e.description.toLowerCase(),a=e.categoryPath.toLowerCase(),o=e.tags.join(` `).toLowerCase(),s=0;r===t&&(s+=80),r.includes(t)&&(s+=30),i.includes(t)&&(s+=20),a.includes(t)&&(s+=10),o.includes(t)&&(s+=10);for(let e of n)r.includes(e)&&(s+=8),i.includes(e)&&(s+=5),a.includes(e)&&(s+=3),o.includes(e)&&(s+=3);return s}async function ta(e){let t;try{t=await G.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await ra(K.join(e,`categories.json`),`categories`,n),await na(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function na(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=K.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await ra(t,`skill`,n),await ra(K.join(e,`metadata.json`),`metadata`,n),await ra(K.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await G.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await na(t,i,n)}}async function ra(e,t,n){try{let r=await G.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function ia(e,t,n){let r;try{r=await G.readFile(Mi(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!oa(e.manifest,n)?void 0:e}catch{return}}async function aa(e,t){if(!await ma(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await G.writeFile(Mi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function oa(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.filePath!==i.filePath||r.kind!==i.kind||r.size!==i.size||r.mtimeMs!==i.mtimeMs)return!1}return!0}async function sa(e){try{let t=await G.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function ca(e,t){let n=await G.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function la(e,t){if((await G.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return G.readFile(e,`utf-8`)}function ua(e){let t=Vt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
|
|
8
|
+
`)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function da(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function fa(e){return e.split(K.sep).join(`/`)}function pa(e){return e instanceof Error?e.message:String(e)}async function ma(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ha(e){return Ft(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function ga(e,t,n,r){return le(ue(e.apiFormat)).createModel(e,t,n,r)}const _a=`/aimax/agents`,va=/^[a-z]+(?:-[a-z]+)*$/;function ya(e){let t=[{dir:e.systemAgentsDir??_a,source:`system`},{dir:K.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:K.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function ba(e){let t=new Map;for(let n of ya(e)){let e=await wa(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function xa(e={}){let t=e.allAgents??e.availableAgents??[],n=Oa(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Ea(n,e),findAny:e=>Ea(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function Sa(e){return!!(e&&typeof e==`object`&&Array.isArray(e.allAgents)&&Array.isArray(e.availableAgents)&&typeof e.findPublic==`function`&&typeof e.findAny==`function`&&typeof e.stats==`function`)}async function Ca(e){return Sa(e.agentPolicy)?e.agentPolicy:xa({allAgents:await ba(e)})}async function wa(e,t){let n;try{n=await G.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=K.join(e,i.name),a=Ta(await G.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Ta(e,t){let n=Vt(e),r=Na(n.data.name)?.trim(),i=Na(n.data.description)?.trim();if(!r||!va.test(r)||!i)return;let a=Na(n.data.model)?.trim(),o=Na(n.data.initPrompt)?.trim()??Na(n.data.initialPrompt)?.trim(),s=Pa(n.data.maxTurns),c=Fa(n.data.tools),l=Fa(n.data.disallowedTools),u=Fa(n.data.skills),d=Ia(n.data.visibility);if(!(n.data.visibility!==void 0&&!d))return{name:r,description:i,visibility:d??`public`,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function Ea(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Da(e)===`public`))}function Da(e){return e.visibility??`public`}function Oa(e){return e.filter(e=>Da(e)===`public`)}function ka(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Aa(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(La)):void 0,r=new Set((t.disallowedTools??[]).map(La));return e.filter(e=>{let t=typeof e.name==`string`?La(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function ja(e){let t=Oa(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name exactly matches one of the listed custom agents, that mention is an explicit delegation request.","For such a matching `@<agent-name>` request, you MUST call `subagent_spawn` to run the request through that custom agent, with the `agent` field set to the exact matched agent name.","Do not answer the request yourself, do not merely describe the agent, and do not omit the tool call when a matching `@<agent-name>` is present.",`If the mention does not exactly match a listed custom agent, do not invent a match; continue with the current agent or ask a concise clarification if needed.`,t.map(e=>`- ${e.name}: ${e.description}`).join(`
|
|
9
9
|
`),``].join(`
|
|
10
|
-
`)}function
|
|
11
|
-
`).trimEnd()}return{cleanedText:r,artifacts:a,warnings:n}}function
|
|
12
|
-
`)}function Xa(e){let t=[];for(let n of e.matchAll(/(^|[^<])<<-?\s*(["']?)([A-Za-z0-9_./-]+)\2/g)){let e=n[3]?.trim();e&&t.push(e)}return t}function Za(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e)continue;let r=e.match(/\bfile\s+(?:generated|created|written|saved)\s*:\s*(.+)$/i)??e.match(/\b(?:generated|created|written|saved)\s+(?:file|to)\s*:\s*(.+)$/i),i=e.match(/文件已生成[::]\s*(.+)$/),a=r?.[1]??i?.[1];a&&t.push(po(a.trim()))}return t}function Qa(e){if(!e||typeof e!=`object`)return{content:typeof e==`string`?e:``};let t=e,n=t.details&&typeof t.details==`object`?t.details:void 0;return{content:Array.isArray(t.content)?t.content.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>typeof e.text==`string`?e.text:``).join(``):typeof e==`string`?e:``,details:n}}function $a(e,t){return e?.trim()?J.normalize(e):t}function eo(e,t){let n=fo(e?.trim()??``);return!n||n.startsWith(`-`)||n===`/dev/null`||n.startsWith(`/dev/`)||mo(n)?null:J.isAbsolute(n)?J.normalize(n):t?.trim()?J.normalize(J.join(t,n)):null}function to(e){let t=e.trim();return!t||/\s/.test(t)?null:ho(t)?new URL(t).toString():null}function no(e){let t=lo(e?.status);return t===`running`||t===`failed`||t===`killed`||t===`timeout`}function ro(e,t,n){return{kind:`file`,file:e,timestamp:t,label:n}}function io(e,t,n){return{kind:`url`,url:e,timestamp:t,label:n}}function ao(e){let t=new Set,n=[];for(let r of e){let e=r.kind===`file`?`file:${r.file}`:`url:${r.url}`;t.has(e)||(t.add(e),n.push(r))}return n}function oo(e){return J.basename(e)||`File artifact`}function so(e){try{return new URL(e).host||`URL artifact`}catch{return`URL artifact`}}function co(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function lo(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function uo(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function fo(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function po(e){return e.replace(/[),.;,。;)]+$/u,``)}function mo(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)}function ho(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}var go=class extends Error{isHitlPause=!0;constructor(e,t,n,r=!1){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.transparentPause=r,this.name=`HitlPauseSignal`}};function _o(e){return!!(e instanceof go||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const vo=new Vt;function yo(){return{}}async function bo(e,t){return await vo.run(e,t)}function xo(e){let t=vo.getStore();!t||t.signal||(t.signal=e)}function So(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function Co(e,t,n){return{temperature:t?.temperature,maxTokens:t?.maxTokens,signal:t?.signal,apiKey:n||t?.apiKey,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata}}function wo(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function To(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:wo(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:wo(e.content,`(tool image omitted: model does not support images)`)}:e)}function Eo(e,t,n){let r=new Map,i=To(e,t).map(e=>{if(e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return e.redacted?a?e:[]:a&&e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:a?e:{type:`text`,text:e.thinking};if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}};for(let e=0;e<i.length;e+=1){let t=i[e];if(t.role===`assistant`){c();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):(t.role===`user`&&c(),a.push(t))}return c(),a}function Do(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Oo(e){if(!Do(e))return null;let t=e,n=ko(t.message),r=jo(n?.code)??jo(t.code),i=jo(n?.type)??jo(t.type),a=jo(n?.message)??Ao(t.error)??jo(t.message)??`Unknown upstream error`;return{message:Mo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:No(r,i),raw:e}}function ko(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function Ao(e){if(!(!e||typeof e!=`object`))return jo(e.message)}function jo(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Mo(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function No(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}function Po(e,t=`error`){let n={};Fo(n,t,e);let r=Bo(e);return r!==void 0&&Fo(n,`${t}Cause`,r),n}function Fo(e,t,n){e[`${t}Type`]=Io(n),e[`${t}Name`]=Ro(n,`name`),e[`${t}Message`]=Lo(n),e[`${t}Code`]=zo(n,`code`),e[`${t}Status`]=zo(n,`status`),e[`${t}StatusCode`]=zo(n,`statusCode`)}function Io(e){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let t=e.constructor?.name;return typeof t==`string`&&t.length>0?t:void 0}function Lo(e){if(e instanceof Error)return Vo(e.message);if(typeof e==`string`)return Vo(e);let t=Ro(e,`message`);return t?Vo(t):void 0}function Ro(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function zo(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0||typeof n==`number`&&Number.isFinite(n)?n:void 0}function Bo(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function Vo(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const Ho=(e,t,n)=>{let r=Kt();return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0},a=0,o=!1;try{let s=Go(e,t,n?.apiKey||qt(e.provider)||``,n?.headers),c=Ko(e,t,n);n?.onPayload?.(c);let l=await s.chat.completions.create(c,{signal:n?.signal});r.push({type:`start`,partial:i}),o=!0;let u=null,d=i.content,f=()=>d.length-1,p=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:f(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:f(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=Jt(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:f(),toolCall:e,partial:i}))}};for await(let t of l){a+=1;let n=Oo(t);if(n)throw new me({message:n.message,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Wt(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=Zo(o.finish_reason)),!o.delta))continue;o.delta.content!==null&&o.delta.content!==void 0&&o.delta.content.length>0&&((!u||u.type!==`text`)&&(p(u),u={type:`text`,text:``},i.content.push(u),r.push({type:`text_start`,contentIndex:f(),partial:i})),u.text+=o.delta.content,r.push({type:`text_delta`,contentIndex:f(),delta:o.delta.content,partial:i}));let s=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=o.delta[e];return t!=null&&t.length>0});if(s){(!u||u.type!==`thinking`)&&(p(u),u={type:`thinking`,thinking:``,thinkingSignature:s},i.content.push(u),r.push({type:`thinking_start`,contentIndex:f(),partial:i}));let e=o.delta[s];u.thinking+=e,r.push({type:`thinking_delta`,contentIndex:f(),delta:e,partial:i})}if(o.delta.tool_calls)for(let e of o.delta.tool_calls){(!u||u.type!==`toolCall`||e.id&&u.id!==e.id)&&(p(u),u={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(u),r.push({type:`toolcall_start`,contentIndex:f(),partial:i})),e.id&&(u.id=e.id),e.function?.name&&(u.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,u.partialArgs+=e.function.arguments,u.arguments=Jt(u.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:i})}let c=o.delta.reasoning_details;if(c&&Array.isArray(c)){for(let e of c)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(p(u),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(t){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,...Po(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`;let s=ts(t);i.errorMessage=s.message,s instanceof me&&Object.assign(i,{errorCode:s.code,statusCode:s.statusCode,statusText:s.statusText,providerMessage:s.providerMessage,providerCode:s.providerCode,providerType:s.providerType,retryable:s.retryable});let c=t?.error?.metadata?.raw;c&&(i.errorMessage+=`\n${c}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Uo=(e,t,n)=>{let r=n?.apiKey||qt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Co(e,n,r),a=n?.reasoning?Gt(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return Ho(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function Wo(e,t,n){return Ko(e,t,n)}function Go(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};return r&&Object.assign(i,r),new Ut({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Ko(e,t,n){let r=$o(e),i=Yo(e,t,r);Jo(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=Xo(t.tools,r):qo(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning||r.thinkingFormat===`qwen`&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:r.thinkingFormat===`qwen-chat-template`&&e.reasoning?a.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0}:r.thinkingFormat===`deepseek`&&e.reasoning&&(a.thinking={type:n?.reasoningEffort?`enabled`:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function qo(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function Jo(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function Yo(e,t,n){let r=[],i=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=Eo(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:So(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:So(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:So(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>So(e.text)).join(``):a.map(e=>({type:`text`,text:So(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
10
|
+
`)}function Ma(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Na(e){return typeof e==`string`?e:void 0}function Pa(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Fa(e){let t;if(typeof e==`string`)t=e.split(`,`);else if(Array.isArray(e))t=e.filter(e=>typeof e==`string`);else return;let n=t.map(e=>e.trim()).filter(Boolean);return n.length>0?n:void 0}function Ia(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function La(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}var Ra=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};try{await this.params.onProgress?.(n)}catch(n){W.warn(`progress handler failed; event dropped`,{sessionId:e,eventType:t.type,error:n instanceof Error?n.message:String(n)})}}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const za=`<aimax_artifacts>`,Ba=`</aimax_artifacts>`;function Va(e,t={}){let n=[];if(!e.includes(za))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf(za);if(e===-1)break;let o=r.indexOf(Ba,e+17);if(o===-1){n.push(`Artifacts block is missing the closing tag; stripping the malformed block`),r=r.slice(0,e).trimEnd();break}let s=r.slice(e+17,o).trim();s&&(i??=(t.now??(()=>new Date))().toISOString(),a.push(...Ha(s,{warnings:n,timestamp:i,workspaceDir:t.workspaceDir}))),r=[r.slice(0,e).trimEnd(),r.slice(o+18).trimStart()].filter(e=>e.length>0).join(`
|
|
11
|
+
`).trimEnd()}return{cleanedText:r,artifacts:a,warnings:n}}function Ha(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=Ua(t,{index:e,warnings:n,timestamp:r,workspaceDir:i});s&&o.push(s)}return o}function Ua(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=Ga(t,a);return o?{kind:`file`,file:o,timestamp:i,label:Wa(e.label,K.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=qa(s)??`URL artifact`;return Ka(s)?{kind:`url`,url:s,timestamp:i,label:Wa(e.label,c,n,r)}:(r.push(`Artifact at index ${n}: url is invalid, skipping`),null)}function Wa(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 Ga(e,t){return K.isAbsolute(e)?K.normalize(e):t?.trim()?K.normalize(K.join(t,e)):null}function Ka(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}function qa(e){try{return new URL(e).host||void 0}catch{return}}var Ja=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(Ba);if(e===-1){let e=Ya(this.buffer,Ba);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(za);if(e!==-1){t+=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e+17),this.suppressing=!0;continue}let n=Ya(this.buffer,za);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 Ya(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 Xa(e){if(e.isError)return[];let t=(e.now??(()=>new Date))().toISOString(),n=ro(e.result),r=[];if(e.toolName===`write_file`){let i=ao(ho(n.details?.path),e.workspaceDir);return i&&r.push(co(i,t,fo(i))),uo(r)}if(e.toolName===`edit_file`){let i=go(n.details?.occurrences),a=ao(ho(n.details?.path),e.workspaceDir);return a&&i!==0&&r.push(co(a,t,fo(a))),uo(r)}if(e.toolName===`apply_patch`)return r.push(...Za(n.details,e.workspaceDir,t)),uo(r);if(e.toolName===`exec`||e.toolName===`bash`||e.toolName===`process`){if(so(n.details))return[];let i=ho(e.input?.command),a=io(ho(n.details?.cwd),e.workspaceDir);return r.push(...Qa({command:i,output:n.content,cwd:a,workspaceDir:e.workspaceDir,timestamp:t})),r}let i=oo(n.content);return i?[lo(i,t,po(i))]:[]}function Za(e,t,n){let r=e?.summary&&typeof e.summary==`object`?e.summary:void 0;return r?[...mo(r.added),...mo(r.modified)].flatMap(e=>{let r=ao(e,t);return r?[co(r,n,fo(r))]:[]}):[]}function Qa(e){let t=[],n=e.cwd??e.workspaceDir,r=r=>{let i=ao(r,n);i&&t.push(co(i,e.timestamp,fo(i)))};if(e.command)for(let t of $a(e.command))r(t);for(let t of no(e.output))r(t);let i=oo(e.output);return i&&t.push(lo(i,e.timestamp,po(i))),uo(t)}function $a(e){let t=eo(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 eo(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(...to(r))}return t.join(`
|
|
12
|
+
`)}function to(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 no(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(vo(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 io(e,t){return e?.trim()?K.normalize(e):t}function ao(e,t){let n=_o(e?.trim()??``);return!n||n.startsWith(`-`)||n===`/dev/null`||n.startsWith(`/dev/`)||yo(n)?null:K.isAbsolute(n)?K.normalize(n):t?.trim()?K.normalize(K.join(t,n)):null}function oo(e){let t=e.trim();return!t||/\s/.test(t)?null:bo(t)?new URL(t).toString():null}function so(e){let t=ho(e?.status);return t===`running`||t===`failed`||t===`killed`||t===`timeout`}function co(e,t,n){return{kind:`file`,file:e,timestamp:t,label:n}}function lo(e,t,n){return{kind:`url`,url:e,timestamp:t,label:n}}function uo(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 fo(e){return K.basename(e)||`File artifact`}function po(e){try{return new URL(e).host||`URL artifact`}catch{return`URL artifact`}}function mo(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function ho(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function go(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function _o(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function vo(e){return e.replace(/[),.;,。;)]+$/u,``)}function yo(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)}function bo(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}var xo=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 So(e){return!!(e instanceof xo||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const Co=new Ut;function wo(){return{}}async function To(e,t){return await Co.run(e,t)}function Eo(e){let t=Co.getStore();!t||t.signal||(t.signal=e)}function Do(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function Oo(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 ko(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 Ao(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:ko(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:ko(e.content,`(tool image omitted: model does not support images)`)}:e)}function jo(e,t,n){let r=new Map,i=Ao(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 Mo(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function No(e){if(!Mo(e))return null;let t=e,n=Po(t.message),r=Io(n?.code)??Io(t.code),i=Io(n?.type)??Io(t.type),a=Io(n?.message)??Fo(t.error)??Io(t.message)??`Unknown upstream error`;return{message:Lo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Ro(r,i),raw:e}}function Po(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 Fo(e){if(!(!e||typeof e!=`object`))return Io(e.message)}function Io(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Lo(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Ro(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 zo(e,t=`error`){let n={};Bo(n,t,e);let r=Go(e);return r!==void 0&&Bo(n,`${t}Cause`,r),n}function Bo(e,t,n){e[`${t}Type`]=Vo(n),e[`${t}Name`]=Uo(n,`name`),e[`${t}Message`]=Ho(n),e[`${t}Code`]=Wo(n,`code`),e[`${t}Status`]=Wo(n,`status`),e[`${t}StatusCode`]=Wo(n,`statusCode`)}function Vo(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 Ho(e){if(e instanceof Error)return Ko(e.message);if(typeof e==`string`)return Ko(e);let t=Uo(e,`message`);return t?Ko(t):void 0}function Uo(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 Wo(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 Go(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function Ko(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const qo=(e,t,n)=>{let r=Jt();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=Xo(e,t,n?.apiKey||Yt(e.provider)||``,n?.headers),c=Zo(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=Xt(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=No(t);if(n)throw new ge({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}},Kt(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=ns(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=Xt(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){W.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,...zo(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`;let s=os(t);i.errorMessage=s.message,s instanceof ge&&Object.assign(i,{errorCode:s.code,statusCode:s.statusCode,statusText:s.statusText,providerMessage:s.providerMessage,providerCode:s.providerCode,providerType:s.providerType,retryable:s.retryable});let c=t?.error?.metadata?.raw;c&&(i.errorMessage+=`\n${c}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Jo=(e,t,n)=>{let r=n?.apiKey||Yt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Oo(e,n,r),a=n?.reasoning?qt(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return qo(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function Yo(e,t,n){return Zo(e,t,n)}function Xo(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 Gt({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Zo(e,t,n){let r=is(e),i=es(e,t,r);$o(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=ts(t.tools,r):Qo(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning||r.thinkingFormat===`qwen`&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:r.thinkingFormat===`qwen-chat-template`&&e.reasoning?a.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0}:r.thinkingFormat===`deepseek`&&e.reasoning&&(a.thinking={type:n?.reasoningEffort?`enabled`:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function Qo(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function $o(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 es(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=jo(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Do(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:Do(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Do(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=>Do(e.text)).join(``):a.map(e=>({type:`text`,text:Do(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
13
13
|
|
|
14
14
|
`);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
|
|
15
15
|
`))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
16
|
-
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:
|
|
17
|
-
`):e.content;return
|
|
18
|
-
`)}const
|
|
19
|
-
`);async function
|
|
20
|
-
`):n.content;r=`Tool(${n.toolName})[${e}]: ${
|
|
21
|
-
`)}function
|
|
22
|
-
`)}function
|
|
23
|
-
`);const
|
|
24
|
-
`),
|
|
25
|
-
`);async function
|
|
16
|
+
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:Do(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function ts(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function ns(e){if(e===null)return`stop`;switch(e){case`stop`:return`stop`;case`length`:return`length`;case`function_call`:case`tool_calls`:return`toolUse`;case`error`:case`content_filter`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function rs(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`deepseek`||n.includes(`deepseek.com`),a=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||i||r||t===`opencode`||n.includes(`opencode.ai`),o=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),s=t===`xai`||n.includes(`api.x.ai`),c=t===`mistral`||n.includes(`mistral.ai`),l=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!a,supportsDeveloperRole:!a,supportsReasoningEffort:!s&&!r,supportsUsageInStreaming:!0,maxTokensField:o?`max_tokens`:`max_completion_tokens`,requiresToolResultName:c,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:c,requiresReasoningContentOnAssistantMessages:i,thinkingFormat:i?`deepseek`:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!0,cacheControlFormat:l,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!0}}function is(e){let t=rs(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}const as=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function os(e){return e instanceof Error?!(e instanceof ge)&&!ss(e)&&cs(e)?new ge({message:`LLM network request failed: ${e.message}`,code:`network_error`,retryable:!0,cause:e}):e:cs(e)?new ge({message:`LLM network request failed: ${String(e)}`,code:`network_error`,retryable:!0,cause:e}):Error(typeof e==`string`?e:JSON.stringify(e))}function ss(e){return e instanceof Error&&e.name===`AbortError`?!0:(e&&typeof e==`object`?e.code:void 0)===`aborted`}function cs(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=n&&typeof n==`object`?n.code:void 0;if(typeof e==`string`&&as.has(e.toLowerCase()))return!0;let r=typeof n==`string`?n:n&&typeof n==`object`?n.message:void 0;if(typeof r==`string`&&r.trim().toLowerCase()===`terminated`)return!0;n=n&&typeof n==`object`?n.cause:void 0}return!1}const ls=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),us=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),ds=[`llmrequesterror`],fs=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function ps(e){let t=_s(e?.maxAttempts,3),n=vs(e?.initialDelayMs,250),r=vs(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function ms(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function hs(e,t){if(!(e<=0)){if(t?.aborted)throw Error(`aborted`);await new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`aborted`))},{once:!0})})}}function gs(e){if(xs(e))return!1;let t=ys(e),n=bs(e),r=t?.message??n;if(js(r))return!0;if(t?.statusCode!==void 0)return Os(t.statusCode);if(t?.providerCode!==void 0)return Ds(t.providerCode);let i=ks(r);if(i!==void 0)return Os(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(ls.has(e))return!0;if(us.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;if(Ss(e))return!0;let a=As(r);return a===void 0?t?.retryable===!0:a}function _s(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function vs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function ys(e){if(!e||typeof e!=`object`)return null;let t=e;return t.retryable===void 0&&t.statusCode===void 0&&t.code===void 0&&t.providerCode===void 0&&t.providerType===void 0?null:{message:typeof t.message==`string`?t.message:void 0,code:t.code,statusCode:t.statusCode,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable}}function bs(e){if(typeof e==`string`)return e;if(e instanceof Error&&typeof e.message==`string`||e&&typeof e==`object`&&typeof e.message==`string`)return e.message}function xs(e){return ys(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Ss(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=Cs(n);if(e!==void 0&&fs.has(e.toLowerCase()))return!0;let r=ws(n);if(r!==void 0&&Ts(r))return!0;n=Es(n)}return!1}function Cs(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`&&t.length>0?t:void 0}function ws(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return;let t=e.message;return typeof t==`string`?t:void 0}function Ts(e){return e.trim().toLowerCase()===`terminated`}function Es(e){if(!(!e||typeof e!=`object`))return e.cause}function Ds(e){return/^\d+$/.test(e)?Os(Number(e)):!1}function Os(e){return e===408||e===409||e===425||e===429||e>=500}function ks(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function As(e){if(!e)return;let t=Ms(e);for(let e of us)if(t.includes(e))return!1;for(let e of ls)if(t.includes(e))return!0}function js(e){if(!e)return!1;let t=Ms(e);return ds.some(e=>t.includes(e))}function Ms(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const Ns=Symbol(`omit-json-value`);function Ps(e,t=new WeakSet){if(e===void 0)return Ns;if(typeof e==`bigint`)return e.toString();if(typeof e==`function`)return`[Function]`;if(typeof e==`symbol`)return`[Symbol]`;if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=Ps(r,t);e!==Ns&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=Ps(i,t);e!==Ns&&(n[r]=e)}return n}finally{t.delete(e)}}function Fs(e,t,n){return K.join(K.dirname(C(e,t,n)),`session-tools.json`)}function Is(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:Ps(e.parameters??{})}))}async function Ls(e,t,n){let r=await o(Fs(e,t,n));if(!r?.trim())return null;try{let e=JSON.parse(r);if(e.version!==1||!Array.isArray(e.tools))return null;let t=e.tools.filter(e=>!!(e&&typeof e.name==`string`)).map(e=>({name:e.name,description:typeof e.description==`string`?e.description:``,parameters:e.parameters??{}}));return{version:1,recordedAt:typeof e.recordedAt==`string`?e.recordedAt:new Date(0).toISOString(),tools:t}}catch{return null}}async function Rs(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:Is(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([L(C(e,t,r),n.systemPrompt,r?.encryptSessions),L(Fs(e,t,r),a,r?.encryptSessions)])}async function zs(e,t,n){let[r,i]=await Promise.all([g(e,t,n),Ls(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function Bs(e){return Math.ceil(e.length/4*1.2)}function Vs(e){if(e.role===`user`)return Bs(e.content);if(e.role===`assistant`){let t=Bs(e.content),n=e.thinking?.trim();n&&(t+=Bs(n)),e.errorMessage&&(t+=Bs(e.errorMessage));for(let n of e.toolCalls??[])t+=Bs(n.name)+Bs(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
|
|
17
|
+
`):e.content;return Bs(e.toolName)+Bs(t)}function J(e){return e.reduce((e,t)=>e+Vs(t),0)}function Hs(e,t){if(!t||t<=0||e.length===0)return e;let n=0,r=e.length;for(let i=e.length-1;i>=0;i--)if(e[i].role===`user`){if(n++,n>t)return e.slice(r);r=i}return e}function Us(e){let t=new Set;for(let n of e)if(n.role===`assistant`)for(let e of n.toolCalls??[])t.add(e.id);let n=e.filter(e=>e.role!==`tool_result`||t.has(e.toolCallId));return n.length===e.length?e:n}const Ws=[`If you need content beyond this preview, do not load the full output into the parent context.`,`Use subagent_spawn to inspect the Full output file and return only a concise, query-focused summary.`,`Pass the Full output path, note that it is relative to dataDir when not absolute, and include the current question or search target in the subagent task.`],Gs={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Ks(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function qs(e,t,n){return e.map(e=>Js(e,t,n))}function Js(e,t,n){let r=new Date(e.timestamp).getTime();if(Ys(e))return{role:`user`,content:e.content,timestamp:r};if(Xs(e)){let i=[],a=e.thinking?.trim();n?.replayThinking&&a&&i.push({type:`thinking`,thinking:a,...n.thinkingSignature?{thinkingSignature:n.thinkingSignature}:{}}),e.content&&i.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])i.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:i,api:t.api,provider:`openai`,model:t.model,usage:Gs,stopReason:e.stopReason??`stop`,errorMessage:e.errorMessage,timestamp:r}}let i=e;return{role:`toolResult`,toolCallId:i.toolCallId,toolName:i.toolName,content:[{type:`text`,text:Zs(i)}],isError:i.isError,timestamp:r}}function Ys(e){return e.role===`user`}function Xs(e){return e.role===`assistant`}function Zs(e){if(!e.toolResultRef)return e.content;let t=e.toolResultRef.preview.trimEnd(),n=[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,`Instruction:`,...Ws];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
|
|
18
|
+
`)}const Qs=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,"- Any unfinished plan submitted through `update_task`, especially pending and in_progress tasks, current progress, and necessary constraints.",`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
|
|
19
|
+
`);async function $s(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=tc(t,r,i,a),u=nc(a),d,f=ce({apiFormat:n.apiFormat,baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:s,hookCtx:c});for(let e=1;e<=3;e++)try{let e=(await f.chat({system:Qs,user:l,temperature:0,maxTokens:u,signal:o})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;d=t,e<3&&await ec(500*e)}throw d}function ec(e){return new Promise(t=>setTimeout(t,e))}function tc(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${oc(t.trim(),rc(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=ic(e,t,n,r),o=ac(t,n,r);for(let[t,n]of e.entries()){if(o<=0){i.push(`[${e.length-t} entries omitted because the summarisation input budget was exhausted]`);break}let r=``;if(n.role===`user`)r=`User: ${oc(n.content,Math.min(a,o))}`;else if(n.role===`assistant`)r=`Assistant:${n.toolCalls&&n.toolCalls.length>0?` [called tools: ${n.toolCalls.map(e=>e.name).join(`, `)}]`:``} ${oc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?sc(n):n.toolResultRef?[`[tool result persisted] ${n.toolResultRef.toolName} (${n.toolResultRef.originalChars} chars).`,`Full output: ${n.toolResultRef.storagePath}`,n.toolResultRef.preview.trim()?`Preview:\n${n.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
|
|
20
|
+
`):n.content;r=`Tool(${n.toolName})[${e}]: ${oc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
|
|
21
|
+
`)}function nc(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function rc(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function ic(e,t,n,r){let i=ac(t,n,r);if(!r||r<=0)return 2e3;let a=nc(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=Qs.length+(t?.length??0)+(n?.length??0)+1e3,c=Math.max(1e3,o*4-s);return Math.max(120,Math.min(2e3,i,Math.floor(c/Math.max(1,e.length))))}function ac(e,t,n){if(!n||n<=0)return 1/0;let r=nc(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=Qs.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function oc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function sc(e){let t=cc(e),n=t.name??`<skill-name>`,r=t.path,i=r?`skill_load(name="${n}", skillPath="${r}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,r?`Original path: ${r}`:``,`If this skill is needed later, call ${i} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].filter(Boolean).join(`
|
|
22
|
+
`)}function cc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=lc(t);if(e.name||e.path)return e}return{}}function lc(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function uc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Vs(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function dc(e){return pc((await ce({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:gc,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.segments},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}async function fc(e){return mc((await ce({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:_c,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedTurns:e.maxSelectedTurns,turns:e.turns},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}function pc(e){let t=hc(e);if(t.version!==1||!Array.isArray(t.selectedSegmentIds))throw Error(`Topic segment selection decision has invalid schema.`);return{version:1,selectedSegmentIds:t.selectedSegmentIds.filter(e=>typeof e==`string`),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function mc(e){let t=hc(e);if(t.version!==1||!Array.isArray(t.selectedTurns))throw Error(`Topic turn selection decision has invalid schema.`);return{version:1,selectedTurns:t.selectedTurns.filter(e=>!!(e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:typeof e.topicLabel==`string`?e.topicLabel.trim():void 0,keywords:Array.isArray(e.keywords)?e.keywords.filter(e=>typeof e==`string`&&e.trim().length>0):void 0})),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function hc(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
|
|
23
|
+
`);const gc=[`You select relevant conversation segments for an IM assistant before final turn-level topic classification.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedSegmentIds":["..."],"reason":"...","confidence":"high|medium|low"}`,`Task: choose which prior segments are relevant to the current user message.`,`Relevant includes same task continuation, explicit topic return, reuse of prior artifact, correction, or combining multiple earlier topics.`,`Prefer recall over over-pruning when the user explicitly refers to older topics by name.`,`Do not answer the user.`].join(`
|
|
24
|
+
`),_c=[`You select relevant historical conversation turns for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurns":[{"turnId":"...","summary":"...","topicLabel":"optional","keywords":["..."]}],"reason":"...","confidence":"high|medium|low"}`,`Task: from the provided turns, select any turn that may be relevant to the current user message.`,`This is recall-first. It is better to include possibly relevant turns than to miss a relevant one.`,`Select turns for same task continuation, explicit old-topic return, reuse of prior artifact, corrections, or combinations of multiple earlier topics.`,`For every selected turn, provide a concise reusable summary, an optional topicLabel, and short keywords.`,`Prefer the provided summary/topicLabel fields when they exist; use raw user/assistant content only when needed.`,`Do not answer the user.`].join(`
|
|
25
|
+
`);async function vc(e){let t=Cc(e);if(t)try{let e=await G.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(zc);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function yc(e){let t=Cc(e);t&&(await G.mkdir(K.dirname(t),{recursive:!0}),await G.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function bc(e){let t=wc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||Tc(t,e)){r.push(e);continue}n.push(Dc(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(Dc(r,n.length+1,!0)),n}function xc(e,t){let n=wc(t);if(n.length===0)return[];if(!e||e.length===0)return bc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return bc(t);if(r.length===n.length)return e;let a=e.map(e=>({...e,turnIds:[...e.turnIds],toolNames:[...e.toolNames],keywords:[...e.keywords]})),o=n.slice(r.length);for(let e of o){let t=a[a.length-1];if(t&&Ec(t,e)){a[a.length-1]=Mc(t,e);continue}t&&(t.status=`closed`),a.push(Dc([e],a.length+1,!0))}if(a.length>1){for(let e=0;e<a.length-1;e+=1)a[e]={...a[e],status:`closed`};a[a.length-1]={...a[a.length-1],status:`active`}}return a}function Sc(e,t){if(!e||e.length===0||t.length===0)return e??[];let n=new Map(t.map(e=>[e.turnId,e])),r=!1,i=e.map(e=>{let t=new Map((e.turnMemories??[]).map(e=>[e.turnId,e])),i=!1;for(let r of e.turnIds){let e=n.get(r);if(!e)continue;let a=t.get(r);(!a||a.summary!==e.summary||a.topicLabel!==e.topicLabel||a.keywords.join(`|`)!==e.keywords.join(`|`))&&(t.set(r,e),i=!0)}if(!i)return e;r=!0;let a=[...t.values()].sort((e,t)=>e.turnId.localeCompare(t.turnId)),o=a.find(t=>e.turnIds.includes(t.turnId)),s=[...new Set([...e.keywords,...a.flatMap(e=>e.keywords)])];return{...e,keywords:s,topicLabel:o?.topicLabel??e.topicLabel,turnMemories:a,updatedAt:o?.updatedAt??e.updatedAt}});return r?i:e}function Cc(e){if(!(!e.dataDir||!e.sessionId))return K.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function wc(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,user:a.content,timestamp:a.timestamp,toolNames:[]};continue}if(n){if(n.endIndex=i,a.role===`assistant`){let e=(a.content||a.errorMessage||``).trim();e&&(n.assistant=e);for(let e of a.toolCalls??[])n.toolNames.push(e.name);continue}a.role===`tool_result`&&n.toolNames.push(a.toolName)}}return r(),t.map(e=>({...e,toolNames:[...new Set(e.toolNames)].sort()}))}function Tc(e,t){return Fc(Pc(e.user,e.assistant),Pc(t.user,t.assistant))>0}function Ec(e,t){return Fc(Pc(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),Pc(t.user,t.assistant,t.toolNames.join(` `)))>0}function Dc(e,t,n){return Oc(e,t,n)}function Oc(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=kc(e,o),c=Rc(r?.summary||s),l=Nc(r?.keywords,c,o),u=Rc(r?.compressedSummary||jc(c,o));return{version:1,segmentId:`segment-${t}`,turnIds:e.map(e=>e.turnId),startTurnId:i.turnId,endTurnId:a.turnId,startIndex:i.startIndex,endIndex:a.endIndex,userSummary:e.map(e=>e.user).join(`
|
|
26
26
|
`),assistantSummary:e.map(e=>e.assistant).filter(Boolean).join(`
|
|
27
|
-
`)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function
|
|
28
|
-
`)||void 0,o=Tc(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Nc(n?.summary||o),compressedSummary:Nc(n?.compressedSummary||Ec(n?.summary||o,r)),keywords:Oc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Oc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:jc(t,n)}function kc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||n.length>64||/^(.)\1{15,}$/u.test(n)||t.add(n)}return t}function Ac(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function jc(e,t){let n=new Set([`the`,`and`,`for`,`with`,`this`,`that`,`from`,`user`,`intents`,`outcomes`,`tools`,`prior`,`segment`,`relevant`,`继续`,`刚才`,`这个`]),r=new Map;for(let i of kc(e,t.join(` `)))n.has(i)||r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e])=>e)}function Mc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Nc(e){return e.replace(/\s+/g,` `).trim()}function Pc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.segmentId==`string`&&Array.isArray(t.turnIds)&&typeof t.startTurnId==`string`&&typeof t.endTurnId==`string`&&typeof t.startIndex==`number`&&typeof t.endIndex==`number`&&typeof t.userSummary==`string`&&typeof t.summary==`string`&&typeof t.compressedSummary==`string`&&Array.isArray(t.keywords)&&Array.isArray(t.toolNames)&&(t.turnMemories===void 0||Array.isArray(t.turnMemories)&&t.turnMemories.every(e=>!!e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`&&Array.isArray(e.keywords)&&typeof e.updatedAt==`string`))&&(t.status===`active`||t.status===`closed`)&&typeof t.updatedAt==`string`}function Fc(e){let t=zc(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Bc(t,n,r,e.segments.length,e.vectorScores)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.segment.startIndex-e.segment.startIndex:t.score-e.score:e.forced?-1:1).slice(0,e.maxSegments)}function Ic(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Lc(e){let t=new Set(e.selectedTurnIds),n=new Set(e.recentProtectedTurnIds),r=[];for(let i of e.segments){let a=i.turnIds.some(e=>t.has(e)),o=i.turnIds.some(e=>n.has(e));!a||o||i.status!==`closed`||r.push({role:`assistant`,content:Rc(i.compressedSummary),timestamp:e.timestamp})}return r}function Rc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function zc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Bc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=zc(t.summary,t.compressedSummary,t.keywords.join(` `),t.topicLabel,a),s=0;for(let t of e)o.has(t)&&(s+=1);let c=Math.max(0,i?.get(t.segmentId)??0),l=(n+1)/Math.max(r,1);return c*30+s*10+l}const Vc=`Xenova/bge-small-zh-v1.5`;let Hc,Uc;const Wc=new Map;async function Gc(e,t){if(e.length===0)return K.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=Xc(t),i=r.path;K.info(`topic segmentation embedding started`,{provider:`transformers`,model:Vc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await Jc({embeddingModelDir:i}),a=[],o=0,s=0;for(let n of e){let e=n.trim();if(!e){a.push([]),s+=1;continue}let r=`${i}\0${e}`,c=Wc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Wc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return K.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Vc,textCount:e.length,embeddedCount:a.filter(e=>e.length>0).length,emptyTextCount:s,cacheHitCount:o,dims:c?.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n}),a}catch(t){throw K.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Vc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Kc(e,t){let[n]=await Gc([e],t);return n??[]}function qc(){return Vc}async function Jc(e){let t=Xc(e).path;return(!Hc||Uc!==t)&&(Uc=t,Hc=Yc(t)),Hc}async function Yc(e){let t=Date.now();K.info(`topic segmentation embedding extractor load started`,{model:Vc,modelDir:e,allowRemoteModels:!1});try{let{env:n,pipeline:r}=await import(`@huggingface/transformers`);n.allowRemoteModels=!1,n.localModelPath=e;let i=await r(`feature-extraction`,Vc,{dtype:`q8`});return K.info(`topic segmentation embedding extractor load completed`,{model:Vc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw K.warn(`topic segmentation embedding extractor load failed`,{model:Vc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function Xc(e){let t=e?.embeddingModelDir?.trim();if(t)return{path:t,source:`config`};let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return{path:n,source:`env`};let r=J.dirname(Qt(import.meta.url)),i=J.resolve(r,`../../../../../model`);if(Ht.existsSync(i))return{path:i,source:`repo_candidate`};let a=J.resolve(process.cwd(),`model`);return Ht.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const Zc=`topic_segments_vec`,Qc=`topic_segments_meta`,$c=`topic_segment_embedding_cache`;async function el(e){let t=Date.now(),n=nl(e);if(!n){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=Ge(n,{allowExtension:!0});try{let i=await il(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 ${Qc}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=qc(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=He(rl(e));return o.get(e.segmentId)!==t});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 Gc(l.map(e=>rl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=rl(t),n=He(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:ll(r,t.segmentId);sl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(cl(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(ol(r,i,o.length),r.prepare(`DELETE FROM ${Zc} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${Zc} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,hl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${Zc} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${Qc} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${$c} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${Zc} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),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 tl(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=nl(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 fl(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=Ge(n,{allowExtension:!0});try{let a=await il(i),o=qc(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?ul(i,o,r,e.limit):dl(i,o,r,e.limit);return 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 nl(e){if(!(!e.dataDir||!e.sessionId))return J.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function rl(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
|
|
29
|
-
`)}async function il(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${Qc} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${$c} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Qc}_hash ON ${Qc}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${$c}_hash ON ${$c}(content_hash)`),{vectorAvailable:(await Be({db:e})).ok,vectorDims:al(e)}}function al(e){let t=e.prepare(`SELECT dims FROM ${$c} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function ol(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${Zc}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${Zc} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function sl(e,t){e.prepare(`INSERT INTO ${Qc} (\n segment_id, version, content_text, content_hash, embedding_model, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n version = excluded.version,\n content_text = excluded.content_text,\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n updated_at = excluded.updated_at`).run(t.segment.segmentId,1,t.contentText,t.contentHash,t.embeddingModel,t.segment.updatedAt)}function cl(e,t){e.prepare(`INSERT INTO ${$c} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function ll(e,t){let n=e.prepare(`SELECT embedding FROM ${$c} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function ul(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${Zc} v\n JOIN ${Qc} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(hl(n),t,hl(n),r)}function dl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${$c} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:ml(n,pl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function fl(e,t){try{return await Kc(e,t)}catch(e){return 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 pl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function ml(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function hl(e){return Buffer.from(new Float32Array(e).buffer)}const gl=8e3,_l=new Map;function vl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:Pl(e?.embeddingModelDir),minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxShortlistCandidates:e?.maxShortlistCandidates??12,maxShortlistSegments:e?.maxShortlistSegments??6,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function yl(e){let t=Tl(e.entries),n=new Map(e.candidates.map(e=>[e.turnId,e])),r=new Set(e.decision.selectedTurnIds),i=e.recentProtectedTurnCount>0?t.slice(-e.recentProtectedTurnCount):[],a=i.map(e=>e.turnId);for(let e of i)r.add(e.turnId);let o=new Set;if(e.useCompressedSegmentMemory!==!1&&e.segmentRecords)for(let t of e.segmentRecords){let e=t.turnIds.some(e=>r.has(e)),n=t.turnIds.some(e=>a.includes(e));if(!(!e||n||t.status!==`closed`))for(let e of t.turnIds)o.add(e)}let s=[],c=[],l=[],u=[];for(let e of t){if(!r.has(e.turnId)){l.push(e.turnId),u.push(kl(e,n.get(e.turnId)));continue}s.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),!o.has(e.turnId)&&c.push(...e.entries)}return{entries:[...e.useCompressedSegmentMemory!==!1&&e.segmentRecords?Lc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function bl(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Fl(e.currentUserMessage),n=new Set(e.recentProtectedTurnCount>0?e.candidates.slice(-e.recentProtectedTurnCount).map(e=>e.turnId):[]);return e.candidates.map((r,i)=>({candidate:r,index:i,forced:n.has(r.turnId),score:Ll(t,r,i,e.candidates.length)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.index-e.index:t.score-e.score:e.forced?-1:1).slice(0,e.maxShortlist).map(e=>e.candidate).sort((e,t)=>e.startIndex-t.startIndex)}async function xl(e){let t=vl(e.config),n=()=>Bl({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){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=Tl(e.entries),i=Z(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=>El(e,t)),o=e.llm.flashModel||e.llm.model,s=await Sl({entries:e.entries,candidates:a,pendingUserMessage:e.pendingUserMessage,config:t,llm:{apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o,timeoutMs:t.timeoutMs,maxTokens:t.maxTokens},dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:t.embeddingModelDir,signal:e.signal}),c=s.segmentRecords,l=new Set(a.map(e=>e.turnId)),u=new Date().toISOString(),d=Date.now();K.info(`topic segmentation classify started`,Bl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Ol({currentUserMessage:e.pendingUserMessage,allCandidates:a,shortlistedCandidates:s.candidates,selectedSegmentIds:s.selectedSegmentIds,supplementalTurnIds:s.supplementalTurnIds,segmentRecords:c,recentProtectedTurnCount:t.recentProtectedTurnCount,maxSelectedTurns:t.maxSelectedTurns}),p=f.selectedTurnIds.filter(e=>!l.has(e));if(p.length>0)throw Error(`Local topic segmentation returned unknown turn ids: ${p.join(`, `)}`);let m=Date.now()-d,h=yl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Dl({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:Z(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await jl(e,g),K.info(`topic segmentation classify succeeded`,{...Bl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}),durationMs:m,selectedTurnCount:f.selectedTurnIds.length,confidence:f.confidence,tokenEstimateAfter:g.tokenEstimate?.after,droppedTurnCount:h.droppedTurnIds.length,droppedTurnPreviews:h.droppedTurns.length>0?JSON.stringify(h.droppedTurns):void 0}),{entries:h.entries,audit:g}}async function Sl(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await Cl({entries:e.entries,llm:e.llm,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,signal:e.signal}),n=e.config.recentProtectedTurnCount>0?e.candidates.slice(-e.config.recentProtectedTurnCount).map(e=>e.turnId):[],r=Date.now(),i=[],a=e.candidates,o=t,s=[],c=[];if(t){let o=await tl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,query:e.pendingUserMessage,limit:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2)}),l=Fc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=Hl(l,e.config.maxShortlistSegments),d=wl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:gl});if(d&&Jl({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await Zl({currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,retrieved:l,llm:{...e.llm,timeoutMs:d},maxSelectedSegments:e.config.maxShortlistSegments,signal:e.signal});t.length>0&&(u=t)}s=u,i=u.map(e=>e.segment.segmentId),a=Ic({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Ul({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:gl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await mc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),Ql({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=ql(a,l.selectedCandidates),d=bl({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function Cl(e){K.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await pc(e);if(!t){let t=hc(e.entries);if(t.length===0){K.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await mc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),Ql({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),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=gc(t,e.entries);return n.length>0&&(await mc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),Ql({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),K.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function wl(e){let t=Math.max(0,(e.nowMs??Date.now())-e.budgetStartedAtMs),n=Math.max(0,e.budgetMs-t);if(!(n<=0))return Math.min(e.requestTimeoutMs,n)}function Tl(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,entries:[a],user:a.content,timestamp:a.timestamp};continue}n&&(n.entries.push(a),n.endIndex=i)}return r(),t}function El(e,t){let n=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim()),r=new Set,i=!1;for(let t of e.entries){if(t.role===`assistant`){for(let e of t.toolCalls??[])r.add(e.name);t.stopReason===`error`&&(i=!0);continue}zl(t)&&(r.add(t.toolName),t.isError&&(i=!0))}return{turnId:e.turnId,startIndex:e.startIndex,endIndex:n?e.entries.indexOf(n)+e.startIndex:e.endIndex,user:Ml(e.user,t.maxCandidateUserChars),assistant:n?Ml((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Dl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:Ml(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,shortlistCount:e.shortlistedCandidates.candidates.length,selectedSegmentIds:e.selectedSegmentIds,selectedTurnIds:e.decision.selectedTurnIds,selectedRanges:e.projected.selectedRanges,forcedKeep:{recentTurnIds:e.projected.recentTurnIds},droppedTurnIds:e.projected.droppedTurnIds,droppedTurns:e.projected.droppedTurns,confidence:e.decision.confidence,reason:e.decision.reason,tokenEstimate:{before:e.tokenEstimateBefore,after:e.tokenEstimateAfter}}}function Ol(e){let t=new Set(e.allCandidates.map(e=>e.turnId)),n=new Set;if(e.segmentRecords&&e.selectedSegmentIds.length>0){let r=e.segmentRecords.filter(t=>e.selectedSegmentIds.includes(t.segmentId));for(let e of r)for(let r of e.turnIds)t.has(r)&&n.add(r)}for(let r of e.supplementalTurnIds)t.has(r)&&n.add(r);if(n.size===0){let t=Fl(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Ll(t,n,r,e.shortlistedCandidates.length)})).sort((e,t)=>t.score-e.score),i=r[0]?.score??0,a=Math.max(8,i>=8?i*.7:1/0);for(let t of r)if(!(t.score<a)&&(n.add(t.candidate.turnId),n.size>=e.maxSelectedTurns))break}return{version:1,selectedTurnIds:[...n].slice(0,e.maxSelectedTurns),reason:e.selectedSegmentIds.length>0||e.supplementalTurnIds.length>0?`local segment retrieval matched prior segments`:`local candidate scoring matched recent turns`,confidence:`high`}}function kl(e,t){let n=t?.assistant??Al(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Nl(t?.user??e.user,50),assistantPreview:n?Nl(n,50):void 0}}function Al(e){let t=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim());return t?(t.content||t.errorMessage||``).trim():void 0}async function jl(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await q.mkdir(n,{recursive:!0}),await q.appendFile(J.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function Ml(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Nl(e,t){return[...e].slice(0,t).join(``)}function Pl(e){return e?.trim()||void 0}function Fl(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Il(e){return[...Fl(e)].slice(0,8)}function Ll(e,t,n,r){let i=Rl(e,Fl(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Rl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function zl(e){return e.role===`tool_result`}function Bl(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Vl(e.params.llm.baseUrl),timeoutMs:e.config.timeoutMs,maxTokens:e.config.maxTokens,hasEmbeddingModelDir:!!e.config.embeddingModelDir,embeddingModelDir:e.config.embeddingModelDir,minUserTurns:e.config.minUserTurns,minEstimatedTokens:e.config.minEstimatedTokens,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxCandidates:e.config.maxCandidates,maxSelectedTurns:e.config.maxSelectedTurns,transcriptEntryCount:e.params.fullTranscript.length,workingEntryCount:e.params.entries.length,pendingUserMessageChars:e.params.pendingUserMessage?.length,candidateCount:e.candidates?.length,shortlistCount:e.shortlistedCandidates?.length,tokenEstimateBefore:e.tokenEstimateBefore,extraPromptChars:e.extraPromptChars}}function Vl(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function Hl(e,t){if(e.length===0)return[];let n=e.slice().sort((e,t)=>t.score-e.score),r=n[0]?.score??0,i=Math.max(8,r>=8?r*.7:1/0);return n.filter(e=>e.forced||e.score>=i).slice(0,t)}async function Ul(e){if(!Wl(e))return{selectedCandidates:[],selectedTurnIds:[]};let t=new Set(e.segmentFilteredCandidates.map(e=>e.turnId)),n=new Set(e.recentProtectedTurnIds),r=e.allCandidates.filter(e=>!t.has(e.turnId)&&!n.has(e.turnId));if(r.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let i=Gl(Kl(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=wl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await sc({currentUserMessage:e.currentUserMessage,turns:i,maxSelectedTurns:e.config.maxSelectedTurns,recentProtectedTurnIds:e.recentProtectedTurnIds,llm:{...e.llm,timeoutMs:a},signal:e.signal}),n=[...new Set(t.selectedTurns.map(e=>e.turnId))].filter(e=>r.some(t=>t.turnId===e));if(n.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let o=r.filter(e=>n.includes(e.turnId)),s=t.selectedTurns.filter(e=>n.includes(e.turnId)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:e.topicLabel?.trim()||void 0,keywords:(e.keywords??Il(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?_c(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Wl(e){let t=e.selectedSegments.filter(e=>!e.forced);return Yl(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:Xl(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Gl(e,t){let n=new Map;for(let e of t??[])for(let t of e.turnIds)n.set(t,e);return e.map(e=>{let t=n.get(e.turnId),r=t?.turnMemories?.find(t=>t.turnId===e.turnId);return{turnId:e.turnId,user:e.user,assistant:e.assistant,toolNames:e.toolNames,hasErrors:e.hasErrors,summary:r?.summary??t?.summary,topicLabel:r?.topicLabel??t?.topicLabel,keywords:r?.keywords??t?.keywords}})}function Kl(e,t,n){let r=Math.max(n.length,1),i=Fl(t);return e.map(e=>({candidate:e,score:Ll(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function ql(...e){let t=new Map;for(let n of e)for(let e of n)t.has(e.turnId)||t.set(e.turnId,e);return[...t.values()].sort((e,t)=>e.startIndex-t.startIndex)}function Jl(e){if(e.retrieved.length<2||!Yl(e.currentUserMessage))return!1;let t=new Set(e.selected.map(e=>e.segment.segmentId));if(e.selected.filter(e=>!e.forced).length>=2||e.retrieved.filter(e=>!e.forced).length<2)return!1;let n=new Set(e.selected.flatMap(e=>e.segment.turnIds));return e.recentProtectedTurnIds.length>0&&[...n].every(t=>e.recentProtectedTurnIds.includes(t))||t.size<2}function Yl(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function Xl(e){let t=e.toLowerCase();return/(回到|刚才|前面|之前|上次|那个|前一个|最早|继续刚才)/u.test(t)?!0:/\b(back to|earlier|previous|that earlier|the earlier)\b/i.test(t)}async function Zl(e){try{let t=await oc({currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.retrieved.map(e=>({segmentId:e.segment.segmentId,turnIds:e.segment.turnIds,summary:e.segment.summary,compressedSummary:e.segment.compressedSummary,keywords:e.segment.keywords,toolNames:e.segment.toolNames,topicLabel:e.segment.topicLabel})),llm:e.llm,signal:e.signal}),n=new Set(t.selectedSegmentIds);return n.size===0?[]:e.retrieved.filter(e=>n.has(e.segment.segmentId))}catch{return[]}}function Ql(e){let t=$l(e);if(!t||_l.has(t)){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=el(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(()=>{_l.delete(t)});_l.set(t,n)}function $l(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
|
|
30
|
-
`);const
|
|
31
|
-
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...
|
|
32
|
-
`)}function
|
|
33
|
-
`),r=n>t*.5?n:t;return e.slice(0,r)}async function
|
|
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}),
|
|
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}),
|
|
27
|
+
`)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function kc(e,t){return Ac(e.map(e=>e.user.trim()).filter(Boolean).slice(0,2).join(` / `),e.map(e=>e.assistant?.trim()).filter(Boolean).slice(-2).join(` / `)||void 0,t)}function Ac(e,t,n){let r=Lc(e,220),i=t?Lc(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return Rc(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function jc(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return Rc(`Relevant prior segment: ${Lc(e,280)}${n}`)}function Mc(e,t,n){let r=[...new Set([...e.toolNames,...t.toolNames])].sort(),i=`${e.userSummary}\n${t.user}`.trim(),a=[e.assistantSummary,t.assistant].filter(Boolean).join(`
|
|
28
|
+
`)||void 0,o=Ac(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Rc(n?.summary||o),compressedSummary:Rc(n?.compressedSummary||jc(n?.summary||o,r)),keywords:Nc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Nc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:Ic(t,n)}function Pc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||n.length>64||/^(.)\1{15,}$/u.test(n)||t.add(n)}return t}function Fc(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Ic(e,t){let n=new Set([`the`,`and`,`for`,`with`,`this`,`that`,`from`,`user`,`intents`,`outcomes`,`tools`,`prior`,`segment`,`relevant`,`继续`,`刚才`,`这个`]),r=new Map;for(let i of Pc(e,t.join(` `)))n.has(i)||r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e])=>e)}function Lc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Rc(e){return e.replace(/\s+/g,` `).trim()}function zc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.segmentId==`string`&&Array.isArray(t.turnIds)&&typeof t.startTurnId==`string`&&typeof t.endTurnId==`string`&&typeof t.startIndex==`number`&&typeof t.endIndex==`number`&&typeof t.userSummary==`string`&&typeof t.summary==`string`&&typeof t.compressedSummary==`string`&&Array.isArray(t.keywords)&&Array.isArray(t.toolNames)&&(t.turnMemories===void 0||Array.isArray(t.turnMemories)&&t.turnMemories.every(e=>!!e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`&&Array.isArray(e.keywords)&&typeof e.updatedAt==`string`))&&(t.status===`active`||t.status===`closed`)&&typeof t.updatedAt==`string`}function Bc(e){let t=Wc(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Gc(t,n,r,e.segments.length,e.vectorScores)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.segment.startIndex-e.segment.startIndex:t.score-e.score:e.forced?-1:1).slice(0,e.maxSegments)}function Vc(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Hc(e){let t=new Set(e.selectedTurnIds),n=new Set(e.recentProtectedTurnIds),r=[];for(let i of e.segments){let a=i.turnIds.some(e=>t.has(e)),o=i.turnIds.some(e=>n.has(e));!a||o||i.status!==`closed`||r.push({role:`assistant`,content:Uc(i.compressedSummary),timestamp:e.timestamp})}return r}function Uc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function Wc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Gc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=Wc(t.summary,t.compressedSummary,t.keywords.join(` `),t.topicLabel,a),s=0;for(let t of e)o.has(t)&&(s+=1);let c=Math.max(0,i?.get(t.segmentId)??0),l=(n+1)/Math.max(r,1);return c*30+s*10+l}const Kc=`Xenova/bge-small-zh-v1.5`;let qc,Jc;const Yc=new Map;async function Xc(e,t){if(e.length===0)return W.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=tl(t),i=r.path;W.info(`topic segmentation embedding started`,{provider:`transformers`,model:Kc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await $c({embeddingModelDir:i}),a=[],o=0,s=0;for(let n of e){let e=n.trim();if(!e){a.push([]),s+=1;continue}let r=`${i}\0${e}`,c=Yc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Yc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return W.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Kc,textCount:e.length,embeddedCount:a.filter(e=>e.length>0).length,emptyTextCount:s,cacheHitCount:o,dims:c?.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n}),a}catch(t){throw W.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Kc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Zc(e,t){let[n]=await Xc([e],t);return n??[]}function Qc(){return Kc}async function $c(e){let t=tl(e).path;return(!qc||Jc!==t)&&(Jc=t,qc=el(t)),qc}async function el(e){let t=Date.now();W.info(`topic segmentation embedding extractor load started`,{model:Kc,modelDir:e,allowRemoteModels:!1});try{let{env:n,pipeline:r}=await import(`@huggingface/transformers`);n.allowRemoteModels=!1,n.localModelPath=e;let i=await r(`feature-extraction`,Kc,{dtype:`q8`});return W.info(`topic segmentation embedding extractor load completed`,{model:Kc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw W.warn(`topic segmentation embedding extractor load failed`,{model:Kc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function tl(e){let t=e?.embeddingModelDir?.trim();if(t)return{path:t,source:`config`};let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return{path:n,source:`env`};let r=K.dirname(en(import.meta.url)),i=K.resolve(r,`../../../../../model`);if(Wt.existsSync(i))return{path:i,source:`repo_candidate`};let a=K.resolve(process.cwd(),`model`);return Wt.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const nl=`topic_segments_vec`,rl=`topic_segments_meta`,il=`topic_segment_embedding_cache`;async function al(e){let t=Date.now(),n=sl(e);if(!n){W.info(`topic segment vector store sync skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir});return}W.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await G.mkdir(K.dirname(n),{recursive:!0});let r=qe(n,{allowExtension:!0});try{let i=await ll(r);W.info(`topic segment vector store ready`,{sessionId:e.sessionId,dbPath:n,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,embeddingModelDir:e.embeddingModelDir});let a=r.prepare(`SELECT segment_id, content_hash FROM ${rl}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=Qc(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=We(cl(e));return o.get(e.segmentId)!==t});W.info(`topic segment vector store embedding plan`,{sessionId:e.sessionId,dbPath:n,existingSegmentCount:a.length,segmentCount:e.segments.length,toEmbedCount:l.length,embeddingModelDir:e.embeddingModelDir,embeddingModel:s});let u=l.length>0?await Xc(l.map(e=>cl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=cl(t),n=We(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:ml(r,t.segmentId);fl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(pl(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(dl(r,i,o.length),r.prepare(`DELETE FROM ${nl} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${nl} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,bl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${nl} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${rl} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${il} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${nl} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),W.info(`topic segment vector store sync completed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,toEmbedCount:l.length,embeddedCount:u.filter(e=>e.length>0).length,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,durationMs:Date.now()-t})}catch(e){throw r.exec(`ROLLBACK`),e}}catch(r){throw W.warn(`topic segment vector store sync failed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{r.close()}}async function ol(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:e.query.trim()?`non_positive_limit`:`empty_query`,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;let n=sl(e);if(!n)return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;try{await G.access(n)}catch{return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}W.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await _l(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return W.warn(`topic segment vector search degraded`,{sessionId:e.sessionId,reason:`empty_query_embedding`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t}),new Map;let i=qe(n,{allowExtension:!0});try{let a=await ll(i),o=Qc(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?hl(i,o,r,e.limit):gl(i,o,r,e.limit);return W.info(`topic segment vector search completed`,{sessionId:e.sessionId,dbPath:n,strategy:s,resultCount:c.length,queryDims:r.length,vectorAvailable:a.vectorAvailable,vectorDims:a.vectorDims,durationMs:Date.now()-t}),new Map(c.map(e=>[e.segment_id,Math.max(0,e.score??0)]))}catch(r){throw W.warn(`topic segment vector search failed`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{i.close()}}function sl(e){if(!(!e.dataDir||!e.sessionId))return K.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function cl(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
|
|
29
|
+
`)}async function ll(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${rl} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${il} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${rl}_hash ON ${rl}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${il}_hash ON ${il}(content_hash)`),{vectorAvailable:(await He({db:e})).ok,vectorDims:ul(e)}}function ul(e){let t=e.prepare(`SELECT dims FROM ${il} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function dl(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${nl}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${nl} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function fl(e,t){e.prepare(`INSERT INTO ${rl} (\n segment_id, version, content_text, content_hash, embedding_model, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n version = excluded.version,\n content_text = excluded.content_text,\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n updated_at = excluded.updated_at`).run(t.segment.segmentId,1,t.contentText,t.contentHash,t.embeddingModel,t.segment.updatedAt)}function pl(e,t){e.prepare(`INSERT INTO ${il} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function ml(e,t){let n=e.prepare(`SELECT embedding FROM ${il} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function hl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${nl} v\n JOIN ${rl} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(bl(n),t,bl(n),r)}function gl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${il} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:yl(n,vl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function _l(e,t){try{return await Zc(e,t)}catch(e){return W.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function vl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function yl(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function bl(e){return Buffer.from(new Float32Array(e).buffer)}const xl=8e3,Sl=new Map;function Cl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:zl(e?.embeddingModelDir),minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxShortlistCandidates:e?.maxShortlistCandidates??12,maxShortlistSegments:e?.maxShortlistSegments??6,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function wl(e){let t=Al(e.entries),n=new Map(e.candidates.map(e=>[e.turnId,e])),r=new Set(e.decision.selectedTurnIds),i=e.recentProtectedTurnCount>0?t.slice(-e.recentProtectedTurnCount):[],a=i.map(e=>e.turnId);for(let e of i)r.add(e.turnId);let o=new Set;if(e.useCompressedSegmentMemory!==!1&&e.segmentRecords)for(let t of e.segmentRecords){let e=t.turnIds.some(e=>r.has(e)),n=t.turnIds.some(e=>a.includes(e));if(!(!e||n||t.status!==`closed`))for(let e of t.turnIds)o.add(e)}let s=[],c=[],l=[],u=[];for(let e of t){if(!r.has(e.turnId)){l.push(e.turnId),u.push(Pl(e,n.get(e.turnId)));continue}s.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),!o.has(e.turnId)&&c.push(...e.entries)}return{entries:[...e.useCompressedSegmentMemory!==!1&&e.segmentRecords?Hc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function Tl(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Bl(e.currentUserMessage),n=new Set(e.recentProtectedTurnCount>0?e.candidates.slice(-e.recentProtectedTurnCount).map(e=>e.turnId):[]);return e.candidates.map((r,i)=>({candidate:r,index:i,forced:n.has(r.turnId),score:Hl(t,r,i,e.candidates.length)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.index-e.index:t.score-e.score:e.forced?-1:1).slice(0,e.maxShortlist).map(e=>e.candidate).sort((e,t)=>e.startIndex-t.startIndex)}async function El(e){let t=Cl(e.config),n=()=>Gl({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){W.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){W.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){W.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Al(e.entries),i=J(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){W.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>jl(e,t)),o=e.llm.flashModel||e.llm.model,s=await Dl({entries:e.entries,candidates:a,pendingUserMessage:e.pendingUserMessage,config:t,llm:{apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o,timeoutMs:t.timeoutMs,maxTokens:t.maxTokens},dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:t.embeddingModelDir,signal:e.signal}),c=s.segmentRecords,l=new Set(a.map(e=>e.turnId)),u=new Date().toISOString(),d=Date.now();W.info(`topic segmentation classify started`,Gl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Nl({currentUserMessage:e.pendingUserMessage,allCandidates:a,shortlistedCandidates:s.candidates,selectedSegmentIds:s.selectedSegmentIds,supplementalTurnIds:s.supplementalTurnIds,segmentRecords:c,recentProtectedTurnCount:t.recentProtectedTurnCount,maxSelectedTurns:t.maxSelectedTurns}),p=f.selectedTurnIds.filter(e=>!l.has(e));if(p.length>0)throw Error(`Local topic segmentation returned unknown turn ids: ${p.join(`, `)}`);let m=Date.now()-d,h=wl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Ml({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:J(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await Il(e,g),W.info(`topic segmentation classify succeeded`,{...Gl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}),durationMs:m,selectedTurnCount:f.selectedTurnIds.length,confidence:f.confidence,tokenEstimateAfter:g.tokenEstimate?.after,droppedTurnCount:h.droppedTurnIds.length,droppedTurnPreviews:h.droppedTurns.length>0?JSON.stringify(h.droppedTurns):void 0}),{entries:h.entries,audit:g}}async function Dl(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await Ol({entries:e.entries,llm:e.llm,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,signal:e.signal}),n=e.config.recentProtectedTurnCount>0?e.candidates.slice(-e.config.recentProtectedTurnCount).map(e=>e.turnId):[],r=Date.now(),i=[],a=e.candidates,o=t,s=[],c=[];if(t){let o=await ol({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,query:e.pendingUserMessage,limit:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2)}),l=Bc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=ql(l,e.config.maxShortlistSegments),d=kl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:xl});if(d&&$l({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await nu({currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,retrieved:l,llm:{...e.llm,timeoutMs:d},maxSelectedSegments:e.config.maxShortlistSegments,signal:e.signal});t.length>0&&(u=t)}s=u,i=u.map(e=>e.segment.segmentId),a=Vc({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Jl({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:xl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),ru({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=Ql(a,l.selectedCandidates),d=Tl({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function Ol(e){W.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await vc(e);if(!t){let t=bc(e.entries);if(t.length===0){W.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),ru({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),W.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}W.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=xc(t,e.entries);return n.length>0&&(await yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),ru({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),W.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function kl(e){let t=Math.max(0,(e.nowMs??Date.now())-e.budgetStartedAtMs),n=Math.max(0,e.budgetMs-t);if(!(n<=0))return Math.min(e.requestTimeoutMs,n)}function Al(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,entries:[a],user:a.content,timestamp:a.timestamp};continue}n&&(n.entries.push(a),n.endIndex=i)}return r(),t}function jl(e,t){let n=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim()),r=new Set,i=!1;for(let t of e.entries){if(t.role===`assistant`){for(let e of t.toolCalls??[])r.add(e.name);t.stopReason===`error`&&(i=!0);continue}Wl(t)&&(r.add(t.toolName),t.isError&&(i=!0))}return{turnId:e.turnId,startIndex:e.startIndex,endIndex:n?e.entries.indexOf(n)+e.startIndex:e.endIndex,user:Ll(e.user,t.maxCandidateUserChars),assistant:n?Ll((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Ml(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:Ll(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,shortlistCount:e.shortlistedCandidates.candidates.length,selectedSegmentIds:e.selectedSegmentIds,selectedTurnIds:e.decision.selectedTurnIds,selectedRanges:e.projected.selectedRanges,forcedKeep:{recentTurnIds:e.projected.recentTurnIds},droppedTurnIds:e.projected.droppedTurnIds,droppedTurns:e.projected.droppedTurns,confidence:e.decision.confidence,reason:e.decision.reason,tokenEstimate:{before:e.tokenEstimateBefore,after:e.tokenEstimateAfter}}}function Nl(e){let t=new Set(e.allCandidates.map(e=>e.turnId)),n=new Set;if(e.segmentRecords&&e.selectedSegmentIds.length>0){let r=e.segmentRecords.filter(t=>e.selectedSegmentIds.includes(t.segmentId));for(let e of r)for(let r of e.turnIds)t.has(r)&&n.add(r)}for(let r of e.supplementalTurnIds)t.has(r)&&n.add(r);if(n.size===0){let t=Bl(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Hl(t,n,r,e.shortlistedCandidates.length)})).sort((e,t)=>t.score-e.score),i=r[0]?.score??0,a=Math.max(8,i>=8?i*.7:1/0);for(let t of r)if(!(t.score<a)&&(n.add(t.candidate.turnId),n.size>=e.maxSelectedTurns))break}return{version:1,selectedTurnIds:[...n].slice(0,e.maxSelectedTurns),reason:e.selectedSegmentIds.length>0||e.supplementalTurnIds.length>0?`local segment retrieval matched prior segments`:`local candidate scoring matched recent turns`,confidence:`high`}}function Pl(e,t){let n=t?.assistant??Fl(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Rl(t?.user??e.user,50),assistantPreview:n?Rl(n,50):void 0}}function Fl(e){let t=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim());return t?(t.content||t.errorMessage||``).trim():void 0}async function Il(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await G.mkdir(n,{recursive:!0}),await G.appendFile(K.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function Ll(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Rl(e,t){return[...e].slice(0,t).join(``)}function zl(e){return e?.trim()||void 0}function Bl(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Vl(e){return[...Bl(e)].slice(0,8)}function Hl(e,t,n,r){let i=Ul(e,Bl(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Ul(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Wl(e){return e.role===`tool_result`}function Gl(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Kl(e.params.llm.baseUrl),timeoutMs:e.config.timeoutMs,maxTokens:e.config.maxTokens,hasEmbeddingModelDir:!!e.config.embeddingModelDir,embeddingModelDir:e.config.embeddingModelDir,minUserTurns:e.config.minUserTurns,minEstimatedTokens:e.config.minEstimatedTokens,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxCandidates:e.config.maxCandidates,maxSelectedTurns:e.config.maxSelectedTurns,transcriptEntryCount:e.params.fullTranscript.length,workingEntryCount:e.params.entries.length,pendingUserMessageChars:e.params.pendingUserMessage?.length,candidateCount:e.candidates?.length,shortlistCount:e.shortlistedCandidates?.length,tokenEstimateBefore:e.tokenEstimateBefore,extraPromptChars:e.extraPromptChars}}function Kl(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function ql(e,t){if(e.length===0)return[];let n=e.slice().sort((e,t)=>t.score-e.score),r=n[0]?.score??0,i=Math.max(8,r>=8?r*.7:1/0);return n.filter(e=>e.forced||e.score>=i).slice(0,t)}async function Jl(e){if(!Yl(e))return{selectedCandidates:[],selectedTurnIds:[]};let t=new Set(e.segmentFilteredCandidates.map(e=>e.turnId)),n=new Set(e.recentProtectedTurnIds),r=e.allCandidates.filter(e=>!t.has(e.turnId)&&!n.has(e.turnId));if(r.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let i=Xl(Zl(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=kl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await fc({currentUserMessage:e.currentUserMessage,turns:i,maxSelectedTurns:e.config.maxSelectedTurns,recentProtectedTurnIds:e.recentProtectedTurnIds,llm:{...e.llm,timeoutMs:a},signal:e.signal}),n=[...new Set(t.selectedTurns.map(e=>e.turnId))].filter(e=>r.some(t=>t.turnId===e));if(n.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let o=r.filter(e=>n.includes(e.turnId)),s=t.selectedTurns.filter(e=>n.includes(e.turnId)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:e.topicLabel?.trim()||void 0,keywords:(e.keywords??Vl(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Sc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Yl(e){let t=e.selectedSegments.filter(e=>!e.forced);return eu(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:tu(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Xl(e,t){let n=new Map;for(let e of t??[])for(let t of e.turnIds)n.set(t,e);return e.map(e=>{let t=n.get(e.turnId),r=t?.turnMemories?.find(t=>t.turnId===e.turnId);return{turnId:e.turnId,user:e.user,assistant:e.assistant,toolNames:e.toolNames,hasErrors:e.hasErrors,summary:r?.summary??t?.summary,topicLabel:r?.topicLabel??t?.topicLabel,keywords:r?.keywords??t?.keywords}})}function Zl(e,t,n){let r=Math.max(n.length,1),i=Bl(t);return e.map(e=>({candidate:e,score:Hl(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function Ql(...e){let t=new Map;for(let n of e)for(let e of n)t.has(e.turnId)||t.set(e.turnId,e);return[...t.values()].sort((e,t)=>e.startIndex-t.startIndex)}function $l(e){if(e.retrieved.length<2||!eu(e.currentUserMessage))return!1;let t=new Set(e.selected.map(e=>e.segment.segmentId));if(e.selected.filter(e=>!e.forced).length>=2||e.retrieved.filter(e=>!e.forced).length<2)return!1;let n=new Set(e.selected.flatMap(e=>e.segment.turnIds));return e.recentProtectedTurnIds.length>0&&[...n].every(t=>e.recentProtectedTurnIds.includes(t))||t.size<2}function eu(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function tu(e){let t=e.toLowerCase();return/(回到|刚才|前面|之前|上次|那个|前一个|最早|继续刚才)/u.test(t)?!0:/\b(back to|earlier|previous|that earlier|the earlier)\b/i.test(t)}async function nu(e){try{let t=await dc({currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.retrieved.map(e=>({segmentId:e.segment.segmentId,turnIds:e.segment.turnIds,summary:e.segment.summary,compressedSummary:e.segment.compressedSummary,keywords:e.segment.keywords,toolNames:e.segment.toolNames,topicLabel:e.segment.topicLabel})),llm:e.llm,signal:e.signal}),n=new Set(t.selectedSegmentIds);return n.size===0?[]:e.retrieved.filter(e=>n.has(e.segment.segmentId))}catch{return[]}}function ru(e){let t=iu(e);if(!t||Sl.has(t)){W.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}W.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=al(e).catch(t=>{W.warn(`topic segment vector sync failed`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length,error:t instanceof Error?t.message:String(t)})}).finally(()=>{Sl.delete(t)});Sl.set(t,n)}function iu(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
|
|
30
|
+
`);const au=[`If you need content beyond this preview, do not load the full output into the parent context.`,`Use subagent_spawn to inspect the Full output file and return only a concise, query-focused summary.`,`Pass the Full output path, note that it is relative to dataDir when not absolute, and include the current question or search target in the subagent task.`];async function ou(e){let t=_(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],a=[],o=[],c,l,u=0,d,f,p=await du(t);for(let e of p.readStates)n.set(su(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);i.push(...p.compaction.budgets),a.push(...p.compaction.snips),o.push(...p.compaction.collapseSpans),c=p.compaction.sessionMemory,l=p.compaction.modelUsage,u=p.compaction.consecutiveAutocompactFailures,d=p.compaction.lastCompactionAt,f=p.compaction.lastCompactionLayer;let m=async()=>{let s={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await G.mkdir(K.dirname(t),{recursive:!0});let p=e.encryptSessions??!1;await L(t,JSON.stringify(s,null,2),p)};return{async findReusableRead(e,t,r){let i=su(e,t,r),a=n.get(i);if(!a)return null;let o=await lu(e);return o===null||o!==a.lastModifiedMs?(n.delete(i),await m(),null):a},async recordRead(e){let t=new Date().toISOString(),r={path:e.path,offset:e.offset,limit:e.limit,contentHash:uu(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await lu(e.path)??Date.now()};return n.set(su(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())cu(i.path)===cu(e)&&(n.delete(r),t=!0);t&&await m()},async persistToolResult(t){let n=t.thresholdChars??12e3;if(t.content.length<=n)return{content:t.content};let a=t.previewChars??2e3,o=s(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=K.join(o,c);await G.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=K.relative(e.dataDir,l).split(K.sep).join(`/`),h=hu(t.content,a),g={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:p,preview:h,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(g.toolCallId,g),i.push({toolCallId:g.toolCallId,toolName:g.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:g.createdAt}),d=g.createdAt,f=`L2`,await m(),{content:mu(g),reference:g}},async recordSnip(e){a.push(e),d=e.createdAt,f=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await m()},async recordCollapse(e){o.push(e),d=e.createdAt,f=e.layer,await m()},async setSessionMemory(t){c=t,await gu(e.dataDir,e.sessionId,t,e),await m()},async recordModelUsage(e){l=e,await m()},async recordAutocompactResult(e){u=e.failed?u+1:0,d=e.timestamp,f=`L6`,await m()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function su(e,t,n){return`${cu(e)}::${t??``}::${n??``}`}function cu(e){return K.normalize(e)}async function lu(e){try{return(await G.stat(e)).mtimeMs}catch{return null}}function uu(e){return Ft(`sha1`).update(e).digest(`hex`)}async function du(e){try{let t=await o(e);if(t===null)return fu();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?fu():{version:2,updatedAt:typeof n.updatedAt==`string`?n.updatedAt:new Date(0).toISOString(),readStates:Array.isArray(n.readStates)?n.readStates:[],toolResults:Array.isArray(n.toolResults)?n.toolResults:[],compaction:{sessionMemory:n.compaction?.sessionMemory,modelUsage:pu(n.compaction?.modelUsage),budgets:Array.isArray(n.compaction?.budgets)?n.compaction.budgets:[],snips:Array.isArray(n.compaction?.snips)?n.compaction.snips:[],collapseSpans:Array.isArray(n.compaction?.collapseSpans)?n.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof n.compaction?.consecutiveAutocompactFailures==`number`?n.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof n.compaction?.lastCompactionAt==`string`?n.compaction.lastCompactionAt:void 0,lastCompactionLayer:n.compaction?.lastCompactionLayer===`L1`||n.compaction?.lastCompactionLayer===`L2`||n.compaction?.lastCompactionLayer===`L3`||n.compaction?.lastCompactionLayer===`L4`||n.compaction?.lastCompactionLayer===`L5`||n.compaction?.lastCompactionLayer===`L6`?n.compaction.lastCompactionLayer:void 0}}}catch{return fu()}}function fu(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function pu(e){if(!e||typeof e!=`object`)return;let t=e;if(!(t.version!==1||typeof t.model!=`string`||typeof t.inputTokens!=`number`||typeof t.outputTokens!=`number`||typeof t.totalTokens!=`number`||typeof t.coveredTranscriptEntryCount!=`number`||typeof t.recordedAt!=`string`))return{version:1,model:t.model,inputTokens:Math.max(0,Math.floor(t.inputTokens)),outputTokens:Math.max(0,Math.floor(t.outputTokens)),totalTokens:Math.max(0,Math.floor(t.totalTokens)),coveredTranscriptEntryCount:Math.max(0,Math.floor(t.coveredTranscriptEntryCount)),recordedAt:t.recordedAt}}function mu(e){let t=e.preview.length<e.originalChars?`
|
|
31
|
+
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...au,`Preview:`,e.preview+t].join(`
|
|
32
|
+
`)}function hu(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
|
|
33
|
+
`),r=n>t*.5?n:t;return e.slice(0,r)}async function gu(e,t,n,r){let i=l(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const _u=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function vu(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,topicSegmentation:c,signal:l,hooks:u,hookCtx:d,contextStore:f,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v,entriesToMessagesOptions:y}=e,b,x=Mu(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=Us(Hs(S,a)),T=[],E=(await El({entries:w,fullTranscript:t,pendingUserMessage:s,llm:i,config:c,sessionId:m,dataDir:p,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v,signal:l}).catch(e=>{W.warn(`topic segmentation failed; falling back to repaired history`,{sessionId:m,channel:_,isSubagent:!!v,error:e instanceof Error?e.message:String(e)})}))?.entries??w;E=await bu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await xu({entries:E,contextStore:f,compactionEvents:T});let D=await Su({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g});if(E=D.entries,b=wu(b,D.summaries),f&&(b=await yu({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let O=f?.getSnapshot(),k=Math.max(1e3,Math.floor(r*.7)),A=Nu({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:O?.compaction.modelUsage}).projectedInputTokens>=k,j=O?.compaction.consecutiveAutocompactFailures??0;if(!A||j>=3)return{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let{toKeep:M,toSummarise:N}=uc(E,r);if(N.length===0)return{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let P=new Date().toISOString();try{let e=O?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await $s({entries:N,llm:i,previousSummary:b,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d}),a={role:`compaction`,content:t,keptCount:M.length,droppedCount:N.length,timestamp:P};return await f?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:P}),T.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${N.length} entries with session memory`:`Autocompact summarised ${N.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,J(N)),affectedEntries:N.length,snapshotVersion:2}),{messages:qs(Us(M),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:M.length,estimatedTokens:J(M),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:P}),{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:[...T,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function yu(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=J(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&ju(t)>=3;if(!d&&!f)return Tu(n,u?.summary);let p=await $s({entries:t,llm:r,previousSummary:Tu(n,u?.summary),instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}),m={version:1,summary:p,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:l,trigger:d?`threshold`:`autocompact`};return await i.setSessionMemory(m),p}async function bu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Eu).length<=n)return t;let c=n,l=[],u=0,d=0;for(let e=t.length-1;e>=0;--e){let n=t[e];if(!Eu(n)){l.push(n);continue}if(c>0&&n.content.length<=r){--c,l.push(n);continue}let i=n.toolResultRef?.preview?.trim()||n.content.slice(0,r).trim(),s=Du(n)?Ou(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
|
|
34
|
+
`);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),Us(l.reverse())}async function xu(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-1728e5,a=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]),o=a.length>=3?a[a.length-3]??t.length:t.length,s=0,c=0,l=[];for(let[e,r]of t.entries()){if(!Eu(r)){l.push(r);continue}if(e>=o){l.push(r);continue}let t=Date.parse(r.timestamp);if(!(t>0&&t<i)){l.push(r);continue}let a=Du(r)?Ou(r):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${r.toolName}`,`Preview:\n${r.toolResultRef?.preview?.trim()||r.content.slice(0,400).trim()}`].join(`
|
|
35
|
+
`);a!==r.content&&(s+=1,c+=Math.max(0,Math.floor((r.content.length-a.length)/4)),await n?.recordSnip({toolCallId:r.toolCallId,toolName:r.toolName,originalChars:r.content.length,retainedChars:a.length,reason:`microcompact`,createdAt:new Date().toISOString()})),l.push({...r,content:a})}return s===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${s} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:c,affectedEntries:s,snapshotVersion:2}),bu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Su(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o,sessionPathScope:s}=e,c={storeName:o,...s},l=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(l.length<=2)return{entries:t,summaries:[]};let u=l[l.length-2]??t.length,d=[],f=[],p=0,m=0,h=0;for(;p<t.length;){if(p>=u||t[p]?.role===`user`){d.push(t[p]),p+=1;continue}let e=p;for(;p<u&&t[p]?.role!==`user`;)p+=1;let r=t.slice(e,p),o=r.filter(Eu).filter(e=>_u.has(e.toolName)),s=o.reduce((e,t)=>e+t.content.length,0);if(o.length<3||s<1500){d.push(...r);continue}let l=Cu(r,o),g=new Date().toISOString();f.push(l),m+=r.length,h+=Math.max(0,Math.floor(J(r)-Math.ceil(l.length/4)));let _={id:Lt(),layer:`L5`,startEntryIndex:e,endEntryIndex:p-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:h,createdAt:g};await n?.recordCollapse(_),i&&a&&await Pu(i,a,_,c)}return m>0&&r.push({type:`compaction`,reason:`Collapsed ${m} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:h,affectedEntries:m,snapshotVersion:2}),{entries:d,summaries:f}}function Cu(e,t){let n=[...new Set(t.map(e=>e.toolName))],r=t.slice(-3).map(e=>`- ${e.toolName}: ${(e.toolResultRef?.preview||e.content).slice(0,180).trim()}`).join(`
|
|
36
36
|
`),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
|
|
37
37
|
`);return[`Historical tool activity summary: ${t.length} tool results across ${n.join(`, `)}.`,i?`Assistant notes:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
|
|
38
38
|
|
|
39
|
-
`)}function
|
|
39
|
+
`)}function wu(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=[`Historical tool activity condensed for continuity:`,...n.map(e=>`- ${e.replace(/\n/g,`
|
|
40
40
|
`)}`)].join(`
|
|
41
41
|
`);return[e?.trim(),r].filter(Boolean).join(`
|
|
42
42
|
|
|
43
|
-
`)}function
|
|
43
|
+
`)}function Tu(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
|
|
44
44
|
|
|
45
|
-
`)||void 0}function
|
|
46
|
-
`)}function
|
|
47
|
-
`)}function
|
|
48
|
-
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const
|
|
49
|
-
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return
|
|
50
|
-
`),l=Math.max(1,r.offset??1),u=Math.min(
|
|
45
|
+
`)||void 0}function Eu(e){return e.role===`tool_result`}function Du(e){return e.toolName===`skill_load`}function Ou(e){let t=ku(e),n=t.name||`<skill-name>`,r=t.path?`skill_load(name="${n}", skillPath="${t.path}")`:`skill_load(name="${n}")`;return[`[skill content folded] The previous skill_load result for "${n}" was folded out of model-visible context.`,`The complete SKILL.md content is no longer available in the current prompt.`,`Before using this skill again, call ${r} again. Do not infer or reconstruct the skill instructions from memory or summaries.`,t.path?`Original path: ${t.path}`:``].filter(Boolean).join(`
|
|
46
|
+
`)}function ku(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Au(t);if(e.name||e.path)return e}return{}}function Au(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function ju(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Mu(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Nu(e){let t=e.pendingUserMessage?.trim()?J([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=J(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=J(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function Pu(e,t,n,r){let i=j(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0}),await G.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Fu(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await ou({dataDir:e.dataDir,sessionId:e.sessionId,...t});return{async getReusableRead(e,t,r){let i=await n.findReusableRead(e,t,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await n.recordRead(e)},async invalidateReadPath(e){await n.invalidatePath(e)},persistToolResult(e){return n.persistToolResult(e)},async recordModelUsage(e){await n.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(t){return vu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Iu(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent,entriesToMessagesOptions:e.entriesToMessagesOptions}):vu({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent,entriesToMessagesOptions:e.entriesToMessagesOptions})}const Lu=q.Object({command:q.String({description:`Shell command to execute`}),workdir:q.Optional(q.String({description:"Working directory, must be inside the workspace root (relative path resolved against workspace, or an absolute path under it). If the desired directory cannot be located inside the workspace, do NOT set workdir — instead adjust the command itself (e.g. prefix with `cd /abs/path && ...` or pass absolute paths as arguments)."})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:q.Optional(q.Number({description:`Foreground wait window in ms before returning a running session to poll (default: 60000). Raise it to wait longer inline for a slow command.`})),background:q.Optional(q.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),Ru=6e4;function zu(e,t,n){return Math.max(t,Math.min(n,e))}function Bu(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Vu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?Ru:zu(Math.floor(e),0,12e4)}function Hu(e,t){if(!t?.trim())return e;let n=K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t));if(!n.startsWith(e+K.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Uu(e){let t=e.outputTail.trim();return`${t.length>0?`${t}\n\n`:``}Process is running in the background. sessionId=${e.sessionId}\nUse process(action="poll"|"log", sessionId) to continue.`}function Wu(e){return Ku({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
|
|
47
|
+
`)}function Gu(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Ku(e){let t=Gu(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function qu(e){return{name:`exec`,label:`Exec`,description:'Execute shell commands. Prefer modern tools: rg (not grep), fd (not find), jq (not python/awk) for JSON. Foreground commands auto-yield after ~60s (override with yieldMs), returning a running session you poll with the process tool. For a long-lived process like a dev server, set background:true to return immediately, then do NOT poll for it to finish (it never will): instead probe readiness with a separate command that exits (e.g. `until curl -sf localhost:PORT/health; do sleep 0.5; done`), do your work, then stop it with process(action="kill", sessionId). Background processes left running are killed when the run ends.',parameters:Lu,async execute(t,n,r){if(!n.command?.trim())return{content:[{type:`text`,text:`Error: command is required.`}],details:{status:`failed`}};let i;try{i=Hu(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Bu(n.timeout);console.log(`Executing command: ${n.command} in ${i} with timeout ${a} seconds`,{command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey});let o=e.registry.start({command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s){let t=c?Vu(n.yieldMs):Ru,r=await e.registry.wait(o.sessionId,e.scopeKey,t);r&&(l=r)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Uu(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?Ku({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Wu(l)],p=Gu(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
|
|
48
|
+
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Ju=q.Object({action:q.String({description:`Process action: list | poll | log | kill`}),sessionId:q.Optional(q.String({description:`Session id for non-list actions`})),offset:q.Optional(q.Number({description:`Log line offset (0-based)`})),limit:q.Optional(q.Number({description:`Maximum lines to return`})),timeout:q.Optional(q.Number({description:`Poll wait time in milliseconds`}))});function Yu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Xu(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Zu(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill. poll waits for a session to FINISH — never use it on a long-lived server (it won't exit); use log to inspect a server's output and kill to stop it.`,parameters:Ju,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
|
|
49
|
+
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Xu(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Yu(n.timeout));return t?{content:[{type:`text`,text:t.status===`running`?`Session ${i} is still running.`:`Session ${i} finished with status=${t.status}, exitCode=${t.exitCode??`null`}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal,aggregated:t.status!==`running`}}:Xu(`No session found for ${i}`)}if(r===`log`){let t=e.registry.readLog({sessionId:i,scopeKey:e.scopeKey,offset:n.offset,limit:n.limit});return t?{content:[{type:`text`,text:t.text.trim().length>0?t.text:`(no output)`}],details:{status:t.status,sessionId:i,totalLines:t.totalLines,totalChars:t.totalChars,truncated:t.truncated,exitCode:t.exitCode,exitSignal:t.exitSignal}}:Xu(`No session found for ${i}`)}if(r===`kill`){let t=await e.registry.terminate(i,e.scopeKey);return t?{content:[{type:`text`,text:t.status===`running`?`Termination signal sent to ${i}.`:`Session ${i} terminated with status=${t.status}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal}}:Xu(`No session found for ${i}`)}return Xu(`Unsupported action: ${n.action}`)}}}function Qu(e){return qu({workspaceDir:e,registry:Rn(),scopeKey:e})}const $u=5*1024*1024,ed=2e3;async function td(e,t){e&&await e(t).catch(()=>{})}function nd(e,t){return K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e))}const rd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),offset:q.Optional(q.Number({description:`Line offset (1-based, default: 1)`})),limit:q.Optional(q.Number({description:`Maximum lines to read (default: 2000)`}))});function id(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:rd,async execute(n,r){let i;try{i=nd(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await G.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await tn(s,s.length))return{content:[{type:`text`,text:`Error: read_file only supports text files. ${r.path} appears to be binary; use another tool or install an appropriate skill to handle it.`}],details:{content:``,lines:0,truncated:!1}};if(o.length>$u){let e=o.slice(0,$u).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${$u} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
|
|
50
|
+
`),l=Math.max(1,r.offset??1),u=Math.min(ed,r.limit??ed),d=c.slice(l-1,l-1+u),f=d.length<c.length-(l-1),p=d.map((e,t)=>`${(l+t).toString().padStart(4)} ${e}`).join(`
|
|
51
51
|
`),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
|
|
52
52
|
`),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
|
|
53
|
-
`),lines:d.length,truncated:f}}}}}const
|
|
54
|
-
`)||`(empty directory)`}],details:{entries:a}}}}}const
|
|
55
|
-
`)}function
|
|
56
|
-
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=
|
|
57
|
-
`)}function
|
|
58
|
-
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function
|
|
59
|
-
`)}
|
|
60
|
-
`)
|
|
53
|
+
`),lines:d.length,truncated:f}}}}}const ad=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),content:q.String({description:`File content to write`})});function od(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:ad,async execute(r,i){let a;try{a=nd(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await G.mkdir(K.dirname(a),{recursive:!0}),await G.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await td(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const sd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),old_string:q.String({description:`Exact text to replace`}),new_string:q.String({description:`Replacement text`})});function cd(e,t,n){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:sd,async execute(r,i){let a;try{a=nd(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await G.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await G.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await td(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const ld=q.Object({path:q.Optional(q.String({description:`Directory path (default: workspace root)`}))});function ud(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:ld,async execute(t,n){let r=n.path??`.`,i;try{i=nd(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await G.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
|
|
54
|
+
`)||`(empty directory)`}],details:{entries:a}}}}}const dd=q.Object({input:q.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function fd(e,t){let n=K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e));if(!n.startsWith(t+K.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function pd(e,t){let n=K.relative(t,e);return!n||n===``?K.basename(e):n.startsWith(`..`)||K.isAbsolute(n)?e:n}async function md(e){await G.mkdir(K.dirname(e),{recursive:!0})}async function hd(e,t){e&&await e(t).catch(()=>{})}function gd(e){let t=[`Success. Updated the following files:`];for(let n of e.added)t.push(`A ${n}`);for(let n of e.modified)t.push(`M ${n}`);for(let n of e.deleted)t.push(`D ${n}`);return t.join(`
|
|
55
|
+
`)}function _d(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:dd,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=yd(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=fd(r.path,e);await md(i),await G.writeFile(i,r.contents,`utf-8`),await hd(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`added`,pd(i,e));continue}if(r.kind===`delete`){let i=fd(r.path,e);await G.rm(i,{force:!0,recursive:!1}),await hd(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`deleted`,pd(i,e));continue}let i=fd(r.path,e),a=await Cd(i,r.chunks);if(r.movePath){let c=fd(r.movePath,e);await md(c),await G.writeFile(c,a,`utf-8`),await G.rm(i,{force:!0,recursive:!1}),await hd(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`modified`,pd(c,e))}else await G.writeFile(i,a,`utf-8`),await hd(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`modified`,pd(i,e))}return{content:[{type:`text`,text:gd(o)}],details:{summary:o}}}catch(e){if(So(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function vd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function yd(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);bd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=xd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function bd(e){let t=e[0]?.trim(),n=e[e.length-1]?.trim();if(t!==`*** Begin Patch`)throw Error(`The first line of the patch must be '*** Begin Patch'`);if(n!==`*** End Patch`)throw Error(`The last line of the patch must be '*** End Patch'`)}function xd(e,t){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: empty hunk`);let n=e[0].trim();if(n.startsWith(`*** Add File: `)){let t=n.slice(14),r=``,i=1;for(let t of e.slice(1))if(t.startsWith(`+`))r+=`${t.slice(1)}\n`,i+=1;else break;return{hunk:{kind:`add`,path:t,contents:r},consumed:i}}if(n.startsWith(`*** Delete File: `))return{hunk:{kind:`delete`,path:n.slice(17)},consumed:1};if(n.startsWith(`*** Update File: `)){let r=n.slice(17),i=e.slice(1),a=1,o,s=i[0]?.trim();s?.startsWith(`*** Move to: `)&&(o=s.slice(13),i=i.slice(1),a+=1);let c=[];for(;i.length>0;){if(i[0].trim()===``){i=i.slice(1),a+=1;continue}if(i[0].startsWith(`***`))break;let{chunk:e,consumed:n}=Sd(i,t+a,c.length===0);c.push(e),i=i.slice(n),a+=n}if(c.length===0)throw Error(`Invalid patch hunk at line ${t}: Update file hunk for path '${r}' is empty`);return{hunk:{kind:`update`,path:r,movePath:o,chunks:c},consumed:a}}throw Error(`Invalid patch hunk at line ${t}: '${e[0]}' is not a valid hunk header.`)}function Sd(e,t,n){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: Update hunk does not contain any lines`);let r,i=0;if(e[0]===`@@`)i=1;else if(e[0].startsWith(`@@ `))r=e[0].slice(3),i=1;else if(!n)throw Error(`Invalid patch hunk at line ${t}: Expected update hunk to start with a @@ context marker.`);if(i>=e.length)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);let a={changeContext:r,oldLines:[],newLines:[],isEndOfFile:!1},o=0;for(let n of e.slice(i)){if(n===`*** End of File`){if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);a.isEndOfFile=!0,o+=1;break}let e=n[0];if(!e){a.oldLines.push(``),a.newLines.push(``),o+=1;continue}if(e===` `){let e=n.slice(1);a.oldLines.push(e),a.newLines.push(e),o+=1;continue}if(e===`+`){a.newLines.push(n.slice(1)),o+=1;continue}if(e===`-`){a.oldLines.push(n.slice(1)),o+=1;continue}if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Unexpected line found in update hunk.`);break}return{chunk:a,consumed:o+i}}async function Cd(e,t){let n=(await G.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
|
|
56
|
+
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=Td(n,wd(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
|
|
57
|
+
`)}function wd(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Ed(e,[a.changeContext],i,!1);if(n===null)throw Error(`Failed to find context '${a.changeContext}' in ${t}`);i=n+1}if(a.oldLines.length===0){let t=e.length>0&&e[e.length-1]===``?e.length-1:e.length;r.push([t,0,a.newLines]);continue}let n=a.oldLines,o=a.newLines,s=Ed(e,n,i,a.isEndOfFile);if(s===null&&n[n.length-1]===``&&(n=n.slice(0,-1),o.length>0&&o[o.length-1]===``&&(o=o.slice(0,-1)),s=Ed(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
|
|
58
|
+
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Td(e,t){let n=[...e];for(let[e,r,i]of[...t].toReversed()){for(let t=0;t<r;t+=1)e<n.length&&n.splice(e,1);for(let t=0;t<i.length;t+=1)n.splice(e+t,0,i[t])}return n}function Ed(e,t,n,r){if(t.length===0)return n;if(t.length>e.length)return null;let i=e.length-t.length,a=r&&e.length>=t.length?i:n;if(a>i)return null;for(let n=a;n<=i;n+=1)if(Dd(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Dd(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Dd(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Dd(e,t,n,e=>Od(e.trim())))return n;return null}function Dd(e,t,n,r){for(let i=0;i<t.length;i+=1)if(r(e[n+i])!==r(t[i]))return!1;return!0}function Od(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}const Y=e=>({ok:!0,value:e}),X=e=>({ok:!1,error:e}),kd=(e,t)=>e.ok===!0?Y(t(e.value)):X(e.error),Ad=(e,t)=>e.ok===!0?t(e.value):X(e.error),Z=e=>!!e&&typeof e==`object`&&!Array.isArray(e),jd=e=>typeof e==`string`&&e.trim()?e.trim():void 0,Md=e=>e.filter(e=>e!==void 0),Nd=e=>Array.isArray(e)?`[${e.map(Nd).join(`,`)}]`:Z(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Nd(e[t])}`).join(`,`)}}`:JSON.stringify(e),Pd=e=>Ft(`sha256`).update(e).digest(`hex`),Fd=e=>Ft(`sha256`).update(e).digest(`hex`),Id=e=>Pd(Nd(e));function Ld(e,t){let n=t?.trim()?K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t)):e;if(!n.startsWith(`${e}${K.sep}`)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}const Rd=(e,t)=>t===e||t.startsWith(`${e}${K.sep}`),zd=(e,t)=>`${e}.${t}`,Bd=(e,t,n)=>t[n]===void 0?Y(void 0):jd(t[n])?Y(jd(t[n])):X(`${zd(e,n)} must be a non-empty string.`),Vd=(e,t,n)=>t[n]===void 0?Y(void 0):typeof t[n]==`number`?Y(t[n]):X(`${zd(e,n)} must be a number.`),Hd=(e,t,n)=>t[n]===void 0?Y(void 0):typeof t[n]==`boolean`?Y(t[n]):X(`${zd(e,n)} must be true or false.`),Ud=(e,t,n,r)=>t[n]===void 0?Y(void 0):r.includes(t[n])?Y(t[n]):X(`${zd(e,n)} must be one of: ${r.join(`, `)}.`),Wd=e=>e.reduce((e,[t,n])=>Ad(e,e=>kd(n,n=>n===void 0?e:{...e,[t]:n})),Y({})),Gd=e=>Array.from(e.matchAll(/{{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*}}/g)).map(e=>e[1]??``),Kd=e=>/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`,qd=(e,t)=>typeof t==`string`?Y(Kd(t)):typeof t==`number`||typeof t==`boolean`?Y(String(t)):X(`Input '${e}' cannot be inserted into a shell template. Use a string, number, or boolean.`),Jd=(e,t)=>Gd(e).reduce((e,n)=>Ad(e,e=>kd(qd(n,t[n]),t=>e.replace(RegExp(`{{\\s*${n}\\s*}}`,`g`),t))),Y(e)),Yd=e=>e.replace(/^["']|["']$/g,``),Xd=e=>Array.from(e.matchAll(/(?:^|\s)(?:bash|sh)?\s*(["']?[^"'\s]+\.sh["']?)/g)).map(e=>Yd(e[1]??``).trim()).filter(Boolean),Zd=(e,t)=>K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t)),Qd=async(e,t,n)=>{let r=Zd(t,n);return Rd(e,r)?await G.readFile(r).then(e=>({path:r,sha256:Fd(e)})).catch(()=>void 0):void 0};async function $d(e){return Md(await Promise.all(Xd(e.command).map(t=>Qd(e.workspaceDir,e.resolvedWorkdir,t))))}const ef=(e,t={})=>({content:[{type:`text`,text:e}],details:{status:`failed`,...t},isError:!0}),tf=(e,t={})=>({content:[{type:`text`,text:e}],details:{status:`skipped`,...t}}),nf=q.Object({command:q.String({description:`Shell command to execute after user approval`}),workdir:q.Optional(q.String({description:`Working directory inside the workspace`})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Max total runtime in seconds`})),yieldMs:q.Optional(q.Number({description:`Foreground wait window in ms`})),background:q.Optional(q.Boolean({description:`Start command in background`})),title:q.String({description:`Approval card title shown to the user`}),reason:q.String({description:`Why this command requires approval`}),risk:q.Optional(q.Union([q.Literal(`low`),q.Literal(`medium`),q.Literal(`high`),q.Literal(`critical`)])),preview:q.Optional(q.String({description:`Optional markdown preview shown to the user`})),policy:q.Optional(q.Object({timeoutMs:q.Optional(q.Number()),defaultOnTimeout:q.Optional(q.Union([q.Literal(`deny`),q.Literal(`cancel`)]))})),source:q.Optional(q.Object({kind:q.Optional(q.Union([q.Literal(`skill`),q.Literal(`skill_action`),q.Literal(`manual`)])),skillName:q.Optional(q.String()),skillPath:q.Optional(q.String()),actionName:q.Optional(q.String()),actionFile:q.Optional(q.String())}))}),rf=e=>({version:1,tool:e.toolName,command:e.guardedParams.command,resolvedWorkdir:e.resolvedWorkdir,...e.guardedParams.env?{env:e.guardedParams.env}:{},...e.guardedParams.timeout===void 0?{}:{timeout:e.guardedParams.timeout},...e.guardedParams.yieldMs===void 0?{}:{yieldMs:e.guardedParams.yieldMs},...e.guardedParams.background===void 0?{}:{background:e.guardedParams.background},...e.scriptHashes.length>0?{scriptHashes:e.scriptHashes}:{},...e.guardedParams.source?{source:e.guardedParams.source}:{},...e.actionHash?{actionHash:e.actionHash}:{}}),af=e=>({tool:e.toolName,risk:e.guardedParams.risk??`medium`,operationHash:e.operationHash,commandHash:Pd(e.guardedParams.command),...e.guardedParams.env?{envHash:Id(e.guardedParams.env)}:{},...e.scriptHashes.length>0?{scriptHash:Id(e.scriptHashes),scriptPaths:e.scriptHashes.map(e=>e.path)}:{},...e.guardedParams.source?{source:e.guardedParams.source}:{},commandPreview:e.guardedParams.command,workdir:e.resolvedWorkdir,...e.actionHash?{actionHash:e.actionHash}:{}}),of=(e,t)=>[e.preview?.trim()?`${e.preview.trim()}\n`:``,`### Command`,"```bash",t.commandPreview,"```",``,`Risk: ${t.risk}`,t.scriptPaths?.length?`Script hash: ${t.scriptHash}`:``,t.actionHash?`Action hash: ${t.actionHash}`:``,`Operation hash: ${t.operationHash}`].filter(Boolean).join(`
|
|
59
|
+
`);async function sf(e){if(!e.sessionId)throw Error(`guarded_exec requires a sessionId to create a HITL approval request.`);let t=Ld(e.workspaceDir,e.guardedParams.workdir),n=await $d({workspaceDir:e.workspaceDir,resolvedWorkdir:t,command:e.guardedParams.command}),r=Id(rf({toolName:e.toolName,guardedParams:e.guardedParams,resolvedWorkdir:t,scriptHashes:n,actionHash:e.actionHash})),i=af({toolName:e.toolName,guardedParams:e.guardedParams,resolvedWorkdir:t,scriptHashes:n,operationHash:r,actionHash:e.actionHash});return{operationHash:r,request:{requestId:Lt(),sessionId:e.hitlResume?.request.sessionId??e.sessionId,kind:`approval`,title:e.guardedParams.title,prompt:e.guardedParams.reason,details:i,preview:{mimeType:`text/markdown`,content:of(e.guardedParams,i)},input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`},{id:`deny`,label:`Deny`}]},policy:{resumable:!0,defaultOnTimeout:e.guardedParams.policy?.defaultOnTimeout??`deny`,...e.guardedParams.policy?.timeoutMs===void 0?{}:{timeoutMs:e.guardedParams.policy.timeoutMs}},createdAt:new Date().toISOString()}}}const cf=e=>typeof e?.request.details?.operationHash==`string`?e.request.details.operationHash:void 0;function lf(e){let t=e.hitlResume;return!t||t.request.kind!==`approval`||t.toolContext?.toolName!==e.toolName||t.toolContext.toolCallId!==e.toolCallId?{kind:`none`}:t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1)?cf(t)===e.operationHash?{kind:`approved`}:{kind:`hash_mismatch`,text:`Guarded command changed after approval; command was not executed.`}:{kind:`denied`,text:`HITL approval denied; guarded command skipped.`}}async function uf(e,t,n,r){return await qu(e).execute(t,{command:n.command,...n.workdir?{workdir:n.workdir}:{},...n.env?{env:n.env}:{},...n.timeout===void 0?{}:{timeout:n.timeout},...n.yieldMs===void 0?{}:{yieldMs:n.yieldMs},...n.background===void 0?{}:{background:n.background}},r)}async function df(e){try{let t=await sf({workspaceDir:e.options.workspaceDir,sessionId:e.options.sessionId,hitlResume:e.options.hitlResume,toolName:e.toolName,toolCallId:e.toolCallId,guardedParams:e.guardedParams,actionHash:e.actionHash}),n=lf({hitlResume:e.options.hitlResume,toolName:e.toolName,toolCallId:e.toolCallId,operationHash:t.operationHash});if(n.kind===`denied`)return tf(n.text);if(n.kind===`hash_mismatch`)return ef(n.text,{operationHash:t.operationHash});if(n.kind===`approved`)return await uf(e.options,e.toolCallId,e.guardedParams,e.signal);throw new xo(t.request,{turnId:e.toolCallId,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:e.toolCallId,toolName:e.toolName,toolArgs:e.guardedParams})}catch(e){if(e instanceof xo)throw e;return ef(e instanceof Error?e.message:String(e))}}function ff(e){return{name:`guarded_exec`,label:`Guarded Exec`,description:`Request HITL approval before executing a shell command. Use for skill-directed side-effectful scripts.`,parameters:nf,async execute(t,n,r){return await df({options:e,toolName:`guarded_exec`,toolCallId:t,guardedParams:n,signal:r})}}}function pf(e){return K.join(e,`.aimax`)}function mf(e){return K.join(pf(e),`MEMORY.md`)}async function hf(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function gf(e,t){let n=pf(e),r=Ke({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return{provider:r.provider,resolvedProviderId:r.providerId,source:r.providerSource}}async function _f(e){return Ye(pf(e))}async function vf(e){try{return await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function yf(e){return vf(mf(e))}async function bf(e,t,n){let{provider:r}=gf(e,n);return await r.search(t)}async function xf(e,t,n,r,i){try{let{provider:a}=gf(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Sf(e,t,n){let{provider:r,resolvedProviderId:i}=gf(e,n);await r.append(t),await hf(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}async function Cf(e,t,n,r){let{provider:i,resolvedProviderId:a}=gf(e,r),o=n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`;if(i.appendRecent){await i.appendRecent(t,n),await hf(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await hf(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});return}await hf(i,r?.onMemoryChanged,{reason:`appendRecent_fallback`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});let s=new Date().toISOString().slice(0,10),c=n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${s}]`;await i.append(`${c} ${t}\n`),await hf(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await hf(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function wf(e,t,n,r){let{provider:i,resolvedProviderId:a}=gf(e,r);await i.updateFile(t,n),await hf(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Tf(e,t,n){let{provider:r,resolvedProviderId:i}=gf(e,n);await r.deleteFile(t),await hf(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Ef=q.Object({query:q.String({description:`Search query (case-insensitive substring match)`})});function Df(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search durable long-term memory docs (for stable facts, preferences, decisions, and project constraints). Use this for persistent knowledge retrieval, not for reconstructing past chat timelines. If the user asks what happened in previous sessions, use session_search instead.`,parameters:Ef,async execute(n,r){let i=(await bf(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({id:e.id,file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.id?`[${e.id}] `:``}${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
|
|
60
|
+
`)}],details:{matches:i}}}}}const Of=q.Object({file:q.String({description:`Memory file path (from memory_search results)`}),start_line:q.Number({description:`Start line number (1-based)`}),end_line:q.Number({description:`End line number (1-based)`})});function kf(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read a specific memory entry's content after memory_search identifies the target path and range`,parameters:Of,async execute(n,r){let i=await xf(e,r.file,r.start_line,r.end_line,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});return i===null?{content:[{type:`text`,text:`File not found: ${r.file}`}],details:{lines:null}}:{content:[{type:`text`,text:i.map((e,t)=>`${(r.start_line+t).toString().padStart(4)} ${e}`).join(`
|
|
61
|
+
`)||`(empty)`}],details:{lines:i}}}}}const Af=q.Object({content:q.String({description:`Content to write to memory`})});function jf(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append a small new fact or note to MEMORY.md without replacing existing sections`,parameters:Af,async execute(n,r){try{return await Sf(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{appended:!0}}}catch(e){return{content:[{type:`text`,text:`Error appending to memory: ${e instanceof Error?e.message:String(e)}`}],details:{appended:!1}}}}}}const Mf=q.Object({section:q.Optional(q.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:q.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:q.Union([q.Literal(`append`),q.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Nf(e,t){return{name:`memory_write`,label:`Write Memory`,description:`Write or update a section in long-term memory (MEMORY.md). Use for durable facts, preferences, decisions, and project constraints. If section is omitted, appends a flat unstructured note. Use mode "append" to add entries and "replace" to rewrite a section.`,parameters:Mf,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Sf(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}let o=`${`## ${i}`}\n${r.content.trimEnd()}\n`;try{return a===`replace`?await wf(e,`MEMORY.md`,Pf(await yf(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Sf(e,o,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: section "${i}" (${a})`}],details:{section:i,mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}}}}function Pf(e,t,n){let r=e.split(`
|
|
61
62
|
`),i=`## ${t}`,a=`${i}\n${n.trimEnd()}`.trimEnd(),o=-1;for(let e=0;e<r.length;e+=1)if(r[e]?.trim()===i){o=e;break}if(o===-1){let t=e.trimEnd();return`${t?`${t}\n`:``}${a}\n`}let s=r.length;for(let e=o+1;e<r.length;e+=1)if(/^##\s+/.test(r[e]??``)){s=e;break}return`${[r.slice(0,o).join(`
|
|
62
63
|
`).trimEnd(),a,r.slice(s).join(`
|
|
63
64
|
`).trimStart()].filter(e=>e.length>0).join(`
|
|
64
|
-
`)}\n`}function
|
|
65
|
+
`)}\n`}function Ff(e,t){let n=e.split(`
|
|
65
66
|
`),r=`## ${t}`,i=-1;for(let e=0;e<n.length;e+=1)if(n[e]?.trim()===r){i=e;break}if(i===-1)return null;let a=n.length;for(let e=i+1;e<n.length;e+=1)if(/^##\s+/.test(n[e]??``)){a=e;break}let o=[n.slice(0,i).join(`
|
|
66
67
|
`).trimEnd(),n.slice(a).join(`
|
|
67
68
|
`).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
|
|
68
|
-
`)}\n`:``}function
|
|
69
|
+
`)}\n`:``}function If(e,t){let n=e.split(`
|
|
69
70
|
`);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
|
|
70
|
-
`)}\n`:``)}function
|
|
71
|
+
`)}\n`:``)}function Lf(e,t,n){let r=e.split(`
|
|
71
72
|
`);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
|
|
72
|
-
`)}\n`)}function
|
|
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
|
|
74
|
-
`),t=
|
|
73
|
+
`)}\n`)}function Rf(e){let t=e.indexOf(`#`);if(t===-1)return{filePath:e};let n=e.slice(0,t),r=e.slice(t+1),i=r.match(/^L(\d+)$/);return i?{filePath:n,line:Number(i[1])}:{filePath:n,section:r}}function zf(e,t){let n=[],r=t.split(`
|
|
74
|
+
`);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const Bf=q.Object({content:q.String({description:`Note to append to today's daily log`}),scope:q.Optional(q.Union([q.Literal(`daily`),q.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Vf(e,t){return{name:`memory_log`,label:`Daily Log`,description:`Append a timestamped daily or session note for short-term context, progress updates, and open questions.`,parameters:Bf,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Cf(e,r.content,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Logged to ${a} memory: ${r.content}`}],details:{date:i,scope:a}}}catch(e){throw Error(`Failed to write daily log: ${e instanceof Error?e.message:String(e)}`)}}}}const Hf=q.Object({scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Uf(e,t){return{name:`memory_list`,label:`List Memories`,description:`List stored memories so you can inspect available entries and obtain exact ids or paths before update/delete.`,parameters:Hf,async execute(n,r){try{let n=r.scope??`all`,i=await _f(e),a=[];for(let n of i.slice(0,30)){let r=await xf(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
|
|
75
|
+
`),t=zf(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
|
|
75
76
|
`):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
|
|
76
77
|
|
|
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
|
|
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
|
|
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
|
|
80
|
-
`),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await
|
|
81
|
-
`);for(let t of r){let r=t.trim();if(!r||!
|
|
82
|
-
`)}function
|
|
83
|
-
`)}`}async function
|
|
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
|
|
78
|
+
`)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const Wf=q.Object({id:q.Optional(q.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:q.Optional(q.String({description:`Search query used to find memories to delete`})),limit:q.Optional(q.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Gf(e,t){return{name:`memory_forget`,label:`Forget Memory`,description:`Delete a specific memory by its entry ID, or delete matching memories by search query. IDs with # (e.g. MEMORY.md#Preferences) delete only that section from the file. Prefer memory_list or memory_search first so you know the target.`,parameters:Wf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Rf(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Ff(await yf(e)??``,t.section);return n===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await wf(e,t.filePath,n,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}let n=await xf(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=Ff(n.join(`
|
|
79
|
+
`),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await wf(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}if(t.line!==void 0){let n=await xf(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=If(n.join(`
|
|
80
|
+
`),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await wf(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten line ${t.line} from ${t.filePath}`}],details:{removed:1,id:r.id}})}return r.id===`MEMORY.md`?{content:[{type:`text`,text:`Cannot delete MEMORY.md directly. Use id with a section (e.g. MEMORY.md#SectionName) to remove individual entries, or use query mode.`}],details:{removed:0,id:r.id}}:(await Tf(e,r.id,i),{content:[{type:`text`,text:`Forgotten memory: ${r.id}`}],details:{removed:1,id:r.id}})}if(r.query){let t=Math.min(Math.max(r.limit??5,1),20),n=await bf(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Tf(e,r.path,i),a+=1);return{content:[{type:`text`,text:`Forgotten ${a} memor${a===1?`y`:`ies`} matching: ${r.query}`}],details:{removed:a,query:r.query}}}return{content:[{type:`text`,text:`Provide id or query to forget memories.`}],details:{removed:0}}}catch(e){throw Error(`Failed to forget memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Kf=q.Object({id:q.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:q.String({description:`New content to replace the existing memory with`})});function qf(e,t){return{name:`memory_update`,label:`Update Memory`,description:`Replace an existing memory's content by its entry ID. Use memory_list or memory_search first to find the correct ID. IDs with # (e.g. MEMORY.md#Preferences) update only that section; IDs without # replace the entire file.`,parameters:Kf,async execute(n,r){try{let n=Rf(r.id);if(n.section){let i=Pf(await yf(e)??``,n.section,r.content);return await wf(e,n.filePath,i,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (section "${n.section}")`}],details:{id:r.id}}}if(n.line!==void 0){let i=await xf(e,n.filePath,1,1e4,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(!i)throw Error(`File not found: ${n.filePath}`);let a=Lf(i.join(`
|
|
81
|
+
`),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await wf(e,n.filePath,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (line ${n.line})`}],details:{id:r.id}}}return await wf(e,r.id,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id}`}],details:{id:r.id}}}catch(e){throw Error(`Failed to update memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Jf=q.Object({query:q.Optional(q.String({description:`Search query; omit to browse recent sessions.`})),role_filter:q.Optional(q.Union([q.Literal(`user`),q.Literal(`assistant`),q.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:q.Optional(q.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:q.Optional(q.Union([q.Literal(`llm`),q.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Yf(e,t){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:Jf,async execute(n,r){let i=Xf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Zf(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await Qf({dataDir:e,query:o,roleFilter:s,messageLimit:50,sessionLimit:i,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(c.length===0){let e={mode:`query`,query:o,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let l=[];for(let n of c){let r=dp(o,n.snippets);if(a===`off`){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let i=await $s({entries:cp(sp(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:up({query:o})});l.push({session_id:n.sessionId,summary:i.trim()||r,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let u={mode:`query`,query:o,count:l.length,results:l};return{content:[{type:`text`,text:JSON.stringify(u,null,2)}],details:u}}}}function Xf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Zf(e,t,n){let r=await x(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await I(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function Qf(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=np(e.query),i=(await fp(n,6,async t=>$f({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(op).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await I(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function $f(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
|
|
82
|
+
`);for(let t of r){let r=t.trim();if(!r||!ep(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!tp(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=ip(i.content,e.terms,i.role);if(a<=0)continue;let o=ap(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(op),n.length=20)}return n.sort(op),n}function ep(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function tp(e){return e===`user`||e===`assistant`||e===`tool_result`}function np(e){let t=e.toLowerCase().trim(),n=new Set;t.length>0&&n.add(t);let r=t.match(/[\p{L}\p{N}_-]+/gu)??[];for(let e of r)e.length>=2&&n.add(e);let i=Array.from(t).filter(e=>rp(e)).join(``);if(i.length>=2)for(let e=0;e<=i.length-2;e+=1)n.add(i.slice(e,e+2));return Array.from(n).slice(0,30)}function rp(e){let t=e.codePointAt(0)??0;return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12352&&t<=12543||t>=44032&&t<=55215}function ip(e,t,n){let r=e.toLowerCase(),i=0;for(let e of t)e&&r.includes(e)&&(i+=1);if(i===0)return 0;let a=n===`user`?1.2:n===`assistant`?1:.7;return i*i*a}function ap(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function op(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function sp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function cp(e,t,n){if(e.length===0)return e;let r=np(t);if(e.reduce((e,t)=>e+t.content.length,0)<=n)return e;let i=[];for(let t=0;t<e.length;t+=1){let n=e[t].content.toLowerCase();r.some(e=>e&&n.includes(e))&&i.push(t)}if(i.length===0)return lp(e,n);let a=i[0],o=i[0],s=e[a].content.length;for(;s<n&&(a>0||o<e.length-1);){if(o<e.length-1){let t=e[o+1].content.length;if(s+t<=n)o+=1,s+=t;else break}if(a>0){let t=e[a-1].content.length;if(s+t<=n)--a,s+=t;else break}}return e.slice(a,o+1)}function lp(e,t){let n=[],r=0;for(let i=e.length-1;i>=0;--i){let a=e[i];if(r+a.content.length>t)break;n.push(a),r+=a.content.length}return n.reverse()}function up(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
|
|
83
|
+
`)}function dp(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
|
|
84
|
+
`)}`}async function fp(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}function pp(e){return K.join(e,`.aimax`,`skills`)}function mp(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function hp(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${mp(n)}\n`)}function gp(e){let t=Vt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
|
|
85
|
+
`);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}function _p(e){let t=Vt(e),n=t.data.metadata,r=(n&&typeof n==`object`&&!Array.isArray(n)?n.version:void 0)??t.data.version;return r==null?``:String(r).trim()}async function vp(e){return(await G.stat(e)).mtime.toISOString()}async function yp(e){return xp([pp(e)])}async function bp(e,t,n=[]){return xp([...n,...t,pp(e)])}async function xp(e){let t=new Map;for(let n of e){let e;try{e=await G.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=K.join(n,e,`SKILL.md`),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=gp(i),o=_p(i),s=await vp(r)}catch(t){hp(e,r,t);continue}t.set(e,{name:e,description:a,location:r,version:o,skillFileMtime:s})}}return Array.from(t.values()).slice(0,50)}async function Sp(e,t){let n=t.trim();if(!n)return;let r=(await xp(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:K.dirname(r.location)}}async function Cp(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=K.resolve(r),a=K.basename(i)===`SKILL.md`?i:K.join(i,`SKILL.md`);if(K.basename(a)!==`SKILL.md`)return;let o;try{o=await G.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=gp(o),c=_p(o),l=await vp(a)}catch(e){hp(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:K.dirname(a)}}async function wp(e,t,n){let r=n?.trim()?await Cp(t,n):await Sp(e,t);if(!r)return;let i=await G.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Tp(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
|
|
85
86
|
`)).join(`
|
|
86
|
-
`)}\n</available_skills>`}const
|
|
87
|
+
`)}\n</available_skills>`}const Ep=q.Object({category:q.Optional(q.String({description:`Reserved category filter field. Not used yet.`}))}),Dp=q.Object({name:q.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Op(e,t,n=[]){return[...n,...t,pp(e)]}function kp(e,t,n=[]){let r=Op(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Ep,async execute(e,t){let n=await xp(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function Ap(e){let t=Op(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:Dp,async execute(r,i){let a=await wp(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const jp=q.Object({skillName:q.Optional(q.String({description:`Skill name from the available skills registry`})),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md`})),action:q.String({description:`Action name declared in actions.yml`}),inputs:q.Optional(q.Record(q.String(),q.Unknown()))}),Mp=/^[a-z][a-z0-9_-]{0,63}$/,Np=[`low`,`medium`,`high`,`critical`],Pp=[`deny`,`cancel`],Fp=(e,t,n=[])=>[...n,...t,pp(e)],Ip=e=>{let t=K.resolve(e),n=K.basename(t)===`SKILL.md`?t:K.join(t,`SKILL.md`);return{rootDir:K.dirname(n),skillFile:n}};async function Lp(e){if(!e.skillName?.trim()&&!e.skillPath?.trim())return X(`skill_action_run requires either skillName or skillPath.`);if(e.skillPath?.trim()){let t=Ip(e.skillPath),n=K.basename(t.rootDir),r=e.skillName?.trim()||n;return e.skillName?.trim()&&e.skillName.trim()!==n?X(`skillName '${e.skillName}' does not match skillPath '${e.skillPath}'.`):await G.access(t.skillFile).then(()=>Y({name:r,rootDir:t.rootDir,skillFile:t.skillFile})).catch(()=>X(`Skill '${r}' not found at '${e.skillPath}'.`))}return await Sp(Fp(e.dataDir,e.pluginDirs,e.skillsLoadPaths),e.skillName??``).then(t=>t?Y({name:t.skill.name,rootDir:t.rootDir,skillFile:t.skill.location}):X(`Skill '${e.skillName}' not found.`))}async function Rp(e){let t=K.join(e.rootDir,`actions.yml`),n=K.join(e.rootDir,`actions.yaml`),[r,i]=await Promise.all([G.access(t).then(()=>!0).catch(()=>!1),G.access(n).then(()=>!0).catch(()=>!1)]);return r&&i?X(`Skill '${e.name}' has both actions.yml and actions.yaml. Keep only actions.yml.`):r||i?await G.readFile(r?t:n,`utf-8`).then(e=>Y({path:r?t:n,content:e})).catch(t=>X(`Failed to read actions file for skill '${e.name}': ${String(t)}`)):X(`Skill '${e.name}' does not define actions.yml.`)}const zp=(e,t)=>{try{return Y(nn(t))}catch(t){return X(`Invalid actions.yml for skill '${e}': ${t instanceof Error?t.message:String(t)}`)}},Bp=e=>typeof e.shell==`string`!==Array.isArray(e.argv),Vp=(e,t)=>Z(t)?Bp(t)?typeof t.shell==`string`&&t.shell.trim()?Y({shell:t.shell}):Array.isArray(t.argv)&&t.argv.every(e=>typeof e==`string`&&e.trim())?Y({argv:t.argv}):X(`Action '${e}' has an invalid command definition.`):X(`Action '${e}' must define exactly one of command.shell or command.argv.`):X(`Action '${e}' must define command.shell or command.argv.`),Hp=(e,t)=>t===void 0?Y(void 0):Z(t)?Object.entries(t).every(([e,t])=>e.trim()&&typeof t==`string`)?Y(t):X(`Action '${e}' env values must be strings.`):X(`Action '${e}' env must be an object.`),Up=(e,t)=>t===void 0?Y(void 0):Z(t)?Y(t):X(`Action '${e}' inputSchema must be an object schema.`),Wp=(e,t)=>t===void 0?Y(void 0):Z(t)?kd(Wd([[`includeCommand`,Hd(`Action '${e}' hitl.preview`,t,`includeCommand`)],[`includeInputs`,Hd(`Action '${e}' hitl.preview`,t,`includeInputs`)],[`includeScriptHash`,Hd(`Action '${e}' hitl.preview`,t,`includeScriptHash`)],[`text`,Bd(`Action '${e}' hitl.preview`,t,`text`)]]),e=>e):X(`Action '${e}' hitl.preview must be an object.`),Gp=(e,t)=>{let n=`Action '${e}' hitl`;return t===void 0?Y(void 0):Z(t)?typeof t.required==`boolean`?kd(Wd([[`title`,Bd(n,t,`title`)],[`reason`,Bd(n,t,`reason`)],[`risk`,Ud(n,t,`risk`,Np)],[`timeoutMs`,Vd(n,t,`timeoutMs`)],[`defaultOnTimeout`,Ud(n,t,`defaultOnTimeout`,Pp)],[`preview`,Wp(e,t.preview)]]),e=>({required:t.required,...e})):X(`${n}.required must be true or false.`):X(`${n} must be an object.`)},Kp=(e,t)=>kd(Wd([[`inputSchema`,Up(e,t.inputSchema)],[`workdir`,Bd(`Action '${e}'`,t,`workdir`)],[`env`,Hp(e,t.env)],[`timeout`,Vd(`Action '${e}'`,t,`timeout`)],[`yieldMs`,Vd(`Action '${e}'`,t,`yieldMs`)],[`background`,Hd(`Action '${e}'`,t,`background`)],[`hitl`,Gp(e,t.hitl)]]),e=>e),qp=(e,t)=>Mp.test(e)?Z(t)?jd(t.description)?Ad(Vp(e,t.command),n=>kd(Kp(e,t),e=>({description:jd(t.description),command:n,...e}))):X(`Action '${e}' is missing description.`):X(`Action '${e}' must be an object.`):X(`Invalid action name '${e}'. Use lowercase letters, numbers, '_' or '-'.`),Jp=e=>Object.entries(e).reduce((e,[t,n])=>Ad(e,e=>kd(qp(t,n),n=>({...e,[t]:n}))),Y({})),Yp=(e,t)=>Z(t)?t.version===1?!Z(t.actions)||Object.keys(t.actions).length===0?X(`actions.yml for skill '${e}' must define non-empty actions.`):kd(Jp(t.actions),e=>({version:1,actions:e})):X(`actions.yml for skill '${e}' must set version: 1.`):X(`actions.yml for skill '${e}' must be an object.`),Xp=e=>e===void 0?Y({}):Z(e)?Y(e):X(`skill_action_run inputs must be an object.`),Zp=()=>new rn({allErrors:!0,strict:!1}),Qp=(e,t,n)=>{if(!t)return Object.keys(n).length===0?Y(n):X(`Action '${e}' does not accept inputs.`);if(t.type!==`object`||!Z(t.properties))return X(`Action '${e}' inputSchema must be an object schema with properties.`);let r=Zp().compile(t);return r(n)?Y(n):X(`Invalid inputs for action '${e}': ${Zp().errorsText(r.errors)}`)},$p=e=>Z(e.inputSchema?.properties)?Object.keys(e.inputSchema.properties):[],em=e=>{let t=`shell`in e.command?Gd(e.command.shell):e.command.argv.flatMap(Gd),n=new Set($p(e)),r=t.filter(e=>!n.has(e));return r.length===0?Y(e):X(`Action command references undeclared input field(s): ${r.join(`, `)}.`)},tm=(e,t)=>e.reduce((e,n)=>Ad(e,e=>kd(Jd(n,t),t=>[...e,t])),Y([])),nm=(e,t)=>`shell`in e.command?Jd(e.command.shell,t):kd(tm(e.command.argv,t),e=>e.map(Kd).join(` `));async function rm(e){let t=await Lp(e);if(t.ok===!1)return X(t.error);let n=await Rp(t.value);if(n.ok===!1)return X(n.error);let r=Ad(zp(t.value.name,n.value.content),e=>Yp(t.value.name,e));if(r.ok===!1)return X(r.error);let i=r.value.actions[e.action];return i?Ad(em(i),r=>Ad(Xp(e.inputs),i=>Ad(Qp(e.action,r.inputSchema,i),i=>kd(nm(r,i),a=>({skill:t.value,actionName:e.action,actionFile:n.value.path,definition:r,inputs:i,command:a,actionHash:Id({version:1,skillName:t.value.name,skillPath:t.value.rootDir,actionName:e.action,actionsFilePath:n.value.path,actionDefinition:r,inputs:i,renderedCommand:a})}))))):X(`Skill '${t.value.name}' does not define action '${e.action}'.`)}const im=e=>[e.definition.hitl?.preview?.text?.trim()?`${e.definition.hitl.preview.text.trim()}\n`:``,`### Skill Action`,`- Skill: ${e.skill.name}`,`- Action: ${e.actionName}`,`- Risk: ${e.definition.hitl?.risk??`medium`}`,``,`### Inputs`,"```json",JSON.stringify(e.inputs,null,2),"```",``,`### Command`,"```bash",e.command,"```",``,`Action hash: ${e.actionHash}`].filter(Boolean).join(`
|
|
88
|
+
`),am=e=>({command:e.command,...e.definition.workdir?{workdir:e.definition.workdir}:{},...e.definition.env?{env:e.definition.env}:{},...e.definition.timeout===void 0?{}:{timeout:e.definition.timeout},...e.definition.yieldMs===void 0?{}:{yieldMs:e.definition.yieldMs},...e.definition.background===void 0?{}:{background:e.definition.background},title:e.definition.hitl?.title||e.definition.description,reason:e.definition.hitl?.reason||`该 action 会执行业务脚本,需要用户确认。`,risk:e.definition.hitl?.risk??`medium`,preview:im(e),policy:{defaultOnTimeout:e.definition.hitl?.defaultOnTimeout??`deny`,...e.definition.hitl?.timeoutMs===void 0?{}:{timeoutMs:e.definition.hitl.timeoutMs}},source:{kind:`skill_action`,skillName:e.skill.name,skillPath:e.skill.rootDir,actionName:e.actionName,actionFile:e.actionFile}});function om(e){return{name:`skill_action_run`,label:`Skill Action Run`,description:`Run an action declared in a skill's actions.yml. Fails closed on invalid config or inputs.`,parameters:jp,async execute(t,n,r){let i=await rm({dataDir:e.dataDir,pluginDirs:e.pluginDirs,skillsLoadPaths:e.skillsLoadPaths,skillName:n.skillName,skillPath:n.skillPath,action:n.action,inputs:n.inputs});if(i.ok===!1)return ef(i.error);try{Ld(e.workspaceDir,i.value.definition.workdir)}catch(e){return ef(e instanceof Error?e.message:String(e))}let a=am(i.value);return i.value.definition.hitl?.required===!0?await df({options:e,toolName:`skill_action_run`,toolCallId:t,guardedParams:a,actionHash:i.value.actionHash,signal:r}):await uf(e,t,a,r)}}}const sm=q.Object({status:q.Union([q.Literal(`complete`),q.Literal(`blocked`)],{description:`Terminal goal status to submit. Use 'complete' only when the objective is genuinely achieved; use 'blocked' when user input or external state is required.`}),summary:q.Optional(q.String({description:`Required for complete: concise final summary of what was achieved.`})),completedTasks:q.Optional(q.Array(q.Object({taskId:q.String({description:`Required task id covered by this completion report entry.`}),evidence:q.Array(q.Object({criterionId:q.String({description:`Acceptance criterion id covered by this evidence.`}),summary:q.String({description:`Manual evidence summary for this acceptance criterion.`}),source:q.String({description:`Where the evidence came from, such as a test command output, file path, or manual review note.`})}))}),{description:`Required for complete: one entry for every required task, with evidence covering every required acceptance criterion.`})),reason:q.Optional(q.String({description:`Required for blocked: concise reason the goal cannot continue.`})),neededInput:q.Optional(q.String({description:`For blocked: exact user input or external condition needed to proceed.`})),risks:q.Optional(q.Array(q.String({description:`Residual risk or follow-up note.`})))});function cm(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function lm(e,t){return cm({ok:!1,error:e,...t})}function um(e){return`warning`in e?e.warning:null}function Q(e){return{storeName:e}}function dm(e){return[...new Set(e.filter(e=>e.trim().length>0))]}async function fm(e,t,n){try{return await Qn(e,t,Q(n))}catch(e){if(e instanceof Hn)return{corrupt:!0};throw e}}function pm(e,t,n,r){let i=n?.trim()?`${t} (needed: ${n.trim()})`:t,a=e.currentTaskId;return{...e,status:`blocked`,blockedReason:i,updatedAt:r,tasks:e.tasks.map(e=>e.id===a?{...e,status:`blocked`,blockedReason:i,updatedAt:r}:e)}}function mm(e,t){let n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`blocked`).map(e=>e.id);if(r.length>0)return{ok:!1,error:`blocked_tasks_remain`,extra:{blockedTaskIds:r}};if(!t||t.length===0)return{ok:!1,error:`missing_completed_tasks`};let i=new Map(e.tasks.map(e=>[e.id,e])),a=new Map;for(let e of t){let t=e.taskId?.trim();if(!t)return{ok:!1,error:`missing_completed_task_id`};let n=i.get(t);if(!n)return{ok:!1,error:`unknown_completed_task`,extra:{taskId:t}};if(n.acceptanceCriteria.length===0)return{ok:!1,error:`missing_acceptance_criteria`,extra:{taskId:t}};let r=new Map(n.acceptanceCriteria.map(e=>[e.id,e])),o=a.get(t)??new Map;a.set(t,o);for(let n of e.evidence??[]){let e=n.criterionId?.trim();if(!e)return{ok:!1,error:`missing_criterion_id`,extra:{taskId:t}};if(!r.has(e))return{ok:!1,error:`unknown_acceptance_criterion`,extra:{taskId:t,criterionId:e}};let i=n.summary?.trim();if(!i)return{ok:!1,error:`missing_evidence_summary`,extra:{taskId:t,criterionId:e}};let a=n.source?.trim();if(!a)return{ok:!1,error:`missing_evidence_source`,extra:{taskId:t,criterionId:e}};let s=o.get(e)??[];s.push({criterionId:e,summary:i,source:a}),o.set(e,s)}}let o=n.filter(e=>!a.has(e.id)).map(e=>e.id);if(o.length>0)return{ok:!1,error:`missing_required_completed_task`,extra:{missingTaskIds:o}};for(let e of n){let t=a.get(e.id),n=e.acceptanceCriteria.filter(e=>e.required!==!1);for(let r of n)if((t.get(r.id)??[]).length===0)return{ok:!1,error:`missing_required_acceptance_evidence`,extra:{taskId:e.id,criterionId:r.id}}}return{ok:!0,report:a}}async function hm(e,t,n,r,i){let a=new Map,o=new Map,s=new Map(n.tasks.map(e=>[e.id,e])),c=[];for(let[n,l]of r.entries()){let r=s.get(n);if(!r)continue;let u=[],d=[],f=new Map(r.acceptanceCriteria.map(e=>[e.id,e]));for(let[a,o]of l.entries()){let s=f.get(a);if(s){for(let l of o){let o=await yr(e,t,{kind:`manual`,summary:`Goal completion ${n}/${a}: ${l.summary}`,content:[`Task: ${r.id} - ${r.title}`,`Acceptance criterion: ${s.id} - ${s.text}`,`Evidence: ${l.summary}`,`Source: ${l.source}`].join(`
|
|
89
|
+
`),source:l.source},Q(i));if(`error`in o)return{ok:!1,error:o.error};u.push(o.evidenceRef),c.push(o.evidenceRef)}d.push(a)}}a.set(n,dm(u)),o.set(n,dm(d))}return{ok:!0,refsByTask:a,criteriaByTask:o,allRefs:dm(c)}}function gm(e,t,n,r,i){return{...e,status:`complete`,currentTaskId:null,blockedReason:null,finalEvidenceRefs:r,completedAt:i,updatedAt:i,tasks:e.tasks.map(e=>e.required===!1?e:{...e,status:`done`,blockedReason:null,acceptanceEvidence:dm([...e.acceptanceEvidence??[],...n.get(e.id)??[]]),evidenceRefs:dm([...e.evidenceRefs??[],...t.get(e.id)??[]]),updatedAt:i})}}function _m(e,t,n){return{name:`goal`,label:`Goal`,description:`Submit a terminal update for the current thread goal. Use only when the goal is complete or genuinely blocked; current goal context is injected by the runtime.`,parameters:sm,async execute(r,i){let a=await H(e,t,Q(n));return a?a.status===`complete`?cm({ok:!0,goalStatus:`complete`,alreadyComplete:!0}):Gn(e,t,Q(n),async()=>{let r=await fm(e,t,n);if(r===null)return lm(`workflow_not_initialized`);if(`corrupt`in r)return lm(`workflow_corrupt`);let o=new Date().toISOString();if(i.status===`blocked`){let s=i.reason?.trim();if(!s)return lm(`missing_reason`);let c=pm(r,s,i.neededInput,o);await pr(e,t,c,Q(n)),await vr(e,t,{type:`goal_task_blocked`,goalId:r.goalId,taskId:r.currentTaskId??void 0,reason:s,neededInput:i.neededInput,evidenceRefs:[]},Q(n)),await gr(e,t,{risks:[c.blockedReason??s]},Q(n));let l=await _r(e,t,c,Q(n));return cm({ok:!0,goalStatus:a.status,workflowStatus:`blocked`,warning:um(l)})}let s=i.summary?.trim();if(!s)return lm(`missing_summary`);let c=mm(r,i.completedTasks);if(c.ok===!1)return lm(c.error,c.extra);let l=await hm(e,t,r,c.report,n);if(l.ok===!1)return lm(l.error);let u=gm(r,l.refsByTask,l.criteriaByTask,l.allRefs,o);await pr(e,t,u,Q(n));try{await V(e,t,{status:`complete`},{...Q(n),eventSource:`tool`})}catch(i){throw await pr(e,t,r,Q(n)),i}await vr(e,t,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:l.allRefs,summary:s,risks:i.risks??[]},Q(n)),await gr(e,t,{finalSummary:s,evidence:l.allRefs,risks:i.risks},Q(n));let d=await _r(e,t,u,Q(n));return cm({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,evidenceRefs:l.allRefs,warning:um(d)})}):lm(`goal_not_found`)}}}q.Object({}),q.Object({status:q.String({description:`Status to set. Only 'complete' is allowed.`})});const vm=q.Union([q.Literal(`pending`),q.Literal(`in_progress`),q.Literal(`completed`)]),ym=q.Object({explanation:q.Optional(q.String({description:`Optional short explanation for why the plan is being updated.`})),tasks:q.Array(q.Object({content:q.String({description:`Short user-visible task description.`}),status:vm}),{description:`Full current task list snapshot in display order.`})}),bm=new Set([`pending`,`in_progress`,`completed`]);function xm(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}function Sm(e){if(!Array.isArray(e.tasks)||e.tasks.length===0)return{ok:!1,error:`empty_tasks`};let t=0,n=[];for(let r of e.tasks){if(!r||typeof r!=`object`)return{ok:!1,error:`invalid_task`};let e=typeof r.content==`string`?r.content.trim():``;if(!e)return{ok:!1,error:`empty_task_content`};let i=r.status;if(!bm.has(i))return{ok:!1,error:`invalid_task_status`};i===`in_progress`&&(t+=1),n.push({content:e,status:i})}if(t>1)return{ok:!1,error:`multiple_in_progress_tasks`};let r=typeof e.explanation==`string`?e.explanation.trim():``;return{ok:!0,...r?{explanation:r}:{},tasks:n}}function Cm(e={}){return{name:`update_task`,label:`Update Task`,description:`Maintain a lightweight task plan for the current coding session. The plan is shown to the user and should help them understand progress on non-trivial work.
|
|
87
90
|
|
|
88
91
|
Use this tool when:
|
|
89
92
|
- The user request has multiple meaningful steps or phases.
|
|
@@ -116,80 +119,80 @@ Numbered/Listed Step Protocol:
|
|
|
116
119
|
- The initial \`update_task\` call must include the ordered list with the first task \`in_progress\` and later tasks \`pending\`.
|
|
117
120
|
- After completing task N, and before any tool call that starts task N+1, call \`update_task\` with task N \`completed\` and task N+1 \`in_progress\`.
|
|
118
121
|
- Never start work for task N+1 while task N is still \`in_progress\`.
|
|
119
|
-
- Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,parameters:
|
|
120
|
-
`)}async function ap(e){let t=zt(await q.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function op(e){let t;try{t=await 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 sp(e){try{return await q.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function cp(e,t){await q.mkdir(J.dirname(e),{recursive:!0}),await q.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function lp(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function up(e){let t=e.trim();if(!t)throw Error(`Auto-skill body cannot be empty.`);if(t.length<20)throw Error(`Auto-skill body is too short to be useful.`);if(t.startsWith(`---`))throw Error(`Auto-skill body must not include frontmatter; metadata is generated by the store.`);return t}function dp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function fp(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function pp(e){return JSON.stringify(e)}const mp=[`create`,`update`,`archive`,`create_category`],hp=Y.Object({}),gp=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.`}))}),vp=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.`}))}),yp=Y.Object({action:Y.Union(mp.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 bp(e){let t=new Gi({dataDir:e});return{name:`auto_skill_categories`,label:`Auto-Skill Categories`,description:`List learned auto-skill categories. Use before auto_skill_list when learned workflows may help.`,parameters:hp,async execute(){try{let e=await t.autoSkillCategories();return Ep({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return Ep({categories:[],count:0,error:Dp(e)})}}}}function xp(e){let t=new Gi({dataDir:e});return{name:`auto_skill_list`,label:`Auto-Skill List`,description:`List active learned auto-skills by category without loading SKILL.md content.`,parameters:gp,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return Ep({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Ep({skills:[],count:0,error:Dp(e)})}}}}function Sp(e){let t=new Gi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:_p,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return Ep({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Ep({skills:[],count:0,error:Dp(e)})}}}}function Cp(e){let t=new Gi({dataDir:e});return{name:`auto_skill_view`,label:`Auto-Skill View`,description:`Load an active learned auto-skill by exact skillId, or read a file inside that auto-skill directory.`,parameters:vp,async execute(e,n){try{return Ep({...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 Ep({skillId:n.skillId,error:Dp(e)})}}}}function wp(e){let t=new rp({dataDir:e});return{name:`auto_skill_manage`,label:`Auto-Skill Manage`,description:`Restricted review-agent tool for creating, updating, archiving learned auto-skills, or creating categories. Do not expose this tool to the main user-facing agent.`,parameters:yp,async execute(e,n){try{return Ep(await Tp(t,n))}catch(e){return Ep({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:Dp(e)})}}}}async function Tp(e,t){if(t.action===`create_category`){if(!t.newCategory)throw Error(`create_category requires newCategory.`);return e.createCategory({path:t.newCategory.path,description:t.newCategory.description})}if(t.action===`create`){if(!t.name||!t.categoryPath||!t.description||!t.body)throw Error(`create requires name, categoryPath, description, and body.`);return e.createSkill({name:t.name,categoryPath:t.categoryPath,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(t.action===`update`){if(!t.skillId)throw Error(`update requires skillId.`);return e.updateSkill({skillId:t.skillId,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(!t.skillId)throw Error(`archive requires skillId.`);return e.archiveSkill({skillId:t.skillId,evidence:t.evidence})}function Ep(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Dp(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const Op=2,kp=5;var Ap=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:ie(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 jp=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.`}))}),Mp=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.`}))}),Np=Y.Object({tasks:Y.Array(jp,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Pp(e){let t=e.label?`"${e.label}"`:`task: ${Ot(e.task)}`;return e.status===`done`?`${t}\n\n${Fp(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Fp(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 Ip(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:ie(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 _=Ft(),v=new AbortController,y=t,b=xa(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return 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?Da(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`,e.artifacts)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),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=Pp({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 Lp(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`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:Mp,async execute(e,t){return Ip(u,e,t)}}}function Rp(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:Np,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 Ip(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${Fp(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
|
|
122
|
+
- Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,parameters:ym,async execute(t,n){let r=Sm(n);return r.ok===!1?xm({ok:!1,error:r.error}):(await e.reportTaskUpdated?.({type:`task_updated`,toolCallId:t,...r.explanation?{explanation:r.explanation}:{},tasks:r.tasks,updatedAt:new Date().toISOString()}),xm({ok:!0,updated:!0,taskCount:r.tasks.length}))}}}var wm=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Ai(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=Fi(e.path),n=Am(e.description,`category description`),r=await this.readCategoryRegistry();if(r[t])throw Error(`Auto-skill category already exists: ${t}`);return r[t]={description:n,createdBy:e.createdBy?.trim()||`review-agent`},await this.writeCategoryRegistry(r),await Yi(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:ji(this.rootDir)}}async createSkill(e){let t=Ii(e.name),n=Fi(e.categoryPath),r=Am(e.description,`auto-skill description`),i=jm(e.body);await this.assertCategoryExists(n);let a=Li(n,t),o=Bi(this.rootDir,n,t);if(await Om(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=K.join(o,`SKILL.md`),l=K.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:Mm(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:Nm(e.evidence,s)};return await G.mkdir(o,{recursive:!0}),await G.writeFile(c,Tm(t,r,i),`utf-8`),await km(l,u),await Yi(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Ri(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Bi(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`SKILL.md`),i=K.join(n,`metadata.json`),a=await Em(r),o=await Dm(i),s=e.description===void 0?a.description:Am(e.description,`auto-skill description`),c=e.body===void 0?a.body:jm(e.body),l=this.now().toISOString(),u={...o,skillId:t.skillId,status:o.status===`archived`?`archived`:`active`,categoryPath:t.categoryPath,source:`auto`,tags:e.tags===void 0?Mm(o.tags):Mm(e.tags),confidence:e.confidence??o.confidence,createdAt:typeof o.createdAt==`string`?o.createdAt:l,updatedAt:l,review:{...typeof o.review==`object`&&o.review!==null?o.review:{},...Nm(e.evidence,l)}};return await G.writeFile(r,Tm(t.skillName,s,c),`utf-8`),await km(i,u),await Yi(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Ri(e.skillId),n=Bi(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`metadata.json`),i=K.join(n,`SKILL.md`);await G.access(i);let a=await Dm(r),o=this.now().toISOString();return await km(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...Nm(e.evidence,o)}}),await Yi(this.rootDir),{action:`archive`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:i,metadataFile:r}}async assertCategoryExists(e){if(!(await this.readCategoryRegistry())[e])throw Error(`Unknown auto-skill category: ${e}. Create it first with create_category.`)}async readCategoryRegistry(){let e=ji(this.rootDir),t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=Fi(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await G.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await km(ji(this.rootDir),t)}};function Tm(e,t,n){return[`---`,`name: ${Pm(e)}`,`description: ${Pm(t)}`,`---`,``,n.trim(),``].join(`
|
|
123
|
+
`)}async function Em(e){let t=Vt(await G.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Dm(e){let t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function Om(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function km(e,t){await G.mkdir(K.dirname(e),{recursive:!0}),await G.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Am(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function jm(e){let t=e.trim();if(!t)throw Error(`Auto-skill body cannot be empty.`);if(t.length<20)throw Error(`Auto-skill body is too short to be useful.`);if(t.startsWith(`---`))throw Error(`Auto-skill body must not include frontmatter; metadata is generated by the store.`);return t}function Mm(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Nm(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Pm(e){return JSON.stringify(e)}const Fm=[`create`,`update`,`archive`,`create_category`],Im=q.Object({}),Lm=q.Object({categoryPath:q.Optional(q.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:q.Optional(q.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),Rm=q.Object({query:q.String({description:`Search query for learned auto-skills.`}),limit:q.Optional(q.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),zm=q.Object({skillId:q.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:q.Optional(q.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),Bm=q.Object({action:q.Union(Fm.map(e=>q.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:q.Optional(q.String({description:`Exact auto-skill id for update/archive.`})),name:q.Optional(q.String({description:`Auto-skill slug for create.`})),categoryPath:q.Optional(q.String({description:`Existing single-level category slug for create.`})),newCategory:q.Optional(q.Object({path:q.String({description:`New single-level category slug to create.`}),description:q.String({description:`New category description.`})})),description:q.Optional(q.String({description:`Auto-skill description for create/update.`})),tags:q.Optional(q.Array(q.String({description:`Auto-skill tag.`}))),confidence:q.Optional(q.Number({description:`Optional confidence score from 0 to 1.`})),body:q.Optional(q.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:q.Optional(q.Object({sessionId:q.String({description:`Source session id.`}),reason:q.String({description:`Why this auto-skill write is justified.`}),toolCallCount:q.Optional(q.Number({description:`Tool calls observed in source run.`})),loadedSkills:q.Optional(q.Array(q.String({description:`Skill loaded during source run.`})))}))});function Vm(e){let t=new Xi({dataDir:e});return{name:`auto_skill_categories`,label:`Auto-Skill Categories`,description:`List learned auto-skill categories. Use before auto_skill_list when learned workflows may help.`,parameters:Im,async execute(){try{let e=await t.autoSkillCategories();return qm({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return qm({categories:[],count:0,error:Jm(e)})}}}}function Hm(e){let t=new Xi({dataDir:e});return{name:`auto_skill_list`,label:`Auto-Skill List`,description:`List active learned auto-skills by category without loading SKILL.md content.`,parameters:Lm,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return qm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return qm({skills:[],count:0,error:Jm(e)})}}}}function Um(e){let t=new Xi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:Rm,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return qm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return qm({skills:[],count:0,error:Jm(e)})}}}}function Wm(e){let t=new Xi({dataDir:e});return{name:`auto_skill_view`,label:`Auto-Skill View`,description:`Load an active learned auto-skill by exact skillId, or read a file inside that auto-skill directory.`,parameters:zm,async execute(e,n){try{return qm({...await t.autoSkillView({skillId:n.skillId,filePath:n.filePath}),usage_hint:n.filePath?`This returned one file inside the auto-skill directory.`:`This returns SKILL.md. If it references helper files, call auto_skill_view({ skillId, filePath }) for only the needed file.`})}catch(e){return qm({skillId:n.skillId,error:Jm(e)})}}}}function Gm(e){let t=new wm({dataDir:e});return{name:`auto_skill_manage`,label:`Auto-Skill Manage`,description:`Restricted review-agent tool for creating, updating, archiving learned auto-skills, or creating categories. Do not expose this tool to the main user-facing agent.`,parameters:Bm,async execute(e,n){try{return qm(await Km(t,n))}catch(e){return qm({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:Jm(e)})}}}}async function Km(e,t){if(t.action===`create_category`){if(!t.newCategory)throw Error(`create_category requires newCategory.`);return e.createCategory({path:t.newCategory.path,description:t.newCategory.description})}if(t.action===`create`){if(!t.name||!t.categoryPath||!t.description||!t.body)throw Error(`create requires name, categoryPath, description, and body.`);return e.createSkill({name:t.name,categoryPath:t.categoryPath,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(t.action===`update`){if(!t.skillId)throw Error(`update requires skillId.`);return e.updateSkill({skillId:t.skillId,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(!t.skillId)throw Error(`archive requires skillId.`);return e.archiveSkill({skillId:t.skillId,evidence:t.evidence})}function qm(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Jm(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const Ym=2,Xm=5;var Zm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),W.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:oe(e.task),startedAt:e.startedAt})}complete(e,t,n){let r=this.entries.get(e);!r||r.record.status!==`running`||(r.record.status=`done`,r.record.result=t,n&&n.length>0&&(r.record.artifacts=n),r.record.endedAt=Date.now(),this.logTerminalStatus(r.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&W.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){W.info(`subagent status changed`,t);return}if(e.status===`killed`){W.warn(`subagent status changed`,t);return}W.error(`subagent status changed`,t)}};const Qm=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),$m=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),eh=q.Object({tasks:q.Array(Qm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function th(e){let t=e.label?`"${e.label}"`:`task: ${At(e.task)}`;return e.status===`done`?`${t}\n\n${nh(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function nh(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function rh(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(W.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:oe(p)}),!p){let e={status:`error`,error:`task must not be empty`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Lt(),v=new AbortController,y=t,b=Ea(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await T(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return W.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}W.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?Ma(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`,e.artifacts)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),W.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,W.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=th({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``,...S.artifacts&&S.artifacts.length>0?{artifacts:S.artifacts}:{}};return W.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return W.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:w}],isError:!0,details:E}}function ih(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?"IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. You MUST also use this tool when the user mentions '@<agent-name>' where <agent-name> matches a custom agent listed in the Custom Agents section — set the `agent` field to that exact name. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. ":`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:$m,async execute(e,t){return rh(u,e,t)}}}function ah(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:eh,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}W.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await rh(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${nh(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
|
|
121
124
|
|
|
122
|
-
`);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const
|
|
123
|
-
`)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Vp(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}function Up(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function Wp(e){let t=Up(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=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 Gp(e){let t=e.watchFactory??((e,t,n)=>Ht.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=Wp({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function $(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function Kp(e){return e.projectDir?.trim()||J.join(e.dataDir,`workspace`)}async function qp(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=Zp(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=Qe({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g,_,v,y,b,x;if(m?.provider)g=m.provider,_=m.registration.id,v=m.registration.pluginId,y=`plugin`,b=!1;else{try{g=Ke({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName},{includeSessions:!0})}catch(e){if(!Ue(e))throw e;x=e instanceof Error?e.message:String(e),g=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=Gp({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,Xp({sessionOptions:$(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,memoryProvider:g,memoryProviderSource:y,memoryFallbackToBuiltin:b,recallState:{recallProvided:!1},compactionRecallState:{recallProvided:!1},appendTranscriptEntry:C,persistInitialUserEntry:async e=>d?!1:(await C({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{S()}}}function Jp(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 Yp(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Xp(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 Zp(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}const Qp=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 $p(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Qp,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}[`Use only the returned evidenceRef values from goal_record_evidence.`,`Natural-language descriptions, file paths, and strings such as 'goal/state.json ...' are not evidence refs unless they are registered in goal/artifacts/registry.jsonl.`,`If command output should prove an acceptance criterion, run it with goal_record_evidence(kind='exec'); regular exec output is not registered goal evidence.`].join(` `);function em(e,t){let n=Kp({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??Pn(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await A(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[Hu({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Ku({registry:i,scopeKey:n}),$u(n,t?.contextManager),td(n,t?.contextManager,s),rd(n,t?.contextManager,s),ad(n),fd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),np({reportTaskUpdated:t?.reportTaskUpdated}),...t?.sessionId?[Xf(e,t.sessionId,t.inheritedRunParams?.sessionStoreName)]:[],Rd(e,r),sf(e,r),Bd(e,r),Wd(e,r),Qd(e,r),ef(e,r),nf(e,r),af(e,r),Vf(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Hf({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(bp(e),xp(e),Sp(e),Cp(e)),t&&c.push(Lp(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Rp(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Hp(t.registry,t.parentSessionId)),c}function tm(e){return e.length===0?``:[`## Auto-Skills`,`Auto-skills are learned from prior completed tasks and are stored separately from curated/user/plugin skills.`,`Auto-skill categories are single-level routing slugs in the current MVP.`,`Prefer curated/user/plugin skills from <available_skills> when both options apply.`,`Use auto-skills only when they clearly match the current task, especially project-specific or previously learned workflows.`,"Match the task to one or more category paths below, call `auto_skill_list({ categoryPath })`, then call `auto_skill_view({ skillId })` for the best match.","If no category is clear but an auto-skill may help, call `auto_skill_search({ query, limit: 5 })`.",`Archived auto-skills are not listed or loaded.`,`<auto_skill_categories>`,[...e].sort((e,t)=>e.path.localeCompare(t.path)).map(e=>e.description?` - ${e.path} | ${e.description}`:` - ${e.path}`).join(`
|
|
125
|
+
`);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const oh=q.Object({action:q.Union([`list`,`kill`].map(e=>q.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:q.Optional(q.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function sh(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.floor(e%6e4/1e3)}s`}function ch(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function lh(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:oh,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let t=o.map((t,n)=>{let r=t.status===`running`?`running`:e.isAnnounced(t.runId)?`delivered`:`pending`;return{index:n+1,runId:t.runId,label:t.label??t.task.slice(0,40),task:t.task,status:t.status,deliveryStatus:r,depth:t.depth,runtimeMs:t.endedAt?t.endedAt-t.startedAt:a-t.startedAt,...t.result===void 0?{}:{result:t.result},...t.error===void 0?{}:{error:t.error}}}),n={action:`list`,runs:t,text:(t.length===0?[`(no subagents)`]:t.map(e=>{let t=e.deliveryStatus===`running`?``:`, ${e.deliveryStatus}`,n=e.result===void 0?e.error===void 0?``:`\n error: ${e.error}`:`\n result: ${e.result}`;return`${e.index}. [${e.status}${t}] ${e.label} (${sh(e.runtimeMs)})${n}`})).join(`
|
|
126
|
+
`)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=ch(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}function uh(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function dh(e){let t=uh(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=K.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function fh(e){let t=e.watchFactory??((e,t,n)=>Wt.watch(e,t,n)),n=K.join(e.dataDir,`.aimax`),r=[{target:K.join(n,`MEMORY.md`),kind:`memory-file`},{target:K.join(n,`memory.md`),kind:`memory-file-lower`},{target:K.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=dh({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function $(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function ph(e){return e.projectDir?.trim()||K.join(e.dataDir,`workspace`)}async function mh(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=ph(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=vh(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??_.id})`:`memory_log routed to ${t} (provider=${p.providerId??_.id})`,details:{providerId:p.providerId??_.id,resolvedProviderId:g?.registration.id??_.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof _.appendRecent==`function`}}).catch(()=>{})}p.source===`sessions`?await n.dispatchDiagnostic(e.sessionId??i,{level:`info`,scope:`memory`,phase:p.reason,message:`session transcript changed`,details:{reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}}).catch(()=>{}):await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=K.join(t.dataDir,`.aimax`),m,g=(()=>{try{return Ke({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName,includeSessions:!0})}catch(e){if(!Ge(e))throw e;m=e instanceof Error?e.message:String(e);let t=hh(p,m);return{provider:t,providerId:t.id,providerSource:`builtin`,fallbackToBuiltin:!0}}})(),_=g.provider,v=g.providerId,y=g.pluginId;m&&await n.dispatchDiagnostic(i,{level:`warn`,scope:`memory`,phase:`memory_provider_degraded`,message:`builtin memory provider degraded after sqlite index failure`,details:{providerId:v,requestedProviderId:o,requestedPluginId:s,error:m}}).catch(()=>{}),await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:v,pluginId:y,providerSource:g.providerSource,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:g.fallbackToBuiltin}}).catch(()=>{});let b=fh({dataDir:t.dataDir,sessionId:i,providerId:o??s??v,provider:_,onMemoryChanged:f});_.sync&&_.sync(`session-start`).catch(()=>{});let x=async e=>{await h(t.dataDir,i,e,_h({sessionOptions:$(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,memoryProvider:_,memoryProviderSource:g.providerSource,memoryFallbackToBuiltin:g.fallbackToBuiltin,recallState:{recallProvided:!1},compactionRecallState:{recallProvided:!1},appendTranscriptEntry:x,persistInitialUserEntry:async e=>d?!1:(await x({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{b()}}}function hh(e,t){return{id:`builtin-memory`,name:`Builtin Memory Provider (degraded)`,status:()=>({backend:`builtin`,provider:`builtin-memory`,workspaceDir:e,dbPath:K.join(e,`.index.sqlite`),dirty:!0,fts:{enabled:!1,available:!1,error:t},vector:{enabled:!1,available:!1,loadError:t},custom:{searchMode:`unavailable`,fallbackActive:!0,fallbackReason:t}}),search:async()=>[],getLines:async()=>[],listFiles:async()=>[],append:async()=>{},updateFile:async()=>{},deleteFile:async()=>{},sync:async()=>{},noteSessionUpdate:()=>{}}}function gh(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function _h(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function vh(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}const yh=q.Object({image:q.String({description:`Image path or URL`}),prompt:q.Optional(q.String({description:`Prompt for image analysis`})),model:q.Optional(q.String({description:`Optional model override`})),maxBytesMb:q.Optional(q.Number({description:`Optional size cap in MB`}))});function bh(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:yh,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}[`Use only the returned evidenceRef values from goal_record_evidence.`,`Natural-language descriptions, file paths, and strings such as 'goal/state.json ...' are not evidence refs unless they are registered in goal/artifacts/registry.jsonl.`,`If command output should prove an acceptance criterion, run it with goal_record_evidence(kind='exec'); regular exec output is not registered goal evidence.`].join(` `);function xh(e,t){let n=ph({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??Rn(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await A(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[qu({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),ff({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Zu({registry:i,scopeKey:n}),id(n,t?.contextManager),od(n,t?.contextManager,s),cd(n,t?.contextManager,s),ud(n),_d(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),Cm({reportTaskUpdated:t?.reportTaskUpdated}),...t?.sessionId?[_m(e,t.sessionId,t.inheritedRunParams?.sessionStoreName)]:[],Df(e,r),Yf(e,r),kf(e,r),Nf(e,r),Vf(e,r),Uf(e,r),Gf(e,r),qf(e,r),kp(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Ap({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed}),om({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,sessionId:t?.sessionId,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv})];return a&&c.push(Vm(e),Hm(e),Um(e),Wm(e)),t&&c.push(ih(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),ah(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),lh(t.registry,t.parentSessionId)),c}function Sh(e){return e.length===0?``:[`## Auto-Skills`,`Auto-skills are learned from prior completed tasks and are stored separately from curated/user/plugin skills.`,`Auto-skill categories are single-level routing slugs in the current MVP.`,`Prefer curated/user/plugin skills from <available_skills> when both options apply.`,`Use auto-skills only when they clearly match the current task, especially project-specific or previously learned workflows.`,"Match the task to one or more category paths below, call `auto_skill_list({ categoryPath })`, then call `auto_skill_view({ skillId })` for the best match.","If no category is clear but an auto-skill may help, call `auto_skill_search({ query, limit: 5 })`.",`Archived auto-skills are not listed or loaded.`,`<auto_skill_categories>`,[...e].sort((e,t)=>e.path.localeCompare(t.path)).map(e=>e.description?` - ${e.path} | ${e.description}`:` - ${e.path}`).join(`
|
|
124
127
|
`),`</auto_skill_categories>`,``].join(`
|
|
125
|
-
`)}const
|
|
128
|
+
`)}const Ch={goal:`Submit a terminal update for the current thread goal: complete or blocked`,read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,guarded_exec:`Request user approval before running a side-effectful command; use when a loaded skill requires HITL before executing a script`,process:`Manage background exec sessions`,update_task:`Update the current task plan for non-trivial multi-step work; initialize before work and advance before starting the next listed step`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,skill_action_run:`Run an action declared in a loaded skill's actions.yml; validates inputs and triggers HITL when required`,auto_skill_categories:`List learned auto-skill categories`,auto_skill_list:`List active learned auto-skills by category`,auto_skill_search:`Search active learned auto-skills`,auto_skill_view:`Load an active learned auto-skill by exact skillId`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},wh=`read_file.write_file.edit_file.list_dir.apply_patch.exec.guarded_exec.process.update_task.skill_list.skill_load.skill_action_run.goal.auto_skill_categories.auto_skill_list.auto_skill_search.auto_skill_view.memory_search.memory_get.memory_write.memory_log.memory_list.memory_forget.memory_update.session_search.subagent_spawn.subagents`.split(`.`);function Th(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...wh.filter(e=>t.has(e)),...n.filter(e=>!wh.includes(e)).sort()],displayName:t}}function Eh(e){let{ordered:t,displayName:n}=Th(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??Ch[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
|
|
126
129
|
`),``].join(`
|
|
127
|
-
`)}function
|
|
128
|
-
`):``}function
|
|
129
|
-
`)}function
|
|
130
|
-
`)}function
|
|
131
|
-
`)}function
|
|
132
|
-
`)}function
|
|
133
|
-
`)}function
|
|
130
|
+
`)}function Dh(e,t){let n=t.toLowerCase();return e.some(e=>e.trim().toLowerCase()===n)}function Oh(e){return Dh(e,`update_task`)?[`## Task Progress`,"When `update_task` is available, use it as the user-visible progress surface for non-trivial multi-step work.","- For multi-step requests, publish an initial plan before the first substantive read, command, or edit, with the first task `in_progress` and later tasks `pending`.","- Keep at most one task `in_progress`, move the next task to `in_progress` when continuing, and publish a final completed snapshot before the final answer when the plan is done.",`- Do not update for tiny internal actions inside one planned step.`,``,`Numbered/Listed Step Protocol:`,`- For explicit numbered or bulleted steps from the user, treat each listed item as a user-visible task.`,"- After completing task N, and before any tool call that starts task N+1, call `update_task` with task N `completed` and task N+1 `in_progress`.","- Never start work for task N+1 while task N is still `in_progress`.",`- Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,`- If you skipped an earlier update, publish the current honest state and continue with per-step updates instead of retroactively pretending progress was tracked.`,``].join(`
|
|
131
|
+
`):``}function kh(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Current goal state is injected through `<goal_context>` when a goal is active.",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,'- Use `goal({ status: "complete", summary, completedTasks })` only when the objective is genuinely achieved and every required task plus required acceptance criterion has evidence summaries and sources.','- Use `goal({ status: "blocked", reason, neededInput })` when user input or external state is required before continuing.',`- Do NOT submit a complete status merely because the budget is nearly exhausted or work is paused.`,`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, the `goal` tool reports an error.",``].join(`
|
|
132
|
+
`)}function Ah(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
|
|
133
|
+
`)}function jh(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
|
|
134
|
+
`)}function Mh(e){return e?``:[`## Tool Call Style`,`Default: call routine low-risk tools directly without narrating every step.`,`Narrate briefly when actions are sensitive, long-running, or likely surprising.`,`When approvals are required, keep the command text exact and complete.`,``].join(`
|
|
135
|
+
`)}function Nh(){return[`## Artifact Declaration`,"Before your final answer, always run an internal artifact audit for the current turn. If the turn produced, modified, returned, exported, downloaded, or made available any user-relevant persistent artifact, declare it at the very end of the assistant message using exactly one `<aimax_artifacts>` block.",`A user-relevant artifact is a deliverable the user or backend may want to open, inspect, download, or display, including files and user-openable URLs.`,`Maintain a private artifact list while working: after every successful tool result, add produced or modified file/URL candidates; before the final answer, serialize the distinct list into the block.`,`Normal answer text does not count as artifact reporting: mentioning a file path or URL in prose is not enough. Every reportable artifact must appear in the block.`,``,`Mandatory artifact sources to audit:`,"- `write_file`: every file written after success.","- `edit_file`: every successfully edited file when the tool says `File edited` or reports occurrences greater than 0. If you changed file contents, declare the edited file even if the final answer only says it was modified.","- `apply_patch`: every added, updated, or moved resulting file; include all files touched by a multi-file patch.","- `exec` / bash / `process`: files generated, exported, downloaded, converted, overwritten, or modified by commands and scripts. Use command arguments, stdout/stderr, path parameters, and follow-up confirmations. If a bash command creates a user deliverable, declare it even when no file-writing tool was used or the result is `(no output)`.",`- Skills, plugin tools, and UI tools: files or URLs produced or returned by tool execution. If a skill returns a user-openable URL as the deliverable, declare that URL even if the visible final answer is only the URL.`,"- `subagent_spawn` / `batch_subagent_spawn`: artifacts returned from child agents; include all child artifacts in the parent block.",`- Assistant-only output: durable URLs or newly created file paths mentioned without a tool call when they are user deliverables.`,``,`Bash/exec detection checklist:`,"- Treat command arguments as evidence; successful `(no output)` does not cancel reporting when the command names a write/edit target.","- Declare files named by redirection or output patterns such as `> file`, `>> file`, `cat > file`, heredoc writers, `tee`, `cp`, `mv`, `curl -o`, `wget -O`, `--output`, `saved to`, `generated file`, `file created`, `file written`, or `文件已生成:<path>`.","- Declare files mutated by commands such as `sed -i`, `perl -pi`, append redirections, `tee -a`, scripts that open/write files, or temp-file replacement patterns like `command > file.tmp && mv file.tmp file`.",`- For heredocs that write a script template, declare the outer script file. Do not declare paths inside the heredoc body until that generated script runs or a later result confirms creation.`,"- Ignore metadata-only lines such as `Generated at:`, file size, byte counts, timestamps, row counts, and column counts; they are not artifact paths.",``,`Do not declare deleted files, failed or rolled-back outputs, files that were only read/listed/searched, temporary/cache files unless explicitly presented as user deliverables, or internal AIMax files such as transcript.jsonl, artifacts.json, session metadata, logs, memory files, context snapshots, and tool-result spill files.`,``,`The block format is a JSON array. Each item must include:`,'- `kind`: `"file"` or `"url"`.','- `file`: file path, required when kind is `"file"`; prefer absolute paths, but use a workspace-relative path if that is what the tool reported.','- `url`: URL value, required when kind is `"url"`.',"- `timestamp`: ISO 8601 timestamp.","- `label`: short human-readable description in the user's language.",``,`Example:`,`<aimax_artifacts>`,`[{"kind":"file","file":"/data/user/workspace/report.md","timestamp":"2026-06-15T10:30:00.000Z","label":"分析报告"},{"kind":"url","url":"https://artifact.example.test/report","timestamp":"2026-06-15T10:31:00.000Z","label":"在线报告"}]`,`</aimax_artifacts>`,``,`Common cases:`,'- After a successful `edit_file` on `src/app.ts`: `[{"kind":"file","file":"src/app.ts","timestamp":"2026-06-15T10:30:00.000Z","label":"已编辑的应用源码"}]`.','- After a bash command writes `dist/report.html`: `[{"kind":"file","file":"dist/report.html","timestamp":"2026-06-15T10:30:00.000Z","label":"生成的 HTML 报告"}]`.','- After a skill returns `https://artifact.example.test/share/abc`: `[{"kind":"url","url":"https://artifact.example.test/share/abc","timestamp":"2026-06-15T10:30:00.000Z","label":"技能生成的在线结果"}]`.',``,`High-risk scenarios:`,"- After `cat > hello.py << 'EOF' ... EOF`, declare `hello.py` even if the command returns `(no output)`.","- After `sed -i '' 's/old/new/' test123.md`, declare `test123.md` even if a later read merely verifies the contents.","- After one turn edits `hello.md` and a subagent returns `test.md`, include both items in the same block. Reporting only one artifact violates the protocol.",`- If a child result text or child task explicitly names a user deliverable path/URL that was created or modified, include it in the parent block even when the child did not emit its own block.`,'- If a skill or command returns a single user-openable URL such as `https://artifact.example.test/result`, declare it as `kind: "url"`; do not return only the visible URL.',``,`Bad outputs that violate the protocol:`,"- Saying `已编辑 test123.md` after `edit_file` or `sed -i` without an `<aimax_artifacts>` block.","- Saying `已创建 hello.py` after `cat > hello.py` without an `<aimax_artifacts>` block.",`- Reporting only one artifact after multiple successful tool calls changed multiple user files.`,``,`Rules:`,`- If no artifacts were produced this turn, do not include the block.`,`- The block must be the last thing in the assistant message.`,"- There must be no text after `</aimax_artifacts>`.",`- The block is for the runtime parser, not for the user.`,`- Do not duplicate the same file or URL inside the block.`,``].join(`
|
|
136
|
+
`)}function Ph(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
|
|
134
137
|
`)).join(`
|
|
135
138
|
`)}\n</available_skills>`,``].join(`
|
|
136
|
-
`)}function
|
|
137
|
-
`)}function
|
|
138
|
-
`)}function
|
|
139
|
-
`)}function
|
|
140
|
-
`)}function
|
|
141
|
-
`)}function
|
|
142
|
-
`)}function
|
|
143
|
-
`)}function
|
|
144
|
-
`)}function
|
|
145
|
-
`)}function
|
|
146
|
-
`)}function
|
|
147
|
-
`)}function
|
|
148
|
-
`):``}function
|
|
149
|
-
`)}function
|
|
150
|
-
`):void 0}var
|
|
151
|
-
`).trim()}function
|
|
152
|
-
|
|
153
|
-
`))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(
|
|
154
|
-
|
|
155
|
-
`))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const
|
|
139
|
+
`)}function Fh(e=[]){let t=Sh(e).trim();return t?`${t}\n`:``}function Ih(){return[`## Scenes`,'If the user message contains a `<scenes category="..." type="..." items="...">...</scenes>` tag, treat it as an explicit scene activation request.',"In this tag, `category` means the scene category, `type` means the scene name, and `items` means the item list required by that scene.","The `category`, `type`, and `items` attributes may each contain one or more comma-separated values. You must split them on commas, trim whitespace, and use every requested value.","Before executing the task, you must enumerate every requested `<category, scene, item>` combination derived from those attributes.","For each requested item, you must call `skill_load(name=<item>, skillPath=/aimax_pvc/scenes/<category>/<scene>/<item>)` to load that item's `SKILL.md`.","If one `<scenes ...>` tag requests multiple items for the same scene, you must load them one by one. Do not stop after the first matching item.","Do not start implementation, analysis, tool execution, or user-facing conclusions until all required scene skills have been loaded with `skill_load`.","After loading those scene `SKILL.md` files through `skill_load`, you must follow their instructions as mandatory task-specific guidance unless a higher-priority instruction overrides them.","For scene skills, if the exact scene SKILL.md is not visible, reload it again with the original `skillPath`.","Scene skills are not loaded by default. Only load them when the user explicitly includes the `<scenes ...>` tag.","Outside explicit scene activation, normal shared skills from `<available_skills>` must still be loaded with `skill_load(name=<skill-name>)` rather than direct file reads.","When a scene is activated, you must load scene instructions only through `skill_load` with `skillPath` pointing at `/aimax_pvc/scenes/<category>/<scene>/<item>` or that directory's `SKILL.md`.","Do not load, match, or fall back to scene instructions from `<dataDir>/.aimax/skills`.","Do not load, match, or fall back to scene instructions from `/aimax/extensions/`.","Do not load, match, or fall back to scene instructions from any path declared in `<available_skills>`.",`Do not ignore, rewrite, or drop the scene tag semantics even if the natural-language request looks answerable without scene skills.`,``].join(`
|
|
140
|
+
`)}function Lh(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
|
|
141
|
+
`)}function Rh(e){return[`## Memory & session recall`,`Choose the right recall surface:`,"- **Durable memory (Markdown / MEMORY.md / memory/ logs)**: stable facts, preferences, policies, decisions. Prefer `memory_search`, then `memory_get` when you need the full passage. Do not guess entry IDs or file paths.","- **Past chat transcripts across sessions** (what was said or done in earlier conversations): use `session_search`. Omit `query` to browse recent sessions; include `query` to search transcripts. Do not use `memory_search` alone to reconstruct a cross-session chat timeline.",'- **Ambiguous** ("last time" could mean chat or written notes): run `session_search` first for conversational evidence, then `memory_search` for durable notes; merge and attribute each source.',"If a listed memory tool call fails, report the failure; do not claim the tool is unavailable. Use `memory_list` before update/delete when needed.","Short tool chains: `memory_search` → `memory_get`; `memory_list` → `memory_update`; `memory_search` → `memory_forget`.",`Routing examples (intent → tool):`,'1) "上次聊天我们怎么修的" → `session_search` with keywords from the bug/symptom.','2) "团队对 release 的硬性规范是什么" → `memory_search` (durable policy).','3) "最近几个会话在忙什么" → `session_search` with no query (recent mode).','4) "把这条写进长期记忆" → `memory_write` (default), not `memory_log` or `session_search`.','5) "昨天日志里有没有记过 X" → `memory_search` on daily logs / `memory_list`.','6) "上次口头结论 vs 正式文档" → `session_search` then `memory_search`.',e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
|
|
142
|
+
`)}function zh(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`,o=e.projectDir?.trim(),s=o?[`Current project directory: ${o}`,`Treat this project directory as the default cwd for repository/code work unless the user specifies another directory.`]:[];return[`## Workspace`,`Your cloud working directory is: ${r}`,...s,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,`Use the workspace temp directories for temporary or intermediate files:`,`- ${r}/temp/daily/ for short-lived files that can be cleaned daily.`,`- ${r}/temp/weekly/ for files that should remain available for about a week.`,`- ${r}/temp/monthly/ for files that should remain available for about a month.`,`Do not pre-initialize these directories; create them only when you actually need to write temporary files.`,``].join(`
|
|
143
|
+
`)}function Bh(e){if(!e?.enabled)return``;let t=[`## Sandbox`,`You are running in a containerized cloud CLI runtime.`];return e.containerWorkspaceDir?.trim()&&t.push(`Container workdir: ${e.containerWorkspaceDir.trim()}`),e.hostWorkspaceDir?.trim()&&t.push(`Host-mounted workspace: ${e.hostWorkspaceDir.trim()}`),t.push(``),t.join(`
|
|
144
|
+
`)}function Vh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Hh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
|
|
145
|
+
`)}function Hh(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(Date.UTC(n,r-1,i));return Number.isNaN(a.getTime())||a.getUTCFullYear()!==n||a.getUTCMonth()!==r-1||a.getUTCDate()!==i?null:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][a.getUTCDay()]}function Uh(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools only when the user or system instructions explicitly require subagents, delegation, or parallel agent execution; otherwise stay in the current agent.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
|
|
146
|
+
`)}function Wh(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
|
|
147
|
+
`)}function Gh(e){return e.isMinimal?``:[`## Silent Replies`,`Do not send empty or filler replies.`,`If a tool already delivered the user-visible output, keep your final reply minimal and avoid duplication.`,``].join(`
|
|
148
|
+
`)}function Kh(e){let t=e.contextFiles,n=(e.bootstrapWarnings??[]).map(e=>e.trim()).filter(Boolean);if(t.length===0&&n.length===0)return``;let r=t.some(e=>(e.path.split(`/`).pop()?.toLowerCase()??``)===`soul.md`),i=[`# Project Context`,``];if(n.length>0){i.push(`⚠ Bootstrap truncation warning:`);for(let e of n)i.push(`- ${e}`);i.push(``)}t.length>0&&(i.push(`The following project context files have been loaded:`),i.push(`These are source-of-truth cloud files at their shown paths. If you update them, use the exact path shown in the heading, especially for files under .aimax.`)),r&&i.push(`If SOUL.md is present, embody its persona and tone. Avoid stiff, generic replies; follow its guidance unless higher-priority instructions override it.`),i.push(``);for(let e of t)i.push(`## ${e.path}`,``,e.content,``);return i.join(`
|
|
149
|
+
`)}function qh(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
|
|
150
|
+
`)}function Jh(e){return e?.trim()?[`## Prior Conversation Summary`,`The following is a summary of the conversation history that occurred before the current context window.`,`Use it to maintain continuity with earlier work.`,``,e.trim(),``].join(`
|
|
151
|
+
`):``}function Yh(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...wh],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,qh(e.subagentDepth??0),Eh({toolNames:i,toolSummaries:e.toolSummaries}),Oh(i),Nh(),Mh(n),kh(),Ah(),ja(e.availableAgents??[]),Ph(a),Fh(e.autoSkillCategories),Ih(),Lh(),Rh(e.memoryCitationsMode??`off`),zh({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Bh(e.sandboxInfo),Vh({currentDate:e.currentDate,timezone:e.timezone}),jh(),Uh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Gh({isMinimal:n}),Wh(e.runtimeInfo),Kh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Jh(e.priorConversationSummary)].filter(Boolean).join(`
|
|
152
|
+
`)}function Xh(e,t,n){return e.map(e=>{let r=e,i=Le(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await me({pluginId:i,hookContext:t,eventDispatcher:n.eventDispatcher},e):await e();try{return await l(async()=>await r.execute(e,c,o,s))}catch(e){if(So(e))return Eo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function Zh(e){let t=!1,n,r;for(let i of e)i&&(i.params&&(r={...r,...i.params}),i.block&&(t=!0,n=i.blockReason));return{blocked:t,blockReason:n,mergedParams:r}}function Qh(e,t){let n=e.content,r=ng(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=$h(n,e.content)),e.details!==void 0){let t=ng(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function $h(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?eg(e,t)?t:[...e,...t]:t}function eg(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!tg(e[n],t[n]))return!1;return!0}function tg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ng(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function rg(e){let{agent:t,hookRegistry:n,hookContext:r,pluginRuntime:i,overrideStore:a}=e,o=new Map;t.beforeToolCall=async({toolCall:e,args:t},s)=>{let c=Date.now();o.set(e.id,c);let l;try{l=await n.dispatch(`before_tool_call`,{toolCallId:e.id,toolName:e.name,params:t},r,i)}catch(t){if(o.delete(e.id),So(t))return Eo(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=Zh(l);if(u){let a=d??`blocked by plugin`;return o.delete(e.id),await n.dispatch(`after_tool_call`,{toolCallId:e.id,toolName:e.name,params:f??t,error:a,durationMs:Math.max(0,Date.now()-c)},r,i),{block:!0,reason:a}}f&&f!==t&&a.set(e.id,f)},t.afterToolCall=async({toolCall:e,args:t,result:a,isError:s},c)=>{let l=o.get(e.id)??Date.now();o.delete(e.id);let u=a.details&&typeof a.details==`object`?a.details:{},d;try{d=await n.dispatch(`tool_result`,{type:`tool_result`,toolCallId:e.id,toolName:e.name,input:t,content:a.content,details:u,isError:s},r,i)}catch(e){if(So(e))return Eo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=Qh({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?ig(f.content)??`tool call failed`:void 0;return await n.dispatch(`after_tool_call`,{toolCallId:e.id,toolName:e.name,params:t,result:{content:f.content,details:f.details,isError:f.isError},...m?{error:m}:{},durationMs:p},r,i),{content:f.content,details:f.details,isError:f.isError}}}function ig(e){if(typeof e==`string`&&e.trim())return e;if(!Array.isArray(e))return;let t=e.map(e=>e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`?e.text.trim():``).filter(Boolean);return t.length>0?t.join(`
|
|
153
|
+
`):void 0}var ag=class e{overrides=new Map;static MAX_SIZE=1e3;set(t,n){this.overrides.size>=e.MAX_SIZE&&this.overrides.clear(),this.overrides.set(t,n)}consume(e,t){let n=this.overrides.get(e);return n?(this.overrides.delete(e),n):t}clear(){this.overrides.clear()}get size(){return this.overrides.size}};const og={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function sg(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function cg(e){let t=sg(e?.warningThreshold,og.warningThreshold),n=sg(e?.criticalThreshold,og.criticalThreshold),r=sg(e?.globalCircuitBreakerThreshold,og.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??og.enabled,historySize:sg(e?.historySize,og.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??og.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??og.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??og.detectors.pingPong}}}function lg(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ug(e,t){return`${e}:${pg(t)}`}function dg(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(dg).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${dg(t[e])}`).join(`,`)}}`}function fg(e){try{return dg(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function pg(e){let t=fg(e);return Ft(`sha256`).update(t).digest(`hex`)}function mg(e,t){if(e===`command_status`)return!0;if(e!==`process`||!lg(t))return!1;let n=t.action;return n===`poll`||n===`log`}function hg(e){return!lg(e)||!Array.isArray(e.content)?``:e.content.filter(e=>lg(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
154
|
+
`).trim()}function gg(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:dg(e)}function _g(e,t,n,r){if(r!==void 0)return`error:${pg(gg(r))}`;if(!lg(n))return n===void 0?void 0:pg(n);let i=lg(n.details)?n.details:{},a=hg(n);if(mg(e,t)&&e===`process`&&lg(t)){let e=t.action;if(e===`poll`)return pg({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return pg({action:e,status:i.status,totalLines:i.totalLines??null,totalChars:i.totalChars??null,truncated:i.truncated??null,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,text:a})}return pg({details:i,text:a})}function vg(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function yg(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function bg(e,t){return[e,t].toSorted().join(`|`)}function xg(e,t,n,r){let i=cg(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ug(t,n),s=vg(a,t,o),c=s.count,l=mg(t,n),u=yg(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${bg(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function Sg(e,t,n,r,i){let a=cg(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ug(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Cg(e,t){let n=cg(t.config),r=_g(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ug(t.toolName,t.toolParams),a=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let o=e.toolCallHistory[n];if(o&&!(t.toolCallId&&o.toolCallId!==t.toolCallId)&&!(o.toolName!==t.toolName||o.argsHash!==i)&&o.resultHash===void 0){o.resultHash=r,a=!0;break}}a||e.toolCallHistory.push({toolName:t.toolName,argsHash:i,toolCallId:t.toolCallId,resultHash:r,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}function wg(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function Tg(e){return e&&e.trim()||`tool`}function Eg(e,t,n){if(!e.execute)return e;let r=Tg(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=xg(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);wg(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Sg(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Cg(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Cg(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Dg(e,t,n){return e.map(e=>Eg(e,t,n))}const Og=new Map;function kg(e){let t=Og.get(e);return t||(t={},Og.set(e,t)),t}function Ag(e){Og.delete(e)}function jg(e){let t=e.streamFn??$t;return(e,n,r)=>(e.api===`anthropic-messages`&&Mg(e),t(e,n,{...r,...zg(e,r)}))}function Mg(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Fg(Rg(e),n)?(globalThis.fetch=t,Ng(await t(e,Ig(e,r)))):t(e,r))}function Ng(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
|
|
155
|
+
|
|
156
|
+
`))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Pg))),a.enqueue(r.encode(e+`
|
|
157
|
+
|
|
158
|
+
`))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Pg=`event: message_start
|
|
156
159
|
data: {"type":"message_start","message":{"id":"","type":"message","role":"assistant","content":[],"model":"","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}
|
|
157
160
|
|
|
158
|
-
`;function
|
|
159
|
-
`),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function Ch(e,t){return`${t.trim()}\n\n${e}`}function wh(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const Th=`<!-- AIMax compaction memory recall -->`;async function Eh(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await Sh({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?`${Th}\n\n${n.block.replace(`${Th}\n\n`,``).trim()}`:void 0}catch{return}}async function Dh(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,$(t)),T={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},E=Vs(t.llm),D=await Au({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=C?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await ju({entries:w,modelInfo:T,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:b,hooks:i,hookCtx:a,contextManager:D,dataDir:t.dataDir,sessionId:n,entriesToMessagesOptions:E});await Ah({runParams:t,sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a,effectivePromptText:f});let k=t.subagentContext?.depth??0,A=r(t.dataDir,n,$(t)),j=Pn(),M=Ta([...em(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,registry:_,processRegistry:j,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:h,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,onLog:t.onLog,messageId:t.messageId,agentPolicy:t.agentPolicy,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:x,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:m,skillsLoadPaths:h,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},reportTaskUpdated:async e=>{await s.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:s,spawnFn:v,baseEnv:t.env}),...p],S),N=M.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),P={};for(let e of M){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||P[t]||(P[t]=n)}let F=t.messaging?.enabled??t.channel!==`CRON`,L=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],R=Om({dataDir:t.dataDir,projectDir:t.projectDir,skills:wa(u,S),autoSkillCategories:x?d:[],contextFiles:c,toolNames:N,toolSummaries:P,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:F,channels:L},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:It.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});R=await kh({systemPrompt:R,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let z,B=t.memory?.core,V=B?.recall?.enabled===!0,H=!!t.subagentContext,U=o.memoryProviderSource===`plugin`&&B?.recall?.forceWithPluginProvider!==!0;if(V&&!H&&!U&&!o.recallState.recallProvided)try{let e=await Sh({provider:o.memoryProvider,query:f,coreConfig:B}),t=B?.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=wh(R,z)),z=e.block,R=Ch(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=Ch(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 ee={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},te=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:R,systemPromptOptions:ee,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=wh(R,z),void 0),R=Ch(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=wh(R,z),void 0),R=Ch(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=oh(km(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},ch),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 Ns(t.dataDir,n,{systemPrompt:R,tools:re},$(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let K=new Bt({initialState:{systemPrompt:R,model:ae,tools:re,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:uh({})}),oe={eventDispatcher:s};a.signal=b;let se=new Rm;return a.toolParamOverrides=se,Im({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 Oh(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 kh(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 Ah(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=jh(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 Eh({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 jh(e){let t=!1,n=[],r=!1;for(let i of e)if(i){if(i.skipPersist&&(t=!0),i.recall?.block?.trim()){n.push(i.recall.block.trim()),r=!0;continue}typeof i.injectRecall==`string`&&i.injectRecall.trim().length>0&&(n.push(i.injectRecall.trim()),r=!0)}return{skipPersist:t,injectRecall:n.length>0?n.join(`
|
|
161
|
+
`;function Fg(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Ig(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Lg(e)&&n.delete(e);return{...t,headers:n}}function Lg(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function Rg(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function zg(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}function Bg(e,t=.3){return e.length===0?!0:e.every(e=>e.score<t)}function Vg(e){return Math.ceil(e.length/4)}function Hg(e,t){if(Vg(e)<=t)return e;let n=t*4;return`${e.slice(0,Math.max(0,n-3)).trimEnd()}...`}async function Ug(e){let t=e.query.trim();if(!t)return{};let n=await e.provider.search(t),r=e.coreConfig?.knowledgeController?.scoreThreshold,i=Bg(n,r);if(n.length===0)return{isWeakLocalRecall:!0};let a=e.coreConfig?.recall?.tokenBudget??1500,o=[`<!-- AIMax persistent memory recall -->`,``,`## Recalled Memory`,``];for(let e of n){let t=e.path.includes(`#`)?e.path:`${e.path} (L${e.startLine})`;o.push(`- **${t}**: ${e.snippet.trim()}`)}return{block:Hg(o.join(`
|
|
162
|
+
`),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function Wg(e,t){return`${t.trim()}\n\n${e}`}function Gg(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const Kg=`<!-- AIMax compaction memory recall -->`;async function qg(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await Ug({provider:e.provider,query:t,coreConfig:{...e.coreConfig,recall:{...e.coreConfig.recall,enabled:!0,tokenBudget:e.coreConfig.compactionRecall?.tokenBudget??e.coreConfig.recall?.tokenBudget}}});return n.block?`${Kg}\n\n${n.block.replace(`${Kg}\n\n`,``).trim()}`:void 0}catch{return}}async function Jg(e){let{session:{runParams:t,sessionId:n,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:l,skills:u,autoSkillCategories:d,effectivePromptText:f,pluginTools:p,pluginSkillDirs:m,skillsLoadPaths:h,presetSystemPrompt:g},dependencies:{registry:_,spawnFn:v,createModel:y,abortSignal:b}}=e,x=t.autoSkills?.load?.enabled===!0,S=t.agentPolicy?.activeAgent,C=t.channel===`CRON`,w=C?[]:await F(t.dataDir,n,$(t)),T={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},E=Ks(t.llm),D=await Fu({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=C?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Iu({entries:w,modelInfo:T,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:b,hooks:i,hookCtx:a,contextManager:D,dataDir:t.dataDir,sessionId:n,entriesToMessagesOptions:E});await Zg({runParams:t,sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a,effectivePromptText:f});let k=t.subagentContext?.depth??0,A=r(t.dataDir,n,$(t)),j=Rn(),M=Aa([...xh(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,registry:_,processRegistry:j,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:h,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,onLog:t.onLog,messageId:t.messageId,agentPolicy:t.agentPolicy,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:x,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:m,skillsLoadPaths:h,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},reportTaskUpdated:async e=>{await s.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:s,spawnFn:v,baseEnv:t.env}),...p],S),N=M.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),P={};for(let e of M){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||P[t]||(P[t]=n)}let ee=t.messaging?.enabled??t.channel!==`CRON`,I=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],L=Yh({dataDir:t.dataDir,projectDir:t.projectDir,skills:ka(u,S),autoSkillCategories:x?d:[],contextFiles:c,toolNames:N,toolSummaries:P,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:ee,channels:I},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Rt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await Xg({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R,te=t.memory?.core,z=te?.recall?.enabled===!0,B=!!t.subagentContext,V=o.memoryProviderSource===`plugin`&&te?.recall?.forceWithPluginProvider!==!0;if(z&&!B&&!V&&!o.recallState.recallProvided)try{let e=await Ug({provider:o.memoryProvider,query:f,coreConfig:te}),t=te?.knowledgeController;if(t?.enabled===!0&&t?.searchMode===`fallback`&&(e.isWeakLocalRecall===!0||!e.block))try{let e=await(await import(`./kc-Omw-bmtO.js`)).runKcFallbackSearch({config:t,query:f});e.block&&(R&&(L=Gg(L,R)),R=e.block,L=Wg(L,R),o.recallState={recallProvided:!0,source:`core`,blockId:e.blockId})}catch(e){await s.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_kc_recall_failed`,message:`KC fallback recall failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}!o.recallState.recallProvided&&e.block&&(R=e.block,L=Wg(L,R),o.recallState={recallProvided:!0,source:`core`,blockId:e.blockId})}catch(e){await s.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_recall_failed`,message:`core recall step failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}let ne={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},re=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:ne,recallState:o.recallState},a,{eventDispatcher:s}),ie=await i.dispatchWithMetadata(`before_prompt_build`,{prompt:f,recallState:o.recallState},a,{eventDispatcher:s});ie.length>0&&console.warn(`[AgentRuntime] before_prompt_build hook(s) fired; this hook is deprecated in favor of before_agent_start. Migrate plugins to before_agent_start.`);let H=[];for(let e of re){if(!e)continue;let t=e;if(t.recall?.block?.trim()){R&&=(L=Gg(L,R),void 0),L=Wg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`),t.message&&H.push(t.message)}for(let e of ie){if(!e.result)continue;let t=e.result;if(t.recall?.block?.trim()){R&&=(L=Gg(L,R),void 0),L=Wg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}if(t.systemPrompt&&(L=t.systemPrompt),t.prependContext){if((e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&o.recallState.recallProvided)continue;L=`${t.prependContext}\n\n${L}`,(e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&(o.recallState={recallProvided:!0,source:`plugin`})}}await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:L},a,{eventDispatcher:s});let ae=Dg(Xh(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},kg),U=S?.model??t.llm.model,oe=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of oe)e&&e.modelOverride&&(U=e.modelOverride);let se=y({...t.llm,model:U},n,t.messageId,t.channel);try{await Rs(t.dataDir,n,{systemPrompt:L,tools:ae},$(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let W=new Ht({initialState:{systemPrompt:L,model:se,tools:ae,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:jg({})}),ce={eventDispatcher:s};a.signal=b;let le=new ag;return a.toolParamOverrides=le,rg({agent:W,hookRegistry:i,hookContext:a,pluginRuntime:ce,overrideStore:le}),O.messages.length>0&&(W.state.messages=O.messages),H.length>0&&(W.state.messages=[...H,...W.state.messages]),{agent:W,resolvedModelId:U,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function Yg(e){let t=await e.hookRegistry.dispatch(`context`,{messages:e.agent.state.messages},e.hookContext,e.pluginRuntime),n=e.agent.state.messages;for(let e of t)!e||!(`messages`in e)||!e.messages||(n=e.messages);n!==e.agent.state.messages&&(e.agent.state.messages=n)}async function Xg(e){if((await m(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})).length<=8)return e.systemPrompt;let t=`Older CRON execution records for this session are stored outside the main transcript at ${N(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})}. The main transcript keeps only the latest 8 CRON summaries. Read that jsonl file explicitly if older CRON outcomes matter.`;return`${e.systemPrompt}\n\n${t}`}async function Zg(e){let{runParams:t,sessionId:n,historyResult:r,runContext:i,eventDispatcher:a,hookRegistry:o,hookContext:s,effectivePromptText:c}=e;for(let e of r.compactionEvents??[])e.type===`compaction`&&await a.dispatchDiagnostic(n,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(r.compactionEntry){let e=r.stats.originalCount-r.stats.keptCount,l=Qg(await o.dispatch(`before_compaction`,{messageCount:r.stats.originalCount,compactingCount:e},s,{eventDispatcher:a})),u=l.injectRecall,d=!!l.pluginRecallProvided;if(t.memory?.core?.compactionRecall?.enabled===!0&&!d&&!i.compactionRecallState.recallProvided)try{let e=await qg({provider:i.memoryProvider,query:c,coreConfig:t.memory.core});e&&(u=e,i.compactionRecallState={recallProvided:!0,source:`core`})}catch(e){await a.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_compaction_recall_failed`,message:`core compaction recall failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}let f=u?{...r.compactionEntry,content:`${u.trim()}\n\n${r.compactionEntry.content}`}:r.compactionEntry;if(l.skipPersist){await a.dispatchDiagnostic(n,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!l.injectRecall}});return}await i.appendTranscriptEntry(f),(r.compactionEvents?.length??0)===0&&await a.dispatchDiagnostic(n,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await o.dispatch(`after_compaction`,{messageCount:r.stats.originalCount,compactedCount:e},s,{eventDispatcher:a})}}function Qg(e){let t=!1,n=[],r=!1;for(let i of e)if(i){if(i.skipPersist&&(t=!0),i.recall?.block?.trim()){n.push(i.recall.block.trim()),r=!0;continue}typeof i.injectRecall==`string`&&i.injectRecall.trim().length>0&&(n.push(i.injectRecall.trim()),r=!0)}return{skipPersist:t,injectRecall:n.length>0?n.join(`
|
|
160
163
|
|
|
161
|
-
`):void 0,pluginRecallProvided:r}}function
|
|
164
|
+
`):void 0,pluginRecallProvided:r}}function $g(e){return e.some(e=>n_(e.message)!==null||e.toolResults.length>0)}function e_(e,t){return{role:`assistant`,content:e,stopReason:(t&&typeof t==`object`?t.code:void 0)===`aborted`||e===`aborted`?`aborted`:`error`,errorMessage:e,timestamp:new Date().toISOString()}}function t_(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];for(let e=r.toolResults.length-1;e>=0;e--){let n=r.toolResults[e];if(n.toolName===t&&n.content.trim().length>0)return n.content}}return``}function n_(e){let t=c_(e),n=r_(e),r=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&r.length===0)return null;let i={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.trim().length>0&&(i.thinking=n),r.length>0&&(i.toolCalls=r),i}function r_(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function i_(e){return e.map(e=>r_(e.message)).filter(e=>e.trim().length>0).join(`
|
|
162
165
|
|
|
163
|
-
`)}function
|
|
166
|
+
`)}function a_(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function o_(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function s_(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:l_(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function c_(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function l_(e){let t=e.indexOf(`
|
|
164
167
|
Preview:
|
|
165
|
-
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function Uh(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f,artifactAccumulator:p}=e,m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=yo(),O=Le(),k=new Ua,A={workspaceDir:l.workspaceDir},j=new Set,M=Promise.resolve(),N,P=0,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(()=>B(e));M=t.catch(()=>{}),L(t)});async function B(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=ig(`partial`in t?t.partial:void 0)??ig(`message`in t?t.message:void 0)??ig(`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=Vh(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=Vh(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=Yh(t));let r=Ia(Vh(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:Bh(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=Rh(Fh(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(zh);(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=rg(e.result),r=ng(e.result);p?.addChild(Wh(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Bh(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(Ga({toolName:e.toolName,input:c,result:e.result,isError:!!e.isError,workspaceDir:l.workspaceDir})),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_completed`,message:`tool call completed`,details:{toolCallId:e.toolCallId,toolName:e.toolName,input:c,output:n,isError:e.isError,...o?{toolResultRef:o}:{}}}),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let V=cs(d),H=V.enabled?V.maxAttempts:1;try{Gh({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=H;e++){let d=C.length;b=void 0,y=void 0,P=0,F=0;try{await Oh({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:H,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await bo(D,async()=>{await pe(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await 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:H,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=og(T),K.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:H,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...Po(T,`providerError`)}),await ee(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:H,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await R(),_o(t)||Ie(t))throw t;if(y=og(t),K.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:H,error:y}),await ee(t,y,e,d))continue;await te(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{z()}function U(){m=``,h=``,g=``}async function ee(e,n,r,a){let o=Jh({error:e,attempt:r,maxAttempts:H,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g});if(!o.retry)return K.warn(`llm turn retry skipped`,{sessionId:i,attempt:r,maxAttempts:H,error:n,reason:o.reason,retryableError:o.retryableError,attemptRecordCount:o.attemptRecordCount,recordsWithToolResults:o.recordsWithToolResults,recordsWithAssistantText:o.recordsWithAssistantText,hasFinalAssistantText:o.hasFinalAssistantText,hasStreamedAssistantSnapshot:o.hasStreamedAssistantSnapshot,hasStreamedTextSinceBoundary:o.hasStreamedTextSinceBoundary}),!1;let c=ls(r,V);return K.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:H,delayMs:c,error:n}),await Qh({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:H,message:n,delayMs:c}),C.length=a,U(),$h(t),await us(c,u),!0}async function te(e,t){f&&await f(Nh(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?Ia(Vh(C[C.length-1].message),A).cleanedText:``,re=Ia(m,A).cleanedText,G=W||re||Ph(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!Mh(C)&&!y&&m.trim().length>0){let e=Ia(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await ie(e.warnings);let t=Lh(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 Wh(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 Gh(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:Kh(a,e.message),s=qh(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Wo(n,{systemPrompt:i,messages:o,tools:s.length>0?s.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},t),c=typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`;e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`runner`,phase:`model_request_preview`,message:`model request preview`,details:{model:n.id,provider:c,systemPrompt:i,tools:s,requestJson:a}})}catch{}}function Kh(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function qh(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 Jh(e){let t=e.turnRecords.slice(e.attemptTurnRecordStart),n=t.filter(e=>e.toolResults.length>0).length,r=t.filter(e=>Vh(e.message).trim().length>0).length,i=e.finalAssistantText.trim().length>0,a=e.streamedAssistantSnapshot.trim().length>0,o=e.streamedTextSinceBoundary.trim().length>0,s=ds(e.error),c={retryableError:s,attemptRecordCount:t.length,recordsWithToolResults:n,recordsWithAssistantText:r,hasFinalAssistantText:i,hasStreamedAssistantSnapshot:a,hasStreamedTextSinceBoundary:o};return e.attempt>=e.maxAttempts?{retry:!1,reason:`max_attempts_exhausted`,...c}:s?i||a||o?{retry:!1,reason:`assistant_text_already_streamed`,...c}:n>0?{retry:!1,reason:`tool_results_already_produced`,...c}:r>0?{retry:!1,reason:`assistant_text_already_recorded`,...c}:{retry:!0,...c}:{retry:!1,reason:`error_not_retryable`,...c}}function Yh(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:Xh(t.errorCode),statusCode:Zh(t.statusCode),providerCode:Xh(t.providerCode),providerType:Xh(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function Xh(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Zh(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Qh(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 $h(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&eg(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function eg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:tg(t.content):!1}function tg(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 ng(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return rg(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):rg(e)}function rg(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function ig(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 og(e){let t=sg(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 sg(e){if(e instanceof me)return e;if(e&&typeof e==`object`&&!(e instanceof Error)){let t=e,n=typeof t.message==`string`&&t.message.trim()?t.message:void 0;return!n&&t.code===void 0&&t.statusCode===void 0?null:{message:n??`Unknown LLM error`,code:Xh(t.code),statusCode:Zh(t.statusCode),statusText:Xh(t.statusText),providerMessage:Xh(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 cg(e){let t=mg(e.toolResultPreviewChars),n=hg(e.systemPrompt,e.agentDefinition),r=_g(e.model,e.agentDefinition),i=Ta(e.tools??[],e.agentDefinition),a=gg(e.message,e.agentDefinition),o=await Uh({agent:new Bt({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:lg({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new le,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:dg(o.turnRecords),toolResults:fg(o.turnRecords,t)}}function lg(e){let t=e.phasePrefix??`silent_agent`;return new Na({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await ug(e.diagnosticDispatcher,t,n)}})}async function ug(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 dg(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 fg(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:pg(e.content,t)})))}function pg(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function mg(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 hg(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
|
|
168
|
+
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function u_(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f,artifactAccumulator:p}=e,m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=wo(),O=ze(),k=new Ja,A={workspaceDir:l.workspaceDir},j=new Set,M=Promise.resolve(),N,P=0,ee=0,F={eventDispatcher:s},I=e=>{j.add(e),e.catch(e=>{N??=e}).finally(()=>{j.delete(e)})},L=async()=>{for(;j.size>0;)await Promise.allSettled([...j]);if(N)throw N},R=t.subscribe(e=>{let t=M.then(()=>te(e));M=t.catch(()=>{}),I(t)});async function te(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`agent_start`){c.dispatch(`agent_start`,{turnIndex:P},l,F).catch(()=>{});return}if(e.type===`turn_start`){ee=P,P+=1,c.dispatch(`turn_start`,{turnIndex:ee,timestamp:Date.now()},l,F).catch(()=>{});return}if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=T_(`partial`in t?t.partial:void 0)??T_(`message`in t?t.message:void 0)??T_(`message`in e?e.message:void 0),a=E_(t.delta,r,h);r?(h=r,g=r):a&&(g+=a);let o=k.push(a);o&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:o})}if(t.type===`done`){let e=t.message;if(n()){m=``,h=``,g=``,k.reset(),e.usage&&(_=e.usage.input,v=e.usage.output);return}m=c_(e);let r=E_(``,m,g||h);h=m,g=m;let a=`${k.push(r)}${k.finish()}`;a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a}),e.usage&&(_=e.usage.input,v=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(_=t.usage.input,v=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=c_(e);!m&&n&&(m=n);let r=k.finish();r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:t.usage?{input:_,output:v,total:_+v}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(b=g_(t));let r=Va(c_(t),A);n||(r.artifacts.length>0&&p?.addOwn(r.artifacts),await oe(r.warnings));let a=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:s_(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),o=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),s=new Set(a.map(e=>e.toolCallId));for(let e of T.values())!s.has(e.toolCallId)&&o.has(e.toolCallId)&&a.push(e);for(let e of a)T.delete(e.toolCallId);if(C.push({message:t,toolResults:a}),f&&!n){let e=!!D.signal,n=!!O.signal;if(!(e&&D.signal.transparentPause)){let i=a_(n_(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(o_);(i||o.length>0)&&await f(i,o)}if(e||n)return}await c.dispatch(`turn_end`,{turnIndex:ee,message:t,toolResults:a},l,F);return}if(e.type===`tool_execution_start`){let t=k.finish();t&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:t}),k.reset(),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_planned`,message:`tool call planned`,details:{toolCallId:e.toolCallId,toolName:e.toolName,args:e.args}}),g=``,w.set(e.toolCallId,e.args),D.signal?.transparentPause!==!0&&!E.has(e.toolCallId)&&(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args}));return}if(e.type===`tool_execution_end`){let n=w_(e.result),r=C_(e.result);p?.addChild(d_(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:s_(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(Xa({toolName:e.toolName,input:c,result:e.result,isError:!!e.isError,workspaceDir:l.workspaceDir})),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_completed`,message:`tool call completed`,details:{toolCallId:e.toolCallId,toolName:e.toolName,input:c,output:n,isError:e.isError,...o?{toolResultRef:o}:{}}}),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let z=ps(d),B=z.enabled?z.maxAttempts:1;try{f_({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=B;e++){let d=C.length;b=void 0,y=void 0,P=0,ee=0;try{await Yg({agent:t,hookRegistry:c,hookContext:l,pluginRuntime:F});let f=await c.dispatch(`before_provider_request`,{model:a,messages:t.state.messages,tools:t.state.tools},l,F);for(let e of f)if(e){if(e.abort)return await L(),{text:m,inputTokens:_,outputTokens:v,error:y,turnRecords:C};e.messages&&(t.state.messages=e.messages),e.tools&&(t.state.tools=e.tools)}if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);W.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await To(D,async()=>{await he(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await L();let p=D.signal;if(p)throw p;let h=O.signal;if(h)throw h;let g=C.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!b&&C.length>0&&!g&&m.trim().length===0&&(W.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let S=t.state,w=typeof S.error==`string`?S.error:typeof S.errorMessage==`string`?S.errorMessage:void 0,T=b??w;if(T){let t=b?`sdk`:`agent_state`;if(y=D_(T),W.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...zo(T,`providerError`)}),await ne(T,y,e,d))continue;await re(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||W.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await L(),So(t)||Re(t))throw t;if(y=D_(t),W.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y}),await ne(t,y,e,d))continue;await re(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{R()}function V(){m=``,h=``,g=``}async function ne(e,n,r,a){let o=h_({error:e,attempt:r,maxAttempts:B,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g});if(!o.retry)return W.warn(`llm turn retry skipped`,{sessionId:i,attempt:r,maxAttempts:B,error:n,reason:o.reason,retryableError:o.retryableError,attemptRecordCount:o.attemptRecordCount,recordsWithToolResults:o.recordsWithToolResults,recordsWithAssistantText:o.recordsWithAssistantText,hasFinalAssistantText:o.hasFinalAssistantText,hasStreamedAssistantSnapshot:o.hasStreamedAssistantSnapshot,hasStreamedTextSinceBoundary:o.hasStreamedTextSinceBoundary}),!1;let c=ms(r,z);return W.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:B,delayMs:c,error:n}),await y_({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:B,message:n,delayMs:c}),C.length=a,V(),b_(t),await hs(c,u),!0}async function re(e,t){f&&await f(e_(e,t),[])}let ie=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:ie,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let H=O.signal?``:C.length>0?Va(c_(C[C.length-1].message),A).cleanedText:``,ae=Va(m,A).cleanedText,U=H||ae||t_(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!$g(C)&&!y&&m.trim().length>0){let e=Va(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await oe(e.warnings);let t=i_(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:U,inputTokens:_,outputTokens:v,error:y,turnRecords:C};async function oe(e){for(let t of e)await s.dispatchDiagnostic(i,{level:`warn`,scope:`runner`,phase:`artifact_parse`,message:t})}}function d_(e,t){if(e!==`subagent_spawn`&&e!==`batch_subagent_spawn`)return[];let n=t&&typeof t==`object`?t.details:void 0;if(!n||typeof n!=`object`)return[];if(e===`subagent_spawn`){let e=n.artifacts;return Array.isArray(e)?e:[]}let r=n.results;return Array.isArray(r)?r.flatMap(e=>{let t=e&&typeof e==`object`?e.artifacts:void 0;return Array.isArray(t)?t:[]}):[]}function f_(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model,r=e.agent.state?.thinkingLevel;if(!n||typeof n.id!=`string`)return;let i=typeof t?.systemPrompt==`string`?t.systemPrompt:``,a=Array.isArray(t?.messages)?[...t.messages]:[],o=e.continueFromHistory?a:p_(a,e.message),s=m_(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Yo(n,{systemPrompt:i,messages:o,tools:s.length>0?s.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},t),c=typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`;e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`runner`,phase:`model_request_preview`,message:`model request preview`,details:{model:n.id,provider:c,systemPrompt:i,tools:s,requestJson:a}})}catch{}}function p_(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function m_(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function h_(e){let t=e.turnRecords.slice(e.attemptTurnRecordStart),n=t.filter(e=>e.toolResults.length>0).length,r=t.filter(e=>c_(e.message).trim().length>0).length,i=e.finalAssistantText.trim().length>0,a=e.streamedAssistantSnapshot.trim().length>0,o=e.streamedTextSinceBoundary.trim().length>0,s=gs(e.error),c={retryableError:s,attemptRecordCount:t.length,recordsWithToolResults:n,recordsWithAssistantText:r,hasFinalAssistantText:i,hasStreamedAssistantSnapshot:a,hasStreamedTextSinceBoundary:o};return e.attempt>=e.maxAttempts?{retry:!1,reason:`max_attempts_exhausted`,...c}:s?i||a||o?{retry:!1,reason:`assistant_text_already_streamed`,...c}:n>0?{retry:!1,reason:`tool_results_already_produced`,...c}:r>0?{retry:!1,reason:`assistant_text_already_recorded`,...c}:{retry:!0,...c}:{retry:!1,reason:`error_not_retryable`,...c}}function g_(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:__(t.errorCode),statusCode:v_(t.statusCode),providerCode:__(t.providerCode),providerType:__(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function __(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function v_(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function y_(e){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`runner`,phase:`llm_turn_retry_scheduled`,message:`retrying transient LLM turn failure`,details:{attempt:e.attempt,nextAttempt:e.attempt+1,maxAttempts:e.maxAttempts,delayMs:e.delayMs,error:e.message}})}function b_(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&x_(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function x_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:S_(t.content):!1}function S_(e){return e==null?!0:typeof e==`string`?e.trim().length===0:Array.isArray(e)?e.every(e=>{if(!e||typeof e!=`object`)return!0;let t=e;return t.type===`toolCall`?!1:t.type===`text`?typeof t.text!=`string`||t.text.trim().length===0:!0}):!1}function C_(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return w_(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):w_(e)}function w_(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function T_(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function E_(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function D_(e){let t=O_(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function O_(e){if(e instanceof ge)return e;if(e&&typeof e==`object`&&!(e instanceof Error)){let t=e,n=typeof t.message==`string`&&t.message.trim()?t.message:void 0;return!n&&t.code===void 0&&t.statusCode===void 0?null:{message:n??`Unknown LLM error`,code:__(t.code),statusCode:v_(t.statusCode),statusText:__(t.statusText),providerMessage:__(t.providerMessage)}}if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function k_(e){let t=F_(e.toolResultPreviewChars),n=I_(e.systemPrompt,e.agentDefinition),r=R_(e.model,e.agentDefinition),i=Aa(e.tools??[],e.agentDefinition),a=L_(e.message,e.agentDefinition),o=await u_({agent:new Ht({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:A_({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new de,hookCtx:{sessionId:e.sessionId},abortSignal:e.abortSignal});return{text:o.text,usage:{input:o.inputTokens,output:o.outputTokens,total:o.inputTokens+o.outputTokens},error:o.error,toolCalls:M_(o.turnRecords),toolResults:N_(o.turnRecords,t)}}function A_(e){let t=e.phasePrefix??`silent_agent`;return new Ra({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await j_(e.diagnosticDispatcher,t,n)}})}async function j_(e,t,n){let r=n.sessionId;if(r){if(n.type===`stream_text_delta`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_stream`,message:`silent agent streamed text`,details:{textLength:n.text.length}});return}if(n.type===`tool_start`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_tool_started`,message:`silent agent tool started`,details:{toolCallId:n.toolCallId,toolName:n.name,input:n.input}});return}if(n.type===`tool_end`){await e.dispatchDiagnostic(r,{level:n.isError?`warn`:`info`,scope:`skill`,phase:`${t}_tool_completed`,message:n.isError?`silent agent tool failed`:`silent agent tool completed`,details:{toolCallId:n.toolCallId,toolName:n.name,isError:n.isError}});return}if(n.type===`error`){await e.dispatchDiagnostic(r,{level:`warn`,scope:`skill`,phase:`${t}_error`,message:`silent agent reported error`,details:{error:n.message}});return}n.type===`diagnostic`&&await e.dispatchDiagnostic(r,{level:n.level,scope:n.scope,phase:`${t}_${n.phase}`,message:n.message,...n.details?{details:n.details}:{}})}}function M_(e){let t=[];for(let n of e)for(let e of n.message.content)e.type===`toolCall`&&t.push({id:e.id,name:e.name,arguments:e.arguments??{}});return t}function N_(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:P_(e.content,t)})))}function P_(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function F_(e){let t=e??800;if(!Number.isFinite(t))throw Error(`toolResultPreviewChars must be a finite non-negative integer.`);return Math.max(0,Math.floor(t))}function I_(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
|
|
166
169
|
|
|
167
|
-
`)}function
|
|
168
|
-
`)}function
|
|
169
|
-
`)}function Og(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=kg(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 kg(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Ag=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],jg=Ag,Mg={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}},Ng=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Pg(e){let t=Ig(e.gates),n={session:Rg(`session`,e.sessionTranscript,t.session),currentRun:Rg(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:Rg(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Hg(e.reviewState?.reviewCount,0),i=Hg(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return Wg(n,a,r,i,o,`run_error`);if(e.result?.paused)return Wg(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return Wg(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return Wg(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 Fg(e,t={}){let n=Gr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Ag),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(Gg(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}Kg(t)&&qg(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 Ig(e){return{session:Lg(e?e.session:Mg.session),currentRun:Lg(e?e.currentRun:Mg.currentRun),reviewWindow:Lg(e?e.reviewWindow:Mg.reviewWindow)}}function Lg(e){let t={};for(let n of Ng){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?jg:void 0;if(typeof r==`number`){let e=Vg(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Vg(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:Ug(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:Ug(r.toolNames,i)})}return t}function Rg(e,t,n){let r=Fg(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Ng.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];zg(t,o,r)?i.push({code:t,description:Bg(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 zg(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 Bg(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 Vg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Hg(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Ug(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function Wg(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 Gg(e){return e.role===`assistant`}function Kg(e){return e.role===`tool_result`}function qg(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:Jg(e.content)?.success===!1}function Jg(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function Yg(e){let t=qr(e.transcript.length,e.transcriptStartIndex),n=Jr(e.transcript.length,e.recentEntryLimit),r=qr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=qr(e.transcript.length,0),a=Yr(e.transcript,t),o=Yr(e.transcript,r),s=Fg(e.transcript),c=Fg(a),l=Fg(o),u=Wr(e.transcript),d=Wr(a),f=Wr(o),p=a.filter(Zg),m=a.filter(Qg);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:Xg(p[0]?.content??``,800),finalResponse:Xg(e.result.text||m.at(-1)?.content||``,800),contextFiles:e.contextFiles,currentRunRange:t,recentRange:n,reviewWindowRange:r,sessionStats:u,currentRunStats:d,reviewWindowStats:f,session:{transcriptRange:i,stats:u,toolStats:s},currentRun:{transcriptRange:t,stats:d,toolStats:c},reviewWindow:{transcriptRange:r,stats:f,toolStats:l},reviewState:{reviewCount:e.reviewState?.reviewCount??0,lastCompletedReviewAt:e.reviewState?.lastCompletedReviewAt??null,lastReviewedTranscriptEndIndex:e.reviewState?.lastReviewedTranscriptEndIndex??null},transcriptSummary:{entryCount:d.totalEntryCount,userTurnCount:d.userTurnCount,assistantTurnCount:d.assistantTurnCount,toolResultCount:d.toolResultCount},toolStats:c,loadedSkills:c.loadedSkills,viewedAutoSkills:c.viewedAutoSkills,failedTools:Kr(a,{limit:8,maxPreviewChars:400}).map(e=>({toolName:e.toolName,preview:e.preview})),activeCategories:(e.activeCategories??[]).map(e=>({path:e.path,description:e.description}))}}function Xg(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Zg(e){return e.role===`user`}function Qg(e){return e.role===`assistant`}function $g(e,t,n){return J.join(r(e,t,n),`auto-skill-review-state.json`)}function e_(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function t_(e,t,n){let r=$g(e,t,n),i;try{i=await q.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return e_(t);throw e}return o_(JSON.parse(i),t)}async function n_(e,t,n){let r=$g(e,t.sessionId,n);await q.mkdir(J.dirname(r),{recursive:!0}),await q.writeFile(r,`${JSON.stringify(o_(t,t.sessionId),null,2)}\n`,`utf-8`)}async function r_(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await n_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function i_(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 n_(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 n_(e.dataDir,t,{storeName:e.sessionStoreName}),t}function o_(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:l_(n.reviewCount,0),lastAttemptedReviewAt:s_(n.lastAttemptedReviewAt),lastCompletedReviewAt:s_(n.lastCompletedReviewAt),lastFailedReviewAt:s_(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:c_(n.lastReviewedTranscriptEndIndex)}}function s_(e){return typeof e==`string`&&e.trim()?e:null}function c_(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function l_(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function u_(e){return J.join(Ei(e),`.reviews`,`run-log.jsonl`)}async function d_(e,t){let n=u_(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 f_=`write`,p_=new Set([`off`,`gate`,`dry_run`,`write`]);async function m_(e){let t=h_(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=__(e);if(n){await x_(e,t,n);return}let r,i;try{let n=await I(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=v_(n,e.transcriptStartIndex),o=await t_(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=y_(o.lastReviewedTranscriptEndIndex,n.length),c=v_(n,s);await S_(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=Pg({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await S_(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 C_(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await S_(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Gi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=Yg({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:ci(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await S_(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await C_(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(wg);if(!p){K.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:wg}),await x_(e,t,`reviewer_agent_missing`,{reviewerAgentName:wg});return}i={mode:f,decision:l,packet:d},r=await r_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:o,sessionStoreName:e.runParams.sessionStoreName}),await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_started`,message:`auto-skill review agent started`,details:{mode:t.mode,selectedGateScope:l.selectedGateScope,reviewCount:l.reviewCount,maxReviewsPerSession:l.maxReviewsPerSession}});let m=e.curator??Tg,h=Cg({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 w_(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await b_(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:T_(g.toolCalls),toolResults:M_(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await i_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await w_(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:j_(g.text,2e3),toolCalls:T_(g.toolCalls),toolResults:M_(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 w_(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await b_(e,n,a?{reviewRunLogPath:a}:void 0)}}function h_(e){return{mode:g_(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function g_(e){if(e==null)return f_;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?p_.has(t)?t:`off`:f_}function __(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 v_(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function y_(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function b_(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 x_(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 S_(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function C_(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:A_(n),...i.packet?{packet:i.packet}:{}}})}async function w_(e,t,n){return d_(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?D_(n.curatorResult.text):void 0,conclusionText:n.curatorResult?O_(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?T_(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?M_(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 T_(e){return e.map(e=>({...e,arguments:E_(e.name,e.arguments)}))}function E_(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 D_(e){let t=k_(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function O_(e){return D_(e)?void 0:j_(e,8e3)}function k_(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 A_(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 j_(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function M_(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let N_=!1;function P_(){N_||=(Xt(),Yt({api:`openai-completions`,stream:Ho,streamSimple:Uo}),!0)}const F_=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`,`- As the user role, summarize the title based on the conversation content`,`- The principle of title generation is to describe the behavioral characteristics of the user in the conversation, rather than answering based on the content of the conversation`].join(`
|
|
170
|
-
`);async function
|
|
170
|
+
`)}function L_(e,t){return!t?.initPrompt||typeof e!=`string`?e:Ma(t,e)}function R_(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const z_=q.Object({kind:q.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>q.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:q.Optional(q.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:q.Optional(q.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:q.Optional(q.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:q.Optional(q.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function B_(e){let t=ui({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??ai}),n={storeName:e.storeName};return{name:`auto_skill_review_context_view`,label:`Auto-Skill Review Context`,description:`Internal read-only review tool for controlled access to the current session transcript and persisted tool-result evidence. Only use inside the auto-skill review agent.`,parameters:z_,async execute(r,i){try{return i.kind===`tool_result`?H_(await li({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?H_(await oi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?H_(await si({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?H_({...await ci({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):H_(await ci({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:V_(i),limits:t}))}catch(r){return H_({kind:i.kind,error:U_(r),limits:t,contextFiles:fi(e.dataDir,e.sessionId,n)})}}}}function V_(e){if(typeof e.startIndex!=`number`||typeof e.endIndex!=`number`)throw Error(`transcript_range requires startIndex and endIndex.`);return{startIndex:e.startIndex,endIndex:e.endIndex}}function H_(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function U_(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function W_(e){let t=[Hm(e.dataDir),Um(e.dataDir),Wm(e.dataDir),B_({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(Gm(e.dataDir)),t}const G_=`auto-skill-reviewer`;async function K_(e){let t=e.createModel??ga,n=e.tools??W_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:e.mode,currentRunRange:e.packet.currentRunRange,recentRange:e.packet.recentRange,reviewWindowRange:e.packet.reviewWindowRange}),r=t(e.runParams.llm,e.sessionId,e.runParams.messageId,e.runParams.channel),i=await k_({sessionId:e.sessionId,systemPrompt:q_(e.mode),message:J_(e.packet,e.mode),tools:n,model:r,getApiKey:t=>e.runParams.llm.apiKey,agentDefinition:e.reviewerAgent,abortSignal:e.runParams.abortSignal,diagnosticDispatcher:e.diagnosticDispatcher,diagnosticPhasePrefix:`auto_skill_review_internal`}),a=i.toolCalls,o=i.toolResults,s=Y_(o);return{text:i.text,usage:i.usage,toolCalls:a,toolResults:o,writeResults:s,wrote:s.some(e=>!e.isError&&e.success===!0&&!e.error),error:i.error}}function q_(e){let t=e===`write`?"Write mode is active. `auto_skill_manage` is exposed for this run.":"Dry-run mode is active. `auto_skill_manage` is not exposed for this run.",n=[`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`auto_skill_review_context_view`,...e===`write`?[`auto_skill_manage`]:[]];return[`Run the configured auto-skill reviewer agent against the review packet for this invocation.`,`Apply the durable reviewer policy from the selected AgentDefinition together with the mode and tool boundaries below.`,``,`Current review mode: ${e}`,`Tools exposed for this run:`,...n.map(e=>`- ${e}`),``,t].join(`
|
|
171
|
+
`)}function J_(e,t){return[`Review mode: ${t}`,`Use the following auto-skill review packet as the source input for this invocation.`,``,`<auto_skill_review_packet>`,JSON.stringify(e,null,2),`</auto_skill_review_packet>`].join(`
|
|
172
|
+
`)}function Y_(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=X_(e.content??e.preview);return{action:typeof t?.action==`string`?t.action:void 0,skillId:typeof t?.skillId==`string`?t.skillId:void 0,categoryPath:typeof t?.categoryPath==`string`?t.categoryPath:void 0,success:typeof t?.success==`boolean`?t.success:void 0,error:typeof t?.error==`string`?t.error:void 0,isError:e.isError}})}function X_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Z_=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Q_=Z_,$_={session:{tool_call_volume:5,state_changing_tools:2},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},ev=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function tv(e){let t=rv(e.gates),n={session:av(`session`,e.sessionTranscript,t.session),currentRun:av(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:av(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=lv(e.reviewState?.reviewCount,0),i=lv(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return dv(n,a,r,i,o,`run_error`);if(e.result?.paused)return dv(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return dv(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return dv(n,a,r,i,o,`max_reviews_per_session`);let s=a.find(e=>n[e].passed),c=s?n[s]:void 0;return{worthReview:!!s,skipped:!1,reasons:c?.reasons??[],stats:c?.stats??o,reviewCount:r,maxReviewsPerSession:i,selectedGateScope:s,consideredGateScopes:a,gateResults:n}}function nv(e,t={}){let n=Yr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Z_),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(fv(t)){for(let e of t.toolCalls??[])a.has(e.name)&&(o.add(e.name),s+=1),e.name===`skill_load`&&typeof e.arguments.name==`string`&&r.add(e.arguments.name),e.name===`auto_skill_view`&&typeof e.arguments.skillId==`string`&&i.add(e.arguments.skillId);continue}pv(t)&&mv(t)&&(c+=1)}return{toolCallCount:n.toolCallCount,distinctToolCount:n.distinctToolCount,toolNames:n.toolNames,stateChangingToolCallCount:s,stateChangingToolNames:Array.from(o).sort(),failedToolResultCount:n.failedToolResultCount,userTurnCount:l,loadedSkills:Array.from(r).sort(),viewedAutoSkills:Array.from(i).sort(),skillLookupFailureCount:c}}function rv(e){return{session:iv(e?e.session:$_.session),currentRun:iv(e?e.currentRun:$_.currentRun),reviewWindow:iv(e?e.reviewWindow:$_.reviewWindow)}}function iv(e){let t={};for(let n of ev){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Q_:void 0;if(typeof r==`number`){let e=cv(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=cv(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:uv(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:uv(r.toolNames,i)})}return t}function av(e,t,n){let r=nv(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=ev.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];ov(t,o,r)?i.push({code:t,description:sv(e,t,o)}):a.push(t)}return{scope:e,configured:o.length>0,passed:o.length>0&&a.length===0,reasons:i,missingReasonCodes:a,stats:r}}function ov(e,t,n){switch(e){case`tool_call_volume`:return n.toolCallCount>=t.min;case`tool_diversity`:return n.distinctToolCount>=t.min;case`state_changing_tools`:return n.stateChangingToolCallCount>=t.min;case`tool_errors`:return n.failedToolResultCount>=t.min;case`multi_turn`:return n.userTurnCount>=t.min}}function sv(e,t,n){let r=e===`currentRun`?`Current run`:e===`reviewWindow`?`Review window`:`Session`;switch(t){case`tool_call_volume`:return`${r} used at least ${n.min} tool calls.`;case`tool_diversity`:return`${r} used at least ${n.min} distinct tools.`;case`state_changing_tools`:return`${r} used at least ${n.min} configured state-changing tool calls.`;case`tool_errors`:return`${r} had at least ${n.min} failed tool results.`;case`multi_turn`:return`${r} had at least ${n.min} user turns.`}}function cv(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function lv(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function uv(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function dv(e,t,n,r,i,a){return{worthReview:!1,skipped:!0,skipReason:a,reasons:[],stats:i,reviewCount:n,maxReviewsPerSession:r,consideredGateScopes:t,gateResults:e}}function fv(e){return e.role===`assistant`}function pv(e){return e.role===`tool_result`}function mv(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:hv(e.content)?.success===!1}function hv(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function gv(e){let t=Zr(e.transcript.length,e.transcriptStartIndex),n=Qr(e.transcript.length,e.recentEntryLimit),r=Zr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Zr(e.transcript.length,0),a=$r(e.transcript,t),o=$r(e.transcript,r),s=nv(e.transcript),c=nv(a),l=nv(o),u=Jr(e.transcript),d=Jr(a),f=Jr(o),p=a.filter(vv),m=a.filter(yv);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:_v(p[0]?.content??``,800),finalResponse:_v(e.result.text||m.at(-1)?.content||``,800),contextFiles:e.contextFiles,currentRunRange:t,recentRange:n,reviewWindowRange:r,sessionStats:u,currentRunStats:d,reviewWindowStats:f,session:{transcriptRange:i,stats:u,toolStats:s},currentRun:{transcriptRange:t,stats:d,toolStats:c},reviewWindow:{transcriptRange:r,stats:f,toolStats:l},reviewState:{reviewCount:e.reviewState?.reviewCount??0,lastCompletedReviewAt:e.reviewState?.lastCompletedReviewAt??null,lastReviewedTranscriptEndIndex:e.reviewState?.lastReviewedTranscriptEndIndex??null},transcriptSummary:{entryCount:d.totalEntryCount,userTurnCount:d.userTurnCount,assistantTurnCount:d.assistantTurnCount,toolResultCount:d.toolResultCount},toolStats:c,loadedSkills:c.loadedSkills,viewedAutoSkills:c.viewedAutoSkills,failedTools:Xr(a,{limit:8,maxPreviewChars:400}).map(e=>({toolName:e.toolName,preview:e.preview})),activeCategories:(e.activeCategories??[]).map(e=>({path:e.path,description:e.description}))}}function _v(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function vv(e){return e.role===`user`}function yv(e){return e.role===`assistant`}function bv(e,t,n){return K.join(r(e,t,n),`auto-skill-review-state.json`)}function xv(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function Sv(e,t,n){let r=bv(e,t,n),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return xv(t);throw e}return Dv(JSON.parse(i),t)}async function Cv(e,t,n){let r=bv(e,t.sessionId,n);await G.mkdir(K.dirname(r),{recursive:!0}),await G.writeFile(r,`${JSON.stringify(Dv(t,t.sessionId),null,2)}\n`,`utf-8`)}async function wv(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await Cv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Tv(e){let t={...e.state,sessionId:e.sessionId,reviewCount:Math.max(0,Math.floor(e.state.reviewCount))+1,lastCompletedReviewAt:e.completedAt??new Date().toISOString(),lastFailedReviewAt:e.state.lastFailedReviewAt??null,lastReviewedTranscriptEndIndex:Math.max(0,Math.floor(e.reviewedTranscriptEndIndex))};return await Cv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Ev(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await Cv(e.dataDir,t,{storeName:e.sessionStoreName}),t}function Dv(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:Av(n.reviewCount,0),lastAttemptedReviewAt:Ov(n.lastAttemptedReviewAt),lastCompletedReviewAt:Ov(n.lastCompletedReviewAt),lastFailedReviewAt:Ov(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:kv(n.lastReviewedTranscriptEndIndex)}}function Ov(e){return typeof e==`string`&&e.trim()?e:null}function kv(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function Av(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function jv(e){return K.join(Ai(e),`.reviews`,`run-log.jsonl`)}async function Mv(e,t){let n=jv(e);await G.mkdir(K.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await G.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const Nv=`write`,Pv=new Set([`off`,`gate`,`dry_run`,`write`]);async function Fv(e){let t=Iv(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=Rv(e);if(n){await Hv(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=zv(n,e.transcriptStartIndex),o=await Sv(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=Bv(o.lastReviewedTranscriptEndIndex,n.length),c=zv(n,s);await Uv(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=tv({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await Uv(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:l.worthReview,selectedGateScope:l.selectedGateScope,skipReason:l.skipReason}),!l.worthReview){await Wv(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await Uv(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Xi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=gv({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:fi(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await Uv(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await Wv(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(G_);if(!p){W.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:G_}),await Hv(e,t,`reviewer_agent_missing`,{reviewerAgentName:G_});return}i={mode:f,decision:l,packet:d},r=await wv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:o,sessionStoreName:e.runParams.sessionStoreName}),await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_started`,message:`auto-skill review agent started`,details:{mode:t.mode,selectedGateScope:l.selectedGateScope,reviewCount:l.reviewCount,maxReviewsPerSession:l.maxReviewsPerSession}});let m=e.curator??K_,h=W_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:d.currentRunRange,recentRange:d.recentRange,reviewWindowRange:d.reviewWindowRange}),g=await m({sessionId:e.sessionId,runParams:e.runParams,packet:d,mode:t.mode,tools:h,reviewerAgent:p,diagnosticDispatcher:e.eventDispatcher});if(g.error){r=await Ev({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await Gv(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await Vv(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:Kv(g.toolCalls),toolResults:$v(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await Tv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await Gv(e.runParams.dataDir,i,{status:`completed`,curatorResult:g,reviewState:r});await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_completed`,message:`auto-skill review agent completed`,details:{mode:t.mode,usage:g.usage,text:Qv(g.text,2e3),toolCalls:Kv(g.toolCalls),toolResults:$v(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewState:r,reviewRunLogPath:_}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await Ev({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await Gv(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await Vv(e,n,a?{reviewRunLogPath:a}:void 0)}}function Iv(e){return{mode:Lv(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function Lv(e){if(e==null)return Nv;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?Pv.has(t)?t:`off`:Nv}function Rv(e){if(e.runParams.subagentContext)return`subagent`;if(e.runParams.channel===`CRON`)return`cron`;if(e.result.error)return`run_error`;if(e.result.paused)return`hitl_paused`;if(e.result.uiToolPending)return`ui_tool_pending`}function zv(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function Bv(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function Vv(e,t,n){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skill_review_failed`,message:`auto-skill review failed`,details:{...n??{},error:t}})}async function Hv(e,t,n,r={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:n===`run_error`?`warn`:`info`,scope:`skill`,phase:`auto_skill_review_skipped`,message:n===`reviewer_agent_missing`?`auto-skill review skipped because reviewer agent is missing`:`auto-skill review skipped before gate evaluation`,details:{mode:t.mode,reason:n,...r}})}async function Uv(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Wv(e,t,n,r,i={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_gated`,message:n.worthReview?`completed run is worth auto-skill review`:`completed run is not worth auto-skill review`,details:{mode:t.mode,worthReview:n.worthReview,skipped:n.skipped,...i.skipReason?{skipReason:i.skipReason}:{},transcriptEntryCount:r.length,transcriptStartIndex:e.transcriptStartIndex,reasons:n.reasons.map(e=>({code:e.code})),stats:n.stats,selectedGateScope:n.selectedGateScope,consideredGateScopes:n.consideredGateScopes,reviewCount:n.reviewCount,maxReviewsPerSession:n.maxReviewsPerSession,gateResults:Zv(n),...i.packet?{packet:i.packet}:{}}})}async function Gv(e,t,n){return Mv(e,{sessionId:t.packet.sessionId,mode:t.mode,status:n.status,selectedGateScope:t.decision.selectedGateScope,reviewCount:t.decision.reviewCount,reasons:t.decision.reasons.map(e=>e.code),currentRunRange:t.packet.currentRunRange,reviewWindowRange:t.packet.reviewWindowRange,conclusion:n.curatorResult?Jv(n.curatorResult.text):void 0,conclusionText:n.curatorResult?Yv(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?Kv(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?$v(n.curatorResult.toolResults):void 0,writeResults:n.curatorResult?.writeResults,wrote:n.curatorResult?.wrote,error:n.error,reviewStateAfter:n.reviewState?{reviewCount:n.reviewState.reviewCount,lastReviewedTranscriptEndIndex:n.reviewState.lastReviewedTranscriptEndIndex}:void 0})}function Kv(e){return e.map(e=>({...e,arguments:qv(e.name,e.arguments)}))}function qv(e,t){if(e!==`auto_skill_manage`)return t;let n={};for(let e of[`action`,`skillId`,`name`,`categoryPath`,`newCategory`])t[e]!==void 0&&(n[e]=t[e]);return n}function Jv(e){let t=Xv(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Yv(e){return Jv(e)?void 0:Qv(e,8e3)}function Xv(e){let t=e.trim(),n=[t],r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);r?.[1]&&n.unshift(r[1].trim());let i=t.indexOf(`{`),a=t.lastIndexOf(`}`);return i>=0&&a>i&&n.push(t.slice(i,a+1)),Array.from(new Set(n.filter(Boolean)))}function Zv(e){return Object.fromEntries(Object.entries(e.gateResults).map(([e,t])=>[e,{configured:t.configured,passed:t.passed,reasons:t.reasons.map(e=>({code:e.code})),missingReasonCodes:t.missingReasonCodes,stats:t.stats}]))}function Qv(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function $v(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let ey=!1;function ty(){ey||=(Qt(),Zt({api:`openai-completions`,stream:qo,streamSimple:Jo}),!0)}const ny=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`,`- As the user role, summarize the title based on the conversation content`,`- The principle of title generation is to describe the behavioral characteristics of the user in the conversation, rather than answering based on the content of the conversation`].join(`
|
|
173
|
+
`);async function ry(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s,titleGeneration:c}=e,l=t.trim().replace(/\s+/g,` `);if(!l)return`New session`;if(c?.enabled===!1||!r.flashModel)return cy(l);let u=cy(l),d=r.flashModel,f=ce({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:d,hooks:a,hookCtx:o}),p=[{role:`user`,content:l}];n&&p.push({role:`assistant`,content:n});let m=ay(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await f.chat({system:ny,user:JSON.stringify(p),temperature:0,maxTokens:100,signal:m.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(oy(t)){if(m.didTimeout())return s?.(`timeout`),u;throw t}e<3&&await iy(500*e,m.signal)}}catch(e){if(oy(e)&&m.didTimeout())return s?.(`timeout`),u;throw e}finally{m.clear()}return s?.(`error`),u}function iy(e,t){return t?t.aborted?Promise.reject(sy()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(sy())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function ay(e,t){let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},t);return e?.aborted?n.abort():e?.addEventListener(`abort`,()=>n.abort(),{once:!0}),{signal:n.signal,clear:()=>clearTimeout(i),didTimeout:()=>r}}function oy(e){return e instanceof Error&&e.name===`AbortError`}function sy(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function cy(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);if(Array.isArray(t))return t?.[0]?.content?.[0].text??e}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}async function ly(e){let{sessionId:t,resetCommand:n,previousSessionId:r,resetMessage:i,startMessage:a,hookRegistry:o,hookContext:s,eventDispatcher:c}=e;n&&i&&await c.dispatchProgress(t,{type:`session_reset`,action:n.action,previousSessionId:r,message:i}),n&&i&&await o.dispatch(`session_reset`,{action:n.action,sessionId:t,previousSessionId:r,message:i},s,{eventDispatcher:c}),await c.dispatchProgress(t,{type:`start`,message:a});let l={eventDispatcher:c};if(await o.dispatch(`session_start`,{sessionId:t,reason:e.resetCommand?`reset`:`startup`},s,l),e.piExtensionDir&&e.registerSkillDir){let t=await o.dispatch(`resources_discover`,{extensionDir:e.piExtensionDir},s,l);for(let n of t)if(!(!n||!(`skillPaths`in n)||!n.skillPaths))for(let t of n.skillPaths)e.registerSkillDir(t)}}async function uy(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await py(await F(r.dataDir,t,{...$(r)}),r);await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs,messages:o},a,{eventDispatcher:e.eventDispatcher})}async function dy(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await F(r.dataDir,t,{...$(r)});await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs,reason:n.error?`error`:`normal`},a,{eventDispatcher:e.eventDispatcher}),a.toolParamOverrides?.clear()}async function fy(e){await uy(e),await dy(e)}async function py(e,t){return e.map(e=>({...e}))}function my(e){let t=[];for(let n of e){if(n.role!==`assistant`)continue;let e=typeof n.content==`string`?n.content.trim():``;e&&t.push(e)}if(t.length!==0)return t.join(`
|
|
171
174
|
|
|
172
|
-
`).slice(0,4e3)}async function
|
|
175
|
+
`).slice(0,4e3)}async function hy(e){if(e.coreConfig?.capture?.enabled!==!0)return;let t=my(e.transcript);if(t)try{typeof e.runContext.memoryProvider.appendRecent==`function`?await e.runContext.memoryProvider.appendRecent(t,`daily`):await e.runContext.memoryProvider.append(t)}catch(t){await e.eventDispatcher?.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`memory`,phase:`capture_flush_failed`,message:`core capture flush failed`,details:{error:t instanceof Error?t.message:String(t)}}).catch(()=>{})}}async function gy(e){if(!(!e.runContext||e.runParams.memory?.core?.capture?.enabled!==!0||e.runParams.subagentContext))try{let t=await F(e.runParams.dataDir,e.sessionId,$(e.runParams));await hy({runContext:e.runContext,coreConfig:e.runParams.memory.core,sessionId:e.sessionId,transcript:t,eventDispatcher:e.eventDispatcher})}catch(t){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`memory`,phase:`capture_flush_failed`,message:`capture flush failed during finalize`,details:{error:t instanceof Error?t.message:String(t)}}).catch(()=>{})}}async function _y(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:c,hookContext:l,startTime:d,compactionEntry:f,eventDispatcher:p}=e,m=$(o);if(a||await h(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},m),f&&await h(o.dataDir,n,f,m),await h(o.dataDir,n,{role:`assistant`,content:t,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},timestamp:new Date().toISOString()},m),r){let t=await by({sessionId:n,titleSource:i.trim()?i:`New session`,text:e.replyText,runParams:o,hookRegistry:c,hookContext:l});await u(o.dataDir,n,{title:t},m),await p.dispatchProgress(n,{type:`title_updated`,title:t})}let g=Date.now()-d,v={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:g,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},context:{snapshotPath:_(o.dataDir,n,$(o)),toolResultsDir:s(o.dataDir,n,$(o))}};return W.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:g,isNewSession:r,textLength:t.length,hasCompactionEntry:!!f,snapshotPath:v.context.snapshotPath,toolResultsDir:v.context.toolResultsDir}),await gy({sessionId:n,runParams:o,runContext:e.runContext,eventDispatcher:p}),await fy({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function vy(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:c,text:l,usage:d,error:f,paused:p,uiToolPending:m,artifacts:h,eventDispatcher:g,sessionEndOnly:v}=e;if(n){let n=$(i),s=await by({sessionId:t,titleSource:r,text:e.text,runParams:i,hookRegistry:a,hookContext:o,logLifecycle:!0});await u(i.dataDir,t,{title:s},n),await g.dispatchProgress(t,{type:`title_updated`,title:s})}let y={sessionId:t,text:l,usage:d,durationMs:Date.now()-c,error:f,paused:p,uiToolPending:m,...h&&h.length>0?{artifacts:h}:{},context:{snapshotPath:_(i.dataDir,t,$(i)),toolResultsDir:s(i.dataDir,t,$(i))}};h&&h.length>0&&e.transcriptStartIndex!==void 0&&!p&&!m&&await yy({dataDir:i.dataDir,sessionId:t,pathOptions:$(i),transcriptStartIndex:e.transcriptStartIndex,artifacts:h});let b={sessionId:t,kind:`completed`,durationMs:y.durationMs,isNewSession:n,inputTokens:d.input,outputTokens:d.output,totalTokens:d.total,hasError:!!f,error:f,paused:!!p,uiToolPending:!!m,textLength:l.length,snapshotPath:y.context.snapshotPath,toolResultsDir:y.context.toolResultsDir};f?W.warn(`agent run finalized with error`,b):W.info(`agent run finalized`,b),await gy({sessionId:t,runParams:i,runContext:e.runContext,eventDispatcher:g});let x={sessionId:t,result:y,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:g};return v?await dy(x):await fy(x),y}async function yy(e){let t=await F(e.dataDir,e.sessionId,e.pathOptions),n=Math.max(0,e.transcriptStartIndex),r=t[n]?.role===`user`?n+1:n,i=t.findIndex((e,t)=>t>=r&&e.role===`user`),a=i===-1?t.length:i,o=-1;for(let e=a-1;e>=n;--e)if(t[e]?.role===`assistant`){o=e;break}o!==-1&&await ee(e.dataDir,e.sessionId,t=>t.map((t,n)=>n!==o||t.role!==`assistant`?t:{...t,artifacts:e.artifacts}),e.pathOptions)}async function by(e){let t=cy(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&W.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await ry({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,titleGeneration:e.runParams.titleGeneration,onFallback:e=>{n=e}});return n?W.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&W.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return W.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const xy=new Set([`pause`,`resume`,`clear`,`help`]),Sy=`/goal
|
|
173
176
|
【目标】:把 src/auth 目录下重复的参数校验逻辑抽离成公共函数。
|
|
174
177
|
【范围】:只处理 src/auth 目录,不扩散到用户模块或订单模块。
|
|
175
178
|
【约束】:保持现有 API 兼容,不引入新依赖,不要改变数据库结构。
|
|
176
179
|
【验证】:每次改动后请自主运行 npm test auth 以及 npm run typecheck。如果测试失败,请定位原因并修复。
|
|
177
|
-
【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function
|
|
178
|
-
`)}function
|
|
179
|
-
`)}async function
|
|
180
|
-
`)}async function
|
|
181
|
-
`)}}if(e.action===`set`){let r=await
|
|
182
|
-
`)}}function
|
|
180
|
+
【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function Cy(){return[`/goal 命令`,` /goal <目标内容> 设置或替换 /goal 目标(设为进行中)`,` /goal --token-budget <n> <目标内容> 设置带 Token 预算的 /goal 目标(0 表示不限)`,` /goal 查看当前 /goal 目标摘要`,` /goal pause 暂停 /goal 目标继续执行`,` /goal resume 恢复已暂停的 /goal 目标`,` /goal clear 清除 /goal 目标`,``,`多行结构化示例(/goal 后换行;Console 用 Shift+Enter 换行,Enter 发送):`,Sy].join(`
|
|
181
|
+
`)}function wy(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,Sy,``,`正文(写入 objective.txt 供 --goal-file):`,Sy.replace(/^\/goal\s+/,``)].join(`
|
|
182
|
+
`)}async function Ty(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await H(e.dataDir,e.sessionId,t);if(!r){let r=await U(e.dataDir,e.sessionId,{goalId:Lt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await rr(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await z(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await U(e.dataDir,e.sessionId,{goalId:Lt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await rr(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`replaced`,goal:r}}if(r.status===`complete`)return{action:`unchanged`,goal:r};let i={};if(r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0)return{action:`unchanged`,goal:r};let a=await V(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function Ey(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(xy.has(n))return{action:n,objective:``};let r=t,i,a=r.match(/^--token-budget\s+(\S+)(?:\s+([\s\S]*))?$/);if(a){let e=a[1]??``;if(i=e===`0`?null:Number.parseInt(e,10),i!==null&&(!Number.isFinite(i)||i<=0))throw Error(`--token-budget 必须是正整数,或使用 0 表示不限。`);r=(a[2]??``).trim()}if(!r)throw Error(`用法:/goal <目标内容> 或 /goal --token-budget <n> <目标内容>`);return{action:`set`,objective:r,tokenBudget:i}}function Dy(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function Oy(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function ky(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${Dy(e.status)}`,`目标内容:${t.length>200?`${t.slice(0,200)}...`:t}`,i,`已用时:${e.timeUsedSeconds} 秒`];return r===`workflow_not_initialized`?a.push(``,`Workflow:未初始化(goal/state.json 缺失)`):n&&(a.push(``,`Workflow:`,` 状态:${Oy(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,jy(e.status)),a.join(`
|
|
183
|
+
`)}async function Ay(e,t,n){let r=await tr(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return ky(t,n,r.goalState,r.workflowWarning)}function jy(e){switch(e){case`active`:return`可用命令:/goal pause、/goal clear`;case`paused`:return`可用命令:/goal resume、/goal clear`;case`budget_limited`:return`/goal 目标已触达预算限制。可用命令:/goal clear(不要仅因预算耗尽就判定为已完成)`;case`complete`:return`/goal 目标已完成。可用命令:/goal clear`;default:return`可用命令:/goal <目标内容>、/goal pause、/goal resume、/goal clear`}}async function My(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:Cy()};if(e.action===`get`){let e=await H(t.dataDir,t.sessionId,n);return e?{replyText:await Ay(t,e,await z(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
|
|
184
|
+
`)}}if(e.action===`set`){let r=await Ty({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await z(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await Ay(t,r.goal,i);return{replyText:r.goal.status===`complete`?`/goal 目标已完成。\n\n${e}`:`/goal 目标未变化。\n\n${e}`}}return{replyText:`${r.action===`resumed`?`/goal 目标已恢复(进行中)。`:r.action===`updated`?`/goal 目标已更新。`:`/goal 目标已设置(进行中)。`}\n\n${await Ay(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await V(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await Ay(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${await Ay(t,e,await z(t.dataDir,t.sessionId,e,n))}`};let r=await V(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await Ay(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ae(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const Ny=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`},{name:`/goal`,description:`设置或查看 /goal 目标`},{name:`/goal pause`,description:`暂停 /goal 目标`},{name:`/goal resume`,description:`恢复 /goal 目标`},{name:`/goal clear`,description:`清除 /goal 目标`}];function Py(){return Ny.map(e=>({...e}))}function Fy(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Iy(e){let t=new Set,n=[];for(let r of e){let e=Fy(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Ly(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function Ry(e,t){let n=Py(),r=Iy(e),i=t?Ly(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function zy(e){let t=e.trim();if(!t)return``;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s);if(!n)return t;let[,r,i]=n,a=i.trimStart();return a?`/${r} ${a}`:`/${r}`}function By(e){let t=zy(e);if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]+))?$/);if(!n)return null;let r=n[1]?.trim().toLowerCase()??``,i=(n[2]??``).trim();return r?{name:r,rest:i}:null}function Vy(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s),r=(n?(()=>{let[,e,t]=n,r=t.trimStart();return r?`/${e} ${r}`:`/${e}`})():t).match(/^\/([^\s@]+)(?:@[^\s]+)?(?:\s+([\s\S]+))?$/);if(!r)return null;let i=r[1]?.trim().toLowerCase()??``;if(i!==`new`&&i!==`reset`)return null;let a=(r[2]??``).trim();return{action:i===`new`?`new`:`reset`,remainder:a}}function Hy(e,t){let n=By(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`goal`)try{let e=Ey(n.rest);return{kind:`goal`,action:e.action,objective:e.objective,tokenBudget:e.tokenBudget}}catch(e){return{kind:`unknown`,name:n.name,args:e.message}}if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:Fy(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Iy(t).map(e=>e.name.slice(1))).has(n.name)?{kind:`skill-direct`,name:n.name,args:n.rest}:{kind:`unknown`,name:n.name,args:n.rest}}const Uy=new Set([`/new`,`/reset`,`/compact`]),Wy=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Gy=new Set([`/help`]);function Ky(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function qy(e){if(e.length===0)return[];let t=e.map(Ky),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Jy(e){let t=Ry(e.skills),n=t.builtin.filter(e=>Uy.has(e.name)),r=t.builtin.filter(e=>Wy.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Gy.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...qy(n)),s.push(``),s.push(`目标命令`),s.push(...qy(r)),s.push(``),s.push(`技能命令`),s.push(...qy(i)),o.length>0?(s.push(...qy(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...qy(a)),{kind:`reply`,text:s.join(`
|
|
185
|
+
`)}}function Yy(e,t){let n=t.trim().toLowerCase();return n&&Iy(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function Xy(e){let t=Yy(e.ctx.skills,e.skillName);return t?{kind:`rewrite`,message:[`Use the "${t.name}" skill for this request.`,e.args?`User input:\n${e.args}`:null].filter(e=>!!e).join(`
|
|
183
186
|
|
|
184
|
-
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function
|
|
185
|
-
`),
|
|
187
|
+
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function Zy(e){let t=Hy(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Jy(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?Xy({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:t.kind===`unknown`&&t.name===`goal`?{kind:`reply`,text:t.args||`用法:/goal <目标内容> | /goal pause | /goal resume | /goal clear`}:{kind:`pass`,message:e.message}}async function Qy(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=$y(t),l=c>=0?t[c].content:void 0,u=Us(c>=0?t.slice(c+1):t);if(u.length===0)return{status:`skipped`,reason:`No history to compact.`,estimatedTokens:0};let{toKeep:d,toSummarise:f}=uc(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:J(u)}:{status:`compacted`,entry:{role:`compaction`,content:await $s({entries:f,llm:r,previousSummary:l,instructions:i,contextWindowTokens:n,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:J(d)}}function $y(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const eb=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
|
|
188
|
+
`),tb=[`.aimax/new.txt`];async function nb(e){try{return(await Nt(e,`utf-8`)).trim()||null}catch{return null}}async function rb(e){for(let t of tb){let n=await nb(Pt(e,t));if(n)return n}return await nb(`/aimax_pvc/new.txt`)||eb}async function ib(e){return{kind:`reply`,text:await rb(e)}}function ab(){return{kind:`reply`,text:`✅ Session reset.`}}async function ob(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function sb(e,t,n){let r=n.before?.status??null,i=n.after?.status??null,a=n.before?.goalId,o=n.after?.goalId;r===i&&a===o||await ob(e,t,{action:n.action,goal:n.after??null})}function cb(e){let t=db(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?fb(r):null,a=n??i?.text,o=a?Vy(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?pb(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:mb(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function lb(e,t,n){if(e.resetShortCircuit)return{kind:`reset_reply`,action:e.resetCommand?.action??`new`,transcriptMessage:e.transcriptMessage,initialUserEntryPersisted:!0};if(!e.slashCommandSource)return{kind:`run`,effectivePrompt:e.promptInput,transcriptMessage:e.transcriptMessage};let r=e.slashCommandSource??``,i=r.match(/^\/([^\s]+)/);if(i&&n&&n.resolveCommand(i[1]??``)){let e=r.replace(/^\/[^\s]+\s*/,``).trim();return{kind:`extension`,name:i[1]??``,args:e}}let a=Hy(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=Zy({message:e.messageForRun??``,skills:t});if(o.kind===`reply`)return{kind:`reply`,replyText:o.text,transcriptMessage:e.transcriptMessage};if(o.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:o.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(o.kind===`rewrite`){let t=e.inputMode===`text`?o.message:pb(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:mb(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function ub(e){let t=lb(e.invocation,e.skills,e.extensionHost);if(t.kind===`extension`&&e.extensionHost){let n=e.extensionHost.resolveCommand(t.name);if(n){let r={sessionId:e.sessionId,workspaceDir:e.hookContext.workspaceDir},i=await n.handler(t.args.split(/\s+/).filter(Boolean),r);return{kind:`completed`,result:await _y({replyText:i&&typeof i==`object`&&`text`in i?String(i.text??`Command executed.`):`Command executed.`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:e.invocation.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}}if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await _y({replyText:(t.action===`reset`?ab():await ib(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await _y({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`goal`){let n;try{n=await My({action:t.action,objective:t.objective,tokenBudget:t.tokenBudget},{dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName})}catch(e){n={replyText:`/goal 错误:${e.message}`}}return n.goalUpdate&&(await ob(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),hb(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await z(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await _y({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}if(t.kind!==`compact`)return{kind:`continue`,effectivePrompt:e.invocation.promptInput,transcriptMessage:e.invocation.transcriptMessage};let n=await Qy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,$(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await _y({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function db(e){return typeof e.message==`string`}function fb(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n.role!==`user`)continue;if(typeof n.content==`string`)return{index:t,text:n.content};if(!Array.isArray(n.content)||n.content.length===0)return null;let r=n.content[0];return r?.type===`text`&&typeof r.text==`string`?{index:t,text:r.text}:null}return null}function pb(e,t){let n=fb(e);return n?e.map((e,r)=>{if(r!==n.index)return e;let i=e;return typeof i.content==`string`?{...e,content:t}:Array.isArray(i.content)&&i.content.length>0?{...e,content:i.content.map((e,n)=>{if(n!==0)return e;let r=e;return r?.type===`text`&&typeof r.text==`string`?{...r,text:t}:e})}:e}):e}function mb(e){return typeof e==`string`?e:JSON.stringify(e)}function hb(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function gb(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,artifactAccumulator:u,appendEntry:d}=e,f=0,p=``,m=0,h=0,g;for(;!c?.aborted&&n.needsAnnounce(r)&&f<10;){f++,W.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){W.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}W.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:f,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let _=_b(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await u_({agent:t,message:_,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,artifactAccumulator:u,onTurnRecordProduced:async(e,t)=>{e&&await d(e);for(let e of t)await d(e)}});p=v.text,m+=v.inputTokens,h+=v.outputTokens,v.error&&!g&&(g=v.error),n.markAnnounced(e.map(e=>e.runId));let y={sessionId:r,announceRound:f,completedCount:e.length,inputTokens:v.inputTokens,outputTokens:v.outputTokens,hasError:!!v.error,error:v.error,responseTextLength:v.text.length};v.error?W.warn(`subagent announce round completed with error`,y):W.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&W.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function _b(e){if(e.length===1){let t=e[0];return th({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>th({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
|
|
186
189
|
|
|
187
190
|
---
|
|
188
191
|
|
|
189
|
-
`)}`}async function
|
|
192
|
+
`)}`}async function vb(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i,runtimeBridge:a}=e,o=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},s=t.plugins?Date.now():void 0,c=t.plugins?Ne({...t.plugins,config:t.plugins.config,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0,l=s===void 0?void 0:Math.max(0,Date.now()-s);if(!c)return o({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`}),{hookRegistry:new de,pluginSkillDirs:[],pluginTools:[]};o({level:c.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:c.registry.plugins.length,enabledPluginCount:c.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:c.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:c.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:c.diagnostics.length,durationMs:l}});for(let e of c.registry.plugins)o({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,durationMs:e.durationMs,errorMessage:e.error}});for(let e of c.diagnostics)o({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}});let u=je(c.normalizedConfig),d;if(u.length>0){let e=await Ae(c.normalizedConfig);if(e.length>0){d=new nt(e);let s=n.session?.getSessionDir?.(),l=t.createPiExtensionDialogBridge?.(r),u={};for(let[e,t]of Object.entries(c.normalizedConfig.entries??{}))t?.config&&typeof t.config==`object`&&(u[e]=t.config);let f=new Map;for(let t of e){let e=`pi:${t.name}`;u[e]&&f.set(e,u[e])}await d.activate({hookRegistry:c.registry.hooks,toolRegistry:c.registry.tools,hookContext:n,eventDispatcher:i,sessionId:r,sessionDir:s,runtimeBridge:a,dialogBridge:l,piExtensionConfigs:f}),o({level:`info`,scope:`plugin`,phase:`pi_extensions_activated`,message:`pi extensions activated`,details:{extensionCount:e.length,extensionNames:e.map(e=>e.name),commandCount:d.getRegisteredCommands().size}})}}return{hookRegistry:c.registry.hooks,pluginSkillDirs:c.registry.skills,pluginTools:[...c.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...c.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??c.normalizedConfig.slots?.memory,extensionHost:d}}var yb=class{agent=null;messageQueue=[];compactRequest=null;bindAgent(e){this.agent=e}dispose(){this.agent=null,this.messageQueue=[],this.compactRequest=null}sendUserMessage(e,t){this.messageQueue.push({content:e,deliverAs:t?.deliverAs,resolve:()=>{}})}isIdle(){if(!this.agent)return!0;let e=this.agent.state;return!e.isStreaming&&(e.pendingToolCalls?.size??0)===0}requestCompact(e){this.compactRequest=e??{}}drainMessages(){let e=this.messageQueue.map(e=>e.content);return this.messageQueue=[],e}drainCompactRequest(){let e=this.compactRequest;return this.compactRequest=null,e}hasPendingMessages(){return this.messageQueue.length>0}hasPendingCompact(){return this.compactRequest!==null}};async function bb(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=ph(t),o=n,s=!o,c=$(t);o?(await w(t.dataDir,o,c)||(s=!0),await v(t.dataDir,o,c)):o=await T(t.dataDir,t.channel,{...c});let l={sessionId:o,messageId:t.messageId,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>F(t.dataDir,o,c)}},u=new yb,d=await vb({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await mh({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:d.memoryPluginId,eventDispatcher:i,hookRegistry:f});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:f,pluginContext:d,runContext:p,runtimeBridge:u,start:e=>ly({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function xb(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Sb(e){if(!(e instanceof Error))return{errorValue:xb(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=xb(n[e]));return t}async function Cb(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Sb(e.error)}})}function wb(e,t,n){return K.join(r(e,t,n),`pending-ui-tool.json`)}async function Tb(e,t,n,i){let a=r(e,t,i);await G.mkdir(a,{recursive:!0}),await L(wb(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function Eb(e,t,n){let r=await o(wb(e,t,n));return r===null?null:JSON.parse(r)}async function Db(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Tb(e,t,a,r),a}async function Ob(e,t,n,r,i){let a=await Eb(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await Tb(e,t,o,i),o}async function kb(e,t,n){try{await G.unlink(wb(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Ab(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function jb(e,t,n,r,i,a){let o=await H(e,t,{storeName:a?.storeName});await Ab(e,t,n,a);let s=await on(e,t,n,r,a);return s.goal&&await sb(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function Mb(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Mt(t))}async function Nb(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=wo();if(i=await To(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(So(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Pb(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function Pb(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const Fb=2e4,Ib=15e4,Lb=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Rb(e){return K.join(e,`.aimax`)}async function zb(e){let t=Rb(e),n=[];for(let e of Lb){let r=K.join(t,e);try{let t=await G.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await G.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function Bb(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
|
|
190
193
|
`),s].join(`
|
|
191
|
-
`),truncated:!0,originalLength:r.length}}function by(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function xy(e,t){let n=t?.maxChars??my,r=Math.max(1,t?.totalMaxChars??Math.max(n,hy)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=by(`[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}=yy(a.content??``,a.name,e),l=by(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 Sy=`You are a personal assistant running inside AiMax.`;async function Cy(e){try{return{presetSystemPrompt:zt(await q.readFile(e,`utf-8`)).content.trim()||Sy}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:Sy};throw e}}async function wy(){return Cy(`/aimax_pvc/system_prompt.md`)}async function Ty(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await vy(t.dataDir),o=[],s=xy(a,{warn:e=>o.push(e)}),c=await wy();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 Mf(t.dataDir,r.pluginSkillDirs,l),d=await va({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),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 Ey({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function Ey(e){if(!e.enabled)return[];try{let t=await new Gi({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var Dy=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 Oy={Inferred:1,Child:2,Own:3};var ky=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=jy(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,Oy.Own)}addInferred(e){this.add(e,Oy.Inferred)}addChild(e){e&&e.length>0&&this.add(e,Oy.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=Ay(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=My(e.url);return t?this.urlWhitelist.has(t):!1}};function Ay(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function jy(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function My(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const Ny=`crons`;function Py(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:ie(e.message)}}async function Fy(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 Uh({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 Yv({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 jv({entries:e.runParams.channel===`CRON`?[]:await I(e.runParams.dataDir,e.sessionId,$(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{apiFormat:e.runParams.llm.apiFormat,baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:a.customInstructions,signal:e.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});t.status===`compacted`&&await e.appendEntry(t.entry),a.onComplete?.(t)}catch(e){a.onError?.(e instanceof Error?e:Error(String(e)))}return{lastResponseText:t,inputTokens:n,outputTokens:r,error:i}}async function Iy(e,t){P_();let n=Date.now(),i=new Na(e),a=new ky({urlWhitelist:e.artifactsUrlWhitelist}),o=Vv(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 $v({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;de(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,$(e))});let f=u.isNewSession,m=u.workspaceDir,h=u.hookContext,g=u.hookRegistry,_=u.pluginContext,v=u.runContext,y=u.runtimeBridge,b=0,x=!1,S=()=>{x||(x=!0,y.dispose())},C=(await I(e.dataDir,d,$(e))).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,Yp({sessionId:d,title:V_(s),channel:e.channel}),$(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 $n(e.dataDir,d,{goalId:t.goalId,objective:e.pendingGoal.objective},{storeName:e.sessionStoreName})}o.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(c=await v.persistInitialUserEntry(s));let w=new AbortController;e.abortSignal?.aborted?w.abort():e.abortSignal?.addEventListener(`abort`,()=>w.abort()),h.signal=w.signal,await u.start({resetCommand:o.resetCommand,previousSessionId:l,resetMessage:o.slashCommandSource,startMessage:typeof o.promptInput==`string`?o.promptInput:s});let T=await Ty({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await Uv({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 Dh({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=>Iy(e,new Ap),createModel:da,abortSignal:w.signal}}),j=A.agent,M=A.resolvedModelId;y.bindAgent(j),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length}}),K.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=Hy(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 Dy,R=``,z,B=!1,V=new en;await ly(e.dataDir,d,V,{storeName:e.sessionStoreName}),w.signal;try{if(dy(e)){let t=await fy({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return R=t.text,S(),Z_({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);B=t,c=t||c;try{await Vn(e.dataDir,d,{storeName:e.sessionStoreName},()=>Fr(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof Rn))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await 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 Rn)o=!0;else throw e}let u=!!(o||l&&Br(l)),p=Ur({hookRegistry:g,isGateActive:()=>u}),m=await Lr(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Do not submit goal complete or blocked until the workflow state is repaired by the runtime.`,`</goal_context>`,``].join(`
|
|
192
|
-
`);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await Ir(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});K.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await Uh({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 Rr(e.dataDir,d,{storeName:e.sessionStoreName}),await i.dispatchDiagnostic(d,{level:x.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens}});let C={sessionId:d,hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens};x.error?K.warn(`first agent turn completed with error`,C):K.info(`first agent turn completed`,C);let T=await uy(e.dataDir,d,V,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 Yv({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 uy(e.dataDir,d,V,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`}),Ar()){let n=new Or;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=Dt;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Nr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:V,abortSignal:w.signal,executeTurn:async t=>{let n=await Uh({agent:j,message:t,continueFromHistory:!1,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{await Pr(E,e,t)}});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 uy(e.dataDir,d,V,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 Yv({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 U_({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 Fy({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(_o(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await it(e.dataDir,o,c,r.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},r.toolContext),await i.dispatchProgress(o,{type:`hitl_requested`,request:c}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),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 Ly({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:B}),S(),Z_({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(Ie(t)){let r=t,o=r.request.outputSchema.properties??{};await oy(e.dataDir,d,r.request,$(e)),await i.dispatchProgress(d,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(d,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length}}),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 Ly({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:B}),S(),Z_({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&&Uy(t))z=`Run timed out after ${N}ms`;else throw await ny({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 uy(e.dataDir,d,V,L.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}V.clearActiveGoal(),lh(d);try{A.processRegistry.disposeAll()}catch{}try{ze.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let H=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:H.input,outputTokens:H.output,totalTokens:H.total,hasError:!!z,error:z}});let U={sessionId:d,durationMs:Date.now()-n,inputTokens:H.input,outputTokens:H.output,totalTokens:H.total,hasError:!!z,error:z};return z?K.warn(`agent run completed with error`,U):K.info(`agent run completed`,U),await Ly({runtime:A,resolvedModelId:M,usage:H,currentUserEntryCoveredByUsage:B}),await m_({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:R,usage:H,durationMs:Date.now()-n,error:z}}),Z_({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:H,error:z,sessionEndOnly:b>0})}async function Ly(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 Ry(e){let t=Date.now(),i=new Na(e),a=Vv(e),o=a.transcriptMessage.trim()||`CRON task`,c=Ny;K.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...Py(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,Yp({sessionId:l,title:V_(o),channel:e.channel}),{storeName:c});let f=r(e.dataDir,l,{storeName:c});de(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f});let m={parentSessionId:l,parentDir:f},g=await T(e.dataDir,e.channel,{storeName:Ny,subagent:m});await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:g,task:o}),K.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:g,taskLength:o.length,taskPreview:ie(o)});let y={...e,sessionId:g,sessionStoreName:Ny,sessionPathScope:{subagent:m},subagentContext:{depth:1,parentSessionId:l}},b,x=`done`;try{b=await Iy(y,new Ap),b.error&&(x=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);b={sessionId:g,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,g,{storeName:Ny,subagent:m}),toolResultsDir:s(e.dataDir,g,{storeName:Ny,subagent:m})}},x=`error`,K.error(`cron child run failed`,{parentSessionId:l,childSessionId:g,error:r})}de(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f}),await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:g,task:o,status:x}),K.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:g,status:x,durationMs:Date.now()-t,hasError:!!b.error});let C=Pp({task:o,status:x,result:b.text,error:b.error}),w=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:C,timestamp:w,source:`cron`},{storeName:c});let E={task:o,status:x,content:C,childSessionId:g,createdAt:w};return await S(e.dataDir,l,E,{storeName:c}),await F(e.dataDir,l,e=>zy(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...b,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function zy(e,t){if(t<=0)return e.filter(e=>!By(e));let n=e.reduce((e,t,n)=>(By(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!By(e)||r.has(t))}function By(e){return`source`in e&&e.source===`cron`}async function Vy(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,...Py(e)}),e.channel===`CRON`&&!e.subagentContext)return Ry(e);let n=t??new Ap;try{return await Iy(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:ty(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}};try{return await(e.onLog?we(e.onLog,n):n())}finally{e.onLog||await Te()}}function Hy(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Uy(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 Wy={"AGENTS.md":`---
|
|
194
|
+
`),truncated:!0,originalLength:r.length}}function Vb(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Hb(e,t){let n=t?.maxChars??Fb,r=Math.max(1,t?.totalMaxChars??Math.max(n,Ib)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Vb(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=Bb(a.content??``,a.name,e),l=Vb(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const Ub=`You are a personal assistant running inside AiMax.`;async function Wb(e){try{return{presetSystemPrompt:Vt(await G.readFile(e,`utf-8`)).content.trim()||Ub}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:Ub};throw e}}async function Gb(){return Wb(`/aimax_pvc/system_prompt.md`)}async function Kb(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await zb(t.dataDir),o=[],s=Hb(a,{warn:e=>o.push(e)}),c=await Gb();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),W.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await bp(t.dataDir,r.pluginSkillDirs,l),d=await Ca({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),W.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),W.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await qb({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function qb(e){if(!e.enabled)return[];try{let t=await new Xi({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var Jb=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const Yb={Inferred:1,Child:2,Own:3};var Xb=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=Qb(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,Yb.Own)}addInferred(e){this.add(e,Yb.Inferred)}addChild(e){e&&e.length>0&&this.add(e,Yb.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=Zb(n),r=this.indices.get(e);if(r!==void 0){let e=this.records[r];e&&t>e.priority&&(this.records[r]={record:n,priority:t});continue}this.indices.set(e,this.records.length),this.records.push({record:n,priority:t})}}shouldCollect(e){if(e.kind!==`url`||!this.urlWhitelist)return!0;let t=$b(e.url);return t?this.urlWhitelist.has(t):!1}};function Zb(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function Qb(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function $b(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const ex=`crons`;function tx(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:oe(e.message)}}async function nx(e){let t,n=0,r=0,i;if(e.runtimeBridge.hasPendingMessages()){let a=e.runtimeBridge.drainMessages();for(let o of a){let a=await u_({agent:e.agent,message:o,continueFromHistory:!1,sessionId:e.sessionId,channel:e.channel,modelId:e.resolvedModelId,historyMessages:e.runtime.historyMessages,eventDispatcher:e.eventDispatcher,hooks:e.hookRegistry,hookCtx:e.hookContext,abortSignal:e.abortSignal,retry:e.retry,onTurnRecordProduced:async(t,n)=>{t&&await e.appendEntry(t);for(let t of n)await e.appendEntry(t)}});n+=a.inputTokens,r+=a.outputTokens,a.text&&(t=a.text),a.error&&(i=a.error);let s=await gb({agent:e.agent,registry:e.registry,sessionId:e.sessionId,resolvedModelId:e.resolvedModelId,eventDispatcher:e.eventDispatcher,hookRegistry:e.hookRegistry,hookContext:e.hookContext,abortSignal:e.abortSignal,appendEntry:e.appendEntry});n+=s.inputTokens,r+=s.outputTokens,s.text&&(t=s.text),s.error&&!i&&(i=s.error)}}let a=e.runtimeBridge.drainCompactRequest();if(a)try{let t=await Qy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,$(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{apiFormat:e.runParams.llm.apiFormat,baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:a.customInstructions,signal:e.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});t.status===`compacted`&&await e.appendEntry(t.entry),a.onComplete?.(t)}catch(e){a.onError?.(e instanceof Error?e:Error(String(e)))}return{lastResponseText:t,inputTokens:n,outputTokens:r,error:i}}async function rx(e,t){ty();let n=Date.now(),i=new Ra(e),a=new Xb({urlWhitelist:e.artifactsUrlWhitelist}),o=cb(e);W.info(`agent invocation prepared`,{requestedSessionId:o.requestedSessionId,previousSessionId:o.previousSessionId,inputMode:o.inputMode,hasSlashCommand:!!o.slashCommandSource,resetAction:o.resetCommand?.action,resetShortCircuit:o.resetShortCircuit,transcriptLength:o.transcriptMessage.length,messageForRunLength:o.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let s=o.transcriptMessage,c=!1,l=o.previousSessionId,u=await bb({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;pe(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,$(e))});let f=u.isNewSession,m=u.workspaceDir,h=u.hookContext,g=u.hookRegistry,_=u.pluginContext,v=u.runContext,y=u.runtimeBridge,b=0,x=!1,S=()=>{x||(x=!0,y.dispose())},C=(await F(e.dataDir,d,$(e))).length;if(W.info(`agent run started`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:f,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:f,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),W.info(f?`session created`:`session resumed`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}),await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:f?`session_created`:`session_resumed`,message:f?`session created`:`session resumed`,details:{requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}}),f&&await p(e.dataDir,gh({sessionId:d,title:cy(s),channel:e.channel}),$(e)),e.pendingGoal){let t=await U(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await rr(e.dataDir,d,{goalId:t.goalId,objective:e.pendingGoal.objective},{storeName:e.sessionStoreName})}o.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(c=await v.persistInitialUserEntry(s));let w=new AbortController;e.abortSignal?.aborted?w.abort():e.abortSignal?.addEventListener(`abort`,()=>w.abort()),h.signal=w.signal,await u.start({resetCommand:o.resetCommand,previousSessionId:l,resetMessage:o.slashCommandSource,startMessage:typeof o.promptInput==`string`?o.promptInput:s});let T=await Kb({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await ub({invocation:o,skills:T.skills,sessionId:d,isNewSession:f,initialUserEntryPersisted:c,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,extensionHost:_.extensionHost});if(D.kind===`completed`)return W.info(`agent run short-circuited`,{sessionId:d,durationMs:Date.now()-n,hasError:!!D.result.error,paused:!!D.result.paused,uiToolPending:!!D.result.uiToolPending,textLength:D.result.text.length}),S(),D.result;let O=D.effectivePrompt;s=D.transcriptMessage;let k=typeof O==`string`?O:s;await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length}}),W.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await Jg({session:{runParams:T.runParamsWithAgentPolicy,sessionId:d,hookRegistry:g,hookContext:h,runContext:v,eventDispatcher:i},runtimeInputs:{contextFiles:T.contextFiles,bootstrapWarnings:T.bootstrapWarnings,skills:T.skills,autoSkillCategories:T.autoSkillCategories,effectivePromptText:k,pluginTools:_.pluginTools,pluginSkillDirs:_.pluginSkillDirs,skillsLoadPaths:T.skillsLoadPaths,presetSystemPrompt:T.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>rx(e,new Zm),createModel:ga,abortSignal:w.signal}}),j=A.agent,M=A.resolvedModelId;y.bindAgent(j),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length}}),W.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=lx(e.timeoutMs),P=!1,ee=N===void 0?void 0:setTimeout(()=>{P=!0,w.abort(),j.abort(),i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:N}}),W.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let I=new Jb,L=``,R,te=!1,z=new an;await Ab(e.dataDir,d,z,{storeName:e.sessionStoreName}),w.signal;try{if(Mb(e)){let t=await Nb({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return L=t.text,S(),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await v.persistInitialUserEntry(s);te=t,c=t||c;try{await Gn(e.dataDir,d,{storeName:e.sessionStoreName},()=>zr(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof Hn))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await H(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await Nr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof Hn)o=!0;else throw e}let u=!!(o||l&&Wr(l)),p=qr({hookRegistry:g,isGateActive:()=>u}),m=await Vr(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Do not submit goal complete or blocked until the workflow state is repaired by the runtime.`,`</goal_context>`,``].join(`
|
|
195
|
+
`);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await Br(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});W.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await u_({agent:j,message:_.prompt,continueFromHistory:!!e.uiToolResume,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{e&&await E(e);for(let e of t)await E(e)}});p(),L=x.text,I.add(x.inputTokens,x.outputTokens),x.error&&(R=x.error),m.hadObjectiveUpdatedSteering&&!x.error&&await Hr(e.dataDir,d,{storeName:e.sessionStoreName}),await i.dispatchDiagnostic(d,{level:x.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens}});let C={sessionId:d,hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens};x.error?W.warn(`first agent turn completed with error`,C):W.info(`first agent turn completed`,C);let T=await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`});T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),W.info(`announce loop started`,{sessionId:d});let D=await gb({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,appendEntry:E});if(D.text&&(L=D.text),I.add(D.inputTokens,D.outputTokens),D.error&&!R&&(R=D.error),await i.dispatchDiagnostic(d,{level:D.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens}}),T=await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`}),T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Pr()){let n=new Mr;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=kt;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Lr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:z,abortSignal:w.signal,executeTurn:async t=>{let n=await u_({agent:j,message:t,continueFromHistory:!1,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{await Rr(E,e,t)}});I.add(n.inputTokens,n.outputTokens),L=n.text||L,n.error&&!R&&(R=n.error);let r=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:r}},flushAccountingAfterTurn:async()=>{(await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),r){let e=await gb({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,artifactAccumulator:a,appendEntry:E});I.add(e.inputTokens,e.outputTokens),e.text&&(L=e.text),e.error&&!R&&(R=e.error)}}do{if(w.signal.aborted)break;if(b++,b>8){i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`bridge_cycle_limit`,message:`SessionRuntimeBridge exceeded max cycles (8)`}).catch(()=>{});break}await uy({sessionId:d,result:{sessionId:d,text:L??``,usage:I.snapshot(),durationMs:Date.now()-n,error:R},runParams:e,hookRegistry:g,hookContext:h,eventDispatcher:i});let r=await nx({runtimeBridge:y,agent:A.agent,runtime:A,sessionId:d,channel:e.channel,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,appendEntry:E,runParams:e,registry:t});I.add(r.inputTokens,r.outputTokens),r.lastResponseText&&(L=r.lastResponseText),r.error&&!R&&(R=r.error)}while(!w.signal.aborted&&(y.hasPendingMessages()||y.hasPendingCompact()));S();let k={sessionId:d,hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens};D.error?W.warn(`announce loop completed with error`,k):W.info(`announce loop completed`,k)}catch(t){if(So(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await ot(e.dataDir,o,c,r.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},r.toolContext),await i.dispatchProgress(o,{type:`hitl_requested`,request:c}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),W.info(`agent paused for HITL`,{sessionId:d,requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let l={...I.snapshot()};return await ix({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:te}),S(),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:l,error:void 0,paused:{requestId:c.requestId,kind:c.kind,title:c.title}})}if(Re(t)){let r=t,o=r.request.outputSchema.properties??{};await Db(e.dataDir,d,r.request,$(e)),await i.dispatchProgress(d,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(d,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length}}),W.info(`agent paused for UI tool input`,{sessionId:d,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length});let c={...I.snapshot()};return await ix({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:te}),S(),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L||``,usage:c,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}if(P&&ux(t))R=`Run timed out after ${N}ms`;else throw await Cb({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),W.error(`agent run failed`,{sessionId:d,channel:e.channel,isNewSession:f,error:t instanceof Error?t.message:String(t)}),t}finally{ee!==void 0&&clearTimeout(ee);try{await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}z.clearActiveGoal(),Ag(d);try{A.processRegistry.disposeAll()}catch{}try{Ve.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let B=I.snapshot();P&&(R=`Run timed out after ${N}ms`),await i.dispatchDiagnostic(d,{level:R?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R}});let V={sessionId:d,durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R};return R?W.warn(`agent run completed with error`,V):W.info(`agent run completed`,V),await ix({runtime:A,resolvedModelId:M,usage:B,currentUserEntryCoveredByUsage:te}),await Fv({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:L,usage:B,durationMs:Date.now()-n,error:R}}),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),transcriptStartIndex:C,text:L,usage:B,error:R,sessionEndOnly:b>0})}async function ix(e){let{runtime:t,resolvedModelId:n,usage:r,currentUserEntryCoveredByUsage:i}=e;r.input<=0&&r.total<=0||await t.contextManager.recordModelUsage({model:n,inputTokens:r.input,outputTokens:r.output,totalTokens:r.total,coveredTranscriptEntryCount:t.usageBaselineTranscriptEntryCount+(i?1:0)})}async function ax(e){let t=Date.now(),i=new Ra(e),a=cb(e),o=a.transcriptMessage.trim()||`CRON task`,c=ex;W.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...tx(e)});let l=a.requestedSessionId,d=!l;l?(await n(e.dataDir,l,{storeName:c})||(d=!0),await v(e.dataDir,l,{storeName:c})):l=await T(e.dataDir,e.channel,{storeName:c}),d&&await p(e.dataDir,gh({sessionId:l,title:cy(o),channel:e.channel}),{storeName:c});let f=r(e.dataDir,l,{storeName:c});pe(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f});let m={parentSessionId:l,parentDir:f},g=await T(e.dataDir,e.channel,{storeName:ex,subagent:m});await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:g,task:o}),W.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:g,taskLength:o.length,taskPreview:oe(o)});let y={...e,sessionId:g,sessionStoreName:ex,sessionPathScope:{subagent:m},subagentContext:{depth:1,parentSessionId:l}},b,x=`done`;try{b=await rx(y,new Zm),b.error&&(x=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);b={sessionId:g,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,g,{storeName:ex,subagent:m}),toolResultsDir:s(e.dataDir,g,{storeName:ex,subagent:m})}},x=`error`,W.error(`cron child run failed`,{parentSessionId:l,childSessionId:g,error:r})}pe(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f}),await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:g,task:o,status:x}),W.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:g,status:x,durationMs:Date.now()-t,hasError:!!b.error});let C=th({task:o,status:x,result:b.text,error:b.error}),w=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:C,timestamp:w,source:`cron`},{storeName:c});let E={task:o,status:x,content:C,childSessionId:g,createdAt:w};return await S(e.dataDir,l,E,{storeName:c}),await ee(e.dataDir,l,e=>ox(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...b,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function ox(e,t){if(t<=0)return e.filter(e=>!sx(e));let n=e.reduce((e,t,n)=>(sx(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!sx(e)||r.has(t))}function sx(e){return`source`in e&&e.source===`cron`}async function cx(e,t){let n=async()=>{if(W.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...tx(e)}),e.channel===`CRON`&&!e.subagentContext)return ax(e);let n=t??new Zm;try{return await rx(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:Sb(t)}),W.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};try{return await(e.onLog?Ee(e.onLog,n):n())}finally{e.onLog||await De()}}function lx(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function ux(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const dx={"AGENTS.md":`---
|
|
193
196
|
title: "AGENTS.md Template"
|
|
194
197
|
summary: ".aimax template for AGENTS.md"
|
|
195
198
|
read_when:
|
|
@@ -482,7 +485,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
|
|
|
482
485
|
This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
|
|
483
486
|
|
|
484
487
|
Add whatever helps you do your job. This is your cheat sheet.
|
|
485
|
-
`},
|
|
488
|
+
`},fx=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function px(e,t){try{if(!(await G.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await G.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function mx(e,t,n){try{if(!(await G.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await G.mkdir(K.dirname(e),{recursive:!0});try{await G.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function hx(e){let t=Rb(e);return[e,t,K.join(t,`skills`),K.join(t,`sessions`),K.join(t,`memory`),K.join(e,`workspace`)]}function gx(e){let t=Rb(e);return[...fx.filter(e=>e!==`BOOTSTRAP.md`).map(e=>K.join(t,e)),K.join(t,`MEMORY.md`)]}function _x(e){return K.join(Rb(e),`.bootstrapped`)}async function vx(e){try{return(await G.stat(_x(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function yx(e){let t=_x(e);await G.mkdir(K.dirname(t),{recursive:!0}),await G.writeFile(t,``,{encoding:`utf-8`})}async function bx(e){let t=[],n=[];for(let n of hx(e))try{(await G.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of gx(e))try{(await G.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function xx(e){return(await bx(e)).ready}async function Sx(e){if(await vx(e))return{ready:!0,performedBootstrap:!1};if((await bx(e)).ready)return await yx(e),{ready:!0,performedBootstrap:!1};let t=await Cx(e);return await yx(e),{ready:!0,performedBootstrap:!0,result:t}}async function Cx(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Rb(e),r=K.join(e,`workspace`),i=K.join(n,`skills`),a=K.join(n,`sessions`),o=K.join(n,`memory`);await px(e,t),await px(n,t),await px(i,t),await px(a,t),await px(o,t),await px(r,t);for(let e of fx){let r=dx[e]??``;await mx(K.join(n,e),r,t)}return await mx(K.join(n,`MEMORY.md`),``,t),t}async function wx(e){let t=K.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await G.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function Tx(e,t){let n=K.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await G.mkdir(K.dirname(n),{recursive:!0}),await G.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Ex(e,t){let n=await wx(e),r=[];for(let e of n.values())if(e.parentSessionId===t){let{abortController:t,...n}=e;r.push({...n,version:1})}return r.sort((e,t)=>e.startedAt-t.startedAt)}async function Dx(e,t=7){let n=await wx(e),r=Date.now()-t*24*60*60*1e3,i=0;for(let[e,t]of n.entries())t.endedAt&&t.endedAt<r&&(n.delete(e),i++);return i>0&&await Tx(e,n),i}var Ox=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function kx(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function Ax(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await H(t,n,s);if(!l){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await z(t,n,l,s)).trim();if(u!==c){if(!a)throw new Ox(`A different goal already exists for this session. Use --force to replace it.`,kx(u));let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new Ox(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,kx(u));if(a){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await V(t,n,d,{storeName:o,eventSource:`cli`})}}async function jx(e,t,n,r){let i=await lt(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?jt(i.request)?(await at(e,t,n,`expired`,void 0,{storeName:r}),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:i}:{valid:!1,reason:`HITL request is already "${i.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${i.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${i.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function Mx(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ct(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await jx(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await at(t,n,r,`resolved`,i,{storeName:a});if(!c)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:c,idempotentReplay:!1}}const Nx={clarify:{label:`澄清问题`,description:`当你需要更多信息才能继续时,向用户提出澄清问题。提供清晰的问题,并可选给出候选选项。任务会暂停,直到用户回复。`,title:`需要你补充信息`,placeholder:`请输入你的回复`},approval:{label:`请求授权`,description:"仅当用户或系统明确要求调用 `request_approval` 时使用。不要把它用于一般确认、澄清或推断式授权检查。说明要执行的动作,以及为什么必须显式授权。任务会暂停,直到用户同意或拒绝。",choices:{approve:{label:`同意`,description:`允许继续执行该操作`},deny:{label:`拒绝`,description:`不允许执行该操作`}},summary:{approved:`已授权。`,denied:`已拒绝。`,timeout:`由于超时,视为拒绝。`}},review:{label:`请求审阅`,description:`在继续之前,将草稿、文档或输出提交给用户审阅。包含需要审阅的内容,以及你希望获得的反馈类型。任务会暂停,直到用户完成审阅并回复。`,choices:{approve:{label:`通过`,description:`内容没有问题,继续执行`},revise:{label:`需要修改`,description:`提供反馈后再修改`},reject:{label:`拒绝`,description:`放弃当前草稿`}}}};function Px(e){return e.action===`timeout`?Nx.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Nx.approval.summary.approved:Nx.approval.summary.denied}function Fx(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Px(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Ix(e){let t=e.values?.text??e.values?.selectedChoiceIds?.join(`, `)??``;return JSON.stringify({action:e.action,answer:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function Lx(e){let t=(e.values?.selectedChoiceIds??[])[0]??e.action,n=e.values?.text??``;return JSON.stringify({action:e.action,verdict:t,feedback:n,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function Rx(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
|
|
486
489
|
`)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
|
|
487
490
|
`)):(n.push(`动作:用户已提交结果。`),e.values?.selectedChoiceIds&&e.values.selectedChoiceIds.length>0&&n.push(`已选项:${e.values.selectedChoiceIds.join(`, `)}`),e.values?.text&&n.push(`用户文本:${e.values.text}`),e.values?.form&&n.push(`表单数据:${JSON.stringify(e.values.form)}`),n.join(`
|
|
488
|
-
`))}export{
|
|
491
|
+
`))}export{Xi as AutoSkillsLoader,Lb as BOOTSTRAP_FILE_NAMES,Fb as BOOTSTRAP_MAX_CHARS,Ib as BOOTSTRAP_TOTAL_MAX_CHARS,cn as CLARIFY_ACCEPTANCE_TEXT,Ur as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,sn as CLARIFY_TASK_TITLE,Mr as ContinuationState,Hn as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,jr as ENV_GOAL_CONTINUATION,wr as FIRST_TURN_GOAL_WORKFLOW_INTRO,Sy as GOAL_MULTILINE_TEMPLATE_EXAMPLE,zn as GOAL_WORKFLOW_STATE_VERSION,an as GoalAccounting,Ox as GoalConflictError,Nx as HITL_MESSAGES,xo as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,Xm as MAX_CHILDREN_PER_SESSION,Ym as MAX_SUBAGENT_DEPTH,Ve as MemoryIndexManager,Ie as PLUGIN_MANIFEST_FILENAME,xe as PLUGIN_MANIFEST_FILENAMES,de as PluginHookRegistry,_e as PluginToolRegistry,_a as SYSTEM_AGENTS_DIR,Zm as SubagentRegistry,se as UiToolPauseSignal,Tt as addAgent,xt as addBinding,ya as agentDirCandidates,Da as agentVisibility,Rb as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,te as appendGoalEvent,Cf as appendRecentToMemory,i as appendSessionFile,Sf as appendToMemory,h as appendTranscriptEntry,Ax as applyCliGoalBeforeRun,Px as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,Ai as autoSkillsDir,Cx as bootstrapMountLayout,ja as buildAgentDelegationPrompt,Ma as buildAgentTaskPrompt,wy as buildAimaxGoalCliHelpExtra,Hb as buildBootstrapContextFiles,Dr as buildBudgetLimitPrompt,Er as buildContinuationPrompt,Tr as buildFirstTurnGoalWorkflowPrompt,kr as buildGoalContextItem,Cy as buildGoalSlashHelpText,Or as buildObjectiveUpdatedPrompt,Rx as buildResumeNarration,Tp as buildSkillsPrompt,th as buildSubagentAnnounceMessage,Yh as buildSystemPrompt,Dx as cleanupOldSubagentRecords,ut as clearPendingHitl,kb as clearPendingUiTool,j as collapseLogPath,Hr as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,Ir as continuationTurnHadMeaningfulOutput,xa as createAgentDefinitionsContext,xh as createAgentTools,_d as createApplyPatchTool,Vm as createAutoSkillCategoriesTool,Hm as createAutoSkillListTool,Um as createAutoSkillSearchTool,Wm as createAutoSkillViewTool,Ji as createAutoSkillsLoader,Qu as createBashTool,ah as createBatchSubagentSpawnTool,Ue as createBuiltinMemoryProvider,Fu as createContextManager,Je as createDefaultMemoryProvider,cd as createEditFileTool,qu as createExecTool,bh as createImageTool,ud as createListDirTool,jf as createMemoryAppendTool,Gf as createMemoryForgetTool,kf as createMemoryGetTool,Uf as createMemoryListTool,Vf as createMemoryLogTool,Df as createMemorySearchTool,qf as createMemoryUpdateTool,Nf as createMemoryWriteTool,ot as createPendingHitl,Db as createPendingUiTool,fe as createPluginProgressEmitter,be as createPluginRuntime,Zu as createProcessTool,id as createReadFileTool,T as createSession,ou as createSessionContextStore,Yf as createSessionSearchTool,kp as createSkillListTool,Ap as createSkillLoadTool,ih as createSubagentSpawnTool,lh as createSubagentsTool,Be as createUiTool,od as createWriteFileTool,N as cronExecutionsPath,ye as defaultUiToolInputSchema,ae as deleteGoal,nr as deleteGoalWorkflow,Tf as deleteMemoryFile,ke as discoverAIMaxPlugins,ob as emitGoalUpdatedProgress,Sx as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,xn as extractWorkflowPlanFromObjective,ka as filterSkillsForAgent,Aa as filterToolsForAgent,Ea as findAgentDefinition,Sp as findSkillByName,on as flushAccounting,Fx as formatApprovalResolution,Ix as formatClarifyResolution,Lx as formatReviewResolution,ry as generateSessionTitle,vt as getAgentConfig,xf as getMemoryLines,Ne as getPluginSystem,Jn as goalArtifactsDir,ne as goalDir,R as goalEventsPath,ie as goalObjectiveMdPath,B as goalPath,qn as goalWorkflowPlanPath,Kn as goalWorkflowStatePath,vx as hasBootstrapSentinel,it as hitlHistoryPath,rr as initializeGoalWorkflow,Te as initializePluginSystem,bx as inspectBootstrapMountLayout,k as inspectSession,qr as installClarifyFirstTurnGate,xx as isBootstrapMountLayoutReady,Gr as isClarifyFirstTurnBlockedTool,Wr as isClarifyWorkflowTask,Pr as isContinuationEnabled,Ar as isGoalContext,So as isHitlPauseSignal,Re as isUiToolPauseSignal,ft as listAgents,Ry as listAvailableSlashCommands,St as listBindings,_f as listMemoryFiles,E as listSessionSummaries,x as listSessions,Ex as listSubagentRunsFromDisk,wa as loadAgentDefinitionsFromDir,wt as loadAgentsConfig,b as loadArtifactOperations,zb as loadBootstrapFiles,m as loadCronExecutionRecords,lt as loadPendingHitl,lt as readPendingHitl,Eb as loadPendingUiTool,Eb as readPendingUiTool,Se as loadPluginManifest,Oe as loadPluginManifestRegistry,Pe as loadPlugins,P as loadSessionContextSnapshot,zs as loadSessionExportSnapshots,I as loadSessionMetadata,wp as loadSkillView,yp as loadSkills,xp as loadSkillsFromDirs,bp as loadSkillsWithPluginDirs,wx as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,Nr as loadWorkflowPromptContext,Lr as maybeContinueGoalIfIdle,pf as memoryDir,f as metadataPath,re as mirrorGoalStatusToSession,pt as normalizeAgentId,we as normalizePluginsConfig,t as normalizeSessionStoreName,Ta as parseAgentDefinition,rt as pendingHitlPath,wb as pendingUiToolPath,Rs as persistSessionExportSnapshots,ve as preloadPluginSystem,Fe as prepareSystemRuntime,Br as prependFirstGoalWorkflowSteeringIfNeeded,Vr as prependObjectiveUpdatedSteeringIfNeeded,mf as primaryMemoryPath,Oa as publicAgentDefinitions,H as readGoal,Qn as readGoalWorkflowState,er as readGoalWorkflowSummary,st as readHitlHistory,vf as readMemoryFile,yf as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,zr as recoverBlockedWorkflowOnUserTurn,Ze as registerEmbeddingProvider,tt as registerMemoryProvider,yt as removeAgent,Et as removeBindings,wn as renderGoalPlanMarkdown,$n as repairGoalWorkflowState,wf as replaceMemoryFile,Xe as resetEmbeddingProviderRegistryForTests,Qe as resetMemoryProviderRegistryForTests,Ca as resolveAgentDefinitionsContext,mt as resolveAgentDir,ht as resolveAgentIdByBinding,Ct as resolveAgentsConfigPath,bt as resolveDefaultAgentId,$e as resolveEmbeddingProvider,z as resolveGoalObjective,tr as resolveGoalToolWorkflowView,Mx as resolveHitlRequest,Mx as resolvePendingHitl,et as resolveMemoryProvider,Ke as resolveMemoryProviderOrDefault,_t as resolveModelFallbacks,gt as resolveModelString,Ob as resolvePendingUiTool,Me as resolvePluginManifestPath,ee as rewriteTranscript,cx as runAgent,dt as saveAgentsConfig,p as saveSessionMetadata,Tx as saveSubagentRegistryToDisk,ba as scanAgentDefinitions,bf as searchMemory,Is as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,Fs as sessionToolsSnapshotPath,e as sessionsDir,Fr as shouldContinueGoal,pp as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,at as transitionHitlStatus,Dt as updateAgent,Ot as updateAgentIdentity,V as updateGoal,u as updateSessionMetadata,Ce as validatePluginsConfig,jx as validateResume,Gn as withGoalWorkflowLock,Xh as wrapToolsWithHooks,U as writeGoal,L as writeSessionFile};
|