@gencode/agents 0.12.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.js +113 -110
- package/dist/{loader-CWpoiWtT.d.ts → loader-CR0TB17A.d.ts} +5 -3
- package/dist/pi-extensions/index.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,152 +1,155 @@
|
|
|
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
|
|
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 tn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function nn(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),tn(e))};return{start(t){let{file:n,args:r,shell:a}=Wt(t.command),o=it(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!Ut}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:nt(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:o,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:c,resolveDone:s};e.set(l.sessionId,l),o.stdout.on(`data`,e=>Yt(l,`stdout`,e)),o.stderr.on(`data`,e=>Yt(l,`stderr`,e));let u=e=>t=>{Yt(l,`stderr`,Buffer.from(`\n[${e} stream error: ${t.message}]\n`))};o.stdout.on(`error`,u(`stdout`)),o.stderr.on(`error`,u(`stderr`)),o.stdin.on(`error`,u(`stdin`));try{o.stdin.end()}catch{}let d=Qt(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Yt(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Gt(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Gt(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Yt(l,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),o.on(`close`,(e,t)=>{i(l,()=>{l.exitCode=e,l.exitSignal=t,l.status===`running`?l.status=e===0?`completed`:`failed`:l.status===`killed`&&e===0&&(l.status=`completed`)})}),Xt(l)},get(e,t){let n=r(e);return!n||!Zt(n,t)?null:Xt(n)},list(n){return[...e.values(),...t.values()].filter(e=>Zt(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Xt(e))},async wait(e,t,n){let i=r(e);if(!i||!Zt(i,t))return null;if(i.status!==`running`)return Xt(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!Zt(a,t)?null:Xt(a)},readLog(e){let t=r(e.sessionId);return!t||!Zt(t,e.scopeKey)?null:en({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Zt(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!Zt(n,t))return null;if(n.status!==`running`)return Xt(n);n.status=`killed`,Gt(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Gt(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?Xt(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Gt(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Gt(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const rn=1;var an=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},on=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},sn=class extends Error{rawContentPreview;constructor(e,t){super(e),this.name=`CorruptGoalWorkflowStateError`,t?.cause!==void 0&&(this.cause=t.cause),this.rawContentPreview=t?.rawContentPreview}};const cn=new Map;function ln(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function un(e,t,n,r){let i=ln(e,t,n),a=cn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});cn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function dn(e,t,n){return W.join(V(e,t,n),`state.json`)}function fn(e,t,n){return W.join(V(e,t,n),`plan.md`)}function pn(e,t,n){return W.join(V(e,t,n),`artifacts`)}async function mn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${tt(4).toString(`hex`)}.tmp`;try{await U.writeFile(n,t,`utf-8`),await U.rename(n,e)}finally{await U.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function hn(e){if(e.version!==1)throw new an(e.version)}function gn(e){let t=e.currentTaskId?e.tasks.find(t=>t.id===e.currentTaskId)??null:null,n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`done`).length,i=n.filter(e=>e.status!==`done`).length;return{workflowStatus:e.status,currentTaskId:e.currentTaskId,currentTaskTitle:t?.title??null,currentTaskStatus:t?.status??null,blockedReason:e.blockedReason,openRequiredTasks:i,doneRequiredTasks:r,finalEvidenceRefs:[...e.finalEvidenceRefs]}}async function _n(e,t,n){let r=dn(e,t,n);try{let e=await U.readFile(r,`utf-8`);try{let t=JSON.parse(e);return hn(t),t}catch(t){throw t instanceof an?t:new sn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof sn||e instanceof an?e:new sn(`corrupt_goal_workflow_state`,{cause:e})}}async function vn(e,t,n){let r=dn(e,t,n),i;try{i=await U.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return hn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof an)throw e}let a=await H(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await z(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await U.writeFile(s,i,`utf-8`),c=s}catch{}return await Sn(e,t,{goalId:a.goalId,objective:o},n),await q(e,t,{type:`goal_workflow_repaired`,goalId:a.goalId,mode:`reinitialized`,backupPath:c},n),{ok:!0,mode:`reinitialized`,goalId:a.goalId,backedUpState:c}}async function yn(e,t,n){let r=await _n(e,t,n);return r?gn(r):null}async function bn(e,t,n){let r=await _n(e,t,n);return r?{goalState:gn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function xn(e,t,n){let r=dn(e,t,n),i=fn(e,t,n),a=pn(e,t,n);await Promise.all([U.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),U.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),U.rm(a,{recursive:!0,force:!0})])}async function Sn(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await xn(e,t,r);let a=zt(i),o=new Date().toISOString(),s=a.tasks.find(e=>e.status===`doing`)?.id??a.tasks[0]?.id??null,c={version:1,goalId:n.goalId,status:`active`,objective:i,currentTaskId:s,tasks:a.tasks,blockedReason:null,finalEvidenceRefs:[],completedAt:null,updatedAt:o},l=V(e,t,r);await U.mkdir(l,{recursive:!0}),await mn(dn(e,t,r),JSON.stringify(c,null,2));let u=Ht(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await mn(fn(e,t,r),u),c}const Cn=1048576,wn=/KEY|TOKEN|SECRET|PASSWORD|COOKIE|AUTH/i,Tn=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g],En=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.pdf`]);function Dn(e,t,n){return W.join(pn(e,t,n),`registry.jsonl`)}function On(e,t,n){return W.join(pn(e,t,n),`notes`)}function kn(e,t,n){return W.join(pn(e,t,n),`commands`)}function An(e,t,n){return W.join(pn(e,t,n),`snapshots`)}function jn(e,t,n){return W.join(V(e,t,n),`plan-meta.json`)}function Mn(e){let t=e,n=!1;for(let e of Tn)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function Nn(e){return`sha256:${et(`sha256`).update(e).digest(`hex`)}`}async function Pn(e){return Nn(await U.readFile(e))}function Fn(e,t){let n=W.normalize(e);return t.some(e=>{let t=W.normalize(e);return n===t||n.startsWith(t+W.sep)})}function In(e){let t=[W.normalize(e.workspaceDir),W.normalize(rt.tmpdir())],n=e.projectDir?.trim();n&&t.push(W.normalize(n));let r=W.join(e.dataDir,`workspace`);return t.includes(W.normalize(r))||t.push(W.normalize(r)),t}function Ln(e,t){return t?.trim()?W.isAbsolute(t)?W.normalize(t):W.normalize(W.join(e,t)):e}function Rn(e,t){return e.byteLength<=t?{data:e,truncated:!1,originalBytes:e.byteLength}:{data:e.subarray(0,t),truncated:!0,originalBytes:e.byteLength}}function zn(e){return`${e}-${Date.now().toString(36)}-${tt(3).toString(`hex`)}`}async function Bn(e,t,n,r){let i=await Vn(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${zn(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function Vn(e,t,n){let r=Dn(e,t,n);try{let e=await U.readFile(r,`utf-8`),t=[],n=e.split(/\r?\n/).map((e,t)=>({line:e,index:t})).filter(e=>e.line.trim().length>0);for(let[e,r]of n.entries())try{t.push(JSON.parse(r.line))}catch{if(e===n.length-1)continue;throw new on(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Hn(e,t,n,r){let i=Dn(e,t,r);await U.mkdir(W.dirname(i),{recursive:!0}),await U.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Un(e,t,n,r){let i=[...new Set(n.filter(e=>e.trim().length>0))];if(i.length===0)return{valid:!1,errors:[{ref:``,code:`unregistered_evidence_ref`,message:`no evidence refs provided`}]};let a=await Vn(e,t,r),o=new Map(a.map(e=>[e.id,e])),s=[],c=Wn(e,t,r);for(let e of i){let t=o.get(e);if(!t){s.push({ref:e,code:`unregistered_evidence_ref`,message:`evidence ref not registered: ${e}`});continue}if(t.kind===`command`){let n=t.stdoutRef?W.join(c,t.stdoutRef):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`stdout artifact missing for ${e}`});continue}try{let r=await U.readFile(n);if(t.hash&&Nn(r)!==t.hash){s.push({ref:e,code:`artifact_integrity_mismatch`,message:`stdout hash mismatch for ${e}`});continue}}catch{s.push({ref:e,code:`missing_artifact_file`,message:`stdout artifact missing for ${e}`});continue}r?.requireCommandSuccess!==!1&&t.exitCode!==0&&s.push({ref:e,code:`command_exit_nonzero`,message:`command evidence exit code ${t.exitCode}`});continue}if(t.kind===`snapshot`){let n=t.snapshotPath?W.join(c,t.snapshotPath):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`snapshot path missing for ${e}`});continue}try{let r=await U.stat(n);if(t.sizeBytes!==void 0&&r.size!==t.sizeBytes){s.push({ref:e,code:`artifact_integrity_mismatch`,message:`snapshot size mismatch for ${e}`});continue}t.hash&&await Pn(n)!==t.hash&&s.push({ref:e,code:`artifact_integrity_mismatch`,message:`snapshot hash mismatch for ${e}`})}catch{s.push({ref:e,code:`missing_artifact_file`,message:`snapshot artifact missing for ${e}`})}continue}let n=t.notePath?W.join(c,t.notePath):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`note path missing for ${e}`});continue}try{let r=await U.stat(n);t.contentBytes!==void 0&&r.size!==t.contentBytes&&s.push({ref:e,code:`artifact_integrity_mismatch`,message:`note size mismatch for ${e}`})}catch{s.push({ref:e,code:`missing_artifact_file`,message:`note artifact missing for ${e}`})}}return{valid:s.length===0,errors:s}}function Wn(e,t,n){return W.dirname(V(e,t,n))}async function Gn(e,t,n,r){hn(n),await mn(dn(e,t,r),JSON.stringify(n,null,2))}async function Kn(e,t,n){let r=jn(e,t,n);try{let e=await U.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function qn(e,t,n,r){await mn(jn(e,t,r),JSON.stringify(n,null,2))}async function Jn(e,t,n,r){let i=await Kn(e,t,r),a={...i,...n,assumptions:n.assumptions??i.assumptions,openQuestions:n.openQuestions??i.openQuestions,progressLog:n.progressLog??i.progressLog,evidence:n.evidence??i.evidence,risks:n.risks??i.risks,criterionEvidence:{...i.criterionEvidence,...n.criterionEvidence}};return await qn(e,t,a,r),a}async function Yn(e,t,n,r){try{let i=Ht(n,await Kn(e,t,r));return await mn(fn(e,t,r),i),{ok:!0}}catch(e){return{ok:!1,warning:`plan_update_failed`,message:e instanceof Error?e.message:String(e)}}}async function q(e,t,n,r){let{type:i,...a}=n,o={timestamp:new Date().toISOString(),sessionId:t,goalId:n.goalId??null,action:i,detail:a},s=R(e,t,r);await U.mkdir(W.dirname(s),{recursive:!0}),await U.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}function Xn(e){let t=e.map(e=>Number.parseInt(e.id.replace(/^task-/,``),10)).filter(e=>Number.isFinite(e));return`task-${(t.length>0?Math.max(...t):0)+1}`}function Zn(e,t=[]){let n=t.map(e=>Number.parseInt(e.id.replace(/^ac-/,``),10)).filter(e=>Number.isFinite(e)),r=n.length>0?Math.max(...n):0,i=[];for(let t=0;t<e;t+=1)r+=1,i.push(`ac-${r}`);return i}async function Qn(e,t,n,r){if(n.kind===`manual`&&!n.source?.trim())return{error:`manual evidence requires source`};if(Buffer.byteLength(n.content,`utf-8`)>65536)return{error:`note_content_too_large`};let i=await Bn(e,t,n.kind,r),a=i.split(`:`)[1]??zn(n.kind),o=On(e,t,r);await U.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=W.join(On(e,t,r),`${a}.md`),l=Mn(n.content);await U.writeFile(c,l.text,`utf-8`);let u={id:i,kind:n.kind,summary:n.summary,source:n.source??`model`,createdAt:new Date().toISOString(),notePath:s,contentBytes:Buffer.byteLength(l.text,`utf-8`),redactionIncomplete:l.redactionIncomplete};try{await Hn(e,t,u,r)}catch{return await U.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}async function $n(e,t,n,r){let i=Ln(n.workspaceDir,n.cwd);if(!Fn(i,n.allowedRoots))return{error:`cwd_outside_allowed_roots`};let a=Math.min(Math.max(n.timeoutMs??12e4,1),6e5),o=Math.ceil(a/1e3),s=nn(),c=s.start({command:n.command,cwd:i,baseEnv:n.baseEnv,timeoutSec:o,scopeKey:n.workspaceDir}),l=await s.wait(c.sessionId,n.workspaceDir)??c,u=s.readOutput(l.sessionId,n.workspaceDir),d=Buffer.from(u?.stdout??l.stdoutTail,`utf-8`),f=Buffer.from(u?.stderr??l.stderrTail,`utf-8`),p=Rn(d,Cn),m=Rn(f,Cn),h=Mn(p.data.toString(`utf-8`)),g=Mn(m.data.toString(`utf-8`)),_=h.redactionIncomplete||g.redactionIncomplete,v=await Bn(e,t,`command`,r),y=v.split(`:`)[1]??zn(`command`),b=kn(e,t,r);await U.mkdir(b,{recursive:!0});let x=`goal/artifacts/commands/${y}.out.txt`,S=`goal/artifacts/commands/${y}.err.txt`,C=W.join(b,`${y}.out.txt`),w=W.join(b,`${y}.err.txt`);await U.writeFile(C,h.text,`utf-8`),await U.writeFile(w,g.text,`utf-8`);let T=Object.keys({...process.env,...n.baseEnv}).filter(e=>wn.test(e)),E={id:v,kind:`command`,command:Mn(n.command).text,cwd:i,exitCode:l.exitCode??1,stdoutRef:x,stderrRef:S,stdoutTruncated:p.truncated,stderrTruncated:m.truncated,stdoutBytes:p.originalBytes,stderrBytes:m.originalBytes,timeoutMs:a,envKeys:T,redactionIncomplete:_,hash:Nn(h.text),createdAt:new Date().toISOString()};try{await Hn(e,t,E,r)}catch{return await Promise.all([U.unlink(C).catch(()=>{}),U.unlink(w).catch(()=>{})]),{error:`registry_write_failed`}}return{evidenceRef:v,exitCode:l.exitCode??1}}function er(e,t){let n=W.normalize(e),r=n.split(W.sep).filter(Boolean);if(r.includes(`.aimax`)||r.includes(`.ssh`)||r.includes(`.gnupg`))return!0;let i=W.normalize(t);return n.startsWith(W.join(i,`.aimax`)+W.sep)||n===W.join(i,`.aimax`)}async function tr(e,t,n,r){let i=W.isAbsolute(n.path)?W.normalize(n.path):W.normalize(W.join(n.workspaceDir,n.path));if(!Fn(i,n.allowedRoots))return{error:`snapshot_path_outside_allowed_roots`};if(er(i,e))return{error:`snapshot_sensitive_path_not_allowed`};let a;try{a=await U.stat(i)}catch{return{error:`snapshot_file_not_found`}}if(!a.isFile())return{error:`snapshot_not_a_file`};if(a.size>5242880)return{error:`snapshot_too_large`};let o=W.extname(i).toLowerCase(),s=o.length>0&&En.has(o),c;try{c=await U.readFile(i)}catch{return{error:`snapshot_read_failed`}}if(!s){let e=Mn(c.toString(`utf-8`));c=Buffer.from(e.text,`utf-8`)}else if(!En.has(o))return{error:`snapshot_binary_type_not_allowed`};let l=await Bn(e,t,`snapshot`,r),u=l.split(`:`)[1]??zn(`snapshot`),d=An(e,t,r);await U.mkdir(d,{recursive:!0});let f=`${u}${o||W.extname(i)}`,p=`goal/artifacts/snapshots/${f}`,m=W.join(d,f);await U.writeFile(m,c);let h={id:l,kind:`snapshot`,summary:n.summary,path:i,hash:Nn(c),sizeBytes:c.byteLength,snapshotPath:p,createdAt:new Date().toISOString()};try{await Hn(e,t,h,r)}catch{return await U.unlink(m).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:l}}function nr(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function rr(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${nr(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${nr(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${nr(e.taskBlockedReason)}`),e.acceptanceCriteria.length>0){t.push(``,`Acceptance criteria (current task):`);for(let n of e.acceptanceCriteria){let e=n.required===!1?``:` [required]`;t.push(`- ${n.id}${e}: ${nr(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${nr(n)}`)}return t}function ir(e){let t=[`- Treat goal/state.json as the only task workflow machine state; use goal/plan.md for human-readable context.`,`- Work on the current task only unless you call goal_add_task or goal_task_start.`,`- Do not claim task completion in prose; use goal_task_done with evidence refs.`,`- Use only evidenceRef values returned by goal_record_note, goal_record_exec, or goal_record_snapshot when filling evidenceRefs, acceptanceEvidence, or finalEvidenceRefs.`,`- Natural-language descriptions and file paths are not evidence refs; strings like "goal/state.json ..." must first be registered with a goal_record_* tool.`,`- In goal workflow, use goal_record_exec instead of exec for bounded command execution; it records command evidence, while exec output is not registered in the goal evidence registry.`,`- If blocked, use goal_task_blocked with a clear reason and needed input.`,`- Finish the goal with goal_complete (final evidence refs); do NOT call update_goal(status="complete").`,`- Use goal_plan_update for plan interpretation, assumptions, or open questions.`,`- Use the current worktree, files, command output, and test results as authoritative evidence.`,`- Do not rely solely on conversation memory to assess completion.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress on the current task.`,`- Do not inform the user about this continuation context; treat it as internal steering.`];return(e.currentTaskKind===`clarify`||e.currentTaskTitle===Tt)&&t.unshift(`- Current task is "${Tt}": explore, clarify, and refine the plan and acceptance criteria.`,`- Do NOT implement deliverables yet; use goal tools to add tasks and criteria before execution work.`),t}function ar(){return[`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- Do not call update_goal(status="complete"); V2-lite completion requires goal_complete with evidence refs after workflow initialization.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`]}const or=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function sr(e,t,n){return cr(e,t,n,{introLine:or})}function cr(e,t,n,r){let i=nr(t),a=e.tokenBudget===null?`none`:String(e.tokenBudget),o=String(e.tokensUsed),s=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed)),c=n?`The user's thread goal is still active. Continue working on the current workflow task below.`:`The user's thread goal is still active. Continue working toward the objective below.`,l=[`<goal_context>`,``,r?.introLine??c,``,`<objective>`,i,`</objective>`,``,`Token budget: ${a}`,`Tokens used: ${o}`,`Tokens remaining: ${s}`,`Time used: ${e.timeUsedSeconds}s`,``];return n?l.push(`<workflow>`,...rr(n),`</workflow>`,``,`Rules:`,...ir(n)):l.push(`Rules:`,...ar()),l.push(``,`</goal_context>`),l.join(`
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
7
|
-
`)}function dr(e){return{role:`user`,content:e}}function fr(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const pr=`AIMAX_GOAL_CONTINUATION`;var mr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function hr(e,t,n){let r=await _n(e,t,{storeName:n?.storeName});if(!r)return null;let i=await Kn(e,t,{storeName:n?.storeName}),a=r.currentTaskId?r.tasks.find(e=>e.id===r.currentTaskId)??null:null;return{workflowStatus:r.status,currentTaskId:r.currentTaskId,currentTaskTitle:a?.title??null,currentTaskKind:a?.kind??null,currentTaskStatus:a?.status??null,blockedReason:r.blockedReason,taskBlockedReason:a?.blockedReason??null,acceptanceCriteria:a?.acceptanceCriteria??[],openQuestions:i.openQuestions??[]}}function gr(){let e=process.env[pr];return e===void 0||e===``||e!==`0`}async function _r(e,t,n,r){if(!gr()||n.continuationCount>=qe)return!1;let i=await H(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-Ddm_lIaP.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function vr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function yr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await _r(n,r,a,{storeName:i}))return!1;let u=await H(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await z(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await hr(n,r,{storeName:i}),h=dr(p?lr(u,f):cr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=vr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=qe){let e=await H(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-DKeFVjM4.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-DvF1LRBK.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${qe}), goal paused`)}}return!0}async function br(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function xr(e,t,n){let r=await _n(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await Gn(e,t,c,{storeName:n?.storeName}),await q(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await Kn(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await Jn(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await Yn(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Sr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await hr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=dr(sr(i,await z(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Cr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=dr(ur(i,await z(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function wr(e,t,n){(await H(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await B(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const Tr=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Er(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===Tt}function Dr(e){return Tr.has(e)}function Or(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use goal_record_exec for bounded command execution that should be recorded as workflow evidence.`,`Use goal_plan_update, goal_add_task, goal_task_done, or goal_repair_workflow_state to refine or recover the plan.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use goal workflow tools such as goal_plan_update, goal_add_task, goal_task_done, goal_record_exec, goal_record_note, goal_record_snapshot, or goal_repair_workflow_state to refine, record evidence, or recover before executing deliverables directly.`].join(` `)}function kr(e){let t=!0;return e.hookRegistry.register({pluginId:`goal-clarify-first-turn-gate`,hookName:`before_tool_call`,source:`agents/goal/clarify-first-turn-gate`,priority:100,handler:n=>{if(!(!t||!e.isGateActive())&&Dr(n.toolName))return{block:!0,blockReason:Or(n.toolName)}}}),()=>{t=!1}}function Ar(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e)o.role===`user`?t+=1:o.role===`assistant`?n+=1:o.role===`tool_result`?r+=1:o.role===`compaction`?i+=1:a+=1;return{userTurnCount:t,assistantTurnCount:n,toolResultCount:r,compactionCount:i,otherEntryCount:a,totalEntryCount:e.length}}function jr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(zr(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}Br(a)&&(r+=1,a.isError&&(i+=1))}let a=Array.from(t).sort();return{toolCallCount:n,distinctToolCount:a.length,toolNames:a,toolResultCount:r,failedToolResultCount:i}}function Mr(e,t={}){let n=Lr(t.limit,`limit`),r=Rr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!Br(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Ir(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Nr(e,t){let n=Rr(e,`totalEntryCount`);return typeof t!=`number`||!Number.isFinite(t)?{startIndex:0,endIndex:n}:{startIndex:Math.min(n,Math.max(0,Math.floor(t))),endIndex:n}}function Pr(e,t=80){let n=Rr(e,`totalEntryCount`),r=Rr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Fr(e,t){return e.slice(t.startIndex,t.endIndex)}function Ir(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Lr(e,t){return e===void 0?1/0:Rr(e,t)}function Rr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function zr(e){return e.role===`assistant`}function Br(e){return e.role===`tool_result`}const Vr=24e3;async function Hr(e){return Xr({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Ur(e){return Xr({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Wr(e){return Xr({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Gr(e){let t=ii(e),n=await qr(e),r=await ei(n.filePath,t.maxBytes);return{kind:`tool_result`,toolCallId:n.reference.toolCallId,toolName:n.reference.toolName,storagePath:n.reference.storagePath,content:r.content,originalBytes:r.originalBytes,returnedBytes:Buffer.byteLength(r.content,`utf-8`),truncated:r.truncated,limits:t,contextFiles:Jr(e.dataDir,e.sessionId,e.sessionOptions)}}function Kr(e){return{maxEntries:ai(e?.maxEntries??80,`limits.maxEntries`),maxBytes:ai(e?.maxBytes??Vr,`limits.maxBytes`)}}async function qr(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Zr(await Qr(e.dataDir,e.sessionId,e.sessionOptions),{toolCallId:e.toolCallId,storagePath:e.storagePath});if(!t)throw Error(`Requested tool result is not referenced by this session transcript or context.`);return{reference:t,filePath:await $r({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Jr(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function Yr(e,t,n){let r=oi(e.startIndex,`startIndex`),i=oi(e.endIndex,`endIndex`);if(r<0||i<r||i>t)throw Error(`Requested transcript range is outside transcript bounds 0..${t}.`);if(i-r>n)throw Error(`Requested transcript range exceeds maximum of ${n} entries.`);return{startIndex:r,endIndex:i}}function Xr(e){let t=ii(e.params),n=Yr(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=ti(r,t.maxBytes);return{kind:e.kind,range:n,entries:i.entries,entryCount:i.entries.length,rangeEntryCount:r.length,totalEntryCount:e.transcript.length,returnedBytes:i.returnedBytes,truncated:i.truncated,limits:t,contextFiles:Jr(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Zr(e,t){if(t.toolCallId&&t.storagePath){let n=e.find(e=>e.toolCallId===t.toolCallId&&e.storagePath===t.storagePath);if(n)return n;let r=e.some(e=>e.toolCallId===t.toolCallId),i=e.some(e=>e.storagePath===t.storagePath);if(r&&i)throw Error(`Requested toolCallId and storagePath do not reference the same tool result.`);return}return e.find(e=>t.toolCallId?e.toolCallId===t.toolCallId:e.storagePath===t.storagePath)}async function Qr(e,t,n){let[r,i]=await Promise.all([F(e,t,n),ee(e,t,n)]),a=new Map;for(let e of r)li(e)&&e.toolResultRef?.sessionId===t&&a.set(ui(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(ui(e),e);return Array.from(a.values())}async function $r(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(W.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=W.resolve(e.dataDir,e.reference.storagePath);if(!ci(W.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!ci(W.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([si(t),si(n),si(i)]);if(!ci(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!ci(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function ei(e,t){let n=await U.stat(e),r=await U.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:ri(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function ti(e,t){let n=[],r=0,i=!1;for(let a of e){let e={...a,content:``},o=Buffer.byteLength(JSON.stringify(e),`utf-8`);if(r+o>=t){i=!0;break}let s=t-r-o,c=ni(a.content,s);c.truncated&&(i=!0);let l={...a,content:c.value},u=Buffer.byteLength(JSON.stringify(l),`utf-8`);if(n.push(l),r+=u,c.truncated)break}return n.length<e.length&&(i=!0),{entries:n,returnedBytes:r,truncated:i}}function ni(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:ri(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function ri(e){let t=new at(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function ii(e){return Kr(e.limits)}function ai(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function oi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function si(e){try{return await U.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${di(e)}`)}}function ci(e,t){let n=W.relative(e,t);return n===``||!n.startsWith(`..`)&&!W.isAbsolute(n)}function li(e){return e.role===`tool_result`}function ui(e){return`${e.toolCallId}\n${e.storagePath}`}function di(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function fi(e){return W.join(e,`.aimax`,`auto-skills`)}function pi(e){return W.join(e,`categories.json`)}function mi(e){return W.join(e,`.auto_skills_prompt_snapshot.json`)}const hi=/^[a-z0-9][a-z0-9-]*$/,gi=/^[a-z0-9][a-z0-9-]*$/;function _i(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||W.win32.isAbsolute(t)||W.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!hi.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function vi(e){let t=e.trim();if(!t)throw Error(`Auto-skill name cannot be empty.`);if(t.length>80)throw Error(`Auto-skill name is too long.`);if(t.includes(`/`)||t.includes(`\\`)||t===`.`||t===`..`||t.startsWith(`.`)||!gi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function yi(e,t){return`auto:${_i(e)}/${vi(t)}`}function bi(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=_i(n.slice(0,r)),a=vi(n.slice(r+1));return{skillId:yi(i,a),categoryPath:i,skillName:a}}function xi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Si(e,t,n){let r=W.resolve(e),i=W.resolve(r,..._i(t).split(`/`),vi(n));return wi(r,i),i}function Ci(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||W.win32.isAbsolute(n)||W.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=W.resolve(e),a=W.resolve(i,...r);return wi(i,a),a}function wi(e,t){let n=W.resolve(e),r=W.resolve(t),i=W.relative(n,r);if(i.startsWith(`..`)||W.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ti(e){let t=pi(e),n;try{n=await U.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=_i(e),r=Di(t);return{path:n,name:n.split(`/`).at(-1)??n,description:r.description,createdBy:r.createdBy}}).sort((e,t)=>e.path.localeCompare(t.path))}function Ei(e){return new Map(e.map(e=>[e.path,e]))}function Di(e){return typeof e==`string`?{description:e.trim()}:!e||typeof e!=`object`||Array.isArray(e)?{description:``}:{description:typeof e.description==`string`?e.description.trim():``,createdBy:typeof e.createdBy==`string`?e.createdBy.trim():void 0}}const Oi=32*1024,ki=new Map;function Ai(e){return new Mi(e)}async function ji(e){let t=W.resolve(e);for(let e of Array.from(ki.keys()))e.startsWith(`${t}|`)&&ki.delete(e);await U.rm(mi(t),{force:!0}).catch(()=>{})}var Mi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=W.resolve(e.rootDir??fi(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Pi(Ei((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?_i(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Fi(e.categoryPath,t)).map(Ni)}async autoSkillSearch(e){let t=e.query.trim().toLowerCase();if(!t)return[];let n=Math.max(1,e.limit??5);return(await this.visibleEntries()).map(e=>({entry:e,score:Ii(e,t)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||e.entry.skillId.localeCompare(t.entry.skillId)).slice(0,n).map(({entry:e,score:t})=>({...Ni(e),score:t}))}async autoSkillView(e){let t=bi(e.skillId),n=(await this.visibleEntries()).find(e=>e.skillId===t.skillId);if(!n)throw Error(`Unknown auto-skill: ${e.skillId}`);if(e.filePath?.trim()){let t=Ci(n.skillDir,e.filePath),r=await Gi(t,this.maxResourceBytes);return{...Ni(n),status:n.status,content:r,path:Ji(W.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Ji(W.relative(n.skillDir,t))}}let r=await Gi(n.skillFile,this.maxSkillBytes);return{...Ni(n),status:n.status,content:r,path:Ji(W.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await Li(this.rootDir),i=ki.get(n);if(!e&&i&&Hi(i.manifest,r))return i;let a=e?void 0:await Bi(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return ki.set(n,e),e}let o=await Ti(this.rootDir),s=Ei(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return ki.set(n,c),await Vi(this.rootDir,c).catch(()=>{}),c}async parseEntriesFromManifest(e){let t=e.filter(e=>e.kind===`skill`).map(e=>e.filePath),n=[];for(let e of t){let t=await this.loadEntry(e);t&&n.push(t)}return n.sort((e,t)=>e.skillId.localeCompare(t.skillId))}async visibleEntries(){let e=await this.loadIndex();return this.visibleEntriesFrom(e)}visibleEntriesFrom(e){return this.includeArchived?e:e.filter(e=>e.status===`active`)}optionsHash(){return Zi({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Oi})}async loadEntry(e){try{let t=W.dirname(e),n=vi(W.basename(t)),r=Ji(W.relative(this.rootDir,t)),i=_i(W.posix.dirname(r)),a=yi(i,n),o=W.join(t,`metadata.json`),s=await Ui(o);if(s?.skillId&&bi(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&_i(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=xi(s?.status);return{skillId:a,name:n,description:Ki(await Wi(e,Oi)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:qi(s?.tags),relatedSkills:qi(s?.relatedSkills),confidence:typeof s?.confidence==`number`?s.confidence:void 0,createdAt:typeof s?.createdAt==`string`?s.createdAt:void 0,updatedAt:typeof s?.updatedAt==`string`?s.updatedAt:void 0}}catch(t){process.stderr.write(`[auto-skills] skipped ${e}: ${Yi(t)}\n`);return}}};function Ni(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Pi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Fi(e,t){return t?e===t:!0}function Ii(e,t){let n=t.split(/\s+/).filter(Boolean),r=e.name.toLowerCase(),i=e.description.toLowerCase(),a=e.categoryPath.toLowerCase(),o=e.tags.join(` `).toLowerCase(),s=0;r===t&&(s+=80),r.includes(t)&&(s+=30),i.includes(t)&&(s+=20),a.includes(t)&&(s+=10),o.includes(t)&&(s+=10);for(let e of n)r.includes(e)&&(s+=8),i.includes(e)&&(s+=5),a.includes(e)&&(s+=3),o.includes(e)&&(s+=3);return s}async function Li(e){let t;try{t=await U.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await zi(W.join(e,`categories.json`),`categories`,n),await Ri(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Ri(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=W.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await zi(t,`skill`,n),await zi(W.join(e,`metadata.json`),`metadata`,n),await zi(W.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await U.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Ri(t,i,n)}}async function zi(e,t,n){try{let r=await U.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function Bi(e,t,n){let r;try{r=await U.readFile(mi(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!Hi(e.manifest,n)?void 0:e}catch{return}}async function Vi(e,t){if(!await Xi(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await U.writeFile(mi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function Hi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.filePath!==i.filePath||r.kind!==i.kind||r.size!==i.size||r.mtimeMs!==i.mtimeMs)return!1}return!0}async function Ui(e){try{let t=await U.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Wi(e,t){let n=await U.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function Gi(e,t){if((await U.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return U.readFile(e,`utf-8`)}function Ki(e){let t=ot(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
|
|
8
|
-
`)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function
|
|
9
|
-
|
|
10
|
-
`)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function
|
|
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-DbQpczup.js";import{n as R,t as te}from"./goal-events-DvF1LRBK.js";import{c as z,i as B,l as V,n as H,o as ne,r as re,s as U,t as ie,u as ae}from"./goal-store-DKeFVjM4.js";import{a as oe,c as se,i as ce,l as le,n as ue,o as de,r as fe,s as pe,u as me}from"./builtin-provider-Bv6TuIMf.js";import{i as he,n as ge,r as _e}from"./provider-registry-Kh5nNG84.js";import{i as ve,t as ye}from"./host-CQ2BhNzZ.js";import{a as be,i as xe,l as Se,n as Ce,o as we,r as Te,s as Ee,t as De}from"./session-store-Ddm_lIaP.js";import{_ as Oe,a as ke,c as Ae,d as je,f as Me,g as Ne,h as Pe,i as Fe,l as Ie,m as Le,n as Re,o as ze,p as Be,s as Ve,t as He,u as Ue,v as We,y as Ge}from"./config-BRWO3tCu.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Ke,formatTaskForDisplay as qe,isHitlExpired as Je,isHitlTool as Ye,validateUiToolResult as Xe}from"@gencode/shared";import W,{readFile as Ze}from"node:fs/promises";import G,{join as Qe}from"node:path";import{createHash as $e,randomBytes as et,randomUUID as tt}from"node:crypto";import nt from"node:os";import{spawn as rt}from"node:child_process";import{TextDecoder as it}from"node:util";import at from"gray-matter";import{Agent as ot}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as st}from"node:async_hooks";import K from"node:fs";import ct from"log4js";import lt from"openai";import{Type as q,calculateCost as ut,clampThinkingLevel as dt,createAssistantMessageEventStream as ft,getEnvApiKey as pt,parseStreamingJson as mt,registerApiProvider as ht,registerBuiltInApiProviders as gt,streamSimple as _t}from"@earendil-works/pi-ai";import{fileURLToPath as vt}from"node:url";import{isBinaryFile as yt}from"isbinaryfile";import bt from"ajv";import{createJiti as xt}from"jiti";var St=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 Ct(e,t,n,r,i){let a=await U(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await 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 wt=`clarify plan and acceptance`,Tt=`补齐后续 task list、每个 task 的验收项和当前下一步`,Et={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},Dt=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function Ot(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function kt(e,t){let n=Ot(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function At(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 jt(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(Et))kt(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?At(t.steps):[],acceptance:t.acceptance?At(t.acceptance):[],raw:e.trim()}}function Mt(e){let t=e.toLowerCase();return Dt.some(e=>t.includes(e.toLowerCase()))}function Nt(e){return e.some(Mt)}function Pt(e,t){return{id:e,text:t,required:!0}}function Ft(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 It(e){return Ft({id:`task-1`,kind:`clarify`,title:wt,status:`doing`,acceptanceCriteria:[Pt(`ac-1`,Tt)],updatedAt:e})}function Lt(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>Pt(`ac-${t+1}`,e)):[Pt(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>Ft({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[Pt(`ac-1`,`完成:${e}`)],updatedAt:n}))}function Rt(e){let t=new Date().toISOString(),n=jt(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:Lt(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&Nt(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:Lt([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&Nt(At(n.raw))){let e=At(n.raw).filter(Mt);return{interpretation:r,assumptions:i,openQuestions:a,tasks:Lt([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[It(t)]}}function zt(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function Bt(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>zt(n.has(e.id),e)),``].join(`
|
|
2
|
+
`)}function Vt(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[Bt(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 Ht=process.platform===`win32`;function Ut(e){return Ht?{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 Wt(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(Ht&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{rt(`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 Gt=2e5;function Kt(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function qt(e,t){let n=e+t;return n.length<=Gt?{text:n,truncated:!1}:{text:n.slice(-Gt),truncated:!0}}function Jt(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=qt(e.output,r);e.output=i.text;let a=qt(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Yt(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:Kt(e.output),stdoutTail:Kt(e.stdout),stderrTail:Kt(e.stderr),outputTruncated:e.outputTruncated}}function Xt(e,t){return t?e.scopeKey===t:!0}function Zt(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Qt(e){return e?e.split(/\r?\n/):[]}function $t(e){let t=Qt(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Zt(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 en(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function tn(){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),en(e))};return{start(t){let{file:n,args:r,shell:a}=Ut(t.command),o=rt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!Ht}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:tt(),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=>Jt(l,`stdout`,e)),o.stderr.on(`data`,e=>Jt(l,`stderr`,e));let u=e=>t=>{Jt(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=Zt(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Jt(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Wt(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Wt(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Jt(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`)})}),Yt(l)},get(e,t){let n=r(e);return!n||!Xt(n,t)?null:Yt(n)},list(n){return[...e.values(),...t.values()].filter(e=>Xt(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Yt(e))},async wait(e,t,n){let i=r(e);if(!i||!Xt(i,t))return null;if(i.status!==`running`)return Yt(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||!Xt(a,t)?null:Yt(a)},readLog(e){let t=r(e.sessionId);return!t||!Xt(t,e.scopeKey)?null:$t({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Xt(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||!Xt(n,t))return null;if(n.status!==`running`)return Yt(n);n.status=`killed`,Wt(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Wt(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?Yt(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Wt(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Wt(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const nn=1;var rn=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},an=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},on=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 sn=new Map;function cn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function ln(e,t,n,r){let i=cn(e,t,n),a=sn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});sn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function un(e,t,n){return G.join(H(e,t,n),`state.json`)}function dn(e,t,n){return G.join(H(e,t,n),`plan.md`)}function fn(e,t,n){return G.join(H(e,t,n),`artifacts`)}async function pn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${et(4).toString(`hex`)}.tmp`;try{await W.writeFile(n,t,`utf-8`),await W.rename(n,e)}finally{await W.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function mn(e){if(e.version!==1)throw new rn(e.version)}function hn(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 gn(e,t,n){let r=un(e,t,n);try{let e=await W.readFile(r,`utf-8`);try{let t=JSON.parse(e);return mn(t),t}catch(t){throw t instanceof rn?t:new on(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof on||e instanceof rn?e:new on(`corrupt_goal_workflow_state`,{cause:e})}}async function _n(e,t,n){let r=un(e,t,n),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return mn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof rn)throw e}let a=await U(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await z(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await W.writeFile(s,i,`utf-8`),c=s}catch{}return await xn(e,t,{goalId:a.goalId,objective:o},n),await J(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 vn(e,t,n){let r=await gn(e,t,n);return r?hn(r):null}async function yn(e,t,n){let r=await gn(e,t,n);return r?{goalState:hn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function bn(e,t,n){let r=un(e,t,n),i=dn(e,t,n),a=fn(e,t,n);await Promise.all([W.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),W.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),W.rm(a,{recursive:!0,force:!0})])}async function xn(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await bn(e,t,r);let a=Rt(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=H(e,t,r);await W.mkdir(l,{recursive:!0}),await pn(un(e,t,r),JSON.stringify(c,null,2));let u=Vt(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await pn(dn(e,t,r),u),c}const Sn=1048576,Cn=/KEY|TOKEN|SECRET|PASSWORD|COOKIE|AUTH/i,wn=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g],Tn=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.pdf`]);function En(e,t,n){return G.join(fn(e,t,n),`registry.jsonl`)}function Dn(e,t,n){return G.join(fn(e,t,n),`notes`)}function On(e,t,n){return G.join(fn(e,t,n),`commands`)}function kn(e,t,n){return G.join(fn(e,t,n),`snapshots`)}function An(e,t,n){return G.join(H(e,t,n),`plan-meta.json`)}function jn(e){let t=e,n=!1;for(let e of wn)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function Mn(e){return`sha256:${$e(`sha256`).update(e).digest(`hex`)}`}async function Nn(e){return Mn(await W.readFile(e))}function Pn(e,t){let n=G.normalize(e);return t.some(e=>{let t=G.normalize(e);return n===t||n.startsWith(t+G.sep)})}function Fn(e){let t=[G.normalize(e.workspaceDir),G.normalize(nt.tmpdir())],n=e.projectDir?.trim();n&&t.push(G.normalize(n));let r=G.join(e.dataDir,`workspace`);return t.includes(G.normalize(r))||t.push(G.normalize(r)),t}function In(e,t){return t?.trim()?G.isAbsolute(t)?G.normalize(t):G.normalize(G.join(e,t)):e}function Ln(e,t){return e.byteLength<=t?{data:e,truncated:!1,originalBytes:e.byteLength}:{data:e.subarray(0,t),truncated:!0,originalBytes:e.byteLength}}function Rn(e){return`${e}-${Date.now().toString(36)}-${et(3).toString(`hex`)}`}async function zn(e,t,n,r){let i=await Bn(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${Rn(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function Bn(e,t,n){let r=En(e,t,n);try{let e=await W.readFile(r,`utf-8`),t=[],n=e.split(/\r?\n/).map((e,t)=>({line:e,index:t})).filter(e=>e.line.trim().length>0);for(let[e,r]of n.entries())try{t.push(JSON.parse(r.line))}catch{if(e===n.length-1)continue;throw new an(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Vn(e,t,n,r){let i=En(e,t,r);await W.mkdir(G.dirname(i),{recursive:!0}),await W.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Hn(e,t,n,r){let i=[...new Set(n.filter(e=>e.trim().length>0))];if(i.length===0)return{valid:!1,errors:[{ref:``,code:`unregistered_evidence_ref`,message:`no evidence refs provided`}]};let a=await Bn(e,t,r),o=new Map(a.map(e=>[e.id,e])),s=[],c=Un(e,t,r);for(let e of i){let t=o.get(e);if(!t){s.push({ref:e,code:`unregistered_evidence_ref`,message:`evidence ref not registered: ${e}`});continue}if(t.kind===`command`){let n=t.stdoutRef?G.join(c,t.stdoutRef):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`stdout artifact missing for ${e}`});continue}try{let r=await W.readFile(n);if(t.hash&&Mn(r)!==t.hash){s.push({ref:e,code:`artifact_integrity_mismatch`,message:`stdout hash mismatch for ${e}`});continue}}catch{s.push({ref:e,code:`missing_artifact_file`,message:`stdout artifact missing for ${e}`});continue}r?.requireCommandSuccess!==!1&&t.exitCode!==0&&s.push({ref:e,code:`command_exit_nonzero`,message:`command evidence exit code ${t.exitCode}`});continue}if(t.kind===`snapshot`){let n=t.snapshotPath?G.join(c,t.snapshotPath):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`snapshot path missing for ${e}`});continue}try{let r=await W.stat(n);if(t.sizeBytes!==void 0&&r.size!==t.sizeBytes){s.push({ref:e,code:`artifact_integrity_mismatch`,message:`snapshot size mismatch for ${e}`});continue}t.hash&&await Nn(n)!==t.hash&&s.push({ref:e,code:`artifact_integrity_mismatch`,message:`snapshot hash mismatch for ${e}`})}catch{s.push({ref:e,code:`missing_artifact_file`,message:`snapshot artifact missing for ${e}`})}continue}let n=t.notePath?G.join(c,t.notePath):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`note path missing for ${e}`});continue}try{let r=await W.stat(n);t.contentBytes!==void 0&&r.size!==t.contentBytes&&s.push({ref:e,code:`artifact_integrity_mismatch`,message:`note size mismatch for ${e}`})}catch{s.push({ref:e,code:`missing_artifact_file`,message:`note artifact missing for ${e}`})}}return{valid:s.length===0,errors:s}}function Un(e,t,n){return G.dirname(H(e,t,n))}async function Wn(e,t,n,r){mn(n),await pn(un(e,t,r),JSON.stringify(n,null,2))}async function Gn(e,t,n){let r=An(e,t,n);try{let e=await W.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function Kn(e,t,n,r){await pn(An(e,t,r),JSON.stringify(n,null,2))}async function qn(e,t,n,r){let i=await Gn(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 Kn(e,t,a,r),a}async function Jn(e,t,n,r){try{let i=Vt(n,await Gn(e,t,r));return await pn(dn(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 J(e,t,n,r){let{type:i,...a}=n,o={timestamp:new Date().toISOString(),sessionId:t,goalId:n.goalId??null,action:i,detail:a},s=R(e,t,r);await W.mkdir(G.dirname(s),{recursive:!0}),await W.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}function Yn(e){let t=e.map(e=>Number.parseInt(e.id.replace(/^task-/,``),10)).filter(e=>Number.isFinite(e));return`task-${(t.length>0?Math.max(...t):0)+1}`}function Xn(e,t=[]){let n=t.map(e=>Number.parseInt(e.id.replace(/^ac-/,``),10)).filter(e=>Number.isFinite(e)),r=n.length>0?Math.max(...n):0,i=[];for(let t=0;t<e;t+=1)r+=1,i.push(`ac-${r}`);return i}async function Zn(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 zn(e,t,n.kind,r),a=i.split(`:`)[1]??Rn(n.kind),o=Dn(e,t,r);await W.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=G.join(Dn(e,t,r),`${a}.md`),l=jn(n.content);await W.writeFile(c,l.text,`utf-8`);let u={id:i,kind:n.kind,summary:n.summary,source:n.source??`model`,createdAt:new Date().toISOString(),notePath:s,contentBytes:Buffer.byteLength(l.text,`utf-8`),redactionIncomplete:l.redactionIncomplete};try{await Vn(e,t,u,r)}catch{return await W.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}async function Qn(e,t,n,r){let i=In(n.workspaceDir,n.cwd);if(!Pn(i,n.allowedRoots))return{error:`cwd_outside_allowed_roots`};let a=Math.min(Math.max(n.timeoutMs??12e4,1),6e5),o=Math.ceil(a/1e3),s=tn(),c=s.start({command:n.command,cwd:i,baseEnv:n.baseEnv,timeoutSec:o,scopeKey:n.workspaceDir}),l=await s.wait(c.sessionId,n.workspaceDir)??c,u=s.readOutput(l.sessionId,n.workspaceDir),d=Buffer.from(u?.stdout??l.stdoutTail,`utf-8`),f=Buffer.from(u?.stderr??l.stderrTail,`utf-8`),p=Ln(d,Sn),m=Ln(f,Sn),h=jn(p.data.toString(`utf-8`)),g=jn(m.data.toString(`utf-8`)),_=h.redactionIncomplete||g.redactionIncomplete,v=await zn(e,t,`command`,r),y=v.split(`:`)[1]??Rn(`command`),b=On(e,t,r);await W.mkdir(b,{recursive:!0});let x=`goal/artifacts/commands/${y}.out.txt`,S=`goal/artifacts/commands/${y}.err.txt`,C=G.join(b,`${y}.out.txt`),w=G.join(b,`${y}.err.txt`);await W.writeFile(C,h.text,`utf-8`),await W.writeFile(w,g.text,`utf-8`);let T=Object.keys({...process.env,...n.baseEnv}).filter(e=>Cn.test(e)),E={id:v,kind:`command`,command:jn(n.command).text,cwd:i,exitCode:l.exitCode??1,stdoutRef:x,stderrRef:S,stdoutTruncated:p.truncated,stderrTruncated:m.truncated,stdoutBytes:p.originalBytes,stderrBytes:m.originalBytes,timeoutMs:a,envKeys:T,redactionIncomplete:_,hash:Mn(h.text),createdAt:new Date().toISOString()};try{await Vn(e,t,E,r)}catch{return await Promise.all([W.unlink(C).catch(()=>{}),W.unlink(w).catch(()=>{})]),{error:`registry_write_failed`}}return{evidenceRef:v,exitCode:l.exitCode??1}}function $n(e,t){let n=G.normalize(e),r=n.split(G.sep).filter(Boolean);if(r.includes(`.aimax`)||r.includes(`.ssh`)||r.includes(`.gnupg`))return!0;let i=G.normalize(t);return n.startsWith(G.join(i,`.aimax`)+G.sep)||n===G.join(i,`.aimax`)}async function er(e,t,n,r){let i=G.isAbsolute(n.path)?G.normalize(n.path):G.normalize(G.join(n.workspaceDir,n.path));if(!Pn(i,n.allowedRoots))return{error:`snapshot_path_outside_allowed_roots`};if($n(i,e))return{error:`snapshot_sensitive_path_not_allowed`};let a;try{a=await W.stat(i)}catch{return{error:`snapshot_file_not_found`}}if(!a.isFile())return{error:`snapshot_not_a_file`};if(a.size>5242880)return{error:`snapshot_too_large`};let o=G.extname(i).toLowerCase(),s=o.length>0&&Tn.has(o),c;try{c=await W.readFile(i)}catch{return{error:`snapshot_read_failed`}}if(!s){let e=jn(c.toString(`utf-8`));c=Buffer.from(e.text,`utf-8`)}else if(!Tn.has(o))return{error:`snapshot_binary_type_not_allowed`};let l=await zn(e,t,`snapshot`,r),u=l.split(`:`)[1]??Rn(`snapshot`),d=kn(e,t,r);await W.mkdir(d,{recursive:!0});let f=`${u}${o||G.extname(i)}`,p=`goal/artifacts/snapshots/${f}`,m=G.join(d,f);await W.writeFile(m,c);let h={id:l,kind:`snapshot`,summary:n.summary,path:i,hash:Mn(c),sizeBytes:c.byteLength,snapshotPath:p,createdAt:new Date().toISOString()};try{await Vn(e,t,h,r)}catch{return await W.unlink(m).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:l}}function tr(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function nr(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${tr(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${tr(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${tr(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}: ${tr(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${tr(n)}`)}return t}function rr(e){let t=[`- Treat goal/state.json as the only task workflow machine state; use goal/plan.md for human-readable context.`,`- Work on the current task only unless you call goal_add_task.`,`- Do not claim task completion in prose; use goal_task_done with evidence refs.`,`- Use only evidenceRef values returned by goal_record_evidence when filling evidenceRefs, acceptanceEvidence, or finalEvidenceRefs.`,`- Natural-language descriptions and file paths are not evidence refs; strings like "goal/state.json ..." must first be registered with a goal_record_* tool.`,`- In goal workflow, use goal_record_evidence(kind="exec") instead of exec for bounded command execution; it records command evidence, while exec output is not registered in the goal evidence registry.`,`- If blocked, use goal_task_blocked with a clear reason and needed input.`,`- Finish the goal with goal_complete (final evidence refs); do NOT call update_goal(status="complete").`,`- Use goal_plan_update for plan interpretation, assumptions, or open questions.`,`- Use the current worktree, files, command output, and test results as authoritative evidence.`,`- Do not rely solely on conversation memory to assess completion.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress on the current task.`,`- Do not inform the user about this continuation context; treat it as internal steering.`];return(e.currentTaskKind===`clarify`||e.currentTaskTitle===wt)&&t.unshift(`- Current task is "${wt}": explore, clarify, and refine the plan and acceptance criteria.`,`- Do NOT implement deliverables yet; use goal tools to add tasks and criteria before execution work.`),t}function ir(){return[`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- Do not call update_goal(status="complete"); V2-lite completion requires goal_complete with evidence refs after workflow initialization.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`]}const ar=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function or(e,t,n){return sr(e,t,n,{introLine:ar})}function sr(e,t,n,r){let i=tr(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>`,...nr(n),`</workflow>`,``,`Rules:`,...rr(n)):l.push(`Rules:`,...ir()),l.push(``,`</goal_context>`),l.join(`
|
|
5
|
+
`)}function cr(e,t){let n=tr(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed);return[`<goal_context>`,``,`The token budget for the current thread goal has been exhausted.`,`The goal status has been set to "budget_limited" automatically.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Instructions:`,`- Wrap up the current turn soon. Do not start new substantive work.`,`- Summarize progress made, any blockers, and what would be needed next.`,`- Do NOT call update_goal(complete) unless the objective is truly achieved.`,`- The user can increase the budget or resume the goal later via the CLI.`,``,`</goal_context>`].join(`
|
|
6
|
+
`)}function lr(e,t){let n=tr(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The thread goal objective has been edited by the user.`,`The following objective supersedes any previous thread goal objective.`,`Adjust your work direction accordingly.`,``,`<untrusted_objective>`,n,`</untrusted_objective>`,``,`Token budget: ${r}`,`Tokens remaining: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Do not call update_goal(status="complete"); V2-lite completion must use goal_complete with evidence refs after workflow initialization.`,``,`</goal_context>`].join(`
|
|
7
|
+
`)}function ur(e){return{role:`user`,content:e}}function dr(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const fr=`AIMAX_GOAL_CONTINUATION`;var pr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function mr(e,t,n){let r=await gn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await Gn(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 hr(){let e=process.env[fr];return e===void 0||e===``||e!==`0`}async function gr(e,t,n,r){if(!hr()||n.continuationCount>=Ke)return!1;let i=await U(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-Ddm_lIaP.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function _r(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function vr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await gr(n,r,a,{storeName:i}))return!1;let u=await U(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await z(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await mr(n,r,{storeName:i}),h=ur(p?cr(u,f):sr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=_r(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=Ke){let e=await U(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-DKeFVjM4.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-DvF1LRBK.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${Ke}), goal paused`)}}return!0}async function yr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function br(e,t,n){let r=await gn(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 Wn(e,t,c,{storeName:n?.storeName}),await J(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await Gn(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await qn(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await Jn(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function xr(e,t,n,r){let i=await U(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await mr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=ur(or(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 Sr(e,t,n,r){let i=await U(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=ur(lr(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 Cr(e,t,n){(await U(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await V(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const wr=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Tr(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===wt}function Er(e){return wr.has(e)}function Dr(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use goal_record_evidence(kind='exec') for bounded command execution that should be recorded as workflow evidence.`,`Use goal_plan_update, goal_add_task, goal_task_done, or goal_repair_workflow_state to refine or recover the plan.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use goal workflow tools such as goal_plan_update, goal_add_task, goal_task_done, goal_record_evidence, or goal_repair_workflow_state to refine, record evidence, or recover before executing deliverables directly.`].join(` `)}function Or(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())&&Er(n.toolName))return{block:!0,blockReason:Dr(n.toolName)}}}),()=>{t=!1}}function kr(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 Ar(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(Rr(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}zr(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 jr(e,t={}){let n=Ir(t.limit,`limit`),r=Lr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!zr(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Fr(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Mr(e,t){let n=Lr(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 Nr(e,t=80){let n=Lr(e,`totalEntryCount`),r=Lr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Pr(e,t){return e.slice(t.startIndex,t.endIndex)}function Fr(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Ir(e,t){return e===void 0?1/0:Lr(e,t)}function Lr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function Rr(e){return e.role===`assistant`}function zr(e){return e.role===`tool_result`}const Br=24e3;async function Vr(e){return Yr({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Hr(e){return Yr({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Ur(e){return Yr({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Wr(e){let t=ri(e),n=await Kr(e),r=await $r(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:qr(e.dataDir,e.sessionId,e.sessionOptions)}}function Gr(e){return{maxEntries:ii(e?.maxEntries??80,`limits.maxEntries`),maxBytes:ii(e?.maxBytes??Br,`limits.maxBytes`)}}async function Kr(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Xr(await Zr(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 Qr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function qr(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function Jr(e,t,n){let r=ai(e.startIndex,`startIndex`),i=ai(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 Yr(e){let t=ri(e.params),n=Jr(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=ei(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:qr(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Xr(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 Zr(e,t,n){let[r,i]=await Promise.all([F(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)ci(e)&&e.toolResultRef?.sessionId===t&&a.set(li(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(li(e),e);return Array.from(a.values())}async function Qr(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(G.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=G.resolve(e.dataDir,e.reference.storagePath);if(!si(G.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!si(G.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([oi(t),oi(n),oi(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 $r(e,t){let n=await W.stat(e),r=await W.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:ni(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function ei(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=ti(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 ti(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:ni(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function ni(e){let t=new it(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function ri(e){return Gr(e.limits)}function ii(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function ai(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function oi(e){try{return await W.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${ui(e)}`)}}function si(e,t){let n=G.relative(e,t);return n===``||!n.startsWith(`..`)&&!G.isAbsolute(n)}function ci(e){return e.role===`tool_result`}function li(e){return`${e.toolCallId}\n${e.storagePath}`}function ui(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function di(e){return G.join(e,`.aimax`,`auto-skills`)}function fi(e){return G.join(e,`categories.json`)}function pi(e){return G.join(e,`.auto_skills_prompt_snapshot.json`)}const mi=/^[a-z0-9][a-z0-9-]*$/,hi=/^[a-z0-9][a-z0-9-]*$/;function gi(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||G.win32.isAbsolute(t)||G.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!mi.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function _i(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(`.`)||!hi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function vi(e,t){return`auto:${gi(e)}/${_i(t)}`}function yi(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=gi(n.slice(0,r)),a=_i(n.slice(r+1));return{skillId:vi(i,a),categoryPath:i,skillName:a}}function bi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function xi(e,t,n){let r=G.resolve(e),i=G.resolve(r,...gi(t).split(`/`),_i(n));return Ci(r,i),i}function Si(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||G.win32.isAbsolute(n)||G.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=G.resolve(e),a=G.resolve(i,...r);return Ci(i,a),a}function Ci(e,t){let n=G.resolve(e),r=G.resolve(t),i=G.relative(n,r);if(i.startsWith(`..`)||G.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function wi(e){let t=fi(e),n;try{n=await W.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=gi(e),r=Ei(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 Ti(e){return new Map(e.map(e=>[e.path,e]))}function Ei(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 Di=32*1024,Oi=new Map;function ki(e){return new ji(e)}async function Ai(e){let t=G.resolve(e);for(let e of Array.from(Oi.keys()))e.startsWith(`${t}|`)&&Oi.delete(e);await W.rm(pi(t),{force:!0}).catch(()=>{})}var ji=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=G.resolve(e.rootDir??di(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Ni(Ti((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?gi(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Pi(e.categoryPath,t)).map(Mi)}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:Fi(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})=>({...Mi(e),score:t}))}async autoSkillView(e){let t=yi(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=Si(n.skillDir,e.filePath),r=await Wi(t,this.maxResourceBytes);return{...Mi(n),status:n.status,content:r,path:qi(G.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:qi(G.relative(n.skillDir,t))}}let r=await Wi(n.skillFile,this.maxSkillBytes);return{...Mi(n),status:n.status,content:r,path:qi(G.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await Ii(this.rootDir),i=Oi.get(n);if(!e&&i&&Vi(i.manifest,r))return i;let a=e?void 0:await zi(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return Oi.set(n,e),e}let o=await wi(this.rootDir),s=Ti(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return Oi.set(n,c),await Bi(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 Xi({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Di})}async loadEntry(e){try{let t=G.dirname(e),n=_i(G.basename(t)),r=qi(G.relative(this.rootDir,t)),i=gi(G.posix.dirname(r)),a=vi(i,n),o=G.join(t,`metadata.json`),s=await Hi(o);if(s?.skillId&&yi(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&gi(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=bi(s?.status);return{skillId:a,name:n,description:Gi(await Ui(e,Di)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:Ki(s?.tags),relatedSkills:Ki(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}: ${Ji(t)}\n`);return}}};function Mi(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Ni(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Pi(e,t){return t?e===t:!0}function Fi(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 Ii(e){let t;try{t=await W.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await Ri(G.join(e,`categories.json`),`categories`,n),await Li(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Li(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=G.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await Ri(t,`skill`,n),await Ri(G.join(e,`metadata.json`),`metadata`,n),await Ri(G.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await W.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Li(t,i,n)}}async function Ri(e,t,n){try{let r=await W.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function zi(e,t,n){let r;try{r=await W.readFile(pi(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)||!Vi(e.manifest,n)?void 0:e}catch{return}}async function Bi(e,t){if(!await Yi(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await W.writeFile(pi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function Vi(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 Hi(e){try{let t=await W.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Ui(e,t){let n=await W.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function Wi(e,t){if((await W.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return W.readFile(e,`utf-8`)}function Gi(e){let t=at(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 Ki(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function qi(e){return e.split(G.sep).join(`/`)}function Ji(e){return e instanceof Error?e.message:String(e)}async function Yi(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Xi(e){return $e(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Zi(e){return e??`openai-completions`}function Qi(e,t,n){let r={"Client-Code":`AIMax`,"X-Session-Id":e};return t&&(r[`X-Message-Id`]=t),n&&(r[`X-Channel`]=n),r}function $i(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}const ea={apiFormat:`anthropic-messages`,createModel:ta,buildRequest:ra,normalizeResponse:ia};function ta(e,t,n,r){return{id:e.model,name:e.model,api:`anthropic-messages`,provider:`anthropic`,baseUrl:na(e.baseUrl),reasoning:!1,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:Qi(t,n,r)}}function na(e){return e.replace(/\/+$/,``).replace(/\/v1$/,``)}function ra(e,t,n,r){let i=e.baseUrl.replace(/\/+$/,``),a=[],o=[];for(let e of n){if(e.role===`system`){e.content.trim()&&o.push(e.content);continue}a.push({role:e.role,content:e.content})}let s={model:t,messages:a.length>0?a:[{role:`user`,content:``}],max_tokens:r.maxTokens??2048,stream:!1};return o.length>0&&(s.system=o.join(`
|
|
9
|
+
|
|
10
|
+
`)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function ia(e){let t=e,n=t.content?.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)??``,r=(t.usage?.input_tokens??0)+(t.usage?.cache_read_input_tokens??0)+(t.usage?.cache_creation_input_tokens??0),i=t.usage?.output_tokens??0;return{text:n,usage:{input:r,output:i,total:r+i},raw:e}}const aa={apiFormat:`openai-completions`,createModel:oa,buildRequest:sa,normalizeResponse:ca};function oa(e,t,n,r){let i=e.baseUrl.includes(`deepseek.com`),a=e.thinking;return{id:e.model,name:e.model,api:`openai-completions`,provider:i?`deepseek`:`openai`,baseUrl:e.baseUrl,reasoning:i||!!a,...i&&{thinkingLevelMap:{high:`high`,xhigh:`max`}},...a&&!i&&{thinkingLevelMap:{high:`high`,xhigh:`high`}},input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:Qi(t,n,r),compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!!(a&&!i),supportsUsageInStreaming:!0,...a&&!i&&{thinkingFormat:`deepseek`}}}}function sa(e,t,n,r){let i={model:t,messages:n,stream:!1};return typeof r.temperature==`number`&&(i.temperature=r.temperature),typeof r.maxTokens==`number`&&(i.max_tokens=r.maxTokens),{url:`${e.baseUrl.replace(/\/+$/,``)}/chat/completions`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:i}}function ca(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:$i(t.usage),raw:e}}const la={"openai-completions":aa,"anthropic-messages":ea};function ua(e){return la[e]}function da(e,t,n,r){return ua(Zi(e.apiFormat)).createModel(e,t,n,r)}const fa=`/aimax/agents`,pa=/^[a-z]+(?:-[a-z]+)*$/;function ma(e){let t=[{dir:e.systemAgentsDir??fa,source:`system`},{dir:G.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:G.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function ha(e){let t=new Map;for(let n of ma(e)){let e=await ya(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function ga(e={}){let t=e.allAgents??e.availableAgents??[],n=Ca(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>xa(n,e),findAny:e=>xa(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function _a(e){return!!(e&&typeof e==`object`&&Array.isArray(e.allAgents)&&Array.isArray(e.availableAgents)&&typeof e.findPublic==`function`&&typeof e.findAny==`function`&&typeof e.stats==`function`)}async function va(e){return _a(e.agentPolicy)?e.agentPolicy:ga({allAgents:await ha(e)})}async function ya(e,t){let n;try{n=await W.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=G.join(e,i.name),a=ba(await W.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function ba(e,t){let n=at(e),r=Oa(n.data.name)?.trim(),i=Oa(n.data.description)?.trim();if(!r||!pa.test(r)||!i)return;let a=Oa(n.data.model)?.trim(),o=Oa(n.data.initPrompt)?.trim()??Oa(n.data.initialPrompt)?.trim(),s=ka(n.data.maxTurns),c=Aa(n.data.tools),l=Aa(n.data.disallowedTools),u=Aa(n.data.skills),d=ja(n.data.visibility);if(!(n.data.visibility!==void 0&&!d))return{name:r,description:i,visibility:d??`public`,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function xa(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Sa(e)===`public`))}function Sa(e){return e.visibility??`public`}function Ca(e){return e.filter(e=>Sa(e)===`public`)}function wa(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Ta(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ma)):void 0,r=new Set((t.disallowedTools??[]).map(Ma));return e.filter(e=>{let t=typeof e.name==`string`?Ma(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Ea(e){let t=Ca(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name exactly matches one of the listed custom agents, that mention is an explicit delegation request.","For such a matching `@<agent-name>` request, you MUST call `subagent_spawn` to run the request through that custom agent, with the `agent` field set to the exact matched agent name.","Do not answer the request yourself, do not merely describe the agent, and do not omit the tool call when a matching `@<agent-name>` is present.",`If the mention does not exactly match a listed custom agent, do not invent a match; continue with the current agent or ask a concise clarification if needed.`,t.map(e=>`- ${e.name}: ${e.description}`).join(`
|
|
11
11
|
`),``].join(`
|
|
12
|
-
`)}function
|
|
13
|
-
`)}async function uo(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function fo(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function po(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function mo(e,t){return e instanceof ao?e:ho(e)?t?new ao({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new ao({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function ho(e){return e instanceof Error&&e.name===`AbortError`}function go(e){return e===408||e===409||e===425||e===429||e>=500}var _o=class extends Error{isHitlPause=!0;constructor(e,t,n,r=!1){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.transparentPause=r,this.name=`HitlPauseSignal`}};function vo(e){return!!(e instanceof _o||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var yo=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function bo(e){return!!(e instanceof yo||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const xo=new ct;function So(){return{}}async function Co(e,t){return await xo.run(e,t)}function wo(e){let t=xo.getStore();!t||t.signal||(t.signal=e)}const To=new ct;function Eo(){return{}}async function Do(e,t){return await To.run(e,t)}function Oo(e){let t=To.getStore();!t||t.signal||(t.signal=e)}function ko(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function Ao(e,t,n){return{temperature:t?.temperature,maxTokens:t?.maxTokens,signal:t?.signal,apiKey:n||t?.apiKey,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata}}function jo(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function Mo(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:jo(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:jo(e.content,`(tool image omitted: model does not support images)`)}:e)}function No(e,t,n){let r=new Map,i=Mo(e,t).map(e=>{if(e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return e.redacted?a?e:[]:a&&e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:a?e:{type:`text`,text:e.thinking};if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}};for(let e=0;e<i.length;e+=1){let t=i[e];if(t.role===`assistant`){c();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):(t.role===`user`&&c(),a.push(t))}return c(),a}function Po(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Fo(e){if(!Po(e))return null;let t=e,n=Io(t.message),r=Ro(n?.code)??Ro(t.code),i=Ro(n?.type)??Ro(t.type),a=Ro(n?.message)??Lo(t.error)??Ro(t.message)??`Unknown upstream error`;return{message:zo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Bo(r,i),raw:e}}function Io(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function Lo(e){if(!(!e||typeof e!=`object`))return Ro(e.message)}function Ro(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function zo(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Bo(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}function Vo(e,t=`error`){let n={};Ho(n,t,e);let r=qo(e);return r!==void 0&&Ho(n,`${t}Cause`,r),n}function Ho(e,t,n){e[`${t}Type`]=Uo(n),e[`${t}Name`]=Go(n,`name`),e[`${t}Message`]=Wo(n),e[`${t}Code`]=Ko(n,`code`),e[`${t}Status`]=Ko(n,`status`),e[`${t}StatusCode`]=Ko(n,`statusCode`)}function Uo(e){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let t=e.constructor?.name;return typeof t==`string`&&t.length>0?t:void 0}function Wo(e){if(e instanceof Error)return Jo(e.message);if(typeof e==`string`)return Jo(e);let t=Go(e,`message`);return t?Jo(t):void 0}function Go(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ko(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0||typeof n==`number`&&Number.isFinite(n)?n:void 0}function qo(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function Jo(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const Yo=(e,t,n)=>{let r=pt();return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0},a=0,o=!1;try{let s=Qo(e,t,n?.apiKey||mt(e.provider)||``,n?.headers),c=$o(e,t,n);n?.onPayload?.(c);let l=await s.chat.completions.create(c,{signal:n?.signal});r.push({type:`start`,partial:i}),o=!0;let u=null,d=i.content,f=()=>d.length-1,p=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:f(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:f(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=ht(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:f(),toolCall:e,partial:i}))}};for await(let t of l){a+=1;let n=Fo(t);if(n)throw new ao({message:n.message,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},dt(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=is(o.finish_reason)),!o.delta))continue;o.delta.content!==null&&o.delta.content!==void 0&&o.delta.content.length>0&&((!u||u.type!==`text`)&&(p(u),u={type:`text`,text:``},i.content.push(u),r.push({type:`text_start`,contentIndex:f(),partial:i})),u.text+=o.delta.content,r.push({type:`text_delta`,contentIndex:f(),delta:o.delta.content,partial:i}));let s=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=o.delta[e];return t!=null&&t.length>0});if(s){(!u||u.type!==`thinking`)&&(p(u),u={type:`thinking`,thinking:``,thinkingSignature:s},i.content.push(u),r.push({type:`thinking_start`,contentIndex:f(),partial:i}));let e=o.delta[s];u.thinking+=e,r.push({type:`thinking_delta`,contentIndex:f(),delta:e,partial:i})}if(o.delta.tool_calls)for(let e of o.delta.tool_calls){(!u||u.type!==`toolCall`||e.id&&u.id!==e.id)&&(p(u),u={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(u),r.push({type:`toolcall_start`,contentIndex:f(),partial:i})),e.id&&(u.id=e.id),e.function?.name&&(u.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,u.partialArgs+=e.function.arguments,u.arguments=ht(u.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:i})}let c=o.delta.reasoning_details;if(c&&Array.isArray(c)){for(let e of c)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(p(u),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(t){J.warn(`openai completions stream failed`,{sessionId:n?.sessionId,modelId:e.id,provider:e.provider,api:e.api,chunkCount:a,streamStarted:o,signalAborted:!!n?.signal?.aborted,stopReason:i.stopReason,...Vo(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=t instanceof Error?t.message:JSON.stringify(t),t instanceof ao&&Object.assign(i,{errorCode:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable});let s=t?.error?.metadata?.raw;s&&(i.errorMessage+=`\n${s}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Xo=(e,t,n)=>{let r=n?.apiKey||mt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ao(e,n,r),a=n?.reasoning?ft(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return Yo(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function Zo(e,t,n){return $o(e,t,n)}function Qo(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};return r&&Object.assign(i,r),new ut({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function $o(e,t,n){let r=os(e),i=ns(e,t,r);ts(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=rs(t.tools,r):es(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning||r.thinkingFormat===`qwen`&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:r.thinkingFormat===`qwen-chat-template`&&e.reasoning?a.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0}:r.thinkingFormat===`deepseek`&&e.reasoning&&(a.thinking={type:n?.reasoningEffort?`enabled`:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function es(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function ts(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function ns(e,t,n){let r=[],i=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=No(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:ko(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:ko(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:ko(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>ko(e.text)).join(``):a.map(e=>({type:`text`,text:ko(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
12
|
+
`)}function Da(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Oa(e){return typeof e==`string`?e:void 0}function ka(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Aa(e){let t;if(typeof e==`string`)t=e.split(`,`);else if(Array.isArray(e))t=e.filter(e=>typeof e==`string`);else return;let n=t.map(e=>e.trim()).filter(Boolean);return n.length>0?n:void 0}function ja(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Ma(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}const Na=new st;async function Pa(e,t){return await Na.run(e,t)}function Fa(e){return{async emit(t){let n=Na.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const Ia={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`};var La=class{hooks=new Map;deprecatedWarned=new Set;register(e){let t=Ia[e.hookName];t&&!this.deprecatedWarned.has(e.hookName)&&(this.deprecatedWarned.add(e.hookName),console.warn(`[PluginHookRegistry] Hook "${e.hookName}" is deprecated. Use "${t}" instead. (plugin: ${e.pluginId})`));let n=this.hooks.get(e.hookName)??[];n.push(e),n.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,n)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await Pa({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};function Ra(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function za(e=new Date){let t=Ra(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Ba=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});const Va=new st;function Ha(e,t){return Va.run(e,t)}let Ua=null,Wa=[];function Ga(){return za()}function Ka(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function qa(e){return G.join(e,`.aimax`)}function Ja(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function Ya(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=Ja(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:G.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:G.join(qa(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:G.join(qa(e),`logs`,r)}}function Xa(e){return{appLogPath:G.join(e,`app.log`),errorLogPath:G.join(e,`errors.log`)}}function Za(e){let{appLogPath:t,errorLogPath:n}=Xa(e);ct.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Qa(e,t,n){return`[${Ga()}] [${e}] ${t}${Ka(n)}`}function $a(e,t,n){let r=Va.getStore();if(r){r({level:e,message:t,context:n,formatted:Qa(e,t,n)});return}try{process.stderr.write(`${Qa(e,t,n)}\n`)}catch{}}function eo(e,t,n){if(!Ua){Wa.push({level:e,message:t,context:n}),Wa.length>200&&(Wa=Wa.slice(-200)),$a(e,t,n);return}let r=Qa(e,t,n),i=ct.getLogger();e===Ba.ERROR?i.error(r):e===Ba.WARN?i.warn(r):i.info(r);let a=Va.getStore();a&&a({level:e,message:t,context:n,formatted:r})}function to(e,t){let{logDir:n,runLogId:r}=Ya(e,t);if(Ua?.dataDir===e&&Ua.runLogId===r&&Ua.logDir===n)return;K.mkdirSync(n,{recursive:!0}),Za(n),Ua={dataDir:e,logDir:n,runLogId:r};let i=Wa;Wa=[];for(let e of i)eo(e.level,e.message,e.context)}const Y={info:(e,t)=>eo(Ba.INFO,e,t),warn:(e,t)=>eo(Ba.WARN,e,t),error:(e,t)=>eo(Ba.ERROR,e,t)};function no(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}var ro=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){Y.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})}},io=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function ao(e){return{async chat(t){let n=so(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await lo(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:co(n),historyMessages:n},e.hookCtx);let i=ua(Zi(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=uo(t.signal,t.timeoutMs);try{let t;try{t=await fetch(a.url,{method:`POST`,headers:a.headers,body:JSON.stringify(a.body),signal:o})}catch(e){throw po(e,c())}if(!t.ok){let e=await fo(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new io({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:ho(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw oo(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await lo(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:l?[l]:[],durationMs:d,usage:u},e.hookCtx),{text:l,usage:u,raw:s}}finally{s()}}}}function oo(e,t){return mo(e)&&t?new io({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):mo(e)?new io({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new io({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function so(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function co(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
|
|
13
|
+
`)}async function lo(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function uo(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function fo(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function po(e,t){return e instanceof io?e:mo(e)?t?new io({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new io({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function mo(e){return e instanceof Error&&e.name===`AbortError`}function ho(e){return e===408||e===409||e===425||e===429||e>=500}const go=`<aimax_artifacts>`,_o=`</aimax_artifacts>`;function vo(e,t={}){let n=[];if(!e.includes(go))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf(go);if(e===-1)break;let o=r.indexOf(_o,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(...yo(s,{warnings:n,timestamp:i,workspaceDir:t.workspaceDir}))),r=[r.slice(0,e).trimEnd(),r.slice(o+18).trimStart()].filter(e=>e.length>0).join(`
|
|
14
|
+
`).trimEnd()}return{cleanedText:r,artifacts:a,warnings:n}}function yo(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=bo(t,{index:e,warnings:n,timestamp:r,workspaceDir:i});s&&o.push(s)}return o}function bo(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=So(t,a);return o?{kind:`file`,file:o,timestamp:i,label:xo(e.label,G.basename(o)||`File artifact`,n,r)}:(r.push(`Artifact at index ${n}: file path must be absolute, skipping`),null)}let s=typeof e.url==`string`?e.url.trim():``;if(!s)return r.push(`Artifact at index ${n}: kind=url but missing url, skipping`),null;let c=wo(s)??`URL artifact`;return Co(s)?{kind:`url`,url:s,timestamp:i,label:xo(e.label,c,n,r)}:(r.push(`Artifact at index ${n}: url is invalid, skipping`),null)}function xo(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 So(e,t){return G.isAbsolute(e)?G.normalize(e):t?.trim()?G.normalize(G.join(t,e)):null}function Co(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}function wo(e){try{return new URL(e).host||void 0}catch{return}}var To=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(_o);if(e===-1){let e=Eo(this.buffer,_o);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(go);if(e!==-1){t+=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e+17),this.suppressing=!0;continue}let n=Eo(this.buffer,go);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 Eo(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 Do(e){if(e.isError)return[];let t=(e.now??(()=>new Date))().toISOString(),n=Po(e.result),r=[];if(e.toolName===`write_file`){let i=Io(Go(n.details?.path),e.workspaceDir);return i&&r.push(zo(i,t,Ho(i))),Vo(r)}if(e.toolName===`edit_file`){let i=Ko(n.details?.occurrences),a=Io(Go(n.details?.path),e.workspaceDir);return a&&i!==0&&r.push(zo(a,t,Ho(a))),Vo(r)}if(e.toolName===`apply_patch`)return r.push(...Oo(n.details,e.workspaceDir,t)),Vo(r);if(e.toolName===`exec`||e.toolName===`bash`||e.toolName===`process`){if(Ro(n.details))return[];let i=Go(e.input?.command),a=Fo(Go(n.details?.cwd),e.workspaceDir);return r.push(...ko({command:i,output:n.content,cwd:a,workspaceDir:e.workspaceDir,timestamp:t})),r}let i=Lo(n.content);return i?[Bo(i,t,Uo(i))]:[]}function Oo(e,t,n){let r=e?.summary&&typeof e.summary==`object`?e.summary:void 0;return r?[...Wo(r.added),...Wo(r.modified)].flatMap(e=>{let r=Io(e,t);return r?[zo(r,n,Ho(r))]:[]}):[]}function ko(e){let t=[],n=e.cwd??e.workspaceDir,r=r=>{let i=Io(r,n);i&&t.push(zo(i,e.timestamp,Ho(i)))};if(e.command)for(let t of Ao(e.command))r(t);for(let t of No(e.output))r(t);let i=Lo(e.output);return i&&t.push(Bo(i,e.timestamp,Uo(i))),Vo(t)}function Ao(e){let t=jo(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 jo(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(...Mo(r))}return t.join(`
|
|
15
|
+
`)}function Mo(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(Jo(a.trim()))}return t}function Po(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 Fo(e,t){return e?.trim()?G.normalize(e):t}function Io(e,t){let n=qo(e?.trim()??``);return!n||n.startsWith(`-`)||n===`/dev/null`||n.startsWith(`/dev/`)||Yo(n)?null:G.isAbsolute(n)?G.normalize(n):t?.trim()?G.normalize(G.join(t,n)):null}function Lo(e){let t=e.trim();return!t||/\s/.test(t)?null:Xo(t)?new URL(t).toString():null}function Ro(e){let t=Go(e?.status);return t===`running`||t===`failed`||t===`killed`||t===`timeout`}function zo(e,t,n){return{kind:`file`,file:e,timestamp:t,label:n}}function Bo(e,t,n){return{kind:`url`,url:e,timestamp:t,label:n}}function Vo(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 Ho(e){return G.basename(e)||`File artifact`}function Uo(e){try{return new URL(e).host||`URL artifact`}catch{return`URL artifact`}}function Wo(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function Go(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function Ko(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function qo(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function Jo(e){return e.replace(/[),.;,。;)]+$/u,``)}function Yo(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)}function Xo(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}var Zo=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 Qo(e){return!!(e instanceof Zo||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var $o=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function es(e){return!!(e instanceof $o||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const ts=new st;function ns(){return{}}async function rs(e,t){return await ts.run(e,t)}function is(e){let t=ts.getStore();!t||t.signal||(t.signal=e)}const as=new st;function os(){return{}}async function ss(e,t){return await as.run(e,t)}function cs(e){let t=as.getStore();!t||t.signal||(t.signal=e)}function ls(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function us(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 ds(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 fs(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:ds(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:ds(e.content,`(tool image omitted: model does not support images)`)}:e)}function ps(e,t,n){let r=new Map,i=fs(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 ms(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function hs(e){if(!ms(e))return null;let t=e,n=gs(t.message),r=vs(n?.code)??vs(t.code),i=vs(n?.type)??vs(t.type),a=vs(n?.message)??_s(t.error)??vs(t.message)??`Unknown upstream error`;return{message:ys(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:bs(r,i),raw:e}}function gs(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 _s(e){if(!(!e||typeof e!=`object`))return vs(e.message)}function vs(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function ys(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function bs(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 xs(e,t=`error`){let n={};Ss(n,t,e);let r=Ds(e);return r!==void 0&&Ss(n,`${t}Cause`,r),n}function Ss(e,t,n){e[`${t}Type`]=Cs(n),e[`${t}Name`]=Ts(n,`name`),e[`${t}Message`]=ws(n),e[`${t}Code`]=Es(n,`code`),e[`${t}Status`]=Es(n,`status`),e[`${t}StatusCode`]=Es(n,`statusCode`)}function Cs(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 ws(e){if(e instanceof Error)return Os(e.message);if(typeof e==`string`)return Os(e);let t=Ts(e,`message`);return t?Os(t):void 0}function Ts(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 Es(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 Ds(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function Os(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const ks=(e,t,n)=>{let r=ft();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=Ms(e,t,n?.apiKey||pt(e.provider)||``,n?.headers),c=Ns(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=mt(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=hs(t);if(n)throw new io({message:n.message,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},ut(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=Rs(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=mt(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){Y.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,...xs(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=t instanceof Error?t.message:JSON.stringify(t),t instanceof io&&Object.assign(i,{errorCode:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable});let s=t?.error?.metadata?.raw;s&&(i.errorMessage+=`\n${s}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},As=(e,t,n)=>{let r=n?.apiKey||pt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=us(e,n,r),a=n?.reasoning?dt(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return ks(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function js(e,t,n){return Ns(e,t,n)}function Ms(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 lt({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Ns(e,t,n){let r=Bs(e),i=Is(e,t,r);Fs(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=Ls(t.tools,r):Ps(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 Ps(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function Fs(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function Is(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=ps(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:ls(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:ls(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:ls(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=>ls(e.text)).join(``):a.map(e=>({type:`text`,text:ls(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
14
16
|
|
|
15
17
|
`);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
|
|
16
18
|
`))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
17
|
-
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:
|
|
18
|
-
`):e.content;return
|
|
19
|
-
`)}const
|
|
20
|
-
`);async function
|
|
21
|
-
`):n.content;r=`Tool(${n.toolName})[${e}]: ${
|
|
22
|
-
`)}function
|
|
23
|
-
`)}function
|
|
24
|
-
`);const
|
|
25
|
-
`),
|
|
26
|
-
`);async function
|
|
19
|
+
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:ls(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 Ls(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Rs(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 zs(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 Bs(e){let t=zs(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}const Vs=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Hs=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),Us=[`llmrequesterror`];function Ws(e){let t=Js(e?.maxAttempts,3),n=Ys(e?.initialDelayMs,250),r=Ys(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Gs(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Ks(e,t){if(!(e<=0)){if(t?.aborted)throw Error(`aborted`);await new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`aborted`))},{once:!0})})}}function qs(e){if(Qs(e))return!1;let t=Xs(e),n=Zs(e);if(t?.statusCode!==void 0)return ec(t.statusCode);if(t?.providerCode!==void 0)return $s(t.providerCode);let r=t?.message??n,i=tc(r);if(i!==void 0)return ec(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Vs.has(e))return!0;if(Hs.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;let a=nc(r);return a===void 0?rc(r)?!0:t?.retryable===!0:a}function Js(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Ys(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Xs(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 Zs(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 Qs(e){return Xs(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function $s(e){return/^\d+$/.test(e)?ec(Number(e)):!1}function ec(e){return e===408||e===409||e===425||e===429||e>=500}function tc(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function nc(e){if(!e)return;let t=ic(e);for(let e of Hs)if(t.includes(e))return!1;for(let e of Vs)if(t.includes(e))return!0}function rc(e){if(!e)return!1;let t=ic(e);return Us.some(e=>t.includes(e))}function ic(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const ac=Symbol(`omit-json-value`);function oc(e,t=new WeakSet){if(e===void 0)return ac;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=oc(r,t);e!==ac&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=oc(i,t);e!==ac&&(n[r]=e)}return n}finally{t.delete(e)}}function sc(e,t,n){return G.join(G.dirname(C(e,t,n)),`session-tools.json`)}function cc(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:oc(e.parameters??{})}))}async function lc(e,t,n){let r=await o(sc(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 uc(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:cc(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([L(C(e,t,r),n.systemPrompt,r?.encryptSessions),L(sc(e,t,r),a,r?.encryptSessions)])}async function dc(e,t,n){let[r,i]=await Promise.all([g(e,t,n),lc(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function fc(e){return Math.ceil(e.length/4*1.2)}function pc(e){if(e.role===`user`)return fc(e.content);if(e.role===`assistant`){let t=fc(e.content),n=e.thinking?.trim();n&&(t+=fc(n)),e.errorMessage&&(t+=fc(e.errorMessage));for(let n of e.toolCalls??[])t+=fc(n.name)+fc(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
|
|
20
|
+
`):e.content;return fc(e.toolName)+fc(t)}function X(e){return e.reduce((e,t)=>e+pc(t),0)}function mc(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 hc(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 gc=[`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.`],_c={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function vc(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function yc(e,t,n){return e.map(e=>bc(e,t,n))}function bc(e,t,n){let r=new Date(e.timestamp).getTime();if(xc(e))return{role:`user`,content:e.content,timestamp:r};if(Sc(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:_c,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:Cc(i)}],isError:i.isError,timestamp:r}}function xc(e){return e.role===`user`}function Sc(e){return e.role===`assistant`}function Cc(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:`,...gc];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
|
|
21
|
+
`)}const wc=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
|
|
22
|
+
`);async function Tc(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=Dc(t,r,i,a),u=Oc(a),d,f=ao({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:wc,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 Dc(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${Mc(t.trim(),kc(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=Ac(e,t,n,r),o=jc(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: ${Mc(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(`, `)}]`:``} ${Mc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?Nc(n):n.toolResultRef?[`[tool result persisted] ${n.toolResultRef.toolName} (${n.toolResultRef.originalChars} chars).`,`Full output: ${n.toolResultRef.storagePath}`,n.toolResultRef.preview.trim()?`Preview:\n${n.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
|
|
23
|
+
`):n.content;r=`Tool(${n.toolName})[${e}]: ${Mc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
|
|
24
|
+
`)}function Oc(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function kc(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function Ac(e,t,n,r){let i=jc(t,n,r);if(!r||r<=0)return 2e3;let a=Oc(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=wc.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 jc(e,t,n){if(!n||n<=0)return 1/0;let r=Oc(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=wc.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function Mc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function Nc(e){let t=Pc(e),n=t.name??`<skill-name>`,r=t.path,i=r?`skill_load(name="${n}", skillPath="${r}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,r?`Original path: ${r}`:``,`If this skill is needed later, call ${i} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].filter(Boolean).join(`
|
|
25
|
+
`)}function Pc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Fc(t);if(e.name||e.path)return e}return{}}function Fc(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function Ic(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=pc(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function Lc(e){return zc((await ao({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:Hc,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 Rc(e){return Bc((await ao({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:Uc,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 zc(e){let t=Vc(e);if(t.version!==1||!Array.isArray(t.selectedSegmentIds))throw Error(`Topic segment selection decision has invalid schema.`);return{version:1,selectedSegmentIds:t.selectedSegmentIds.filter(e=>typeof e==`string`),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Bc(e){let t=Vc(e);if(t.version!==1||!Array.isArray(t.selectedTurns))throw Error(`Topic turn selection decision has invalid schema.`);return{version:1,selectedTurns:t.selectedTurns.filter(e=>!!(e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:typeof e.topicLabel==`string`?e.topicLabel.trim():void 0,keywords:Array.isArray(e.keywords)?e.keywords.filter(e=>typeof e==`string`&&e.trim().length>0):void 0})),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Vc(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
|
|
26
|
+
`);const Hc=[`You select relevant conversation segments for an IM assistant before final turn-level topic classification.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedSegmentIds":["..."],"reason":"...","confidence":"high|medium|low"}`,`Task: choose which prior segments are relevant to the current user message.`,`Relevant includes same task continuation, explicit topic return, reuse of prior artifact, correction, or combining multiple earlier topics.`,`Prefer recall over over-pruning when the user explicitly refers to older topics by name.`,`Do not answer the user.`].join(`
|
|
27
|
+
`),Uc=[`You select relevant historical conversation turns for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurns":[{"turnId":"...","summary":"...","topicLabel":"optional","keywords":["..."]}],"reason":"...","confidence":"high|medium|low"}`,`Task: from the provided turns, select any turn that may be relevant to the current user message.`,`This is recall-first. It is better to include possibly relevant turns than to miss a relevant one.`,`Select turns for same task continuation, explicit old-topic return, reuse of prior artifact, corrections, or combinations of multiple earlier topics.`,`For every selected turn, provide a concise reusable summary, an optional topicLabel, and short keywords.`,`Prefer the provided summary/topicLabel fields when they exist; use raw user/assistant content only when needed.`,`Do not answer the user.`].join(`
|
|
28
|
+
`);async function Wc(e){let t=Yc(e);if(t)try{let e=await W.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(dl);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function Gc(e){let t=Yc(e);t&&(await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function Kc(e){let t=Xc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||Zc(t,e)){r.push(e);continue}n.push($c(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push($c(r,n.length+1,!0)),n}function qc(e,t){let n=Xc(t);if(n.length===0)return[];if(!e||e.length===0)return Kc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return Kc(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&&Qc(t,e)){a[a.length-1]=il(t,e);continue}t&&(t.status=`closed`),a.push($c([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 Jc(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 Yc(e){if(!(!e.dataDir||!e.sessionId))return G.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function Xc(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,user:a.content,timestamp:a.timestamp,toolNames:[]};continue}if(n){if(n.endIndex=i,a.role===`assistant`){let e=(a.content||a.errorMessage||``).trim();e&&(n.assistant=e);for(let e of a.toolCalls??[])n.toolNames.push(e.name);continue}a.role===`tool_result`&&n.toolNames.push(a.toolName)}}return r(),t.map(e=>({...e,toolNames:[...new Set(e.toolNames)].sort()}))}function Zc(e,t){return sl(ol(e.user,e.assistant),ol(t.user,t.assistant))>0}function Qc(e,t){return sl(ol(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),ol(t.user,t.assistant,t.toolNames.join(` `)))>0}function $c(e,t,n){return el(e,t,n)}function el(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=tl(e,o),c=ul(r?.summary||s),l=al(r?.keywords,c,o),u=ul(r?.compressedSummary||rl(c,o));return{version:1,segmentId:`segment-${t}`,turnIds:e.map(e=>e.turnId),startTurnId:i.turnId,endTurnId:a.turnId,startIndex:i.startIndex,endIndex:a.endIndex,userSummary:e.map(e=>e.user).join(`
|
|
27
29
|
`),assistantSummary:e.map(e=>e.assistant).filter(Boolean).join(`
|
|
28
|
-
`)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function
|
|
29
|
-
`)||void 0,o=Sc(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Ac(n?.summary||o),compressedSummary:Ac(n?.compressedSummary||Cc(n?.summary||o,r)),keywords:Tc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Tc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:Oc(t,n)}function Ec(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||n.length>64||/^(.)\1{15,}$/u.test(n)||t.add(n)}return t}function Dc(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Oc(e,t){let n=new Set([`the`,`and`,`for`,`with`,`this`,`that`,`from`,`user`,`intents`,`outcomes`,`tools`,`prior`,`segment`,`relevant`,`继续`,`刚才`,`这个`]),r=new Map;for(let i of Ec(e,t.join(` `)))n.has(i)||r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e])=>e)}function kc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Ac(e){return e.replace(/\s+/g,` `).trim()}function jc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.segmentId==`string`&&Array.isArray(t.turnIds)&&typeof t.startTurnId==`string`&&typeof t.endTurnId==`string`&&typeof t.startIndex==`number`&&typeof t.endIndex==`number`&&typeof t.userSummary==`string`&&typeof t.summary==`string`&&typeof t.compressedSummary==`string`&&Array.isArray(t.keywords)&&Array.isArray(t.toolNames)&&(t.turnMemories===void 0||Array.isArray(t.turnMemories)&&t.turnMemories.every(e=>!!e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`&&Array.isArray(e.keywords)&&typeof e.updatedAt==`string`))&&(t.status===`active`||t.status===`closed`)&&typeof t.updatedAt==`string`}function Mc(e){let t=Ic(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Lc(t,n,r,e.segments.length,e.vectorScores)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.segment.startIndex-e.segment.startIndex:t.score-e.score:e.forced?-1:1).slice(0,e.maxSegments)}function Nc(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Pc(e){let t=new Set(e.selectedTurnIds),n=new Set(e.recentProtectedTurnIds),r=[];for(let i of e.segments){let a=i.turnIds.some(e=>t.has(e)),o=i.turnIds.some(e=>n.has(e));!a||o||i.status!==`closed`||r.push({role:`assistant`,content:Fc(i.compressedSummary),timestamp:e.timestamp})}return r}function Fc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function Ic(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Lc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=Ic(t.summary,t.compressedSummary,t.keywords.join(` `),t.topicLabel,a),s=0;for(let t of e)o.has(t)&&(s+=1);let c=Math.max(0,i?.get(t.segmentId)??0),l=(n+1)/Math.max(r,1);return c*30+s*10+l}const Rc=`Xenova/bge-small-zh-v1.5`;let zc,Bc;const Vc=new Map;async function Hc(e,t){if(e.length===0)return J.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=qc(t),i=r.path;J.info(`topic segmentation embedding started`,{provider:`transformers`,model:Rc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await Gc({embeddingModelDir:i}),a=[],o=0,s=0;for(let n of e){let e=n.trim();if(!e){a.push([]),s+=1;continue}let r=`${i}\0${e}`,c=Vc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Vc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return J.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Rc,textCount:e.length,embeddedCount:a.filter(e=>e.length>0).length,emptyTextCount:s,cacheHitCount:o,dims:c?.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n}),a}catch(t){throw J.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Rc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Uc(e,t){let[n]=await Hc([e],t);return n??[]}function Wc(){return Rc}async function Gc(e){let t=qc(e).path;return(!zc||Bc!==t)&&(Bc=t,zc=Kc(t)),zc}async function Kc(e){let t=Date.now();J.info(`topic segmentation embedding extractor load started`,{model:Rc,modelDir:e,allowRemoteModels:!1});try{let{env:n,pipeline:r}=await import(`@huggingface/transformers`);n.allowRemoteModels=!1,n.localModelPath=e;let i=await r(`feature-extraction`,Rc,{dtype:`q8`});return J.info(`topic segmentation embedding extractor load completed`,{model:Rc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw J.warn(`topic segmentation embedding extractor load failed`,{model:Rc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function qc(e){let t=e?.embeddingModelDir?.trim();if(t)return{path:t,source:`config`};let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return{path:n,source:`env`};let r=W.dirname(yt(import.meta.url)),i=W.resolve(r,`../../../../../model`);if(G.existsSync(i))return{path:i,source:`repo_candidate`};let a=W.resolve(process.cwd(),`model`);return G.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const Jc=`topic_segments_vec`,Yc=`topic_segments_meta`,Xc=`topic_segment_embedding_cache`;async function Zc(e){let t=Date.now(),n=$c(e);if(!n){J.info(`topic segment vector store sync skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir});return}J.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await U.mkdir(W.dirname(n),{recursive:!0});let r=me(n,{allowExtension:!0});try{let i=await tl(r);J.info(`topic segment vector store ready`,{sessionId:e.sessionId,dbPath:n,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,embeddingModelDir:e.embeddingModelDir});let a=r.prepare(`SELECT segment_id, content_hash FROM ${Yc}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=Wc(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=ue(el(e));return o.get(e.segmentId)!==t});J.info(`topic segment vector store embedding plan`,{sessionId:e.sessionId,dbPath:n,existingSegmentCount:a.length,segmentCount:e.segments.length,toEmbedCount:l.length,embeddingModelDir:e.embeddingModelDir,embeddingModel:s});let u=l.length>0?await Hc(l.map(e=>el(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=el(t),n=ue(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:ol(r,t.segmentId);il(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(al(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(rl(r,i,o.length),r.prepare(`DELETE FROM ${Jc} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${Jc} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,fl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${Jc} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${Yc} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${Xc} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${Jc} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),J.info(`topic segment vector store sync completed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,toEmbedCount:l.length,embeddedCount:u.filter(e=>e.length>0).length,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,durationMs:Date.now()-t})}catch(e){throw r.exec(`ROLLBACK`),e}}catch(r){throw J.warn(`topic segment vector store sync failed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{r.close()}}async function Qc(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return J.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:e.query.trim()?`non_positive_limit`:`empty_query`,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;let n=$c(e);if(!n)return J.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;try{await U.access(n)}catch{return J.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}J.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await ll(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return J.warn(`topic segment vector search degraded`,{sessionId:e.sessionId,reason:`empty_query_embedding`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t}),new Map;let i=me(n,{allowExtension:!0});try{let a=await tl(i),o=Wc(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?sl(i,o,r,e.limit):cl(i,o,r,e.limit);return J.info(`topic segment vector search completed`,{sessionId:e.sessionId,dbPath:n,strategy:s,resultCount:c.length,queryDims:r.length,vectorAvailable:a.vectorAvailable,vectorDims:a.vectorDims,durationMs:Date.now()-t}),new Map(c.map(e=>[e.segment_id,Math.max(0,e.score??0)]))}catch(r){throw J.warn(`topic segment vector search failed`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{i.close()}}function $c(e){if(!(!e.dataDir||!e.sessionId))return W.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function el(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
|
|
30
|
-
`)}async function tl(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${Yc} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${Xc} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Yc}_hash ON ${Yc}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Xc}_hash ON ${Xc}(content_hash)`),{vectorAvailable:(await ce({db:e})).ok,vectorDims:nl(e)}}function nl(e){let t=e.prepare(`SELECT dims FROM ${Xc} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function rl(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${Jc}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${Jc} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function il(e,t){e.prepare(`INSERT INTO ${Yc} (\n segment_id, version, content_text, content_hash, embedding_model, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n version = excluded.version,\n content_text = excluded.content_text,\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n updated_at = excluded.updated_at`).run(t.segment.segmentId,1,t.contentText,t.contentHash,t.embeddingModel,t.segment.updatedAt)}function al(e,t){e.prepare(`INSERT INTO ${Xc} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function ol(e,t){let n=e.prepare(`SELECT embedding FROM ${Xc} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function sl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${Jc} v\n JOIN ${Yc} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(fl(n),t,fl(n),r)}function cl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${Xc} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:dl(n,ul(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function ll(e,t){try{return await Uc(e,t)}catch(e){return J.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function ul(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function dl(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function fl(e){return Buffer.from(new Float32Array(e).buffer)}const pl=8e3,ml=new Map;function hl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:jl(e?.embeddingModelDir),minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxShortlistCandidates:e?.maxShortlistCandidates??12,maxShortlistSegments:e?.maxShortlistSegments??6,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function gl(e){let t=Sl(e.entries),n=new Map(e.candidates.map(e=>[e.turnId,e])),r=new Set(e.decision.selectedTurnIds),i=e.recentProtectedTurnCount>0?t.slice(-e.recentProtectedTurnCount):[],a=i.map(e=>e.turnId);for(let e of i)r.add(e.turnId);let o=new Set;if(e.useCompressedSegmentMemory!==!1&&e.segmentRecords)for(let t of e.segmentRecords){let e=t.turnIds.some(e=>r.has(e)),n=t.turnIds.some(e=>a.includes(e));if(!(!e||n||t.status!==`closed`))for(let e of t.turnIds)o.add(e)}let s=[],c=[],l=[],u=[];for(let e of t){if(!r.has(e.turnId)){l.push(e.turnId),u.push(El(e,n.get(e.turnId)));continue}s.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),!o.has(e.turnId)&&c.push(...e.entries)}return{entries:[...e.useCompressedSegmentMemory!==!1&&e.segmentRecords?Pc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function _l(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Ml(e.currentUserMessage),n=new Set(e.recentProtectedTurnCount>0?e.candidates.slice(-e.recentProtectedTurnCount).map(e=>e.turnId):[]);return e.candidates.map((r,i)=>({candidate:r,index:i,forced:n.has(r.turnId),score:Pl(t,r,i,e.candidates.length)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.index-e.index:t.score-e.score:e.forced?-1:1).slice(0,e.maxShortlist).map(e=>e.candidate).sort((e,t)=>e.startIndex-t.startIndex)}async function vl(e){let t=hl(e.config),n=()=>Ll({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){J.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){J.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){J.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Sl(e.entries),i=Y(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){J.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>Cl(e,t)),o=e.llm.flashModel||e.llm.model,s=await yl({entries:e.entries,candidates:a,pendingUserMessage:e.pendingUserMessage,config:t,llm:{apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o,timeoutMs:t.timeoutMs,maxTokens:t.maxTokens},dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:t.embeddingModelDir,signal:e.signal}),c=s.segmentRecords,l=new Set(a.map(e=>e.turnId)),u=new Date().toISOString(),d=Date.now();J.info(`topic segmentation classify started`,Ll({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Tl({currentUserMessage:e.pendingUserMessage,allCandidates:a,shortlistedCandidates:s.candidates,selectedSegmentIds:s.selectedSegmentIds,supplementalTurnIds:s.supplementalTurnIds,segmentRecords:c,recentProtectedTurnCount:t.recentProtectedTurnCount,maxSelectedTurns:t.maxSelectedTurns}),p=f.selectedTurnIds.filter(e=>!l.has(e));if(p.length>0)throw Error(`Local topic segmentation returned unknown turn ids: ${p.join(`, `)}`);let m=Date.now()-d,h=gl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=wl({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:Y(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await Ol(e,g),J.info(`topic segmentation classify succeeded`,{...Ll({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}),durationMs:m,selectedTurnCount:f.selectedTurnIds.length,confidence:f.confidence,tokenEstimateAfter:g.tokenEstimate?.after,droppedTurnCount:h.droppedTurnIds.length,droppedTurnPreviews:h.droppedTurns.length>0?JSON.stringify(h.droppedTurns):void 0}),{entries:h.entries,audit:g}}async function yl(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await bl({entries:e.entries,llm:e.llm,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,signal:e.signal}),n=e.config.recentProtectedTurnCount>0?e.candidates.slice(-e.config.recentProtectedTurnCount).map(e=>e.turnId):[],r=Date.now(),i=[],a=e.candidates,o=t,s=[],c=[];if(t){let o=await Qc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,query:e.pendingUserMessage,limit:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2)}),l=Mc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=zl(l,e.config.maxShortlistSegments),d=xl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:pl});if(d&&Gl({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await Jl({currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,retrieved:l,llm:{...e.llm,timeoutMs:d},maxSelectedSegments:e.config.maxShortlistSegments,signal:e.signal});t.length>0&&(u=t)}s=u,i=u.map(e=>e.segment.segmentId),a=Nc({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Bl({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:pl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await dc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),Yl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=Wl(a,l.selectedCandidates),d=_l({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function bl(e){J.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await uc(e);if(!t){let t=fc(e.entries);if(t.length===0){J.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await dc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),Yl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),J.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}J.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=pc(t,e.entries);return n.length>0&&(await dc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),Yl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),J.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function xl(e){let t=Math.max(0,(e.nowMs??Date.now())-e.budgetStartedAtMs),n=Math.max(0,e.budgetMs-t);if(!(n<=0))return Math.min(e.requestTimeoutMs,n)}function Sl(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,entries:[a],user:a.content,timestamp:a.timestamp};continue}n&&(n.entries.push(a),n.endIndex=i)}return r(),t}function Cl(e,t){let n=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim()),r=new Set,i=!1;for(let t of e.entries){if(t.role===`assistant`){for(let e of t.toolCalls??[])r.add(e.name);t.stopReason===`error`&&(i=!0);continue}Il(t)&&(r.add(t.toolName),t.isError&&(i=!0))}return{turnId:e.turnId,startIndex:e.startIndex,endIndex:n?e.entries.indexOf(n)+e.startIndex:e.endIndex,user:kl(e.user,t.maxCandidateUserChars),assistant:n?kl((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function wl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:kl(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,shortlistCount:e.shortlistedCandidates.candidates.length,selectedSegmentIds:e.selectedSegmentIds,selectedTurnIds:e.decision.selectedTurnIds,selectedRanges:e.projected.selectedRanges,forcedKeep:{recentTurnIds:e.projected.recentTurnIds},droppedTurnIds:e.projected.droppedTurnIds,droppedTurns:e.projected.droppedTurns,confidence:e.decision.confidence,reason:e.decision.reason,tokenEstimate:{before:e.tokenEstimateBefore,after:e.tokenEstimateAfter}}}function Tl(e){let t=new Set(e.allCandidates.map(e=>e.turnId)),n=new Set;if(e.segmentRecords&&e.selectedSegmentIds.length>0){let r=e.segmentRecords.filter(t=>e.selectedSegmentIds.includes(t.segmentId));for(let e of r)for(let r of e.turnIds)t.has(r)&&n.add(r)}for(let r of e.supplementalTurnIds)t.has(r)&&n.add(r);if(n.size===0){let t=Ml(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Pl(t,n,r,e.shortlistedCandidates.length)})).sort((e,t)=>t.score-e.score),i=r[0]?.score??0,a=Math.max(8,i>=8?i*.7:1/0);for(let t of r)if(!(t.score<a)&&(n.add(t.candidate.turnId),n.size>=e.maxSelectedTurns))break}return{version:1,selectedTurnIds:[...n].slice(0,e.maxSelectedTurns),reason:e.selectedSegmentIds.length>0||e.supplementalTurnIds.length>0?`local segment retrieval matched prior segments`:`local candidate scoring matched recent turns`,confidence:`high`}}function El(e,t){let n=t?.assistant??Dl(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Al(t?.user??e.user,50),assistantPreview:n?Al(n,50):void 0}}function Dl(e){let t=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim());return t?(t.content||t.errorMessage||``).trim():void 0}async function Ol(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await U.mkdir(n,{recursive:!0}),await U.appendFile(W.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function kl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Al(e,t){return[...e].slice(0,t).join(``)}function jl(e){return e?.trim()||void 0}function Ml(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Nl(e){return[...Ml(e)].slice(0,8)}function Pl(e,t,n,r){let i=Fl(e,Ml(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Fl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Il(e){return e.role===`tool_result`}function Ll(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Rl(e.params.llm.baseUrl),timeoutMs:e.config.timeoutMs,maxTokens:e.config.maxTokens,hasEmbeddingModelDir:!!e.config.embeddingModelDir,embeddingModelDir:e.config.embeddingModelDir,minUserTurns:e.config.minUserTurns,minEstimatedTokens:e.config.minEstimatedTokens,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxCandidates:e.config.maxCandidates,maxSelectedTurns:e.config.maxSelectedTurns,transcriptEntryCount:e.params.fullTranscript.length,workingEntryCount:e.params.entries.length,pendingUserMessageChars:e.params.pendingUserMessage?.length,candidateCount:e.candidates?.length,shortlistCount:e.shortlistedCandidates?.length,tokenEstimateBefore:e.tokenEstimateBefore,extraPromptChars:e.extraPromptChars}}function Rl(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function zl(e,t){if(e.length===0)return[];let n=e.slice().sort((e,t)=>t.score-e.score),r=n[0]?.score??0,i=Math.max(8,r>=8?r*.7:1/0);return n.filter(e=>e.forced||e.score>=i).slice(0,t)}async function Bl(e){if(!Vl(e))return{selectedCandidates:[],selectedTurnIds:[]};let t=new Set(e.segmentFilteredCandidates.map(e=>e.turnId)),n=new Set(e.recentProtectedTurnIds),r=e.allCandidates.filter(e=>!t.has(e.turnId)&&!n.has(e.turnId));if(r.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let i=Hl(Ul(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=xl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await ic({currentUserMessage:e.currentUserMessage,turns:i,maxSelectedTurns:e.config.maxSelectedTurns,recentProtectedTurnIds:e.recentProtectedTurnIds,llm:{...e.llm,timeoutMs:a},signal:e.signal}),n=[...new Set(t.selectedTurns.map(e=>e.turnId))].filter(e=>r.some(t=>t.turnId===e));if(n.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let o=r.filter(e=>n.includes(e.turnId)),s=t.selectedTurns.filter(e=>n.includes(e.turnId)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:e.topicLabel?.trim()||void 0,keywords:(e.keywords??Nl(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?mc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Vl(e){let t=e.selectedSegments.filter(e=>!e.forced);return Kl(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:ql(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Hl(e,t){let n=new Map;for(let e of t??[])for(let t of e.turnIds)n.set(t,e);return e.map(e=>{let t=n.get(e.turnId),r=t?.turnMemories?.find(t=>t.turnId===e.turnId);return{turnId:e.turnId,user:e.user,assistant:e.assistant,toolNames:e.toolNames,hasErrors:e.hasErrors,summary:r?.summary??t?.summary,topicLabel:r?.topicLabel??t?.topicLabel,keywords:r?.keywords??t?.keywords}})}function Ul(e,t,n){let r=Math.max(n.length,1),i=Ml(t);return e.map(e=>({candidate:e,score:Pl(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function Wl(...e){let t=new Map;for(let n of e)for(let e of n)t.has(e.turnId)||t.set(e.turnId,e);return[...t.values()].sort((e,t)=>e.startIndex-t.startIndex)}function Gl(e){if(e.retrieved.length<2||!Kl(e.currentUserMessage))return!1;let t=new Set(e.selected.map(e=>e.segment.segmentId));if(e.selected.filter(e=>!e.forced).length>=2||e.retrieved.filter(e=>!e.forced).length<2)return!1;let n=new Set(e.selected.flatMap(e=>e.segment.turnIds));return e.recentProtectedTurnIds.length>0&&[...n].every(t=>e.recentProtectedTurnIds.includes(t))||t.size<2}function Kl(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function ql(e){let t=e.toLowerCase();return/(回到|刚才|前面|之前|上次|那个|前一个|最早|继续刚才)/u.test(t)?!0:/\b(back to|earlier|previous|that earlier|the earlier)\b/i.test(t)}async function Jl(e){try{let t=await rc({currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.retrieved.map(e=>({segmentId:e.segment.segmentId,turnIds:e.segment.turnIds,summary:e.segment.summary,compressedSummary:e.segment.compressedSummary,keywords:e.segment.keywords,toolNames:e.segment.toolNames,topicLabel:e.segment.topicLabel})),llm:e.llm,signal:e.signal}),n=new Set(t.selectedSegmentIds);return n.size===0?[]:e.retrieved.filter(e=>n.has(e.segment.segmentId))}catch{return[]}}function Yl(e){let t=Xl(e);if(!t||ml.has(t)){J.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}J.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=Zc(e).catch(t=>{J.warn(`topic segment vector sync failed`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length,error:t instanceof Error?t.message:String(t)})}).finally(()=>{ml.delete(t)});ml.set(t,n)}function Xl(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
|
|
31
|
-
`);const
|
|
32
|
-
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...
|
|
33
|
-
`)}function
|
|
34
|
-
`),r=n>t*.5?n:t;return e.slice(0,r)}async function
|
|
35
|
-
`);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),
|
|
36
|
-
`);a!==r.content&&(s+=1,c+=Math.max(0,Math.floor((r.content.length-a.length)/4)),await n?.recordSnip({toolCallId:r.toolCallId,toolName:r.toolName,originalChars:r.content.length,retainedChars:a.length,reason:`microcompact`,createdAt:new Date().toISOString()})),l.push({...r,content:a})}return s===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${s} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:c,affectedEntries:s,snapshotVersion:2}),
|
|
30
|
+
`)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function tl(e,t){return nl(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 nl(e,t,n){let r=ll(e,220),i=t?ll(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return ul(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function rl(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return ul(`Relevant prior segment: ${ll(e,280)}${n}`)}function il(e,t,n){let r=[...new Set([...e.toolNames,...t.toolNames])].sort(),i=`${e.userSummary}\n${t.user}`.trim(),a=[e.assistantSummary,t.assistant].filter(Boolean).join(`
|
|
31
|
+
`)||void 0,o=nl(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:ul(n?.summary||o),compressedSummary:ul(n?.compressedSummary||rl(n?.summary||o,r)),keywords:al(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function al(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:cl(t,n)}function ol(...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 sl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function cl(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 ol(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 ll(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ul(e){return e.replace(/\s+/g,` `).trim()}function dl(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 fl(e){let t=gl(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:_l(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 pl(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function ml(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:hl(i.compressedSummary),timestamp:e.timestamp})}return r}function hl(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function gl(...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 _l(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=gl(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 vl=`Xenova/bge-small-zh-v1.5`;let yl,bl;const xl=new Map;async function Sl(e,t){if(e.length===0)return Y.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=Dl(t),i=r.path;Y.info(`topic segmentation embedding started`,{provider:`transformers`,model:vl,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await Tl({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=xl.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);xl.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return Y.info(`topic segmentation embedding completed`,{provider:`transformers`,model:vl,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 Y.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:vl,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Cl(e,t){let[n]=await Sl([e],t);return n??[]}function wl(){return vl}async function Tl(e){let t=Dl(e).path;return(!yl||bl!==t)&&(bl=t,yl=El(t)),yl}async function El(e){let t=Date.now();Y.info(`topic segmentation embedding extractor load started`,{model:vl,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`,vl,{dtype:`q8`});return Y.info(`topic segmentation embedding extractor load completed`,{model:vl,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw Y.warn(`topic segmentation embedding extractor load failed`,{model:vl,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function Dl(e){let t=e?.embeddingModelDir?.trim();if(t)return{path:t,source:`config`};let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return{path:n,source:`env`};let r=G.dirname(vt(import.meta.url)),i=G.resolve(r,`../../../../../model`);if(K.existsSync(i))return{path:i,source:`repo_candidate`};let a=G.resolve(process.cwd(),`model`);return K.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const Ol=`topic_segments_vec`,kl=`topic_segments_meta`,Al=`topic_segment_embedding_cache`;async function jl(e){let t=Date.now(),n=Nl(e);if(!n){Y.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}Y.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await W.mkdir(G.dirname(n),{recursive:!0});let r=pe(n,{allowExtension:!0});try{let i=await Fl(r);Y.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 ${kl}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=wl(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=le(Pl(e));return o.get(e.segmentId)!==t});Y.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 Sl(l.map(e=>Pl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=Pl(t),n=le(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:Bl(r,t.segmentId);Rl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(zl(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(Ll(r,i,o.length),r.prepare(`DELETE FROM ${Ol} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${Ol} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,Kl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${Ol} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${kl} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${Al} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${Ol} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),Y.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 Y.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 Ml(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return Y.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 Y.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;try{await W.access(n)}catch{return Y.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}Y.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await Ul(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return Y.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=pe(n,{allowExtension:!0});try{let a=await Fl(i),o=wl(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?Vl(i,o,r,e.limit):Hl(i,o,r,e.limit);return Y.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 Y.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 G.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function Pl(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
|
|
32
|
+
`)}async function Fl(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${kl} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${Al} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${kl}_hash ON ${kl}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Al}_hash ON ${Al}(content_hash)`),{vectorAvailable:(await se({db:e})).ok,vectorDims:Il(e)}}function Il(e){let t=e.prepare(`SELECT dims FROM ${Al} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function Ll(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${Ol}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${Ol} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function Rl(e,t){e.prepare(`INSERT INTO ${kl} (\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 zl(e,t){e.prepare(`INSERT INTO ${Al} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function Bl(e,t){let n=e.prepare(`SELECT embedding FROM ${Al} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function Vl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${Ol} v\n JOIN ${kl} 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(Kl(n),t,Kl(n),r)}function Hl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${Al} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:Gl(n,Wl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function Ul(e,t){try{return await Cl(e,t)}catch(e){return Y.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function Wl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Gl(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 Kl(e){return Buffer.from(new Float32Array(e).buffer)}const ql=8e3,Jl=new Map;function Yl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:du(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 Xl(e){let t=nu(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(ou(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?ml({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function Zl(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=fu(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:mu(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 Ql(e){let t=Yl(e.config),n=()=>_u({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){Y.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){Y.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){Y.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=nu(e.entries),i=X(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){Y.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>ru(e,t)),o=e.llm.flashModel||e.llm.model,s=await $l({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();Y.info(`topic segmentation classify started`,_u({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=au({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=Xl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=iu({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:X(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await cu(e,g),Y.info(`topic segmentation classify succeeded`,{..._u({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 $l(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await eu({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 Ml({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=fl({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=yu(l,e.config.maxShortlistSegments),d=tu({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:ql});if(d&&Tu({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await Ou({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=pl({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await bu({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:ql,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await Gc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),ku({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=wu(a,l.selectedCandidates),d=Zl({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function eu(e){Y.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await Wc(e);if(!t){let t=Kc(e.entries);if(t.length===0){Y.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await Gc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),ku({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),Y.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}Y.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=qc(t,e.entries);return n.length>0&&(await Gc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),ku({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),Y.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function tu(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 nu(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 ru(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}gu(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:lu(e.user,t.maxCandidateUserChars),assistant:n?lu((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function iu(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:lu(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 au(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=fu(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:mu(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 ou(e,t){let n=t?.assistant??su(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:uu(t?.user??e.user,50),assistantPreview:n?uu(n,50):void 0}}function su(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 cu(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await W.mkdir(n,{recursive:!0}),await W.appendFile(G.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function lu(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function uu(e,t){return[...e].slice(0,t).join(``)}function du(e){return e?.trim()||void 0}function fu(...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 pu(e){return[...fu(e)].slice(0,8)}function mu(e,t,n,r){let i=hu(e,fu(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function hu(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function gu(e){return e.role===`tool_result`}function _u(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:vu(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 vu(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function yu(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 bu(e){if(!xu(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=Su(Cu(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=tu({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await Rc({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??pu(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Jc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function xu(e){let t=e.selectedSegments.filter(e=>!e.forced);return Eu(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:Du(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Su(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 Cu(e,t,n){let r=Math.max(n.length,1),i=fu(t);return e.map(e=>({candidate:e,score:mu(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function wu(...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 Tu(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 Du(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 Ou(e){try{let t=await Lc({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 ku(e){let t=Au(e);if(!t||Jl.has(t)){Y.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}Y.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=jl(e).catch(t=>{Y.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(()=>{Jl.delete(t)});Jl.set(t,n)}function Au(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
|
|
33
|
+
`);const ju=[`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 Mu(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 Lu(t);for(let e of p.readStates)n.set(Nu(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);i.push(...p.compaction.budgets),a.push(...p.compaction.snips),o.push(...p.compaction.collapseSpans),c=p.compaction.sessionMemory,l=p.compaction.modelUsage,u=p.compaction.consecutiveAutocompactFailures,d=p.compaction.lastCompactionAt,f=p.compaction.lastCompactionLayer;let m=async()=>{let s={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await W.mkdir(G.dirname(t),{recursive:!0});let p=e.encryptSessions??!1;await L(t,JSON.stringify(s,null,2),p)};return{async findReusableRead(e,t,r){let i=Nu(e,t,r),a=n.get(i);if(!a)return null;let o=await Fu(e);return o===null||o!==a.lastModifiedMs?(n.delete(i),await m(),null):a},async recordRead(e){let t=new Date().toISOString(),r={path:e.path,offset:e.offset,limit:e.limit,contentHash:Iu(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await Fu(e.path)??Date.now()};return n.set(Nu(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Pu(i.path)===Pu(e)&&(n.delete(r),t=!0);t&&await m()},async persistToolResult(t){let n=t.thresholdChars??12e3;if(t.content.length<=n)return{content:t.content};let a=t.previewChars??2e3,o=s(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=G.join(o,c);await W.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=G.relative(e.dataDir,l).split(G.sep).join(`/`),h=Vu(t.content,a),g={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:p,preview:h,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(g.toolCallId,g),i.push({toolCallId:g.toolCallId,toolName:g.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:g.createdAt}),d=g.createdAt,f=`L2`,await m(),{content:Bu(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 Hu(e.dataDir,e.sessionId,t,e),await m()},async recordModelUsage(e){l=e,await m()},async recordAutocompactResult(e){u=e.failed?u+1:0,d=e.timestamp,f=`L6`,await m()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function Nu(e,t,n){return`${Pu(e)}::${t??``}::${n??``}`}function Pu(e){return G.normalize(e)}async function Fu(e){try{return(await W.stat(e)).mtimeMs}catch{return null}}function Iu(e){return $e(`sha1`).update(e).digest(`hex`)}async function Lu(e){try{let t=await o(e);if(t===null)return Ru();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Ru():{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:zu(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 Ru()}}function Ru(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function zu(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 Bu(e){let t=e.preview.length<e.originalChars?`
|
|
34
|
+
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...ju,`Preview:`,e.preview+t].join(`
|
|
35
|
+
`)}function Vu(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
|
|
36
|
+
`),r=n>t*.5?n:t;return e.slice(0,r)}async function Hu(e,t,n,r){let i=l(e,t,r);await W.mkdir(G.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const Uu=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Wu(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=nd(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=hc(mc(S,a)),T=[],E=(await Ql({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=>{Y.warn(`topic segmentation failed; falling back to repaired history`,{sessionId:m,channel:_,isSubagent:!!v,error:e instanceof Error?e.message:String(e)})}))?.entries??w;if(E=await Ku({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await qu({entries:E,contextStore:f,compactionEvents:T}),E=await Ju({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g}),f&&(b=await Gu({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:yc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let D=f?.getSnapshot(),O=Math.max(1e3,Math.floor(r*.7)),k=rd({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:D?.compaction.modelUsage}).projectedInputTokens>=O,A=D?.compaction.consecutiveAutocompactFailures??0;if(!k||A>=3)return{messages:yc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let{toKeep:j,toSummarise:M}=Ic(E,r);if(M.length===0)return{messages:yc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let N=new Date().toISOString();try{let e=D?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Tc({entries:M,llm:i,previousSummary:b,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d}),a={role:`compaction`,content:t,keptCount:j.length,droppedCount:M.length,timestamp:N};return await f?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:N}),T.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${M.length} entries with session memory`:`Autocompact summarised ${M.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,X(M)),affectedEntries:M.length,snapshotVersion:2}),{messages:yc(hc(j),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:j.length,estimatedTokens:X(j),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:N}),{messages:yc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:[...T,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function Gu(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=X(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&td(t)>=3;if(!d&&!f)return n??u?.summary;let p=await Tc({entries:t,llm:r,previousSummary:n??u?.summary,instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}),m={version:1,summary:p,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:l,trigger:d?`threshold`:`autocompact`};return await i.setSessionMemory(m),p}async function Ku(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Xu).length<=n)return t;let c=n,l=[],u=0,d=0;for(let e=t.length-1;e>=0;--e){let n=t[e];if(!Xu(n)){l.push(n);continue}if(c>0&&n.content.length<=r){--c,l.push(n);continue}let i=n.toolResultRef?.preview?.trim()||n.content.slice(0,r).trim(),s=Zu(n)?Qu(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
|
|
37
|
+
`);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),hc(l.reverse())}async function qu(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-1728e5,a=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]),o=a.length>=3?a[a.length-3]??t.length:t.length,s=0,c=0,l=[];for(let[e,r]of t.entries()){if(!Xu(r)){l.push(r);continue}if(e>=o){l.push(r);continue}let t=Date.parse(r.timestamp);if(!(t>0&&t<i)){l.push(r);continue}let a=Zu(r)?Qu(r):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${r.toolName}`,`Preview:\n${r.toolResultRef?.preview?.trim()||r.content.slice(0,400).trim()}`].join(`
|
|
38
|
+
`);a!==r.content&&(s+=1,c+=Math.max(0,Math.floor((r.content.length-a.length)/4)),await n?.recordSnip({toolCallId:r.toolCallId,toolName:r.toolName,originalChars:r.content.length,retainedChars:a.length,reason:`microcompact`,createdAt:new Date().toISOString()})),l.push({...r,content:a})}return s===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${s} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:c,affectedEntries:s,snapshotVersion:2}),Ku({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Ju(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o,sessionPathScope:s}=e,c={storeName:o,...s},l=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(l.length<=2)return t;let u=l[l.length-2]??t.length,d=[],f=0,p=0,m=0;for(;f<t.length;){if(f>=u||t[f]?.role===`user`){d.push(t[f]),f+=1;continue}let e=f;for(;f<u&&t[f]?.role!==`user`;)f+=1;let r=t.slice(e,f),o=r.filter(Xu).filter(e=>Uu.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=Yu(r,o),h=new Date().toISOString(),g={role:`assistant`,content:l,timestamp:h};d.push(g),p+=r.length,m+=Math.max(0,Math.floor(X(r)-X([g])));let _={id:tt(),layer:`L5`,startEntryIndex:e,endEntryIndex:f-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:m,createdAt:h};await n?.recordCollapse(_),i&&a&&await id(i,a,_,c)}return p>0&&r.push({type:`compaction`,reason:`Collapsed ${p} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:m,affectedEntries:p,snapshotVersion:2}),d}function Yu(e,t){let n=[...new Set(t.map(e=>e.toolName))],r=t.slice(-3).map(e=>`- ${e.toolName}: ${(e.toolResultRef?.preview||e.content).slice(0,180).trim()}`).join(`
|
|
37
39
|
`),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
|
|
38
40
|
`);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
|
|
39
41
|
|
|
40
|
-
`)}function
|
|
41
|
-
`)}function
|
|
42
|
-
`)}function
|
|
43
|
-
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const
|
|
44
|
-
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return
|
|
45
|
-
`),l=Math.max(1,r.offset??1),u=Math.min(
|
|
42
|
+
`)}function Xu(e){return e.role===`tool_result`}function Zu(e){return e.toolName===`skill_load`}function Qu(e){let t=$u(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(`
|
|
43
|
+
`)}function $u(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=ed(t);if(e.name||e.path)return e}return{}}function ed(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 td(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function nd(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function rd(e){let t=e.pendingUserMessage?.trim()?X([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=X(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=X(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function id(e,t,n,r){let i=j(e,t,r);await W.mkdir(G.dirname(i),{recursive:!0}),await W.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function ad(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await Mu({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 Wu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function od(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}):Wu({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 sd=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)`}))}),cd=6e4;function ld(e,t,n){return Math.max(t,Math.min(n,e))}function ud(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function dd(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?cd:ld(Math.floor(e),0,12e4)}function fd(e,t){if(!t?.trim())return e;let n=G.isAbsolute(t)?G.normalize(t):G.normalize(G.join(e,t));if(!n.startsWith(e+G.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function pd(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 md(e){return gd({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
|
|
44
|
+
`)}function hd(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function gd(e){let t=hd(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 _d(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:sd,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=fd(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=ud(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?dd(n.yieldMs):cd,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:pd(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?gd({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[md(l)],p=hd(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(`
|
|
45
|
+
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const vd=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 yd(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function bd(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function xd(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:vd,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(`
|
|
46
|
+
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return bd(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,yd(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`}}:bd(`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}}:bd(`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}}:bd(`No session found for ${i}`)}return bd(`Unsupported action: ${n.action}`)}}}function Sd(e){return _d({workspaceDir:e,registry:tn(),scopeKey:e})}const Cd=5*1024*1024,wd=2e3;async function Td(e,t){e&&await e(t).catch(()=>{})}function Ed(e,t){return G.isAbsolute(e)?G.normalize(e):G.normalize(G.join(t,e))}const Dd=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 Od(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Dd,async execute(n,r){let i;try{i=Ed(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await W.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await yt(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>Cd){let e=o.slice(0,Cd).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Cd} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
|
|
47
|
+
`),l=Math.max(1,r.offset??1),u=Math.min(wd,r.limit??wd),d=c.slice(l-1,l-1+u),f=d.length<c.length-(l-1),p=d.map((e,t)=>`${(l+t).toString().padStart(4)} ${e}`).join(`
|
|
46
48
|
`),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
|
|
47
49
|
`),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
|
|
48
|
-
`),lines:d.length,truncated:f}}}}}const
|
|
49
|
-
`)||`(empty directory)`}],details:{entries:a}}}}}const
|
|
50
|
-
`)}function
|
|
51
|
-
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=
|
|
52
|
-
`)}function
|
|
53
|
-
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function
|
|
54
|
-
`)}],details:{matches:i}}}}}const
|
|
55
|
-
`)||`(empty)`}],details:{lines:i}}}}}const
|
|
50
|
+
`),lines:d.length,truncated:f}}}}}const kd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),content:q.String({description:`File content to write`})});function Ad(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:kd,async execute(r,i){let a;try{a=Ed(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await W.mkdir(G.dirname(a),{recursive:!0}),await W.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await 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 jd=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 Md(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:jd,async execute(r,i){let a;try{a=Ed(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await W.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await W.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await 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 Nd=q.Object({path:q.Optional(q.String({description:`Directory path (default: workspace root)`}))});function Pd(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Nd,async execute(t,n){let r=n.path??`.`,i;try{i=Ed(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await W.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
|
|
51
|
+
`)||`(empty directory)`}],details:{entries:a}}}}}const Fd=q.Object({input:q.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Id(e,t){let n=G.isAbsolute(e)?G.normalize(e):G.normalize(G.join(t,e));if(!n.startsWith(t+G.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Ld(e,t){let n=G.relative(t,e);return!n||n===``?G.basename(e):n.startsWith(`..`)||G.isAbsolute(n)?e:n}async function Rd(e){await W.mkdir(G.dirname(e),{recursive:!0})}async function zd(e,t){e&&await e(t).catch(()=>{})}function Bd(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(`
|
|
52
|
+
`)}function Vd(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:Fd,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=Ud(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=Id(r.path,e);await Rd(i),await W.writeFile(i,r.contents,`utf-8`),await zd(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Hd(o,s,`added`,Ld(i,e));continue}if(r.kind===`delete`){let i=Id(r.path,e);await W.rm(i,{force:!0,recursive:!1}),await zd(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Hd(o,s,`deleted`,Ld(i,e));continue}let i=Id(r.path,e),a=await qd(i,r.chunks);if(r.movePath){let c=Id(r.movePath,e);await Rd(c),await W.writeFile(c,a,`utf-8`),await W.rm(i,{force:!0,recursive:!1}),await zd(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Hd(o,s,`modified`,Ld(c,e))}else await W.writeFile(i,a,`utf-8`),await zd(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Hd(o,s,`modified`,Ld(i,e))}return{content:[{type:`text`,text:Bd(o)}],details:{summary:o}}}catch(e){if(Qo(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Hd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Ud(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Wd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Gd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Wd(e){let t=e[0]?.trim(),n=e[e.length-1]?.trim();if(t!==`*** Begin Patch`)throw Error(`The first line of the patch must be '*** Begin Patch'`);if(n!==`*** End Patch`)throw Error(`The last line of the patch must be '*** End Patch'`)}function Gd(e,t){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: empty hunk`);let n=e[0].trim();if(n.startsWith(`*** Add File: `)){let t=n.slice(14),r=``,i=1;for(let t of e.slice(1))if(t.startsWith(`+`))r+=`${t.slice(1)}\n`,i+=1;else break;return{hunk:{kind:`add`,path:t,contents:r},consumed:i}}if(n.startsWith(`*** Delete File: `))return{hunk:{kind:`delete`,path:n.slice(17)},consumed:1};if(n.startsWith(`*** Update File: `)){let r=n.slice(17),i=e.slice(1),a=1,o,s=i[0]?.trim();s?.startsWith(`*** Move to: `)&&(o=s.slice(13),i=i.slice(1),a+=1);let c=[];for(;i.length>0;){if(i[0].trim()===``){i=i.slice(1),a+=1;continue}if(i[0].startsWith(`***`))break;let{chunk:e,consumed:n}=Kd(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 Kd(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 qd(e,t){let n=(await W.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
|
|
53
|
+
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=Yd(n,Jd(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
|
|
54
|
+
`)}function Jd(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Xd(e,[a.changeContext],i,!1);if(n===null)throw Error(`Failed to find context '${a.changeContext}' in ${t}`);i=n+1}if(a.oldLines.length===0){let t=e.length>0&&e[e.length-1]===``?e.length-1:e.length;r.push([t,0,a.newLines]);continue}let n=a.oldLines,o=a.newLines,s=Xd(e,n,i,a.isEndOfFile);if(s===null&&n[n.length-1]===``&&(n=n.slice(0,-1),o.length>0&&o[o.length-1]===``&&(o=o.slice(0,-1)),s=Xd(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
|
|
55
|
+
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Yd(e,t){let n=[...e];for(let[e,r,i]of[...t].toReversed()){for(let t=0;t<r;t+=1)e<n.length&&n.splice(e,1);for(let t=0;t<i.length;t+=1)n.splice(e+t,0,i[t])}return n}function Xd(e,t,n,r){if(t.length===0)return n;if(t.length>e.length)return null;let i=e.length-t.length,a=r&&e.length>=t.length?i:n;if(a>i)return null;for(let n=a;n<=i;n+=1)if(Zd(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Zd(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Zd(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Zd(e,t,n,e=>Qd(e.trim())))return n;return null}function Zd(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 Qd(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}function $d(e){return G.join(e,`.aimax`)}function ef(e){return G.join($d(e),`MEMORY.md`)}async function tf(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function nf(e,t){let n=$d(e),r=he({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?{provider:r.provider,resolvedProviderId:r.registration.id,source:`plugin`}:{provider:ue({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function rf(e){return me($d(e))}async function af(e){try{return await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function of(e){return af(ef(e))}async function sf(e,t,n){let{provider:r}=nf(e,n);return await r.search(t)}async function cf(e,t,n,r,i){try{let{provider:a}=nf(e,i);return await a.getLines(t,n,r)}catch{return null}}async function lf(e,t,n){let{provider:r,resolvedProviderId:i}=nf(e,n);await r.append(t),await tf(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 uf(e,t,n,r){let{provider:i,resolvedProviderId:a}=nf(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 tf(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await tf(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 tf(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 tf(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await tf(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 df(e,t,n,r){let{provider:i,resolvedProviderId:a}=nf(e,r);await i.updateFile(t,n),await tf(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function ff(e,t,n){let{provider:r,resolvedProviderId:i}=nf(e,n);await r.deleteFile(t),await tf(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const pf=q.Object({query:q.String({description:`Search query (case-insensitive substring match)`})});function mf(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:pf,async execute(n,r){let i=(await sf(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(`
|
|
56
|
+
`)}],details:{matches:i}}}}}const hf=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 gf(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:hf,async execute(n,r){let i=await cf(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(`
|
|
57
|
+
`)||`(empty)`}],details:{lines:i}}}}}const _f=q.Object({content:q.String({description:`Content to write to memory`})});function vf(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:_f,async execute(n,r){try{return await lf(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 yf=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 bf(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:yf,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await lf(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 df(e,`MEMORY.md`,xf(await of(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await lf(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 xf(e,t,n){let r=e.split(`
|
|
56
58
|
`),i=`## ${t}`,a=`${i}\n${n.trimEnd()}`.trimEnd(),o=-1;for(let e=0;e<r.length;e+=1)if(r[e]?.trim()===i){o=e;break}if(o===-1){let t=e.trimEnd();return`${t?`${t}\n`:``}${a}\n`}let s=r.length;for(let e=o+1;e<r.length;e+=1)if(/^##\s+/.test(r[e]??``)){s=e;break}return`${[r.slice(0,o).join(`
|
|
57
59
|
`).trimEnd(),a,r.slice(s).join(`
|
|
58
60
|
`).trimStart()].filter(e=>e.length>0).join(`
|
|
59
|
-
`)}\n`}function
|
|
61
|
+
`)}\n`}function Sf(e,t){let n=e.split(`
|
|
60
62
|
`),r=`## ${t}`,i=-1;for(let e=0;e<n.length;e+=1)if(n[e]?.trim()===r){i=e;break}if(i===-1)return null;let a=n.length;for(let e=i+1;e<n.length;e+=1)if(/^##\s+/.test(n[e]??``)){a=e;break}let o=[n.slice(0,i).join(`
|
|
61
63
|
`).trimEnd(),n.slice(a).join(`
|
|
62
64
|
`).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
|
|
63
|
-
`)}\n`:``}function
|
|
65
|
+
`)}\n`:``}function Cf(e,t){let n=e.split(`
|
|
64
66
|
`);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
|
|
65
|
-
`)}\n`:``)}function
|
|
67
|
+
`)}\n`:``)}function wf(e,t,n){let r=e.split(`
|
|
66
68
|
`);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
|
|
67
|
-
`)}\n`)}function
|
|
68
|
-
`);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const
|
|
69
|
-
`),t=
|
|
69
|
+
`)}\n`)}function Tf(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 Ef(e,t){let n=[],r=t.split(`
|
|
70
|
+
`);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 Df=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 Of(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:Df,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await uf(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 kf=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 Af(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:kf,async execute(n,r){try{let n=r.scope??`all`,i=await rf(e),a=[];for(let n of i.slice(0,30)){let r=await cf(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
|
|
71
|
+
`),t=Ef(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
|
|
70
72
|
`):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
|
|
71
73
|
|
|
72
|
-
`)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const
|
|
73
|
-
`),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await
|
|
74
|
-
`),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await
|
|
75
|
-
`),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await
|
|
76
|
-
`);for(let t of r){let r=t.trim();if(!r||!
|
|
77
|
-
`)}function
|
|
78
|
-
`)}`}async function
|
|
79
|
-
`);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}function
|
|
74
|
+
`)||`(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 jf=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 Mf(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:jf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Tf(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Sf(await of(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 df(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 cf(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=Sf(n.join(`
|
|
75
|
+
`),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await df(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 cf(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=Cf(n.join(`
|
|
76
|
+
`),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 df(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 ff(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 sf(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await ff(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 Nf=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 Pf(e,t){return{name:`memory_update`,label:`Update Memory`,description:`Replace an existing memory's content by its entry ID. Use memory_list or memory_search first to find the correct ID. IDs with # (e.g. MEMORY.md#Preferences) update only that section; IDs without # replace the entire file.`,parameters:Nf,async execute(n,r){try{let n=Tf(r.id);if(n.section){let i=xf(await of(e)??``,n.section,r.content);return await df(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 cf(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=wf(i.join(`
|
|
77
|
+
`),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await df(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 df(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 Ff=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 If(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:Ff,async execute(n,r){let i=Lf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Rf(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await zf({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=Qf(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 Tc({entries:Yf(Jf(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Zf({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 Lf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Rf(e,t,n){let r=await x(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await I(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function zf(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Uf(e.query),i=(await $f(n,6,async t=>Bf({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(qf).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 Bf(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
|
|
78
|
+
`);for(let t of r){let r=t.trim();if(!r||!Vf(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!Hf(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Gf(i.content,e.terms,i.role);if(a<=0)continue;let o=Kf(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(qf),n.length=20)}return n.sort(qf),n}function Vf(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Hf(e){return e===`user`||e===`assistant`||e===`tool_result`}function Uf(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=>Wf(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 Wf(e){let t=e.codePointAt(0)??0;return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12352&&t<=12543||t>=44032&&t<=55215}function Gf(e,t,n){let r=e.toLowerCase(),i=0;for(let e of t)e&&r.includes(e)&&(i+=1);if(i===0)return 0;let a=n===`user`?1.2:n===`assistant`?1:.7;return i*i*a}function Kf(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function qf(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Jf(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Yf(e,t,n){if(e.length===0)return e;let r=Uf(t);if(e.reduce((e,t)=>e+t.content.length,0)<=n)return e;let i=[];for(let t=0;t<e.length;t+=1){let n=e[t].content.toLowerCase();r.some(e=>e&&n.includes(e))&&i.push(t)}if(i.length===0)return Xf(e,n);let a=i[0],o=i[0],s=e[a].content.length;for(;s<n&&(a>0||o<e.length-1);){if(o<e.length-1){let t=e[o+1].content.length;if(s+t<=n)o+=1,s+=t;else break}if(a>0){let t=e[a-1].content.length;if(s+t<=n)--a,s+=t;else break}}return e.slice(a,o+1)}function Xf(e,t){let n=[],r=0;for(let i=e.length-1;i>=0;--i){let a=e[i];if(r+a.content.length>t)break;n.push(a),r+=a.content.length}return n.reverse()}function Zf(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(`
|
|
79
|
+
`)}function Qf(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(`
|
|
80
|
+
`)}`}async function $f(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 ep(e){return G.join(e,`.aimax`,`skills`)}function tp(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function np(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${tp(n)}\n`)}function rp(e){let t=at(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
|
|
81
|
+
`);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 ip(e){let t=at(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 ap(e){return(await W.stat(e)).mtime.toISOString()}async function op(e){return cp([ep(e)])}async function sp(e,t,n=[]){return cp([...n,...t,ep(e)])}async function cp(e){let t=new Map;for(let n of e){let e;try{e=await W.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=G.join(n,e,`SKILL.md`),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=rp(i),o=ip(i),s=await ap(r)}catch(t){np(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 lp(e,t){let n=t.trim();if(!n)return;let r=(await cp(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:G.dirname(r.location)}}async function up(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=G.resolve(r),a=G.basename(i)===`SKILL.md`?i:G.join(i,`SKILL.md`);if(G.basename(a)!==`SKILL.md`)return;let o;try{o=await W.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=rp(o),c=ip(o),l=await ap(a)}catch(e){np(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:G.dirname(a)}}async function dp(e,t,n){let r=n?.trim()?await up(t,n):await lp(e,t);if(!r)return;let i=await W.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function fp(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
|
|
80
82
|
`)).join(`
|
|
81
|
-
`)}\n</available_skills>`}const Nf=K.Object({category:K.Optional(K.String({description:`Reserved category filter field. Not used yet.`}))}),Pf=K.Object({name:K.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:K.Optional(K.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Ff(e,t,n=[]){return[...n,...t,bf(e)]}function If(e,t,n=[]){let r=Ff(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Nf,async execute(e,t){let n=await Of(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function Lf(e){let t=Ff(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:Pf,async execute(r,i){let a=await jf(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const Rf=K.Object({});function zf(e,t,n){return{name:`get_goal`,label:`Get Goal`,description:"Get the current thread goal, including status, budget, token and time usage, remaining token budget, and V2-lite workflow summary (`goalState`). Returns null when no goal is set.",parameters:Rf,async execute(r,i){let a=await H(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,goalState:null,workflowWarning:null})}],details:{}};let o=await z(e,t,a,{storeName:n}),s=await bn(e,t,{storeName:n}),c={goal:{...a,objective:o,remainingTokens:a.tokenBudget===null?void 0:Math.max(0,a.tokenBudget-a.tokensUsed)},goalState:s.goalState,workflowWarning:s.workflowWarning};return{content:[{type:`text`,text:JSON.stringify(c,null,2)}],details:{}}}}}const Bf=K.Object({status:K.String({description:`Status to set. Only 'complete' is allowed.`})});function Vf(e,t,n,r,i=t){return{name:`update_goal`,label:`Update Goal`,description:'Legacy goal completion tool. V2-lite workflow goals must use `goal_complete` with final evidence refs instead. This tool rejects `status: "complete"` when workflow is active or not initialized.',parameters:Bf,async execute(r,i){if(i.status!==`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Invalid status: "${i.status}". Only "complete" is allowed via this tool.`},null,2)}],details:{}};let a=await H(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`No active goal exists for this session. Use the CLI to set a goal first.`},null,2)}],details:{}};if(a.status===`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:a},null,2)}],details:{}};let o=await bn(e,t,{storeName:n});return o.workflowWarning===`workflow_not_initialized`?{content:[{type:`text`,text:JSON.stringify({goal:null,error:`workflow_not_initialized: goal exists under goal/ but goal/state.json is missing. Re-create the goal or initialize workflow before completing.`},null,2)}],details:{}}:o.goalState?{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Cannot complete goal via update_goal when V2-lite workflow is active. Use goal_complete with finalEvidenceRefs instead.`},null,2)}],details:{}}:{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Cannot complete goal via update_goal in V2-lite. Use goal_complete with finalEvidenceRefs instead.`},null,2)}],details:{}}}}}function Hf(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function Uf(e){let t=Hf(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=W.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Wf(e){let t=e.watchFactory??((e,t,n)=>G.watch(e,t,n)),n=W.join(e.dataDir,`.aimax`),r=[{target:W.join(n,`MEMORY.md`),kind:`memory-file`},{target:W.join(n,`memory.md`),kind:`memory-file-lower`},{target:W.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=Uf({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function X(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function Gf(e){return e.projectDir?.trim()||W.join(e.dataDir,`workspace`)}async function Kf(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Gf(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Yf(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:m?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}p.source===`sessions`?await n.dispatchDiagnostic(e.sessionId??i,{level:`info`,scope:`memory`,phase:p.reason,message:`session transcript changed`,details:{reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}}).catch(()=>{}):await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=W.join(t.dataDir,`.aimax`),m=ge({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g=m?.provider??de({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),_=m?.registration.id??g.id,v=m?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:m?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!m}}).catch(()=>{});let y=Wf({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await h(t.dataDir,i,e,Jf({sessionOptions:X(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function qf(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Jf(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function Yf(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function Z(e){return{storeName:e.sessionStoreName}}function Xf(e){return Gf({dataDir:e.dataDir,projectDir:e.projectDir})}function Zf(e){return In({dataDir:e.dataDir,workspaceDir:Xf(e),projectDir:e.projectDir})}function Q(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function $(e,t){return Q({ok:!1,error:e,...t})}function Qf(e,t){return un(e.dataDir,e.sessionId,Z(e),t)}async function $f(e){try{return await _n(e.dataDir,e.sessionId,Z(e))}catch(e){if(e instanceof sn)return{corrupt:!0};throw e}}function ep(){return $(`workflow_corrupt`,{repairTool:`goal_repair_workflow_state`})}const tp={hint:[`Use only the returned evidenceRef values from goal_record_note, goal_record_exec, or goal_record_snapshot.`,`Natural-language descriptions, file paths, and strings such as 'goal/state.json ...' are not evidence refs unless they are registered in goal/artifacts/registry.jsonl.`,`If command output should prove an acceptance criterion, run it with goal_record_exec; exec does not register goal evidence.`].join(` `),suggestedTools:[`goal_record_note`,`goal_record_exec`,`goal_record_snapshot`],example:{registerManualEvidence:{tool:`goal_record_note`,args:{kind:`manual`,source:`goal/state.json`,summary:`planning evidence`,content:`Task list and acceptance criteria were added to goal/state.json.`}},registerCommandEvidence:{tool:`goal_record_exec`,args:{command:`npm test`,cwd:`<workspace>`,timeoutMs:12e4}},registerSnapshotEvidence:{tool:`goal_record_snapshot`,args:{path:`<workspace>/artifact.html`,summary:`final deliverable`}},evidenceRefs:[`manual:...`]}},np=/goal[/\\]state\.json|\btask\s*list\b|\btask-\d+|\b(plan|planning|planned|added|through|workflow)\b/i,rp=/[/\\]|\.(?:html|css|js|ts|tsx|jsx|json|md|txt|py|go|rs|yaml|yml|sh)\b|\bexists\b/i,ip=/\b(npm|pnpm|yarn|cargo|go test|pytest|vitest|jest|exit code|stdout|stderr|command output|test pass|tests pass)\b/i;function ap(e,t){let n=`${e}\n${t}`;return np.test(n)?`goal/state.json`:/\buser\b/i.test(n)&&/\bconfirm/i.test(n)?`user`:`model`}function op(e){let t=e.match(/^(.+?)\s+exists\s*$/i);if(t)return t[1].trim();let n=e.match(/(?:^|\s)((?:[\w.-]+\/)+[\w.-]+\.\w{1,10})(?:\s|$)/);return n?n[1].trim():/^[\w./-]+\.\w{1,10}$/.test(e.trim())?e.trim():null}function sp(e){let t=e.trim();return np.test(t)?{tool:`goal_record_note`,reason:`the ref describes planning state`}:rp.test(t)?{tool:`goal_record_snapshot`,reason:`the ref describes a file artifact`}:ip.test(t)?{tool:`goal_record_exec`,reason:`the ref describes command output`}:{tool:`goal_record_note`,reason:`the ref is natural language and must be registered as evidence`}}function cp(e,t){let n=e.trim();switch(t.tool){case`goal_record_note`:return{kind:`manual`,source:ap(n,n),summary:n.slice(0,120),content:n};case`goal_record_snapshot`:{let e=op(n);return e?{path:e,summary:n.slice(0,120)}:{kind:`manual`,source:`model`,summary:n.slice(0,120),content:n}}case`goal_record_exec`:return{command:n.includes(`npm test`)?`npm test`:`<command>`,cwd:`<workspace>`,timeoutMs:12e4}}}function lp(e){let t=new Set,n=[];for(let r of e){if(r.code!==`unregistered_evidence_ref`||!r.ref.trim())continue;let e=r.ref.trim();if(t.has(e))continue;t.add(e);let i=sp(e),a=i.tool===`goal_record_snapshot`&&!op(e)?`goal_record_note`:i.tool,o=a===`goal_record_note`&&i.tool===`goal_record_snapshot`?`the ref describes a file artifact but no reliable path could be extracted`:i.reason;n.push({tool:a,reason:o,args:cp(e,{tool:a,reason:o})})}return n}function up(e){let t=e.errors[0]?.code??`invalid_evidence`;return t===`unregistered_evidence_ref`?$(t,{errors:e.errors,repairPlan:lp(e.errors),...tp}):$(t,{errors:e.errors})}function dp(e,t){return $(`manual_source_required`,{hint:`Manual evidence requires a source. Use source='goal/state.json' for plan/workflow facts, source='user' for user confirmation, or another concise origin string.`,retryWith:{kind:`manual`,source:ap(e,t),summary:e,content:t},example:{kind:`manual`,source:`goal/state.json`,summary:`planning evidence`,content:`Task list and acceptance criteria were added to goal/state.json.`}})}function fp(e){let t=Zn(e.length);return e.map((e,n)=>typeof e==`string`?{id:t[n],text:e.trim(),required:!0}:{id:t[n],text:e.text.trim(),required:e.required!==!1}).filter(e=>e.text.length>0)}function pp(e,t){let n=new Set;for(let t of e??[])t.trim()&&n.add(t.trim());for(let e of t??[])for(let t of e.evidenceRefs??[])t.trim()&&n.add(t.trim());return[...n]}function mp(e,t){return e.tasks.find(e=>e.id===t)}function hp(e){return e.tasks.some(e=>e.kind===`execution`&&e.required!==!1)}function gp(e){return e.ok===!1?e.warning:null}async function _p(e,t){await Gn(e.dataDir,e.sessionId,t,Z(e));let n=gp(await Yn(e.dataDir,e.sessionId,t,Z(e)));return n?{planWarning:n}:{}}function vp(e){return{name:`goal_plan_update`,label:`Goal Plan Update`,description:`Update controlled sections of goal/plan.md without changing task workflow state.`,parameters:K.Object({interpretation:K.Optional(K.String()),assumptions:K.Optional(K.Array(K.String())),openQuestions:K.Optional(K.Array(K.String())),taskPlanNotes:K.Optional(K.String())}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t;await q(e.dataDir,e.sessionId,{type:`goal_plan_updated`,goalId:r.goalId,interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Z(e));let i=await Jn(e.dataDir,e.sessionId,{interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Z(e)),a=await Yn(e.dataDir,e.sessionId,r,Z(e));return Q({ok:!0,goalId:r.goalId,planMeta:i,warning:gp(a),hint:`Use goal_add_task to project executable tasks into goal/state.json.`})})}}}function yp(e){return{name:`goal_checkpoint`,label:`Goal Checkpoint`,description:`Record intermediate progress without marking a task done.`,parameters:K.Object({summary:K.String(),evidenceRefs:K.Optional(K.Array(K.String()))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=!0,a=n.evidenceRefs??[];a.length>0&&(i=(await Un(e.dataDir,e.sessionId,a,{...Z(e),requireCommandSuccess:!1})).valid),await q(e.dataDir,e.sessionId,{type:`goal_checkpoint`,goalId:r.goalId,taskId:r.currentTaskId,summary:n.summary,evidenceRefs:a,verified:i},Z(e));let o=[...(await Kn(e.dataDir,e.sessionId,Z(e))).progressLog??[],`${new Date().toISOString().slice(0,16).replace(`T`,` `)}: ${n.summary}${i?``:` (unverified evidence)`}`],s=await Jn(e.dataDir,e.sessionId,{progressLog:o},Z(e)),c=await Yn(e.dataDir,e.sessionId,r,Z(e));return Q({ok:!0,verified:i,planMeta:s,warning:gp(c)})})}}}function bp(e){return{name:`goal_task_start`,label:`Goal Task Start`,description:`Switch the current task to doing.`,parameters:K.Object({taskId:K.String()}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t;if(r.status===`blocked`)return $(`workflow_blocked`);let i=mp(r,n.taskId);if(!i)return $(`task_not_found`);if(i.status===`doing`&&i.id===r.currentTaskId)return Q({ok:!0,alreadyStarted:!0,currentTaskId:i.id});if(i.status!==`todo`&&i.status!==`blocked`)return $(`task_not_startable`);let a=r.tasks.find(e=>e.status===`doing`&&e.id!==i.id);if(a)return $(`another_task_is_doing`,{taskId:a.id});let o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i.id?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,currentTaskId:i.id,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await q(e.dataDir,e.sessionId,{type:`goal_task_started`,goalId:r.goalId,taskId:i.id},Z(e));let{planWarning:l}=await _p(e,c);return Q({ok:!0,currentTaskId:i.id,warning:l??null})})}}}function xp(e){return{name:`goal_task_done`,label:`Goal Task Done`,description:`Mark the current doing task done with evidence covering required acceptance criteria.`,parameters:K.Object({taskId:K.String(),summary:K.Optional(K.String()),evidenceRefs:K.Optional(K.Array(K.String())),acceptanceEvidence:K.Optional(K.Array(K.Object({criterionId:K.String(),evidenceRefs:K.Array(K.String())})))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=mp(r,n.taskId);if(!i)return $(`task_not_found`);if(i.status!==`doing`)return $(`task_not_doing`);if(i.acceptanceCriteria.length===0)return $(`missing_acceptance_criteria`);let a=pp(n.evidenceRefs,n.acceptanceEvidence);if(a.length===0)return $(`missing_evidence_refs`);let o=i.acceptanceCriteria.filter(e=>e.required!==!1),s=new Map;for(let e of n.acceptanceEvidence??[])s.set(e.criterionId,e.evidenceRefs??[]);for(let e of o)if((s.get(e.id)??[]).length===0)return $(`missing_required_acceptance_evidence`,{criterionId:e.id});let c=await Un(e.dataDir,e.sessionId,a,Z(e));if(!c.valid)return up(c);if(i.kind===`clarify`){if(!hp(r))return $(`missing_executable_followup_task`);if(!a.some(e=>e.startsWith(`note:`)||e.startsWith(`manual:`)))return $(`clarify_requires_note_or_manual_evidence`)}let l=new Date().toISOString(),u={};for(let e of n.acceptanceEvidence??[])u[e.criterionId]=e.evidenceRefs??[];let d=r.tasks.map(e=>e.id===i.id?{...e,status:`done`,acceptanceEvidence:Object.keys(u),evidenceRefs:a,updatedAt:l}:e),f=d.find(e=>e.status===`todo`&&e.required!==!1),p=d.map(e=>f&&e.id===f.id?{...e,status:`doing`,updatedAt:l}:e),m={...r,tasks:p,currentTaskId:f?.id??null,status:`active`,blockedReason:null,updatedAt:l};await q(e.dataDir,e.sessionId,{type:`goal_task_done`,goalId:r.goalId,taskId:i.id,summary:n.summary,acceptanceEvidence:n.acceptanceEvidence,evidenceRefs:a},Z(e));let h=await Kn(e.dataDir,e.sessionId,Z(e));await Jn(e.dataDir,e.sessionId,{progressLog:[...h.progressLog??[],`${l.slice(0,16).replace(`T`,` `)}: ${n.summary??`Completed ${i.id}`}`],criterionEvidence:{[i.id]:Object.keys(u)},evidence:a},Z(e));let{planWarning:g}=await _p(e,m);return Q({ok:!0,currentTaskId:m.currentTaskId,hint:m.currentTaskId?null:`All tasks done. Call goal_complete with finalEvidenceRefs.`,warning:g??null})})}}}function Sp(e){return{name:`goal_task_blocked`,label:`Goal Task Blocked`,description:`Mark a task and the workflow as blocked without changing goal/goal.json status.`,parameters:K.Object({taskId:K.String(),reason:K.String(),neededInput:K.Optional(K.String()),evidenceRefs:K.Optional(K.Array(K.String()))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=mp(r,n.taskId);if(!i)return $(`task_not_found`);let a=n.evidenceRefs??[];if(a.length>0){let t=await Un(e.dataDir,e.sessionId,a,{...Z(e),requireCommandSuccess:!1});if(!t.valid)return $(t.errors[0]?.code??`invalid_evidence`,{errors:t.errors})}let o=new Date().toISOString(),s=n.neededInput?`${n.reason} (needed: ${n.neededInput})`:n.reason,c=r.tasks.map(e=>e.id===i.id?{...e,status:`blocked`,blockedReason:s,updatedAt:o}:e),l={...r,status:`blocked`,blockedReason:s,currentTaskId:i.id,tasks:c,updatedAt:o};await q(e.dataDir,e.sessionId,{type:`goal_task_blocked`,goalId:r.goalId,taskId:i.id,reason:n.reason,neededInput:n.neededInput,evidenceRefs:a},Z(e)),await Jn(e.dataDir,e.sessionId,{risks:[s]},Z(e));let{planWarning:u}=await _p(e,l);return Q({ok:!0,workflowStatus:`blocked`,warning:u??null})})}}}function Cp(e){return{name:`goal_add_task`,label:`Goal Add Task`,description:`Add a new execution task to goal/state.json. Concurrent calls in the same turn are serialized; add tasks one at a time or rely on the store lock.`,parameters:K.Object({title:K.String(),kind:K.Optional(K.Literal(`execution`)),required:K.Optional(K.Boolean()),acceptanceCriteria:K.Array(K.Union([K.String(),K.Object({text:K.String(),required:K.Optional(K.Boolean())})])),afterTaskId:K.Optional(K.String()),startNow:K.Optional(K.Boolean())}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t;if((n.kind??`execution`)!==`execution`)return $(`invalid_task_kind`);if(n.acceptanceCriteria.length===0)return $(`missing_acceptance_criteria`);let i=new Date().toISOString(),a=Xn(r.tasks),o=fp(n.acceptanceCriteria),s={id:a,kind:`execution`,title:n.title.trim(),required:n.required!==!1,status:n.startNow?`doing`:`todo`,acceptanceCriteria:o,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:i},c=[...r.tasks];if(n.afterTaskId){let e=c.findIndex(e=>e.id===n.afterTaskId);if(e<0)return $(`after_task_not_found`);c.splice(e+1,0,s)}else c.push(s);n.startNow&&(c=c.map(e=>e.id===a?s:e.status===`doing`?{...e,status:`todo`,updatedAt:i}:e));let l={...r,tasks:c,currentTaskId:n.startNow?a:r.currentTaskId,updatedAt:i};await q(e.dataDir,e.sessionId,{type:`goal_task_added`,goalId:r.goalId,taskId:a,kind:`execution`,required:s.required,acceptanceCriteria:o},Z(e));let{planWarning:u}=await _p(e,l);return Q({ok:!0,taskId:a,warning:u??null})})}}}function wp(e){return{name:`goal_record_note`,label:`Goal Record Note`,description:`Record note or manual evidence in the artifact registry.`,parameters:K.Object({kind:K.Union([K.Literal(`note`),K.Literal(`manual`)]),summary:K.String(),content:K.String(),taskId:K.Optional(K.String()),source:K.Optional(K.String())}),async execute(t,n){let r=await $f(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return ep();let i=r,a=await Qn(e.dataDir,e.sessionId,{kind:n.kind,summary:n.summary,content:n.content,source:n.source},Z(e));return`error`in a?a.error===`manual evidence requires source`?dp(n.summary,n.content):$(a.error):(await q(e.dataDir,e.sessionId,{type:`goal_note_recorded`,goalId:i.goalId,taskId:n.taskId,evidenceRef:a.evidenceRef,kind:n.kind,summary:n.summary,source:n.source??`model`},Z(e)),Q({ok:!0,evidenceRef:a.evidenceRef}))}}}function Tp(e){return{name:`goal_record_exec`,label:`Goal Record Exec`,description:`Execute a bounded command and record command evidence.`,parameters:K.Object({command:K.String(),cwd:K.Optional(K.String()),timeoutMs:K.Optional(K.Number())}),async execute(t,n){let r=await $f(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return ep();let i=r,a=await $n(e.dataDir,e.sessionId,{command:n.command,cwd:n.cwd,timeoutMs:n.timeoutMs,workspaceDir:Xf(e),allowedRoots:Zf(e),baseEnv:e.baseEnv},Z(e));return`error`in a?$(a.error):(await q(e.dataDir,e.sessionId,{type:`goal_command_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,command:n.command,cwd:n.cwd??Xf(e),exitCode:a.exitCode},Z(e)),Q({ok:!0,evidenceRef:a.evidenceRef,exitCode:a.exitCode}))}}}function Ep(e){return{name:`goal_record_snapshot`,label:`Goal Record Snapshot`,description:`Snapshot a workspace file as evidence.`,parameters:K.Object({path:K.String(),summary:K.Optional(K.String())}),async execute(t,n){let r=await $f(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return ep();let i=r,a=await tr(e.dataDir,e.sessionId,{path:n.path,summary:n.summary,workspaceDir:Xf(e),allowedRoots:Zf(e)},Z(e));return`error`in a?$(a.error):(await q(e.dataDir,e.sessionId,{type:`goal_snapshot_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,path:n.path},Z(e)),Q({ok:!0,evidenceRef:a.evidenceRef}))}}}function Dp(e){return{name:`goal_complete`,label:`Goal Complete`,description:`Complete the goal after all required tasks are done and final evidence is recorded.`,parameters:K.Object({summary:K.String(),finalEvidenceRefs:K.Array(K.String()),risks:K.Optional(K.Array(K.String()))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=r.tasks.filter(e=>e.required!==!1),a=i.filter(e=>e.status!==`done`);if(a.length>0)return $(`required_tasks_not_done`,{pendingTaskIds:a.map(e=>e.id)});if(i.filter(e=>e.status===`blocked`).length>0)return $(`blocked_tasks_remain`);for(let e of i)if((e.evidenceRefs??[]).length===0)return $(`done_task_missing_evidence`,{taskId:e.id});if(n.finalEvidenceRefs.length===0)return $(`missing_final_evidence_refs`);let o=await Un(e.dataDir,e.sessionId,n.finalEvidenceRefs,Z(e));if(!o.valid)return up(o);let s=new Date().toISOString(),c={...r,status:`complete`,finalEvidenceRefs:n.finalEvidenceRefs,completedAt:s,currentTaskId:null,updatedAt:s};if(!await H(e.dataDir,e.sessionId,Z(e)))return $(`goal_not_found`);await Gn(e.dataDir,e.sessionId,c,Z(e));try{await B(e.dataDir,e.sessionId,{status:`complete`},{...Z(e),eventSource:`tool`})}catch(t){throw await Gn(e.dataDir,e.sessionId,r,Z(e)),t}return await q(e.dataDir,e.sessionId,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:n.finalEvidenceRefs,summary:n.summary,risks:n.risks??[]},Z(e)),await Jn(e.dataDir,e.sessionId,{finalSummary:n.summary,evidence:n.finalEvidenceRefs,risks:n.risks},Z(e)),Q({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,warning:gp(await Yn(e.dataDir,e.sessionId,c,Z(e)))})})}}}function Op(e){return{name:`goal_repair_workflow_state`,label:`Goal Repair Workflow State`,description:`Reinitialize unreadable goal/state.json from the saved objective. Requires confirm:true.`,parameters:K.Object({confirm:K.Literal(!0)}),async execute(t,n){return Q(await Qf(e,()=>vn(e.dataDir,e.sessionId,Z(e))))}}}function kp(e){return[vp(e),yp(e),bp(e),xp(e),Sp(e),Cp(e),Op(e),wp(e),Tp(e),Ep(e),Dp(e)]}var Ap=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=W.resolve(e.rootDir??fi(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=_i(e.path),n=Ip(e.description,`category description`),r=await this.readCategoryRegistry();if(r[t])throw Error(`Auto-skill category already exists: ${t}`);return r[t]={description:n,createdBy:e.createdBy?.trim()||`review-agent`},await this.writeCategoryRegistry(r),await ji(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:pi(this.rootDir)}}async createSkill(e){let t=vi(e.name),n=_i(e.categoryPath),r=Ip(e.description,`auto-skill description`),i=Lp(e.body);await this.assertCategoryExists(n);let a=yi(n,t),o=Si(this.rootDir,n,t);if(await Pp(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=W.join(o,`SKILL.md`),l=W.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:Rp(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:zp(e.evidence,s)};return await U.mkdir(o,{recursive:!0}),await U.writeFile(c,jp(t,r,i),`utf-8`),await Fp(l,u),await ji(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=bi(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Si(this.rootDir,t.categoryPath,t.skillName),r=W.join(n,`SKILL.md`),i=W.join(n,`metadata.json`),a=await Mp(r),o=await Np(i),s=e.description===void 0?a.description:Ip(e.description,`auto-skill description`),c=e.body===void 0?a.body:Lp(e.body),l=this.now().toISOString(),u={...o,skillId:t.skillId,status:o.status===`archived`?`archived`:`active`,categoryPath:t.categoryPath,source:`auto`,tags:e.tags===void 0?Rp(o.tags):Rp(e.tags),confidence:e.confidence??o.confidence,createdAt:typeof o.createdAt==`string`?o.createdAt:l,updatedAt:l,review:{...typeof o.review==`object`&&o.review!==null?o.review:{},...zp(e.evidence,l)}};return await U.writeFile(r,jp(t.skillName,s,c),`utf-8`),await Fp(i,u),await ji(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=bi(e.skillId),n=Si(this.rootDir,t.categoryPath,t.skillName),r=W.join(n,`metadata.json`),i=W.join(n,`SKILL.md`);await U.access(i);let a=await Np(r),o=this.now().toISOString();return await Fp(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...zp(e.evidence,o)}}),await ji(this.rootDir),{action:`archive`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:i,metadataFile:r}}async assertCategoryExists(e){if(!(await this.readCategoryRegistry())[e])throw Error(`Unknown auto-skill category: ${e}. Create it first with create_category.`)}async readCategoryRegistry(){let e=pi(this.rootDir),t;try{t=await U.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=_i(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await U.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await Fp(pi(this.rootDir),t)}};function jp(e,t,n){return[`---`,`name: ${Bp(e)}`,`description: ${Bp(t)}`,`---`,``,n.trim(),``].join(`
|
|
82
|
-
`)}async function Mp(e){let t=ot(await U.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Np(e){let t;try{t=await U.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function Pp(e){try{return await U.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Fp(e,t){await U.mkdir(W.dirname(e),{recursive:!0}),await U.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Ip(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function Lp(e){let t=e.trim();if(!t)throw Error(`Auto-skill body cannot be empty.`);if(t.length<20)throw Error(`Auto-skill body is too short to be useful.`);if(t.startsWith(`---`))throw Error(`Auto-skill body must not include frontmatter; metadata is generated by the store.`);return t}function Rp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function zp(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Bp(e){return JSON.stringify(e)}const Vp=[`create`,`update`,`archive`,`create_category`],Hp=K.Object({}),Up=K.Object({categoryPath:K.Optional(K.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:K.Optional(K.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),Wp=K.Object({query:K.String({description:`Search query for learned auto-skills.`}),limit:K.Optional(K.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),Gp=K.Object({skillId:K.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:K.Optional(K.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),Kp=K.Object({action:K.Union(Vp.map(e=>K.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:K.Optional(K.String({description:`Exact auto-skill id for update/archive.`})),name:K.Optional(K.String({description:`Auto-skill slug for create.`})),categoryPath:K.Optional(K.String({description:`Existing single-level category slug for create.`})),newCategory:K.Optional(K.Object({path:K.String({description:`New single-level category slug to create.`}),description:K.String({description:`New category description.`})})),description:K.Optional(K.String({description:`Auto-skill description for create/update.`})),tags:K.Optional(K.Array(K.String({description:`Auto-skill tag.`}))),confidence:K.Optional(K.Number({description:`Optional confidence score from 0 to 1.`})),body:K.Optional(K.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:K.Optional(K.Object({sessionId:K.String({description:`Source session id.`}),reason:K.String({description:`Why this auto-skill write is justified.`}),toolCallCount:K.Optional(K.Number({description:`Tool calls observed in source run.`})),loadedSkills:K.Optional(K.Array(K.String({description:`Skill loaded during source run.`})))}))});function qp(e){let t=new Mi({dataDir:e});return{name:`auto_skill_categories`,label:`Auto-Skill Categories`,description:`List learned auto-skill categories. Use before auto_skill_list when learned workflows may help.`,parameters:Hp,async execute(){try{let e=await t.autoSkillCategories();return $p({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return $p({categories:[],count:0,error:em(e)})}}}}function Jp(e){let t=new Mi({dataDir:e});return{name:`auto_skill_list`,label:`Auto-Skill List`,description:`List active learned auto-skills by category without loading SKILL.md content.`,parameters:Up,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return $p({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return $p({skills:[],count:0,error:em(e)})}}}}function Yp(e){let t=new Mi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:Wp,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return $p({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return $p({skills:[],count:0,error:em(e)})}}}}function Xp(e){let t=new Mi({dataDir:e});return{name:`auto_skill_view`,label:`Auto-Skill View`,description:`Load an active learned auto-skill by exact skillId, or read a file inside that auto-skill directory.`,parameters:Gp,async execute(e,n){try{return $p({...await t.autoSkillView({skillId:n.skillId,filePath:n.filePath}),usage_hint:n.filePath?`This returned one file inside the auto-skill directory.`:`This returns SKILL.md. If it references helper files, call auto_skill_view({ skillId, filePath }) for only the needed file.`})}catch(e){return $p({skillId:n.skillId,error:em(e)})}}}}function Zp(e){let t=new Ap({dataDir:e});return{name:`auto_skill_manage`,label:`Auto-Skill Manage`,description:`Restricted review-agent tool for creating, updating, archiving learned auto-skills, or creating categories. Do not expose this tool to the main user-facing agent.`,parameters:Kp,async execute(e,n){try{return $p(await Qp(t,n))}catch(e){return $p({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:em(e)})}}}}async function Qp(e,t){if(t.action===`create_category`){if(!t.newCategory)throw Error(`create_category requires newCategory.`);return e.createCategory({path:t.newCategory.path,description:t.newCategory.description})}if(t.action===`create`){if(!t.name||!t.categoryPath||!t.description||!t.body)throw Error(`create requires name, categoryPath, description, and body.`);return e.createSkill({name:t.name,categoryPath:t.categoryPath,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(t.action===`update`){if(!t.skillId)throw Error(`update requires skillId.`);return e.updateSkill({skillId:t.skillId,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(!t.skillId)throw Error(`archive requires skillId.`);return e.archiveSkill({skillId:t.skillId,evidence:t.evidence})}function $p(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function em(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const tm=2,nm=5;var rm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),J.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:ro(e.task),startedAt:e.startedAt})}complete(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`done`,n.record.result=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&J.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){J.info(`subagent status changed`,t);return}if(e.status===`killed`){J.warn(`subagent status changed`,t);return}J.error(`subagent status changed`,t)}};const im=K.Object({task:K.String({description:`The task description for the subagent to execute`}),label:K.Optional(K.String({description:`Optional short label to identify this subagent`})),agent:K.Optional(K.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),am=K.Object({task:K.String({description:`The task description for the subagent to execute`}),label:K.Optional(K.String({description:`Optional short label to identify this subagent`})),agent:K.Optional(K.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),om=K.Object({tasks:K.Array(im,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function sm(e){let t=e.label?`"${e.label}"`:`task: ${Je(e.task)}`;return e.status===`done`?`${t}\n\n${cm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function cm(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function lm(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(J.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:ro(p)}),!p){let e={status:`error`,error:`task must not be empty`};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=nt(),v=new AbortController,y=t,b=Sa(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await T(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return J.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}J.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?Oa(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),J.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,J.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=sm({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``};return J.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return J.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:w}],isError:!0,details:E}}function um(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?"IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. You MUST also use this tool when the user mentions '@<agent-name>' where <agent-name> matches a custom agent listed in the Custom Agents section — set the `agent` field to that exact name. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. ":`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:am,async execute(e,t){return lm(u,e,t)}}}function dm(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:om,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}J.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await lm(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${cm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
|
|
83
|
+
`)}\n</available_skills>`}const pp=q.Object({category:q.Optional(q.String({description:`Reserved category filter field. Not used yet.`}))}),mp=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 hp(e,t,n=[]){return[...n,...t,ep(e)]}function gp(e,t,n=[]){let r=hp(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:pp,async execute(e,t){let n=await cp(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 _p(e){let t=hp(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:mp,async execute(r,i){let a=await dp(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 vp=q.Object({});function yp(e,t,n){return{name:`get_goal`,label:`Get Goal`,description:"Get the current thread goal, including status, budget, token and time usage, remaining token budget, and V2-lite workflow summary (`goalState`). Returns null when no goal is set.",parameters:vp,async execute(r,i){let a=await U(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,goalState:null,workflowWarning:null})}],details:{}};let o=await z(e,t,a,{storeName:n}),s=await yn(e,t,{storeName:n}),c={goal:{...a,objective:o,remainingTokens:a.tokenBudget===null?void 0:Math.max(0,a.tokenBudget-a.tokensUsed)},goalState:s.goalState,workflowWarning:s.workflowWarning};return{content:[{type:`text`,text:JSON.stringify(c,null,2)}],details:{}}}}}q.Object({status:q.String({description:`Status to set. Only 'complete' is allowed.`})});function bp(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 xp(e){let t=bp(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=G.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Sp(e){let t=e.watchFactory??((e,t,n)=>K.watch(e,t,n)),n=G.join(e.dataDir,`.aimax`),r=[{target:G.join(n,`MEMORY.md`),kind:`memory-file`},{target:G.join(n,`memory.md`),kind:`memory-file-lower`},{target:G.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=xp({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function Z(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function Cp(e){return e.projectDir?.trim()||G.join(e.dataDir,`workspace`)}async function wp(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Cp(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Dp(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:m?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}p.source===`sessions`?await n.dispatchDiagnostic(e.sessionId??i,{level:`info`,scope:`memory`,phase:p.reason,message:`session transcript changed`,details:{reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}}).catch(()=>{}):await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=G.join(t.dataDir,`.aimax`),m=he({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g=m?.provider??ue({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),_=m?.registration.id??g.id,v=m?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:m?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!m}}).catch(()=>{});let y=Sp({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await h(t.dataDir,i,e,Ep({sessionOptions:Z(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function Tp(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Ep(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 Dp(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function Q(e){return{storeName:e.sessionStoreName}}function Op(e){return Cp({dataDir:e.dataDir,projectDir:e.projectDir})}function kp(e){return Fn({dataDir:e.dataDir,workspaceDir:Op(e),projectDir:e.projectDir})}function Ap(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function $(e,t){return Ap({ok:!1,error:e,...t})}function jp(e,t){return ln(e.dataDir,e.sessionId,Q(e),t)}async function Mp(e){try{return await gn(e.dataDir,e.sessionId,Q(e))}catch(e){if(e instanceof on)return{corrupt:!0};throw e}}function Np(){return $(`workflow_corrupt`,{repairTool:`goal_repair_workflow_state`})}const Pp={hint:[`Use only the returned evidenceRef values from goal_record_evidence.`,`Natural-language descriptions, file paths, and strings such as 'goal/state.json ...' are not evidence refs unless they are registered in goal/artifacts/registry.jsonl.`,`If command output should prove an acceptance criterion, run it with goal_record_evidence(kind='exec'); regular exec output is not registered goal evidence.`].join(` `),suggestedTools:[`goal_record_evidence`],example:{registerManualEvidence:{tool:`goal_record_evidence`,args:{kind:`manual`,source:`goal/state.json`,summary:`planning evidence`,content:`Task list and acceptance criteria were added to goal/state.json.`}},registerCommandEvidence:{tool:`goal_record_evidence`,args:{kind:`exec`,command:`npm test`,cwd:`<workspace>`,timeoutMs:12e4}},registerSnapshotEvidence:{tool:`goal_record_evidence`,args:{kind:`snapshot`,path:`<workspace>/artifact.html`,summary:`final deliverable`}},evidenceRefs:[`manual:...`]}},Fp=/goal[/\\]state\.json|\btask\s*list\b|\btask-\d+|\b(plan|planning|planned|added|through|workflow)\b/i,Ip=/[/\\]|\.(?:html|css|js|ts|tsx|jsx|json|md|txt|py|go|rs|yaml|yml|sh)\b|\bexists\b/i,Lp=/\b(npm|pnpm|yarn|cargo|go test|pytest|vitest|jest|exit code|stdout|stderr|command output|test pass|tests pass)\b/i;function Rp(e,t){let n=`${e}\n${t}`;return Fp.test(n)?`goal/state.json`:/\buser\b/i.test(n)&&/\bconfirm/i.test(n)?`user`:`model`}function zp(e){let t=e.match(/^(.+?)\s+exists\s*$/i);if(t)return t[1].trim();let n=e.match(/(?:^|\s)((?:[\w.-]+\/)+[\w.-]+\.\w{1,10})(?:\s|$)/);return n?n[1].trim():/^[\w./-]+\.\w{1,10}$/.test(e.trim())?e.trim():null}function Bp(e){let t=e.trim();return Fp.test(t)?{reason:`the ref describes planning state`}:Ip.test(t)?{reason:zp(t)?`the ref describes a file artifact`:`the ref describes a file artifact but no reliable path could be extracted`}:Lp.test(t)?{reason:`the ref describes command output`}:{reason:`the ref is natural language and must be registered as evidence`}}function Vp(e){let t=e.trim();if(Fp.test(t))return{kind:`manual`,source:`goal/state.json`,summary:t.slice(0,120),content:t};if(Ip.test(t)){let e=zp(t);if(e)return{kind:`snapshot`,path:e,summary:t.slice(0,120)}}return Lp.test(t)?{kind:`exec`,command:t.includes(`npm test`)?`npm test`:`<command>`,cwd:`<workspace>`,timeoutMs:12e4}:{kind:`manual`,source:Rp(t,t),summary:t.slice(0,120),content:t}}function Hp(e){let t=new Set,n=[];for(let r of e){if(r.code!==`unregistered_evidence_ref`||!r.ref.trim())continue;let e=r.ref.trim();if(t.has(e))continue;t.add(e);let i=Bp(e);n.push({tool:`goal_record_evidence`,reason:i.reason,args:Vp(e)})}return n}function Up(e){let t=e.errors[0]?.code??`invalid_evidence`;return t===`unregistered_evidence_ref`?$(t,{errors:e.errors,repairPlan:Hp(e.errors),...Pp}):$(t,{errors:e.errors})}function Wp(e,t){return $(`manual_source_required`,{hint:`Manual evidence requires a source. Use source='goal/state.json' for plan/workflow facts, source='user' for user confirmation, or another concise origin string.`,retryWith:{kind:`manual`,source:Rp(e,t),summary:e,content:t},example:{kind:`manual`,source:`goal/state.json`,summary:`planning evidence`,content:`Task list and acceptance criteria were added to goal/state.json.`}})}function Gp(e){let t=Xn(e.length);return e.map((e,n)=>typeof e==`string`?{id:t[n],text:e.trim(),required:!0}:{id:t[n],text:e.text.trim(),required:e.required!==!1}).filter(e=>e.text.length>0)}function Kp(e,t){let n=new Set;for(let t of e??[])t.trim()&&n.add(t.trim());for(let e of t??[])for(let t of e.evidenceRefs??[])t.trim()&&n.add(t.trim());return[...n]}function qp(e,t){return e.tasks.find(e=>e.id===t)}function Jp(e){return e.tasks.some(e=>e.kind===`execution`&&e.required!==!1)}function Yp(e){return e.ok===!1?e.warning:null}async function Xp(e,t){await Wn(e.dataDir,e.sessionId,t,Q(e));let n=Yp(await Jn(e.dataDir,e.sessionId,t,Q(e)));return n?{planWarning:n}:{}}function Zp(e){return{name:`goal_plan_update`,label:`Goal Plan Update`,description:`Update controlled sections of goal/plan.md without changing task workflow state.`,parameters:q.Object({interpretation:q.Optional(q.String()),assumptions:q.Optional(q.Array(q.String())),openQuestions:q.Optional(q.Array(q.String())),taskPlanNotes:q.Optional(q.String())}),async execute(t,n){return jp(e,async()=>{let t=await Mp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return Np();let r=t;await J(e.dataDir,e.sessionId,{type:`goal_plan_updated`,goalId:r.goalId,interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Q(e));let i=await qn(e.dataDir,e.sessionId,{interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Q(e)),a=await Jn(e.dataDir,e.sessionId,r,Q(e));return Ap({ok:!0,goalId:r.goalId,planMeta:i,warning:Yp(a),hint:`Use goal_add_task to project executable tasks into goal/state.json.`})})}}}function Qp(e){return{name:`goal_task_done`,label:`Goal Task Done`,description:`Mark the current doing task done with evidence covering required acceptance criteria.`,parameters:q.Object({taskId:q.String(),summary:q.Optional(q.String()),evidenceRefs:q.Optional(q.Array(q.String())),acceptanceEvidence:q.Optional(q.Array(q.Object({criterionId:q.String(),evidenceRefs:q.Array(q.String())})))}),async execute(t,n){return jp(e,async()=>{let t=await Mp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return Np();let r=t,i=qp(r,n.taskId);if(!i)return $(`task_not_found`);if(i.status!==`doing`)return $(`task_not_doing`);if(i.acceptanceCriteria.length===0)return $(`missing_acceptance_criteria`);let a=Kp(n.evidenceRefs,n.acceptanceEvidence);if(a.length===0)return $(`missing_evidence_refs`);let o=i.acceptanceCriteria.filter(e=>e.required!==!1),s=new Map;for(let e of n.acceptanceEvidence??[])s.set(e.criterionId,e.evidenceRefs??[]);for(let e of o)if((s.get(e.id)??[]).length===0)return $(`missing_required_acceptance_evidence`,{criterionId:e.id});let c=await Hn(e.dataDir,e.sessionId,a,Q(e));if(!c.valid)return Up(c);if(i.kind===`clarify`){if(!Jp(r))return $(`missing_executable_followup_task`);if(!a.some(e=>e.startsWith(`note:`)||e.startsWith(`manual:`)))return $(`clarify_requires_note_or_manual_evidence`)}let l=new Date().toISOString(),u={};for(let e of n.acceptanceEvidence??[])u[e.criterionId]=e.evidenceRefs??[];let d=r.tasks.map(e=>e.id===i.id?{...e,status:`done`,acceptanceEvidence:Object.keys(u),evidenceRefs:a,updatedAt:l}:e),f=d.find(e=>e.status===`todo`&&e.required!==!1),p=d.map(e=>f&&e.id===f.id?{...e,status:`doing`,updatedAt:l}:e),m={...r,tasks:p,currentTaskId:f?.id??null,status:`active`,blockedReason:null,updatedAt:l};await J(e.dataDir,e.sessionId,{type:`goal_task_done`,goalId:r.goalId,taskId:i.id,summary:n.summary,acceptanceEvidence:n.acceptanceEvidence,evidenceRefs:a},Q(e));let h=await Gn(e.dataDir,e.sessionId,Q(e));await qn(e.dataDir,e.sessionId,{progressLog:[...h.progressLog??[],`${l.slice(0,16).replace(`T`,` `)}: ${n.summary??`Completed ${i.id}`}`],criterionEvidence:{[i.id]:Object.keys(u)},evidence:a},Q(e));let{planWarning:g}=await Xp(e,m);return Ap({ok:!0,currentTaskId:m.currentTaskId,hint:m.currentTaskId?null:`All tasks done. Call goal_complete with finalEvidenceRefs.`,warning:g??null})})}}}function $p(e){return{name:`goal_task_blocked`,label:`Goal Task Blocked`,description:`Mark a task and the workflow as blocked without changing goal/goal.json status.`,parameters:q.Object({taskId:q.String(),reason:q.String(),neededInput:q.Optional(q.String()),evidenceRefs:q.Optional(q.Array(q.String()))}),async execute(t,n){return jp(e,async()=>{let t=await Mp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return Np();let r=t,i=qp(r,n.taskId);if(!i)return $(`task_not_found`);let a=n.evidenceRefs??[];if(a.length>0){let t=await Hn(e.dataDir,e.sessionId,a,{...Q(e),requireCommandSuccess:!1});if(!t.valid)return $(t.errors[0]?.code??`invalid_evidence`,{errors:t.errors})}let o=new Date().toISOString(),s=n.neededInput?`${n.reason} (needed: ${n.neededInput})`:n.reason,c=r.tasks.map(e=>e.id===i.id?{...e,status:`blocked`,blockedReason:s,updatedAt:o}:e),l={...r,status:`blocked`,blockedReason:s,currentTaskId:i.id,tasks:c,updatedAt:o};await J(e.dataDir,e.sessionId,{type:`goal_task_blocked`,goalId:r.goalId,taskId:i.id,reason:n.reason,neededInput:n.neededInput,evidenceRefs:a},Q(e)),await qn(e.dataDir,e.sessionId,{risks:[s]},Q(e));let{planWarning:u}=await Xp(e,l);return Ap({ok:!0,workflowStatus:`blocked`,warning:u??null})})}}}function em(e){return{name:`goal_add_task`,label:`Goal Add Task`,description:`Add a new execution task to goal/state.json. Concurrent calls in the same turn are serialized; add tasks one at a time or rely on the store lock.`,parameters:q.Object({title:q.String(),kind:q.Optional(q.Literal(`execution`)),required:q.Optional(q.Boolean()),acceptanceCriteria:q.Array(q.Union([q.String(),q.Object({text:q.String(),required:q.Optional(q.Boolean())})])),afterTaskId:q.Optional(q.String()),startNow:q.Optional(q.Boolean())}),async execute(t,n){return jp(e,async()=>{let t=await Mp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return Np();let r=t;if((n.kind??`execution`)!==`execution`)return $(`invalid_task_kind`);if(n.acceptanceCriteria.length===0)return $(`missing_acceptance_criteria`);let i=new Date().toISOString(),a=Yn(r.tasks),o=Gp(n.acceptanceCriteria),s={id:a,kind:`execution`,title:n.title.trim(),required:n.required!==!1,status:n.startNow?`doing`:`todo`,acceptanceCriteria:o,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:i},c=[...r.tasks];if(n.afterTaskId){let e=c.findIndex(e=>e.id===n.afterTaskId);if(e<0)return $(`after_task_not_found`);c.splice(e+1,0,s)}else c.push(s);n.startNow&&(c=c.map(e=>e.id===a?s:e.status===`doing`?{...e,status:`todo`,updatedAt:i}:e));let l={...r,tasks:c,currentTaskId:n.startNow?a:r.currentTaskId,updatedAt:i};await J(e.dataDir,e.sessionId,{type:`goal_task_added`,goalId:r.goalId,taskId:a,kind:`execution`,required:s.required,acceptanceCriteria:o},Q(e));let{planWarning:u}=await Xp(e,l);return Ap({ok:!0,taskId:a,warning:u??null})})}}}function tm(e){return{name:`goal_record_evidence`,label:`Goal Record Evidence`,description:`Record note/manual/exec/snapshot evidence and return an evidenceRef for goal_task_done or goal_complete.`,parameters:q.Object({kind:q.Union([q.Literal(`note`),q.Literal(`manual`),q.Literal(`exec`),q.Literal(`snapshot`)]),summary:q.Optional(q.String()),content:q.Optional(q.String()),taskId:q.Optional(q.String()),source:q.Optional(q.String()),command:q.Optional(q.String()),cwd:q.Optional(q.String()),timeoutMs:q.Optional(q.Number()),path:q.Optional(q.String())}),async execute(t,n){let r=await Mp(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return Np();let i=r;if(n.kind===`note`||n.kind===`manual`){if(!n.summary?.trim())return $(`missing_summary`);if(!n.content?.trim())return $(`missing_content`);let t=await Zn(e.dataDir,e.sessionId,{kind:n.kind,summary:n.summary,content:n.content,source:n.source},Q(e));return`error`in t?t.error===`manual evidence requires source`?Wp(n.summary,n.content):$(t.error):(await J(e.dataDir,e.sessionId,{type:`goal_note_recorded`,goalId:i.goalId,taskId:n.taskId,evidenceRef:t.evidenceRef,kind:n.kind,summary:n.summary,source:n.source??`model`},Q(e)),Ap({ok:!0,evidenceRef:t.evidenceRef}))}if(n.kind===`exec`){if(!n.command?.trim())return $(`missing_command`);let t=await Qn(e.dataDir,e.sessionId,{command:n.command,cwd:n.cwd,timeoutMs:n.timeoutMs,workspaceDir:Op(e),allowedRoots:kp(e),baseEnv:e.baseEnv},Q(e));return`error`in t?$(t.error):(await J(e.dataDir,e.sessionId,{type:`goal_command_recorded`,goalId:i.goalId,evidenceRef:t.evidenceRef,command:n.command,cwd:n.cwd??Op(e),exitCode:t.exitCode},Q(e)),Ap({ok:!0,evidenceRef:t.evidenceRef,exitCode:t.exitCode}))}if(!n.path?.trim())return $(`missing_path`);let a=await er(e.dataDir,e.sessionId,{path:n.path,summary:n.summary,workspaceDir:Op(e),allowedRoots:kp(e)},Q(e));return`error`in a?$(a.error):(await J(e.dataDir,e.sessionId,{type:`goal_snapshot_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,path:n.path},Q(e)),Ap({ok:!0,evidenceRef:a.evidenceRef}))}}}function nm(e){return{name:`goal_complete`,label:`Goal Complete`,description:`Complete the goal after all required tasks are done and final evidence is recorded.`,parameters:q.Object({summary:q.String(),finalEvidenceRefs:q.Array(q.String()),risks:q.Optional(q.Array(q.String()))}),async execute(t,n){return jp(e,async()=>{let t=await Mp(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return Np();let r=t,i=r.tasks.filter(e=>e.required!==!1),a=i.filter(e=>e.status!==`done`);if(a.length>0)return $(`required_tasks_not_done`,{pendingTaskIds:a.map(e=>e.id)});if(i.filter(e=>e.status===`blocked`).length>0)return $(`blocked_tasks_remain`);for(let e of i)if((e.evidenceRefs??[]).length===0)return $(`done_task_missing_evidence`,{taskId:e.id});if(n.finalEvidenceRefs.length===0)return $(`missing_final_evidence_refs`);let o=await Hn(e.dataDir,e.sessionId,n.finalEvidenceRefs,Q(e));if(!o.valid)return Up(o);let s=new Date().toISOString(),c={...r,status:`complete`,finalEvidenceRefs:n.finalEvidenceRefs,completedAt:s,currentTaskId:null,updatedAt:s};if(!await U(e.dataDir,e.sessionId,Q(e)))return $(`goal_not_found`);await Wn(e.dataDir,e.sessionId,c,Q(e));try{await V(e.dataDir,e.sessionId,{status:`complete`},{...Q(e),eventSource:`tool`})}catch(t){throw await Wn(e.dataDir,e.sessionId,r,Q(e)),t}return await J(e.dataDir,e.sessionId,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:n.finalEvidenceRefs,summary:n.summary,risks:n.risks??[]},Q(e)),await qn(e.dataDir,e.sessionId,{finalSummary:n.summary,evidence:n.finalEvidenceRefs,risks:n.risks},Q(e)),Ap({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,warning:Yp(await Jn(e.dataDir,e.sessionId,c,Q(e)))})})}}}function rm(e){return{name:`goal_repair_workflow_state`,label:`Goal Repair Workflow State`,description:`Reinitialize unreadable goal/state.json from the saved objective. Requires confirm:true.`,parameters:q.Object({confirm:q.Literal(!0)}),async execute(t,n){return Ap(await jp(e,()=>_n(e.dataDir,e.sessionId,Q(e))))}}}function im(e){return[Zp(e),em(e),tm(e),Qp(e),$p(e),rm(e),nm(e)]}var am=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=G.resolve(e.rootDir??di(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=gi(e.path),n=dm(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 Ai(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:fi(this.rootDir)}}async createSkill(e){let t=_i(e.name),n=gi(e.categoryPath),r=dm(e.description,`auto-skill description`),i=fm(e.body);await this.assertCategoryExists(n);let a=vi(n,t),o=xi(this.rootDir,n,t);if(await lm(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=G.join(o,`SKILL.md`),l=G.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:pm(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:mm(e.evidence,s)};return await W.mkdir(o,{recursive:!0}),await W.writeFile(c,om(t,r,i),`utf-8`),await um(l,u),await Ai(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=yi(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=xi(this.rootDir,t.categoryPath,t.skillName),r=G.join(n,`SKILL.md`),i=G.join(n,`metadata.json`),a=await sm(r),o=await cm(i),s=e.description===void 0?a.description:dm(e.description,`auto-skill description`),c=e.body===void 0?a.body:fm(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?pm(o.tags):pm(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:{},...mm(e.evidence,l)}};return await W.writeFile(r,om(t.skillName,s,c),`utf-8`),await um(i,u),await Ai(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=yi(e.skillId),n=xi(this.rootDir,t.categoryPath,t.skillName),r=G.join(n,`metadata.json`),i=G.join(n,`SKILL.md`);await W.access(i);let a=await cm(r),o=this.now().toISOString();return await um(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...mm(e.evidence,o)}}),await Ai(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=fi(this.rootDir),t;try{t=await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=gi(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await W.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await um(fi(this.rootDir),t)}};function om(e,t,n){return[`---`,`name: ${hm(e)}`,`description: ${hm(t)}`,`---`,``,n.trim(),``].join(`
|
|
84
|
+
`)}async function sm(e){let t=at(await W.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function cm(e){let t;try{t=await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function lm(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function um(e,t){await W.mkdir(G.dirname(e),{recursive:!0}),await W.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function dm(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function fm(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 pm(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function mm(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function hm(e){return JSON.stringify(e)}const gm=[`create`,`update`,`archive`,`create_category`],_m=q.Object({}),vm=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.`}))}),ym=q.Object({query:q.String({description:`Search query for learned auto-skills.`}),limit:q.Optional(q.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),bm=q.Object({skillId:q.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:q.Optional(q.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),xm=q.Object({action:q.Union(gm.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 Sm(e){let t=new ji({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:_m,async execute(){try{let e=await t.autoSkillCategories();return Om({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return Om({categories:[],count:0,error:km(e)})}}}}function Cm(e){let t=new ji({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:vm,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return Om({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Om({skills:[],count:0,error:km(e)})}}}}function wm(e){let t=new ji({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:ym,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return Om({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Om({skills:[],count:0,error:km(e)})}}}}function Tm(e){let t=new ji({dataDir:e});return{name:`auto_skill_view`,label:`Auto-Skill View`,description:`Load an active learned auto-skill by exact skillId, or read a file inside that auto-skill directory.`,parameters:bm,async execute(e,n){try{return Om({...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 Om({skillId:n.skillId,error:km(e)})}}}}function Em(e){let t=new am({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:xm,async execute(e,n){try{return Om(await Dm(t,n))}catch(e){return Om({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:km(e)})}}}}async function Dm(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 Om(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function km(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const Am=2,jm=5;var Mm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),Y.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:no(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&&Y.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`){Y.info(`subagent status changed`,t);return}if(e.status===`killed`){Y.warn(`subagent status changed`,t);return}Y.error(`subagent status changed`,t)}};const Nm=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.`}))}),Pm=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.`}))}),Fm=q.Object({tasks:q.Array(Nm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Im(e){let t=e.label?`"${e.label}"`:`task: ${qe(e.task)}`;return e.status===`done`?`${t}\n\n${Lm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Lm(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 Rm(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(Y.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:no(p)}),!p){let e={status:`error`,error:`task must not be empty`};return Y.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 Y.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=tt(),v=new AbortController,y=t,b=xa(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return Y.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 Y.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}Y.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),Y.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,Y.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=Im({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 Y.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 Y.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 zm(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:Pm,async execute(e,t){return Rm(u,e,t)}}}function Bm(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:Fm,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}}Y.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 Rm(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${Lm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
|
|
83
85
|
|
|
84
|
-
`);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const
|
|
85
|
-
`)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=
|
|
86
|
+
`);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const Vm=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 Hm(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 Um(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function Wm(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:Vm,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} (${Hm(e.runtimeMs)})${n}`})).join(`
|
|
87
|
+
`)};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=Um(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}const Gm=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 Km(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Gm,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}const qm=q.Object({reason:q.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Jm(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??qm,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=Xe(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new $o(e,i,t,e,o,s,n);throw cs(r),r}}}function Ym(e,t){let n=Cp({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??tn(),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=[_d({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),xd({registry:i,scopeKey:n}),Od(n,t?.contextManager),Ad(n,t?.contextManager,s),Md(n,t?.contextManager,s),Pd(n),Vd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[yp(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),...im({dataDir:e,sessionId:t.sessionId,sessionStoreName:t.inheritedRunParams?.sessionStoreName,projectDir:t.inheritedRunParams?.projectDir,baseEnv:t.baseEnv})]:[],mf(e,r),If(e,r),gf(e,r),bf(e,r),Of(e,r),Af(e,r),Mf(e,r),Pf(e,r),gp(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),_p({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(Sm(e),Cm(e),wm(e),Tm(e)),t&&c.push(zm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Bm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Wm(t.registry,t.parentSessionId)),c}function Xm(e){return e.length===0?``:[`## Auto-Skills`,`Auto-skills are learned from prior completed tasks and are stored separately from curated/user/plugin skills.`,`Auto-skill categories are single-level routing slugs in the current MVP.`,`Prefer curated/user/plugin skills from <available_skills> when both options apply.`,`Use auto-skills only when they clearly match the current task, especially project-specific or previously learned workflows.`,"Match the task to one or more category paths below, call `auto_skill_list({ categoryPath })`, then call `auto_skill_view({ skillId })` for the best match.","If no category is clear but an auto-skill may help, call `auto_skill_search({ query, limit: 5 })`.",`Archived auto-skills are not listed or loaded.`,`<auto_skill_categories>`,[...e].sort((e,t)=>e.path.localeCompare(t.path)).map(e=>e.description?` - ${e.path} | ${e.description}`:` - ${e.path}`).join(`
|
|
86
88
|
`),`</auto_skill_categories>`,``].join(`
|
|
87
|
-
`)}const
|
|
89
|
+
`)}const Zm={get_goal:`Get the current thread goal including status, budget, usage, and workflow summary`,goal_plan_update:`Update controlled planning sections without changing workflow task state`,goal_add_task:`Add an execution task with acceptance criteria to the goal workflow`,goal_record_evidence:`Record note/manual/exec/snapshot evidence and return an evidenceRef`,goal_task_done:`Mark the current task done with evidence covering required acceptance criteria`,goal_task_blocked:`Mark the current task and workflow blocked with a clear reason`,goal_repair_workflow_state:`Repair corrupt goal workflow state from the saved objective`,goal_complete:`Complete the goal after required tasks and final evidence are recorded`,read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,auto_skill_categories:`List learned auto-skill categories`,auto_skill_list:`List active learned auto-skills by category`,auto_skill_search:`Search active learned auto-skills`,auto_skill_view:`Load an active learned auto-skill by exact skillId`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Qm=`read_file.write_file.edit_file.list_dir.apply_patch.exec.process.skill_list.skill_load.get_goal.goal_plan_update.goal_add_task.goal_record_evidence.goal_task_done.goal_task_blocked.goal_repair_workflow_state.goal_complete.auto_skill_categories.auto_skill_list.auto_skill_search.auto_skill_view.memory_search.memory_get.memory_write.memory_log.memory_list.memory_forget.memory_update.session_search.subagent_spawn.subagents`.split(`.`);function $m(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:[...Qm.filter(e=>t.has(e)),...n.filter(e=>!Qm.includes(e)).sort()],displayName:t}}function eh(e){let{ordered:t,displayName:n}=$m(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??Zm[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
|
|
88
90
|
`),``].join(`
|
|
89
|
-
`)}function
|
|
90
|
-
`)}function
|
|
91
|
-
`)}function
|
|
92
|
-
`)}function
|
|
93
|
-
`)}function
|
|
91
|
+
`)}function th(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Use `get_goal` to view the current goal, its status, budget, usage, and V2-lite workflow summary (`goalState`).",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,"- When V2-lite workflow is active, complete tasks with `goal_task_done` and finish the goal with `goal_complete` (with evidence refs).","- Use `goal_record_evidence` to create evidence refs before filling `evidenceRefs`, `acceptanceEvidence`, or `finalEvidenceRefs`.","- Do NOT call `goal_complete` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and goal workflow tools report an error.",``].join(`
|
|
92
|
+
`)}function nh(){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(`
|
|
93
|
+
`)}function rh(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
|
|
94
|
+
`)}function ih(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(`
|
|
95
|
+
`)}function ah(){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(`
|
|
96
|
+
`)}function oh(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
|
|
94
97
|
`)).join(`
|
|
95
98
|
`)}\n</available_skills>`,``].join(`
|
|
96
|
-
`)}function
|
|
97
|
-
`)}function
|
|
98
|
-
`)}function
|
|
99
|
-
`)}function
|
|
100
|
-
`)}function
|
|
101
|
-
`)}function
|
|
102
|
-
`)}function
|
|
103
|
-
`)}function
|
|
104
|
-
`)}function
|
|
105
|
-
`)}function
|
|
106
|
-
`)}function
|
|
107
|
-
`)}function
|
|
108
|
-
`):``}function
|
|
109
|
-
`)}const
|
|
110
|
-
`):void 0}var
|
|
111
|
-
`).trim()}function
|
|
112
|
-
|
|
113
|
-
`))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(
|
|
114
|
-
|
|
115
|
-
`))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const
|
|
99
|
+
`)}function sh(e=[]){let t=Xm(e).trim();return t?`${t}\n`:``}function ch(){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(`
|
|
100
|
+
`)}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(`
|
|
101
|
+
`)}function uh(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(`
|
|
102
|
+
`)}function dh(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(`
|
|
103
|
+
`)}function fh(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(`
|
|
104
|
+
`)}function ph(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=mh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
|
|
105
|
+
`)}function mh(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 hh(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(`
|
|
106
|
+
`)}function gh(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
|
|
107
|
+
`)}function _h(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(`
|
|
108
|
+
`)}function vh(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(`
|
|
109
|
+
`)}function yh(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(`
|
|
110
|
+
`)}function bh(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(`
|
|
111
|
+
`):``}function xh(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Qm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,yh(e.subagentDepth??0),eh({toolNames:i,toolSummaries:e.toolSummaries}),ah(),ih(n),th(),nh(),Ea(e.availableAgents??[]),oh(a),sh(e.autoSkillCategories),ch(),lh(),uh(e.memoryCitationsMode??`off`),dh({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),fh(e.sandboxInfo),ph({currentDate:e.currentDate,timezone:e.timezone}),rh(),hh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),_h({isMinimal:n}),gh(e.runtimeInfo),vh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),bh(e.priorConversationSummary)].filter(Boolean).join(`
|
|
112
|
+
`)}const Sh=Symbol(`pluginToolOwner`);var Ch=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,Sh,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=Jm({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,Sh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function wh(e){return e[Sh]}function Th(e,t,n){return e.map(e=>{let r=e,i=wh(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await Pa({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(Qo(e))return is(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function Eh(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 Dh(e,t){let n=e.content,r=jh(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=Oh(n,e.content)),e.details!==void 0){let t=jh(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function Oh(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?kh(e,t)?t:[...e,...t]:t}function kh(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!Ah(e[n],t[n]))return!1;return!0}function Ah(e,t){return JSON.stringify(e)===JSON.stringify(t)}function jh(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function Mh(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),Qo(t))return is(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=Eh(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(Qo(e))return is(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=Dh({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?Nh(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 Nh(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(`
|
|
113
|
+
`):void 0}var Ph=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 Fh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Ih(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Lh(e){let t=Ih(e?.warningThreshold,Fh.warningThreshold),n=Ih(e?.criticalThreshold,Fh.criticalThreshold),r=Ih(e?.globalCircuitBreakerThreshold,Fh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Fh.enabled,historySize:Ih(e?.historySize,Fh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Fh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Fh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Fh.detectors.pingPong}}}function Rh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function zh(e,t){return`${e}:${Hh(t)}`}function Bh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Bh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Bh(t[e])}`).join(`,`)}}`}function Vh(e){try{return Bh(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 Hh(e){let t=Vh(e);return $e(`sha256`).update(t).digest(`hex`)}function Uh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Rh(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Wh(e){return!Rh(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Rh(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
114
|
+
`).trim()}function Gh(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Bh(e)}function Kh(e,t,n,r){if(r!==void 0)return`error:${Hh(Gh(r))}`;if(!Rh(n))return n===void 0?void 0:Hh(n);let i=Rh(n.details)?n.details:{},a=Wh(n);if(Uh(e,t)&&e===`process`&&Rh(t)){let e=t.action;if(e===`poll`)return Hh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Hh({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 Hh({details:i,text:a})}function qh(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 Jh(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function Yh(e,t){return[e,t].toSorted().join(`|`)}function Xh(e,t,n,r){let i=Lh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=zh(t,n),s=qh(a,t,o),c=s.count,l=Uh(t,n),u=Jh(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${Yh(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function Zh(e,t,n,r,i){let a=Lh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:zh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Qh(e,t){let n=Lh(t.config),r=Kh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=zh(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 $h(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function eg(e){return e&&e.trim()||`tool`}function tg(e,t,n){if(!e.execute)return e;let r=eg(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Xh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);$h(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Zh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Qh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Qh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function ng(e,t,n){return e.map(e=>tg(e,t,n))}const rg=new Map;function ig(e){let t=rg.get(e);return t||(t={},rg.set(e,t)),t}function ag(e){rg.delete(e)}function og(e){let t=e.streamFn??_t;return(e,n,r)=>(e.api===`anthropic-messages`&&sg(e),t(e,n,{...r,...mg(e,r)}))}function sg(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>ug(pg(e),n)?(globalThis.fetch=t,cg(await t(e,dg(e,r)))):t(e,r))}function cg(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(`
|
|
115
|
+
|
|
116
|
+
`))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(lg))),a.enqueue(r.encode(e+`
|
|
117
|
+
|
|
118
|
+
`))}},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 lg=`event: message_start
|
|
116
119
|
data: {"type":"message_start","message":{"id":"","type":"message","role":"assistant","content":[],"model":"","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}
|
|
117
120
|
|
|
118
|
-
`;function
|
|
121
|
+
`;function ug(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function dg(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))fg(e)&&n.delete(e);return{...t,headers:n}}function fg(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 pg(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function mg(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function hg(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,Z(t)),T={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},E=vc(t.llm),D=await ad({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 od({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 vg({sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let k=t.subagentContext?.depth??0,A=r(t.dataDir,n,Z(t)),j=tn(),M=Ta([...Ym(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,registry:_,processRegistry:j,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:h,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:x,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:m,skillsLoadPaths:h,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:s,spawnFn:v,baseEnv:t.env}),...p],S),N=M.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),P={};for(let e of M){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||P[t]||(P[t]=n)}let ee=t.messaging?.enabled??t.channel!==`CRON`,I=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],L=xh({dataDir:t.dataDir,projectDir:t.projectDir,skills:wa(u,S),autoSkillCategories:x?d:[],contextFiles:c,toolNames:N,toolSummaries:P,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:ee,channels:I},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:nt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await _g({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},te=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:R},a,{eventDispatcher:s}),z=await i.dispatch(`before_prompt_build`,{prompt:f},a,{eventDispatcher:s});z.length>0&&console.warn(`[AgentRuntime] before_prompt_build hook(s) fired; this hook is deprecated in favor of before_agent_start. Migrate plugins to before_agent_start.`);let B=[];for(let e of te){if(!e)continue;let t=e;t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`),t.message&&B.push(t.message)}for(let e of z){if(!e)continue;let t=e;t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`)}await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:L},a,{eventDispatcher:s});let V=ng(Th(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},ig),H=S?.model??t.llm.model,ne=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of ne)e&&e.modelOverride&&(H=e.modelOverride);let re=y({...t.llm,model:H},n,t.messageId,t.channel);try{await uc(t.dataDir,n,{systemPrompt:L,tools:V},Z(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let U=new ot({initialState:{systemPrompt:L,model:re,tools:V,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:og({})}),ie={eventDispatcher:s};a.signal=b;let ae=new Ph;return a.toolParamOverrides=ae,Mh({agent:U,hookRegistry:i,hookContext:a,pluginRuntime:ie,overrideStore:ae}),O.messages.length>0&&(U.state.messages=O.messages),B.length>0&&(U.state.messages=[...B,...U.state.messages]),{agent:U,resolvedModelId:H,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function gg(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 _g(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 vg(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount,s=yg(await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i})),c=s.injectRecall?{...n.compactionEntry,content:`${s.injectRecall.trim()}\n\n${n.compactionEntry.content}`}:n.compactionEntry;if(s.skipPersist){await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!s.injectRecall}});return}await r.appendTranscriptEntry(c),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o,{eventDispatcher:i})}}function yg(e){let t=!1,n=[];for(let r of e)r&&(r.skipPersist&&(t=!0),typeof r.injectRecall==`string`&&r.injectRecall.trim().length>0&&n.push(r.injectRecall.trim()));return{skipPersist:t,injectRecall:n.length>0?n.join(`
|
|
119
122
|
|
|
120
|
-
`):void 0}}function
|
|
123
|
+
`):void 0}}function bg(e){return e.some(e=>Cg(e.message)!==null||e.toolResults.length>0)}function xg(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 Sg(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 Cg(e){let t=kg(e),n=wg(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 wg(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function Tg(e){return e.map(e=>wg(e.message)).filter(e=>e.trim().length>0).join(`
|
|
121
124
|
|
|
122
|
-
`)}function
|
|
125
|
+
`)}function Eg(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Dg(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 Og(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:Ag(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function kg(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ag(e){let t=e.indexOf(`
|
|
123
126
|
Preview:
|
|
124
|
-
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function tg(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f}=e,p=``,m=``,h=``,g=0,_=0,v,y,b=0,x=0,S=[],C=new Map,w=new Map,T=new Set,E=So(),D=Eo(),O=new Set,k=Promise.resolve(),A,j=0,M=0,N={eventDispatcher:s},ee=e=>{O.add(e),e.catch(e=>{A??=e}).finally(()=>{O.delete(e)})},P=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(A)throw A},F=t.subscribe(e=>{let t=k.then(()=>I(e));k=t.catch(()=>{}),ee(t)});async function I(e){let n=()=>!!D.signal||E.signal?.transparentPause===!0;if(e.type===`agent_start`){c.dispatch(`agent_start`,{turnIndex:j},l,N).catch(()=>{});return}if(e.type===`turn_start`){M=j,j+=1,c.dispatch(`turn_start`,{turnIndex:M,timestamp:Date.now()},l,N).catch(()=>{});return}if(e.type===`message_update`){let t=e.assistantMessageEvent;if(x===0&&(t.type===`text_delta`||t.type===`done`)&&(x=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=mg(`partial`in t?t.partial:void 0)??mg(`message`in t?t.message:void 0)??mg(`message`in e?e.message:void 0),a=hg(t.delta,r,m);r?(m=r,h=r):a&&(h+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){p=``,m=``,h=``,e.usage&&(g=e.usage.input,_=e.usage.output);return}p=$h(e);let r=hg(``,p,h||m);m=p,h=p,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(g=e.usage.input,_=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(g=t.usage.input,_=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=$h(e);!p&&n&&(p=n),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:t.usage?{input:g,output:_,total:g+_}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(y=og(t));let r=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Qh(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),a=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),o=new Set(r.map(e=>e.toolCallId));for(let e of w.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)w.delete(e.toolCallId);if(S.push({message:t,toolResults:r}),f&&!n){let e=!!E.signal,n=!!D.signal;if(e&&E.signal.transparentPause||await f(Xh(qh(t),e||n),n?[]:r.map(Zh)),e||n)return}await c.dispatch(`turn_end`,{turnIndex:M,message:t,toolResults:r},l,N);return}if(e.type===`tool_execution_start`){await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_planned`,message:`tool call planned`,details:{toolCallId:e.toolCallId,toolName:e.toolName,args:e.args}}),h=``,C.set(e.toolCallId,e.args),E.signal?.transparentPause!==!0&&!T.has(e.toolCallId)&&(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args}));return}if(e.type===`tool_execution_end`){let n=pg(e.result),r=fg(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Qh(r,i,e.toolCallId,e.toolName),c=C.get(e.toolCallId);if(C.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}w.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_completed`,message:`tool call completed`,details:{toolCallId:e.toolCallId,toolName:e.toolName,input:c,output:n,isError:e.isError,...o?{toolResultRef:o}:{}}}),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let L=us(d),R=L.enabled?L.maxAttempts:1;try{ng({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=R;e++){let d=S.length;y=void 0,v=void 0,j=0,M=0;try{await Bh({agent:t,hookRegistry:c,hookContext:l,pluginRuntime:N});let f=await c.dispatch(`before_provider_request`,{model:a,messages:t.state.messages,tools:t.state.tools},l,N);for(let e of f)if(e){if(e.abort)return await P(),{text:p,inputTokens:g,outputTokens:_,error:v,turnRecords:S};e.messages&&(t.state.messages=e.messages),e.tools&&(t.state.tools=e.tools)}if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);J.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),b=Date.now(),await Co(E,async()=>{await Do(D,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await P();let m=E.signal;if(m)throw m;let h=D.signal;if(h)throw h;let x=S.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!y&&S.length>0&&!x&&p.trim().length===0&&(J.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,turnRecordCount:S.length}),y={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let C=t.state,w=typeof C.error==`string`?C.error:typeof C.errorMessage==`string`?C.errorMessage:void 0,T=y??w;if(T){let t=y?`sdk`:`agent_state`;if(v=gg(T),J.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,error:v,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:S.length-d,...Vo(T,`providerError`)}),await z(T,v,e,d))continue;await ne(v,T),await s.dispatchProgress(i,{type:`error`,message:v})}v||J.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await P(),vo(t)||bo(t))throw t;if(v=gg(t),J.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,error:v}),await z(t,v,e,d))continue;await ne(v,t),await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{F()}function te(){p=``,m=``,h=``}async function z(e,n,r,a){if(!ag({error:e,attempt:r,maxAttempts:R,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=ds(r,L);return J.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:R,delayMs:o,error:n}),await lg({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:R,message:n,delayMs:o}),S.length=a,te(),ug(t),await fs(o,u),!0}async function ne(e,t){f&&await f(Gh(e,t),[])}let B=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:B,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let V=(D.signal?``:S.length>0?$h(S[S.length-1].message):``)||p||Kh(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;if(f&&!Wh(S)&&!v&&p.trim().length>0){let e=Yh(S);await f({role:`assistant`,content:p,...e?{thinking:e}:{},timestamp:new Date().toISOString()},[])}return{text:V,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function ng(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model,r=e.agent.state?.thinkingLevel;if(!n||typeof n.id!=`string`)return;let i=typeof t?.systemPrompt==`string`?t.systemPrompt:``,a=Array.isArray(t?.messages)?[...t.messages]:[],o=e.continueFromHistory?a:rg(a,e.message),s=ig(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Zo(n,{systemPrompt:i,messages:o,tools:s.length>0?s.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},t),c=typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`;e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`runner`,phase:`model_request_preview`,message:`model request preview`,details:{model:n.id,provider:c,systemPrompt:i,tools:s,requestJson:a}})}catch{}}function rg(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function ig(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function ag(e){return e.attempt>=e.maxAttempts||!ps(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&$h(e.message).trim().length===0)}function og(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:sg(t.errorCode),statusCode:cg(t.statusCode),providerCode:sg(t.providerCode),providerType:sg(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function sg(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function cg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function lg(e){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`runner`,phase:`llm_turn_retry_scheduled`,message:`retrying transient LLM turn failure`,details:{attempt:e.attempt,nextAttempt:e.attempt+1,maxAttempts:e.maxAttempts,delayMs:e.delayMs,error:e.message}})}function ug(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&dg(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function dg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function fg(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return pg(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):pg(e)}function pg(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function mg(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function hg(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function gg(e){let t=_g(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function _g(e){if(e instanceof ao)return e;if(e&&typeof e==`object`&&!(e instanceof Error)){let t=e,n=typeof t.message==`string`&&t.message.trim()?t.message:void 0;return!n&&t.code===void 0&&t.statusCode===void 0?null:{message:n??`Unknown LLM error`,code:sg(t.code),statusCode:cg(t.statusCode),statusText:sg(t.statusText),providerMessage:sg(t.providerMessage)}}if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function vg(e){let t=wg(e.toolResultPreviewChars),n=Tg(e.systemPrompt,e.agentDefinition),r=Dg(e.model,e.agentDefinition),i=Ea(e.tools??[],e.agentDefinition),a=Eg(e.message,e.agentDefinition),o=await tg({agent:new st({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:yg({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new Ra,hookCtx:{sessionId:e.sessionId},abortSignal:e.abortSignal});return{text:o.text,usage:{input:o.inputTokens,output:o.outputTokens,total:o.inputTokens+o.outputTokens},error:o.error,toolCalls:xg(o.turnRecords),toolResults:Sg(o.turnRecords,t)}}function yg(e){let t=e.phasePrefix??`silent_agent`;return new io({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await bg(e.diagnosticDispatcher,t,n)}})}async function bg(e,t,n){let r=n.sessionId;if(r){if(n.type===`stream_text_delta`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_stream`,message:`silent agent streamed text`,details:{textLength:n.text.length}});return}if(n.type===`tool_start`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_tool_started`,message:`silent agent tool started`,details:{toolCallId:n.toolCallId,toolName:n.name,input:n.input}});return}if(n.type===`tool_end`){await e.dispatchDiagnostic(r,{level:n.isError?`warn`:`info`,scope:`skill`,phase:`${t}_tool_completed`,message:n.isError?`silent agent tool failed`:`silent agent tool completed`,details:{toolCallId:n.toolCallId,toolName:n.name,isError:n.isError}});return}if(n.type===`error`){await e.dispatchDiagnostic(r,{level:`warn`,scope:`skill`,phase:`${t}_error`,message:`silent agent reported error`,details:{error:n.message}});return}n.type===`diagnostic`&&await e.dispatchDiagnostic(r,{level:n.level,scope:n.scope,phase:`${t}_${n.phase}`,message:n.message,...n.details?{details:n.details}:{}})}}function xg(e){let t=[];for(let n of e)for(let e of n.message.content)e.type===`toolCall`&&t.push({id:e.id,name:e.name,arguments:e.arguments??{}});return t}function Sg(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Cg(e.content,t)})))}function Cg(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function wg(e){let t=e??800;if(!Number.isFinite(t))throw Error(`toolResultPreviewChars must be a finite non-negative integer.`);return Math.max(0,Math.floor(t))}function Tg(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
|
|
127
|
+
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function jg(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=ns(),O=os(),k=new To,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=Gg(`partial`in t?t.partial:void 0)??Gg(`message`in t?t.message:void 0)??Gg(`message`in e?e.message:void 0),a=Kg(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=kg(e);let r=Kg(``,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=kg(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=Lg(t));let r=vo(kg(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:Og(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=Eg(Cg(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText),await f(i,n?[]:a.map(Dg))}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=Wg(e.result),r=Ug(e.result);p?.addChild(Mg(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Og(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(Do({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=Ws(d),B=z.enabled?z.maxAttempts:1;try{Ng({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 gg({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`);Y.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 rs(D,async()=>{await ss(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&&(Y.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=qg(T),Y.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,...xs(T,`providerError`)}),await H(T,y,e,d))continue;await ne(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||Y.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(),Qo(t)||es(t))throw t;if(y=qg(t),Y.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y}),await H(t,y,e,d))continue;await ne(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{R()}function V(){m=``,h=``,g=``}async function H(e,n,r,a){if(!Ig({error:e,attempt:r,maxAttempts:B,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g}))return!1;let o=Gs(r,z);return Y.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:B,delayMs:o,error:n}),await Bg({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:B,message:n,delayMs:o}),C.length=a,V(),Vg(t),await Ks(o,u),!0}async function ne(e,t){f&&await f(xg(e,t),[])}let re=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:re,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let U=O.signal?``:C.length>0?vo(kg(C[C.length-1].message),A).cleanedText:``,ie=vo(m,A).cleanedText,ae=U||ie||Sg(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!bg(C)&&!y&&m.trim().length>0){let e=vo(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await oe(e.warnings);let t=Tg(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:ae,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 Mg(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 Ng(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model,r=e.agent.state?.thinkingLevel;if(!n||typeof n.id!=`string`)return;let i=typeof t?.systemPrompt==`string`?t.systemPrompt:``,a=Array.isArray(t?.messages)?[...t.messages]:[],o=e.continueFromHistory?a:Pg(a,e.message),s=Fg(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=js(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 Pg(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function Fg(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 Ig(e){return e.attempt>=e.maxAttempts||!qs(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&kg(e.message).trim().length===0)}function Lg(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:Rg(t.errorCode),statusCode:zg(t.statusCode),providerCode:Rg(t.providerCode),providerType:Rg(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function Rg(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function zg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Bg(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 Vg(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&Hg(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function Hg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function Ug(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return Wg(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):Wg(e)}function Wg(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function Gg(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 Kg(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function qg(e){let t=Jg(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 Jg(e){if(e instanceof io)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:Rg(t.code),statusCode:zg(t.statusCode),statusText:Rg(t.statusText),providerMessage:Rg(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 Yg(e){let t=t_(e.toolResultPreviewChars),n=n_(e.systemPrompt,e.agentDefinition),r=i_(e.model,e.agentDefinition),i=Ta(e.tools??[],e.agentDefinition),a=r_(e.message,e.agentDefinition),o=await jg({agent:new ot({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:Xg({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new La,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:Qg(o.turnRecords),toolResults:$g(o.turnRecords,t)}}function Xg(e){let t=e.phasePrefix??`silent_agent`;return new ro({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await Zg(e.diagnosticDispatcher,t,n)}})}async function Zg(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 Qg(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 $g(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:e_(e.content,t)})))}function e_(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function t_(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 n_(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
|
|
125
128
|
|
|
126
|
-
`)}function
|
|
127
|
-
`)}function
|
|
128
|
-
`)}function Rg(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=zg(e.content??e.preview);return{action:typeof t?.action==`string`?t.action:void 0,skillId:typeof t?.skillId==`string`?t.skillId:void 0,categoryPath:typeof t?.categoryPath==`string`?t.categoryPath:void 0,success:typeof t?.success==`boolean`?t.success:void 0,error:typeof t?.error==`string`?t.error:void 0,isError:e.isError}})}function zg(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Bg=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Vg=Bg,Hg={session:{tool_call_volume:5,state_changing_tools:2},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},Ug=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Wg(e){let t=Kg(e.gates),n={session:Jg(`session`,e.sessionTranscript,t.session),currentRun:Jg(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:Jg(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Qg(e.reviewState?.reviewCount,0),i=Qg(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return e_(n,a,r,i,o,`run_error`);if(e.result?.paused)return e_(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return e_(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return e_(n,a,r,i,o,`max_reviews_per_session`);let s=a.find(e=>n[e].passed),c=s?n[s]:void 0;return{worthReview:!!s,skipped:!1,reasons:c?.reasons??[],stats:c?.stats??o,reviewCount:r,maxReviewsPerSession:i,selectedGateScope:s,consideredGateScopes:a,gateResults:n}}function Gg(e,t={}){let n=jr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Bg),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(t_(t)){for(let e of t.toolCalls??[])a.has(e.name)&&(o.add(e.name),s+=1),e.name===`skill_load`&&typeof e.arguments.name==`string`&&r.add(e.arguments.name),e.name===`auto_skill_view`&&typeof e.arguments.skillId==`string`&&i.add(e.arguments.skillId);continue}n_(t)&&r_(t)&&(c+=1)}return{toolCallCount:n.toolCallCount,distinctToolCount:n.distinctToolCount,toolNames:n.toolNames,stateChangingToolCallCount:s,stateChangingToolNames:Array.from(o).sort(),failedToolResultCount:n.failedToolResultCount,userTurnCount:l,loadedSkills:Array.from(r).sort(),viewedAutoSkills:Array.from(i).sort(),skillLookupFailureCount:c}}function Kg(e){return{session:qg(e?e.session:Hg.session),currentRun:qg(e?e.currentRun:Hg.currentRun),reviewWindow:qg(e?e.reviewWindow:Hg.reviewWindow)}}function qg(e){let t={};for(let n of Ug){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Vg:void 0;if(typeof r==`number`){let e=Zg(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Zg(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:$g(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:$g(r.toolNames,i)})}return t}function Jg(e,t,n){let r=Gg(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Ug.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];Yg(t,o,r)?i.push({code:t,description:Xg(e,t,o)}):a.push(t)}return{scope:e,configured:o.length>0,passed:o.length>0&&a.length===0,reasons:i,missingReasonCodes:a,stats:r}}function Yg(e,t,n){switch(e){case`tool_call_volume`:return n.toolCallCount>=t.min;case`tool_diversity`:return n.distinctToolCount>=t.min;case`state_changing_tools`:return n.stateChangingToolCallCount>=t.min;case`tool_errors`:return n.failedToolResultCount>=t.min;case`multi_turn`:return n.userTurnCount>=t.min}}function Xg(e,t,n){let r=e===`currentRun`?`Current run`:e===`reviewWindow`?`Review window`:`Session`;switch(t){case`tool_call_volume`:return`${r} used at least ${n.min} tool calls.`;case`tool_diversity`:return`${r} used at least ${n.min} distinct tools.`;case`state_changing_tools`:return`${r} used at least ${n.min} configured state-changing tool calls.`;case`tool_errors`:return`${r} had at least ${n.min} failed tool results.`;case`multi_turn`:return`${r} had at least ${n.min} user turns.`}}function Zg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Qg(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function $g(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function e_(e,t,n,r,i,a){return{worthReview:!1,skipped:!0,skipReason:a,reasons:[],stats:i,reviewCount:n,maxReviewsPerSession:r,consideredGateScopes:t,gateResults:e}}function t_(e){return e.role===`assistant`}function n_(e){return e.role===`tool_result`}function r_(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:i_(e.content)?.success===!1}function i_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function a_(e){let t=Nr(e.transcript.length,e.transcriptStartIndex),n=Pr(e.transcript.length,e.recentEntryLimit),r=Nr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Nr(e.transcript.length,0),a=Fr(e.transcript,t),o=Fr(e.transcript,r),s=Gg(e.transcript),c=Gg(a),l=Gg(o),u=Ar(e.transcript),d=Ar(a),f=Ar(o),p=a.filter(s_),m=a.filter(c_);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:o_(p[0]?.content??``,800),finalResponse:o_(e.result.text||m.at(-1)?.content||``,800),contextFiles:e.contextFiles,currentRunRange:t,recentRange:n,reviewWindowRange:r,sessionStats:u,currentRunStats:d,reviewWindowStats:f,session:{transcriptRange:i,stats:u,toolStats:s},currentRun:{transcriptRange:t,stats:d,toolStats:c},reviewWindow:{transcriptRange:r,stats:f,toolStats:l},reviewState:{reviewCount:e.reviewState?.reviewCount??0,lastCompletedReviewAt:e.reviewState?.lastCompletedReviewAt??null,lastReviewedTranscriptEndIndex:e.reviewState?.lastReviewedTranscriptEndIndex??null},transcriptSummary:{entryCount:d.totalEntryCount,userTurnCount:d.userTurnCount,assistantTurnCount:d.assistantTurnCount,toolResultCount:d.toolResultCount},toolStats:c,loadedSkills:c.loadedSkills,viewedAutoSkills:c.viewedAutoSkills,failedTools:Mr(a,{limit:8,maxPreviewChars:400}).map(e=>({toolName:e.toolName,preview:e.preview})),activeCategories:(e.activeCategories??[]).map(e=>({path:e.path,description:e.description}))}}function o_(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function s_(e){return e.role===`user`}function c_(e){return e.role===`assistant`}function l_(e,t,n){return W.join(r(e,t,n),`auto-skill-review-state.json`)}function u_(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function d_(e,t,n){let r=l_(e,t,n),i;try{i=await U.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return u_(t);throw e}return g_(JSON.parse(i),t)}async function f_(e,t,n){let r=l_(e,t.sessionId,n);await U.mkdir(W.dirname(r),{recursive:!0}),await U.writeFile(r,`${JSON.stringify(g_(t,t.sessionId),null,2)}\n`,`utf-8`)}async function p_(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await f_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function m_(e){let t={...e.state,sessionId:e.sessionId,reviewCount:Math.max(0,Math.floor(e.state.reviewCount))+1,lastCompletedReviewAt:e.completedAt??new Date().toISOString(),lastFailedReviewAt:e.state.lastFailedReviewAt??null,lastReviewedTranscriptEndIndex:Math.max(0,Math.floor(e.reviewedTranscriptEndIndex))};return await f_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function h_(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await f_(e.dataDir,t,{storeName:e.sessionStoreName}),t}function g_(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:y_(n.reviewCount,0),lastAttemptedReviewAt:__(n.lastAttemptedReviewAt),lastCompletedReviewAt:__(n.lastCompletedReviewAt),lastFailedReviewAt:__(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:v_(n.lastReviewedTranscriptEndIndex)}}function __(e){return typeof e==`string`&&e.trim()?e:null}function v_(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function y_(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function b_(e){return W.join(fi(e),`.reviews`,`run-log.jsonl`)}async function x_(e,t){let n=b_(e);await U.mkdir(W.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await U.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const S_=`write`,C_=new Set([`off`,`gate`,`dry_run`,`write`]);async function w_(e){let t=T_(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=D_(e);if(n){await j_(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=O_(n,e.transcriptStartIndex),o=await d_(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=k_(o.lastReviewedTranscriptEndIndex,n.length),c=O_(n,s);await M_(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=Wg({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await M_(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:l.worthReview,selectedGateScope:l.selectedGateScope,skipReason:l.skipReason}),!l.worthReview){await N_(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await M_(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Mi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=a_({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:Jr(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await M_(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await N_(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(Pg);if(!p){J.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:Pg}),await j_(e,t,`reviewer_agent_missing`,{reviewerAgentName:Pg});return}i={mode:f,decision:l,packet:d},r=await p_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:o,sessionStoreName:e.runParams.sessionStoreName}),await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_started`,message:`auto-skill review agent started`,details:{mode:t.mode,selectedGateScope:l.selectedGateScope,reviewCount:l.reviewCount,maxReviewsPerSession:l.maxReviewsPerSession}});let m=e.curator??Fg,h=Ng({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:d.currentRunRange,recentRange:d.recentRange,reviewWindowRange:d.reviewWindowRange}),g=await m({sessionId:e.sessionId,runParams:e.runParams,packet:d,mode:t.mode,tools:h,reviewerAgent:p,diagnosticDispatcher:e.eventDispatcher});if(g.error){r=await h_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await P_(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await A_(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:F_(g.toolCalls),toolResults:H_(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await m_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await P_(e.runParams.dataDir,i,{status:`completed`,curatorResult:g,reviewState:r});await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_completed`,message:`auto-skill review agent completed`,details:{mode:t.mode,usage:g.usage,text:V_(g.text,2e3),toolCalls:F_(g.toolCalls),toolResults:H_(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewState:r,reviewRunLogPath:_}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await h_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await P_(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await A_(e,n,a?{reviewRunLogPath:a}:void 0)}}function T_(e){return{mode:E_(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function E_(e){if(e==null)return S_;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?C_.has(t)?t:`off`:S_}function D_(e){if(e.runParams.subagentContext)return`subagent`;if(e.runParams.channel===`CRON`)return`cron`;if(e.result.error)return`run_error`;if(e.result.paused)return`hitl_paused`;if(e.result.uiToolPending)return`ui_tool_pending`}function O_(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function k_(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function A_(e,t,n){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skill_review_failed`,message:`auto-skill review failed`,details:{...n??{},error:t}})}async function j_(e,t,n,r={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:n===`run_error`?`warn`:`info`,scope:`skill`,phase:`auto_skill_review_skipped`,message:n===`reviewer_agent_missing`?`auto-skill review skipped because reviewer agent is missing`:`auto-skill review skipped before gate evaluation`,details:{mode:t.mode,reason:n,...r}})}async function M_(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function N_(e,t,n,r,i={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_gated`,message:n.worthReview?`completed run is worth auto-skill review`:`completed run is not worth auto-skill review`,details:{mode:t.mode,worthReview:n.worthReview,skipped:n.skipped,...i.skipReason?{skipReason:i.skipReason}:{},transcriptEntryCount:r.length,transcriptStartIndex:e.transcriptStartIndex,reasons:n.reasons.map(e=>({code:e.code})),stats:n.stats,selectedGateScope:n.selectedGateScope,consideredGateScopes:n.consideredGateScopes,reviewCount:n.reviewCount,maxReviewsPerSession:n.maxReviewsPerSession,gateResults:B_(n),...i.packet?{packet:i.packet}:{}}})}async function P_(e,t,n){return x_(e,{sessionId:t.packet.sessionId,mode:t.mode,status:n.status,selectedGateScope:t.decision.selectedGateScope,reviewCount:t.decision.reviewCount,reasons:t.decision.reasons.map(e=>e.code),currentRunRange:t.packet.currentRunRange,reviewWindowRange:t.packet.reviewWindowRange,conclusion:n.curatorResult?L_(n.curatorResult.text):void 0,conclusionText:n.curatorResult?R_(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?F_(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?H_(n.curatorResult.toolResults):void 0,writeResults:n.curatorResult?.writeResults,wrote:n.curatorResult?.wrote,error:n.error,reviewStateAfter:n.reviewState?{reviewCount:n.reviewState.reviewCount,lastReviewedTranscriptEndIndex:n.reviewState.lastReviewedTranscriptEndIndex}:void 0})}function F_(e){return e.map(e=>({...e,arguments:I_(e.name,e.arguments)}))}function I_(e,t){if(e!==`auto_skill_manage`)return t;let n={};for(let e of[`action`,`skillId`,`name`,`categoryPath`,`newCategory`])t[e]!==void 0&&(n[e]=t[e]);return n}function L_(e){let t=z_(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function R_(e){return L_(e)?void 0:V_(e,8e3)}function z_(e){let t=e.trim(),n=[t],r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);r?.[1]&&n.unshift(r[1].trim());let i=t.indexOf(`{`),a=t.lastIndexOf(`}`);return i>=0&&a>i&&n.push(t.slice(i,a+1)),Array.from(new Set(n.filter(Boolean)))}function B_(e){return Object.fromEntries(Object.entries(e.gateResults).map(([e,t])=>[e,{configured:t.configured,passed:t.passed,reasons:t.reasons.map(e=>({code:e.code})),missingReasonCodes:t.missingReasonCodes,stats:t.stats}]))}function V_(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function H_(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let U_=!1;function W_(){U_||=(_t(),gt({api:`openai-completions`,stream:Yo,streamSimple:Xo}),!0)}const G_=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`,`- As the user role, summarize the title based on the conversation content`,`- The principle of title generation is to describe the behavioral characteristics of the user in the conversation, rather than answering based on the content of the conversation`].join(`
|
|
129
|
-
`);async function
|
|
129
|
+
`)}function r_(e,t){return!t?.initPrompt||typeof e!=`string`?e:Da(t,e)}function i_(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const a_=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 o_(e){let t=Gr({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??Br}),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:a_,async execute(r,i){try{return i.kind===`tool_result`?c_(await Wr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?c_(await Vr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?c_(await Hr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?c_({...await Ur({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):c_(await Ur({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:s_(i),limits:t}))}catch(r){return c_({kind:i.kind,error:l_(r),limits:t,contextFiles:qr(e.dataDir,e.sessionId,n)})}}}}function s_(e){if(typeof e.startIndex!=`number`||typeof e.endIndex!=`number`)throw Error(`transcript_range requires startIndex and endIndex.`);return{startIndex:e.startIndex,endIndex:e.endIndex}}function c_(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function l_(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function u_(e){let t=[Cm(e.dataDir),wm(e.dataDir),Tm(e.dataDir),o_({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(Em(e.dataDir)),t}const d_=`auto-skill-reviewer`;async function f_(e){let t=e.createModel??da,n=e.tools??u_({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 Yg({sessionId:e.sessionId,systemPrompt:p_(e.mode),message:m_(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=h_(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 p_(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(`
|
|
130
|
+
`)}function m_(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(`
|
|
131
|
+
`)}function h_(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=g_(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 g_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const __=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],v_=__,y_={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}},b_=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function x_(e){let t=C_(e.gates),n={session:T_(`session`,e.sessionTranscript,t.session),currentRun:T_(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:T_(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=k_(e.reviewState?.reviewCount,0),i=k_(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return j_(n,a,r,i,o,`run_error`);if(e.result?.paused)return j_(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return j_(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return j_(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 S_(e,t={}){let n=Ar(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??__),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(M_(t)){for(let e of t.toolCalls??[])a.has(e.name)&&(o.add(e.name),s+=1),e.name===`skill_load`&&typeof e.arguments.name==`string`&&r.add(e.arguments.name),e.name===`auto_skill_view`&&typeof e.arguments.skillId==`string`&&i.add(e.arguments.skillId);continue}N_(t)&&P_(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 C_(e){return{session:w_(e?e.session:y_.session),currentRun:w_(e?e.currentRun:y_.currentRun),reviewWindow:w_(e?e.reviewWindow:y_.reviewWindow)}}function w_(e){let t={};for(let n of b_){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?v_:void 0;if(typeof r==`number`){let e=O_(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=O_(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:A_(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:A_(r.toolNames,i)})}return t}function T_(e,t,n){let r=S_(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=b_.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];E_(t,o,r)?i.push({code:t,description:D_(e,t,o)}):a.push(t)}return{scope:e,configured:o.length>0,passed:o.length>0&&a.length===0,reasons:i,missingReasonCodes:a,stats:r}}function E_(e,t,n){switch(e){case`tool_call_volume`:return n.toolCallCount>=t.min;case`tool_diversity`:return n.distinctToolCount>=t.min;case`state_changing_tools`:return n.stateChangingToolCallCount>=t.min;case`tool_errors`:return n.failedToolResultCount>=t.min;case`multi_turn`:return n.userTurnCount>=t.min}}function D_(e,t,n){let r=e===`currentRun`?`Current run`:e===`reviewWindow`?`Review window`:`Session`;switch(t){case`tool_call_volume`:return`${r} used at least ${n.min} tool calls.`;case`tool_diversity`:return`${r} used at least ${n.min} distinct tools.`;case`state_changing_tools`:return`${r} used at least ${n.min} configured state-changing tool calls.`;case`tool_errors`:return`${r} had at least ${n.min} failed tool results.`;case`multi_turn`:return`${r} had at least ${n.min} user turns.`}}function O_(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function k_(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function A_(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function j_(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 M_(e){return e.role===`assistant`}function N_(e){return e.role===`tool_result`}function P_(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:F_(e.content)?.success===!1}function F_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function I_(e){let t=Mr(e.transcript.length,e.transcriptStartIndex),n=Nr(e.transcript.length,e.recentEntryLimit),r=Mr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Mr(e.transcript.length,0),a=Pr(e.transcript,t),o=Pr(e.transcript,r),s=S_(e.transcript),c=S_(a),l=S_(o),u=kr(e.transcript),d=kr(a),f=kr(o),p=a.filter(R_),m=a.filter(z_);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:L_(p[0]?.content??``,800),finalResponse:L_(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:jr(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 L_(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function R_(e){return e.role===`user`}function z_(e){return e.role===`assistant`}function B_(e,t,n){return G.join(r(e,t,n),`auto-skill-review-state.json`)}function V_(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function H_(e,t,n){let r=B_(e,t,n),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return V_(t);throw e}return q_(JSON.parse(i),t)}async function U_(e,t,n){let r=B_(e,t.sessionId,n);await W.mkdir(G.dirname(r),{recursive:!0}),await W.writeFile(r,`${JSON.stringify(q_(t,t.sessionId),null,2)}\n`,`utf-8`)}async function W_(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await U_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function G_(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 U_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function K_(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await U_(e.dataDir,t,{storeName:e.sessionStoreName}),t}function q_(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:X_(n.reviewCount,0),lastAttemptedReviewAt:J_(n.lastAttemptedReviewAt),lastCompletedReviewAt:J_(n.lastCompletedReviewAt),lastFailedReviewAt:J_(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:Y_(n.lastReviewedTranscriptEndIndex)}}function J_(e){return typeof e==`string`&&e.trim()?e:null}function Y_(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function X_(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function Z_(e){return G.join(di(e),`.reviews`,`run-log.jsonl`)}async function Q_(e,t){let n=Z_(e);await W.mkdir(G.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await W.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const $_=`write`,ev=new Set([`off`,`gate`,`dry_run`,`write`]);async function tv(e){let t=nv(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=iv(e);if(n){await cv(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=av(n,e.transcriptStartIndex),o=await H_(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=ov(o.lastReviewedTranscriptEndIndex,n.length),c=av(n,s);await lv(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=x_({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await lv(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 uv(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await lv(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new ji({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=I_({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:qr(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await lv(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await uv(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(d_);if(!p){Y.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:d_}),await cv(e,t,`reviewer_agent_missing`,{reviewerAgentName:d_});return}i={mode:f,decision:l,packet:d},r=await W_({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??f_,h=u_({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 K_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await dv(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await sv(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:fv(g.toolCalls),toolResults:yv(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await G_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await dv(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:vv(g.text,2e3),toolCalls:fv(g.toolCalls),toolResults:yv(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 K_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await dv(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await sv(e,n,a?{reviewRunLogPath:a}:void 0)}}function nv(e){return{mode:rv(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function rv(e){if(e==null)return $_;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?ev.has(t)?t:`off`:$_}function iv(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 av(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function ov(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function sv(e,t,n){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skill_review_failed`,message:`auto-skill review failed`,details:{...n??{},error:t}})}async function cv(e,t,n,r={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:n===`run_error`?`warn`:`info`,scope:`skill`,phase:`auto_skill_review_skipped`,message:n===`reviewer_agent_missing`?`auto-skill review skipped because reviewer agent is missing`:`auto-skill review skipped before gate evaluation`,details:{mode:t.mode,reason:n,...r}})}async function lv(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function uv(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:_v(n),...i.packet?{packet:i.packet}:{}}})}async function dv(e,t,n){return Q_(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?mv(n.curatorResult.text):void 0,conclusionText:n.curatorResult?hv(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?fv(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?yv(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 fv(e){return e.map(e=>({...e,arguments:pv(e.name,e.arguments)}))}function pv(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 mv(e){let t=gv(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function hv(e){return mv(e)?void 0:vv(e,8e3)}function gv(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 _v(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 vv(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function yv(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let bv=!1;function xv(){bv||=(gt(),ht({api:`openai-completions`,stream:ks,streamSimple:As}),!0)}const Sv=[`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(`
|
|
132
|
+
`);async function Cv(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s}=e,c=t.trim().replace(/\s+/g,` `);if(!c)return`New session`;if(!r.flashModel)return Ov(c);let l=Ov(c),u=r.flashModel,d=ao({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:u,hooks:a,hookCtx:o}),f=[{role:`user`,content:c}];n&&f.push({role:`assistant`,content:n});let p=Tv(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await d.chat({system:Sv,user:JSON.stringify(f),temperature:0,maxTokens:100,signal:p.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(Ev(t)){if(p.didTimeout())return s?.(`timeout`),l;throw t}e<3&&await wv(500*e,p.signal)}}catch(e){if(Ev(e)&&p.didTimeout())return s?.(`timeout`),l;throw e}finally{p.clear()}return s?.(`error`),l}function wv(e,t){return t?t.aborted?Promise.reject(Dv()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(Dv())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function Tv(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 Ev(e){return e instanceof Error&&e.name===`AbortError`}function Dv(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function Ov(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 kv(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 Av(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await Nv(await F(r.dataDir,t,{...Z(r)}),r);await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs,messages:o},a,{eventDispatcher:e.eventDispatcher})}async function jv(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await F(r.dataDir,t,{...Z(r)});await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs,reason:n.error?`error`:`normal`},a,{eventDispatcher:e.eventDispatcher}),a.toolParamOverrides?.clear()}async function Mv(e){await Av(e),await jv(e)}async function Nv(e,t){return e.map(e=>({...e}))}async function Pv(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:c,hookContext:l,startTime:d,compactionEntry:f,eventDispatcher:p}=e,m=Z(o);if(a||await h(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},m),f&&await h(o.dataDir,n,f,m),await h(o.dataDir,n,{role:`assistant`,content:t,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},timestamp:new Date().toISOString()},m),r){let t=await Lv({sessionId:n,titleSource:i.trim()?i:`New session`,text:e.replyText,runParams:o,hookRegistry:c,hookContext:l});await u(o.dataDir,n,{title:t},m),await p.dispatchProgress(n,{type:`title_updated`,title:t})}let g=Date.now()-d,v={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:g,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},context:{snapshotPath:_(o.dataDir,n,Z(o)),toolResultsDir:s(o.dataDir,n,Z(o))}};return Y.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 Mv({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function Fv(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:c,text:l,usage:d,error:f,paused:p,uiToolPending:m,artifacts:h,eventDispatcher:g,sessionEndOnly:v}=e;if(n){let n=Z(i),s=await Lv({sessionId:t,titleSource:r,text:e.text,runParams:i,hookRegistry:a,hookContext:o,logLifecycle:!0});await u(i.dataDir,t,{title:s},n),await g.dispatchProgress(t,{type:`title_updated`,title:s})}let y={sessionId:t,text:l,usage:d,durationMs:Date.now()-c,error:f,paused:p,uiToolPending:m,...h&&h.length>0?{artifacts:h}:{},context:{snapshotPath:_(i.dataDir,t,Z(i)),toolResultsDir:s(i.dataDir,t,Z(i))}};h&&h.length>0&&e.transcriptStartIndex!==void 0&&!p&&!m&&await Iv({dataDir:i.dataDir,sessionId:t,pathOptions:Z(i),transcriptStartIndex:e.transcriptStartIndex,artifacts:h});let b={sessionId:t,kind:`completed`,durationMs:y.durationMs,isNewSession:n,inputTokens:d.input,outputTokens:d.output,totalTokens:d.total,hasError:!!f,error:f,paused:!!p,uiToolPending:!!m,textLength:l.length,snapshotPath:y.context.snapshotPath,toolResultsDir:y.context.toolResultsDir};f?Y.warn(`agent run finalized with error`,b):Y.info(`agent run finalized`,b);let x={sessionId:t,result:y,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:g};return v?await jv(x):await Mv(x),y}async function Iv(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 Lv(e){let t=Ov(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&Y.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await Cv({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,onFallback:e=>{n=e}});return n?Y.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&Y.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return Y.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const Rv=new Set([`pause`,`resume`,`clear`,`help`]),zv=`/goal
|
|
130
133
|
【目标】:把 src/auth 目录下重复的参数校验逻辑抽离成公共函数。
|
|
131
134
|
【范围】:只处理 src/auth 目录,不扩散到用户模块或订单模块。
|
|
132
135
|
【约束】:保持现有 API 兼容,不引入新依赖,不要改变数据库结构。
|
|
133
136
|
【验证】:每次改动后请自主运行 npm test auth 以及 npm run typecheck。如果测试失败,请定位原因并修复。
|
|
134
|
-
【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function
|
|
135
|
-
`)}function
|
|
136
|
-
`)}async function
|
|
137
|
-
`)}async function
|
|
138
|
-
`)}}if(e.action===`set`){let r=await
|
|
139
|
-
`)}}function
|
|
137
|
+
【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function Bv(){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 发送):`,zv].join(`
|
|
138
|
+
`)}function Vv(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,zv,``,`正文(写入 objective.txt 供 --goal-file):`,zv.replace(/^\/goal\s+/,``)].join(`
|
|
139
|
+
`)}async function Hv(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await U(e.dataDir,e.sessionId,t);if(!r){let r=await ae(e.dataDir,e.sessionId,{goalId:tt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await xn(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 ae(e.dataDir,e.sessionId,{goalId:tt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await xn(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 Uv(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(Rv.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 Wv(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function Gv(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function Kv(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${Wv(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:`,` 状态:${Gv(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,Jv(e.status)),a.join(`
|
|
140
|
+
`)}async function qv(e,t,n){let r=await yn(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return Kv(t,n,r.goalState,r.workflowWarning)}function Jv(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 Yv(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:Bv()};if(e.action===`get`){let e=await U(t.dataDir,t.sessionId,n);return e?{replyText:await qv(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(`
|
|
141
|
+
`)}}if(e.action===`set`){let r=await Hv({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 qv(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 qv(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await U(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await V(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await qv(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await U(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${await qv(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 qv(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ie(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const Xv=[{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 Zv(){return Xv.map(e=>({...e}))}function Qv(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function $v(e){let t=new Set,n=[];for(let r of e){let e=Qv(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function ey(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function ty(e,t){let n=Zv(),r=$v(e),i=t?ey(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function ny(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 ry(e){let t=ny(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 iy(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 ay(e,t){let n=ry(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=Uv(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:Qv(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set($v(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 oy=new Set([`/new`,`/reset`,`/compact`]),sy=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),cy=new Set([`/help`]);function ly(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function uy(e){if(e.length===0)return[];let t=e.map(ly),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function dy(e){let t=ty(e.skills),n=t.builtin.filter(e=>oy.has(e.name)),r=t.builtin.filter(e=>sy.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>cy.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...uy(n)),s.push(``),s.push(`目标命令`),s.push(...uy(r)),s.push(``),s.push(`技能命令`),s.push(...uy(i)),o.length>0?(s.push(...uy(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...uy(a)),{kind:`reply`,text:s.join(`
|
|
142
|
+
`)}}function fy(e,t){let n=t.trim().toLowerCase();return n&&$v(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function py(e){let t=fy(e.ctx.skills,e.skillName);return t?{kind:`rewrite`,message:[`Use the "${t.name}" skill for this request.`,e.args?`User input:\n${e.args}`:null].filter(e=>!!e).join(`
|
|
140
143
|
|
|
141
|
-
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function
|
|
142
|
-
`),
|
|
144
|
+
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function my(e){let t=ay(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?dy(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?py({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 hy(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=gy(t),l=c>=0?t[c].content:void 0,u=hc(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}=Ic(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:X(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Tc({entries:f,llm:r,previousSummary:l,instructions:i,contextWindowTokens:n,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:X(d)}}function gy(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const _y=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
|
|
145
|
+
`),vy=[`.aimax/new.txt`];async function yy(e){try{return(await Ze(e,`utf-8`)).trim()||null}catch{return null}}async function by(e){for(let t of vy){let n=await yy(Qe(e,t));if(n)return n}return await yy(`/aimax_pvc/new.txt`)||_y}async function xy(e){return{kind:`reply`,text:await by(e)}}function Sy(){return{kind:`reply`,text:`✅ Session reset.`}}async function Cy(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function wy(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 Cy(e,t,{action:n.action,goal:n.after??null})}function Ty(e){let t=Oy(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?ky(r):null,a=n??i?.text,o=a?iy(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Ay(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:jy(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Ey(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=ay(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=my({message:e.messageForRun??``,skills:t});if(o.kind===`reply`)return{kind:`reply`,replyText:o.text,transcriptMessage:e.transcriptMessage};if(o.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:o.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(o.kind===`rewrite`){let t=e.inputMode===`text`?o.message:Ay(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:jy(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Dy(e){let t=Ey(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 Pv({replyText:i&&typeof i==`object`&&`text`in i?String(i.text??`Command executed.`):`Command executed.`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:e.invocation.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}}if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await Pv({replyText:(t.action===`reset`?Sy():await xy(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await Pv({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`goal`){let n;try{n=await Yv({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 Cy(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),My(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 Pv({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}if(t.kind!==`compact`)return{kind:`continue`,effectivePrompt:e.invocation.promptInput,transcriptMessage:e.invocation.transcriptMessage};let n=await hy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,Z(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await Pv({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function Oy(e){return typeof e.message==`string`}function ky(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 Ay(e,t){let n=ky(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 jy(e){return typeof e==`string`?e:JSON.stringify(e)}function My(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function Ny(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++,Y.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){Y.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}Y.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 _=Py(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await jg({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?Y.warn(`subagent announce round completed with error`,y):Y.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&Y.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function Py(e){if(e.length===1){let t=e[0];return Im({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Im({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
|
|
143
146
|
|
|
144
147
|
---
|
|
145
148
|
|
|
146
|
-
`)}`}function ry(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iy(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function ay(){let e=rt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function oy(e){let t=e.trim(),n=ay();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?W.join(n,t.slice(2)):void 0:W.resolve(t)}const sy=new xt({allErrors:!0,strict:!1}),cy=new Map;function ly(e,t){let n=cy.get(t);if(n)return n;let r=sy.compile(e);return cy.set(t,r),r}function uy(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ly(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function dy(e){let t=iy(e?.allow),n=iy(e?.deny),r=iy(e?.load?.paths),i=iy(e?.piExtensions?.paths),a=e?.entries??{},o=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),piExtensionPaths:Array.from(new Set(i)),entries:a,slots:o}}function fy(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=uy({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function py(e){try{return G.realpathSync(e)}catch{return null}}function my(e){try{return G.statSync(e)}catch{return null}}function hy(e,t){let n=W.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!W.isAbsolute(n)}function gy(e){return`0o${e.toString(8).padStart(3,`0`)}`}const _y=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),vy=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function yy(e){let t=W.join(e,`package.json`);if(G.existsSync(t))try{let e=JSON.parse(G.readFileSync(t,`utf-8`));return ry(e)?e:void 0}catch{return}}function by(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function xy(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Sy(e){let t=py(e.source),n=py(e.rootDir);return!t||!n||hy(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Cy(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=W.resolve(r);if(n.has(t))continue;n.add(t);let i=my(r);if(!i)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let a=i.mode&511;if(a&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:a};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid==`number`&&i.uid!==e.uid&&i.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:i.uid,expectedUid:e.uid}}return null}function wy(e){return Sy({source:e.source,rootDir:e.rootDir})||Cy({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:xy(e.ownershipUid)})}function Ty(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${gy(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Ey(e){let t=wy({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Ty(t),source:e.source}),!0):!1}function Dy(e){return W.basename(e,W.extname(e))}function Oy(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function ky(e){for(let t of vy){let n=W.join(e,t);if(G.existsSync(n))return n}return null}function Ay(e){let t;try{t=G.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=W.join(e.rootDir,n.name);if(n.isFile()){if(!_y.has(W.extname(n.name)))continue;let r=W.dirname(t);if(Ey({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Oy({idHint:Dy(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=yy(t),i=by(r);if(i.status===`ok`){for(let n of i.entries){let i=W.resolve(t,n);if(!hy(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!G.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!_y.has(W.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Ey({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Dy(i)}`:Dy(i);e.candidates.push(Oy({idHint:o,source:i,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let a=ky(t);a&&(Ey({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Oy({idHint:W.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function jy(e){return e?e.map(oy).filter(e=>typeof e==`string`&&e.length>0):[]}function My(){let e=ay();if(e)return W.join(e,`.aimax`,`extensions`)}function Ny(e){return W.join(e,`.aimax`,`extensions`)}function Py(e){return W.join(e,`.aimax`,`extensions`)}function Fy(e={}){let t=[],n=[],r=jy(e.extraPaths);for(let i of r){if(!G.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=my(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!_y.has(W.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=W.dirname(i);if(Ey({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Oy({idHint:Dy(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Ay({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Ay({rootDir:Ny(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Ay({rootDir:Py(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=My();return i?Ay({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&Ay({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Iy(e){let t=e.rejectHardlinks??!0,n=py(e.rootPath),r=py(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!hy(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=G.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:G.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ly=`aimax.plugin.json`,Ry=[Ly];function zy(e){for(let t of Ry){let n=W.join(e,t);if(G.existsSync(n))return n}return W.join(e,Ly)}function By(e,t=!0){let n=zy(e),r=Iy({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(G.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{G.closeSync(r.fd)}if(!ry(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=ry(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let s=typeof i.kind==`string`?i.kind:void 0,c=typeof i.name==`string`?i.name.trim():void 0,l=typeof i.description==`string`?i.description.trim():void 0,u=typeof i.version==`string`?i.version.trim():void 0,d=iy(i.skills),f;return ry(i.uiHints)&&(f=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:s,name:c,description:l,version:u,skills:d,uiHints:f},manifestPath:n}}function Vy(e){let t=new Map,n=[];for(let r of e){let e=By(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let Hy=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Uy(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Hy.ERROR){J.error(i);return}if(e===Hy.WARN){J.warn(i);return}J.info(i)}function Wy(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Uy(Hy.INFO,e.pluginId,t,n),warn:n=>Uy(Hy.WARN,e.pluginId,t,n),error:n=>Uy(Hy.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}let Gy;function Ky(){return Gy||=St(import.meta.url,{interopDefault:!0,requireCache:!0}),Gy}function qy(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function Jy(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function Yy(e){let t=[...e.registry.diagnostics],n=new qm,r=new Ra,i=[],a=[],o=e.runtime?.llm?oo({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Xy(e.runtime?.llmAllowlist),c=Ky();for(let l of e.registry.manifests.values()){let u=qy({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Jy({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f=Date.now(),p;try{p=c(l.source)}catch(e){d.status=`error`,d.error=String(e),d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){d.status=`error`,d.error=`plugin module does not export a register function`,d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let g=Wy({pluginId:l.id,env:e.runtime?.env}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Zy(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);le({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);_e({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=W.isAbsolute(e)?e:W.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Ia(l.id)};try{h(v)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=W.isAbsolute(e)?e:W.resolve(l.rootDir,e);i.push(t)}d.durationMs=Math.max(0,Date.now()-f),a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Xy(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Zy(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}let Qy=null,$y=null;function eb(e){let{dataDir:t,bundledDir:n,workspaceDir:r}=e,i=e.config?JSON.stringify({allow:e.config.allow,deny:e.config.deny,enabled:e.config.enabled,piExtensions:e.config.piExtensions}):``;return`${t??``}|${n??``}|${r??``}|${i}`}function tb(e){let t=eb(e);return Qy&&$y===t?Qy:(Qy=rb(e),$y=t,Qy)}function nb(e){return Qy&&$y===eb(e)?Qy:rb(e)}function rb(e={}){let t=dy(e.config),n=Fy({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Vy(n.candidates),i=fy({config:t,registry:r}),a=Yy({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t,piExtensions:[]}}function ib(e,t){return Array.from(new Set([...t?.piExtensionPaths??[],...e.piExtensionPaths]))}async function ab(e,t){let n=ib(e,t);return n.length===0?[]:ye(n)}async function ob(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i,runtimeBridge:a}=e,o=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},s=t.plugins?Date.now():void 0,c=t.plugins?rb({...t.plugins,config:t.plugins.config,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0,l=s===void 0?void 0:Math.max(0,Date.now()-s);if(!c)return o({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`}),{hookRegistry:new Ra,pluginSkillDirs:[],pluginTools:[]};o({level:c.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:c.registry.plugins.length,enabledPluginCount:c.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:c.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:c.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:c.diagnostics.length,durationMs:l}});for(let e of c.registry.plugins)o({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,durationMs:e.durationMs,errorMessage:e.error}});for(let e of c.diagnostics)o({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}});let u=ib(c.normalizedConfig),d;if(u.length>0){let e=await ab(c.normalizedConfig);if(e.length>0){d=new be(e);let s=n.session?.getSessionDir?.(),l=t.createPiExtensionDialogBridge?.(r),u={};for(let[e,t]of Object.entries(c.normalizedConfig.entries??{}))t?.config&&typeof t.config==`object`&&(u[e]=t.config);let f=new Map;for(let t of e){let e=`pi:${t.name}`;u[e]&&f.set(e,u[e])}await d.activate({hookRegistry:c.registry.hooks,toolRegistry:c.registry.tools,hookContext:n,eventDispatcher:i,sessionId:r,sessionDir:s,runtimeBridge:a,dialogBridge:l,piExtensionConfigs:f}),o({level:`info`,scope:`plugin`,phase:`pi_extensions_activated`,message:`pi extensions activated`,details:{extensionCount:e.length,extensionNames:e.map(e=>e.name),commandCount:d.getRegisteredCommands().size}})}}return{hookRegistry:c.registry.hooks,pluginSkillDirs:c.registry.skills,pluginTools:[...c.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...c.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??c.normalizedConfig.slots?.memory,extensionHost:d}}var sb=class{agent=null;messageQueue=[];compactRequest=null;bindAgent(e){this.agent=e}dispose(){this.agent=null,this.messageQueue=[],this.compactRequest=null}sendUserMessage(e,t){this.messageQueue.push({content:e,deliverAs:t?.deliverAs,resolve:()=>{}})}isIdle(){if(!this.agent)return!0;let e=this.agent.state;return!e.isStreaming&&(e.pendingToolCalls?.size??0)===0}requestCompact(e){this.compactRequest=e??{}}drainMessages(){let e=this.messageQueue.map(e=>e.content);return this.messageQueue=[],e}drainCompactRequest(){let e=this.compactRequest;return this.compactRequest=null,e}hasPendingMessages(){return this.messageQueue.length>0}hasPendingCompact(){return this.compactRequest!==null}};async function cb(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Gf(t),o=n,s=!o,c=X(t);o?(await w(t.dataDir,o,c)||(s=!0),await v(t.dataDir,o,c)):o=await T(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>F(t.dataDir,o,c)}},u=new sb,d=await ob({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await Kf({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:d.memoryPluginId,eventDispatcher:i,hookRegistry:f});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:f,pluginContext:d,runContext:p,runtimeBridge:u,start:e=>Q_({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function lb(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ub(e){if(!(e instanceof Error))return{errorValue:lb(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=lb(n[e]));return t}async function db(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ub(e.error)}})}function fb(e,t,n){return W.join(r(e,t,n),`pending-ui-tool.json`)}async function pb(e,t,n,i){let a=r(e,t,i);await U.mkdir(a,{recursive:!0}),await L(fb(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function mb(e,t,n){let r=await o(fb(e,t,n));return r===null?null:JSON.parse(r)}async function hb(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await pb(e,t,a,r),a}async function gb(e,t,n,r,i){let a=await mb(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await pb(e,t,o,i),o}async function _b(e,t,n){try{await U.unlink(fb(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function vb(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function yb(e,t,n,r,i,a){let o=await H(e,t,{storeName:a?.storeName});await vb(e,t,n,a);let s=await wt(e,t,n,r,a);return s.goal&&await Kv(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function bb(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Xe(t))}async function xb(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=So();if(i=await Co(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(vo(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Sb(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function Sb(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const Cb=2e4,wb=15e4,Tb=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Eb(e){return W.join(e,`.aimax`)}async function Db(e){let t=Eb(e),n=[];for(let e of Tb){let r=W.join(t,e);try{let t=await U.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await U.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function Ob(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
|
|
149
|
+
`)}`}function Fy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Iy(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Ly(){let e=nt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ry(e){let t=e.trim(),n=Ly();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?G.join(n,t.slice(2)):void 0:G.resolve(t)}const zy=new bt({allErrors:!0,strict:!1}),By=new Map;function Vy(e,t){let n=By.get(t);if(n)return n;let r=zy.compile(e);return By.set(t,r),r}function Hy(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Vy(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Uy(e){let t=Iy(e?.allow),n=Iy(e?.deny),r=Iy(e?.load?.paths),i=Iy(e?.piExtensions?.paths),a=e?.entries??{},o=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),piExtensionPaths:Array.from(new Set(i)),entries:a,slots:o}}function Wy(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=Hy({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function Gy(e){try{return K.realpathSync(e)}catch{return null}}function Ky(e){try{return K.statSync(e)}catch{return null}}function qy(e,t){let n=G.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!G.isAbsolute(n)}function Jy(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Yy=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Xy=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function Zy(e){let t=G.join(e,`package.json`);if(K.existsSync(t))try{let e=JSON.parse(K.readFileSync(t,`utf-8`));return Fy(e)?e:void 0}catch{return}}function Qy(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function $y(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function eb(e){let t=Gy(e.source),n=Gy(e.rootDir);return!t||!n||qy(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function tb(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=G.resolve(r);if(n.has(t))continue;n.add(t);let i=Ky(r);if(!i)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let a=i.mode&511;if(a&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:a};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid==`number`&&i.uid!==e.uid&&i.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:i.uid,expectedUid:e.uid}}return null}function nb(e){return eb({source:e.source,rootDir:e.rootDir})||tb({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:$y(e.ownershipUid)})}function rb(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${Jy(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function ib(e){let t=nb({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:rb(t),source:e.source}),!0):!1}function ab(e){return G.basename(e,G.extname(e))}function ob(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function sb(e){for(let t of Xy){let n=G.join(e,t);if(K.existsSync(n))return n}return null}function cb(e){let t;try{t=K.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=G.join(e.rootDir,n.name);if(n.isFile()){if(!Yy.has(G.extname(n.name)))continue;let r=G.dirname(t);if(ib({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(ob({idHint:ab(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Zy(t),i=Qy(r);if(i.status===`ok`){for(let n of i.entries){let i=G.resolve(t,n);if(!qy(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!K.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Yy.has(G.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(ib({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${ab(i)}`:ab(i);e.candidates.push(ob({idHint:o,source:i,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let a=sb(t);a&&(ib({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(ob({idHint:G.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function lb(e){return e?e.map(Ry).filter(e=>typeof e==`string`&&e.length>0):[]}function ub(){let e=Ly();if(e)return G.join(e,`.aimax`,`extensions`)}function db(e){return G.join(e,`.aimax`,`extensions`)}function fb(e){return G.join(e,`.aimax`,`extensions`)}function pb(e={}){let t=[],n=[],r=lb(e.extraPaths);for(let i of r){if(!K.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Ky(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Yy.has(G.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=G.dirname(i);if(ib({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(ob({idHint:ab(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&cb({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?cb({rootDir:db(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&cb({rootDir:fb(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=ub();return i?cb({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&cb({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function mb(e){let t=e.rejectHardlinks??!0,n=Gy(e.rootPath),r=Gy(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!qy(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=K.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:K.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const hb=`aimax.plugin.json`,gb=[hb];function _b(e){for(let t of gb){let n=G.join(e,t);if(K.existsSync(n))return n}return G.join(e,hb)}function vb(e,t=!0){let n=_b(e),r=mb({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(K.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{K.closeSync(r.fd)}if(!Fy(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=Fy(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let s=typeof i.kind==`string`?i.kind:void 0,c=typeof i.name==`string`?i.name.trim():void 0,l=typeof i.description==`string`?i.description.trim():void 0,u=typeof i.version==`string`?i.version.trim():void 0,d=Iy(i.skills),f;return Fy(i.uiHints)&&(f=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:s,name:c,description:l,version:u,skills:d,uiHints:f},manifestPath:n}}function yb(e){let t=new Map,n=[];for(let r of e){let e=vb(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let bb=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function xb(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===bb.ERROR){Y.error(i);return}if(e===bb.WARN){Y.warn(i);return}Y.info(i)}function Sb(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>xb(bb.INFO,e.pluginId,t,n),warn:n=>xb(bb.WARN,e.pluginId,t,n),error:n=>xb(bb.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}let Cb;function wb(){return Cb||=xt(import.meta.url,{interopDefault:!0,requireCache:!0}),Cb}function Tb(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function Eb(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function Db(e){let t=[...e.registry.diagnostics],n=new Ch,r=new La,i=[],a=[],o=e.runtime?.llm?ao({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Ob(e.runtime?.llmAllowlist),c=wb();for(let l of e.registry.manifests.values()){let u=Tb({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Eb({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f=Date.now(),p;try{p=c(l.source)}catch(e){d.status=`error`,d.error=String(e),d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){d.status=`error`,d.error=`plugin module does not export a register function`,d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let g=Sb({pluginId:l.id,env:e.runtime?.env}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!kb(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);ce({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);ge({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Fa(l.id)};try{h(v)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)}d.durationMs=Math.max(0,Date.now()-f),a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Ob(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function kb(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}let Ab=null,jb=null;function Mb(e){let{dataDir:t,bundledDir:n,workspaceDir:r}=e,i=e.config?JSON.stringify({allow:e.config.allow,deny:e.config.deny,enabled:e.config.enabled,piExtensions:e.config.piExtensions}):``;return`${t??``}|${n??``}|${r??``}|${i}`}function Nb(e){let t=Mb(e);return Ab&&jb===t?Ab:(Ab=Fb(e),jb=t,Ab)}function Pb(e){return Ab&&jb===Mb(e)?Ab:Fb(e)}function Fb(e={}){let t=Uy(e.config),n=pb({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=yb(n.candidates),i=Wy({config:t,registry:r}),a=Db({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t,piExtensions:[]}}function Ib(e,t){return Array.from(new Set([...t?.piExtensionPaths??[],...e.piExtensionPaths]))}async function Lb(e,t){let n=Ib(e,t);return n.length===0?[]:ve(n)}async function Rb(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?Fb({...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 La,pluginSkillDirs:[],pluginTools:[]};o({level:c.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:c.registry.plugins.length,enabledPluginCount:c.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:c.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:c.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:c.diagnostics.length,durationMs:l}});for(let e of c.registry.plugins)o({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,durationMs:e.durationMs,errorMessage:e.error}});for(let e of c.diagnostics)o({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}});let u=Ib(c.normalizedConfig),d;if(u.length>0){let e=await Lb(c.normalizedConfig);if(e.length>0){d=new ye(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 zb=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=Cp(t),o=n,s=!o,c=Z(t);o?(await w(t.dataDir,o,c)||(s=!0),await v(t.dataDir,o,c)):o=await T(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>F(t.dataDir,o,c)}},u=new zb,d=await Rb({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await wp({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=>kv({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function Vb(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Hb(e){if(!(e instanceof Error))return{errorValue:Vb(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]=Vb(n[e]));return t}async function Ub(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Hb(e.error)}})}function Wb(e,t,n){return G.join(r(e,t,n),`pending-ui-tool.json`)}async function Gb(e,t,n,i){let a=r(e,t,i);await W.mkdir(a,{recursive:!0}),await L(Wb(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function Kb(e,t,n){let r=await o(Wb(e,t,n));return r===null?null:JSON.parse(r)}async function qb(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Gb(e,t,a,r),a}async function Jb(e,t,n,r,i){let a=await Kb(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 Gb(e,t,o,i),o}async function Yb(e,t,n){try{await W.unlink(Wb(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Xb(e,t,n,r){let i=await U(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function Zb(e,t,n,r,i,a){let o=await U(e,t,{storeName:a?.storeName});await Xb(e,t,n,a);let s=await Ct(e,t,n,r,a);return s.goal&&await wy(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function Qb(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ye(t))}async function $b(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=ns();if(i=await rs(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Qo(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=ex(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 ex(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 tx=2e4,nx=15e4,rx=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function ix(e){return G.join(e,`.aimax`)}async function ax(e){let t=ix(e),n=[];for(let e of rx){let r=G.join(t,e);try{let t=await W.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await W.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function ox(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
|
|
147
150
|
`),s].join(`
|
|
148
|
-
`),truncated:!0,originalLength:r.length}}function kb(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Ab(e,t){let n=t?.maxChars??Cb,r=Math.max(1,t?.totalMaxChars??Math.max(n,wb)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=kb(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=Ob(a.content??``,a.name,e),l=kb(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const jb=`You are a personal assistant running inside AiMax.`;async function Mb(e){try{return{presetSystemPrompt:ot(await U.readFile(e,`utf-8`)).content.trim()||jb}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:jb};throw e}}async function Nb(){return Mb(`/aimax_pvc/system_prompt.md`)}async function Pb(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await Db(t.dataDir),o=[],s=Ab(a,{warn:e=>o.push(e)}),c=await Nb();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),J.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await Df(t.dataDir,r.pluginSkillDirs,l),d=await ya({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),J.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),J.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await Fb({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function Fb(e){if(!e.enabled)return[];try{let t=await new Mi({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var Ib=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const Lb=`crons`;function Rb(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:ro(e.message)}}async function zb(e){let t,n=0,r=0,i;if(e.runtimeBridge.hasPendingMessages()){let a=e.runtimeBridge.drainMessages();for(let o of a){let a=await tg({agent:e.agent,message:o,continueFromHistory:!1,sessionId:e.sessionId,channel:e.channel,modelId:e.resolvedModelId,historyMessages:e.runtime.historyMessages,eventDispatcher:e.eventDispatcher,hooks:e.hookRegistry,hookCtx:e.hookContext,abortSignal:e.abortSignal,retry:e.retry,onTurnRecordProduced:async(t,n)=>{t&&await e.appendEntry(t);for(let t of n)await e.appendEntry(t)}});n+=a.inputTokens,r+=a.outputTokens,a.text&&(t=a.text),a.error&&(i=a.error);let s=await ty({agent:e.agent,registry:e.registry,sessionId:e.sessionId,resolvedModelId:e.resolvedModelId,eventDispatcher:e.eventDispatcher,hookRegistry:e.hookRegistry,hookContext:e.hookContext,abortSignal:e.abortSignal,appendEntry:e.appendEntry});n+=s.inputTokens,r+=s.outputTokens,s.text&&(t=s.text),s.error&&!i&&(i=s.error)}}let a=e.runtimeBridge.drainCompactRequest();if(a)try{let t=await Lv({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,X(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{apiFormat:e.runParams.llm.apiFormat,baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:a.customInstructions,signal:e.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});t.status===`compacted`&&await e.appendEntry(t.entry),a.onComplete?.(t)}catch(e){a.onError?.(e instanceof Error?e:Error(String(e)))}return{lastResponseText:t,inputTokens:n,outputTokens:r,error:i}}async function Bb(e,t){W_();let n=Date.now(),i=new io(e),a=qv(e);J.info(`agent invocation prepared`,{requestedSessionId:a.requestedSessionId,previousSessionId:a.previousSessionId,inputMode:a.inputMode,hasSlashCommand:!!a.slashCommandSource,resetAction:a.resetCommand?.action,resetShortCircuit:a.resetShortCircuit,transcriptLength:a.transcriptMessage.length,messageForRunLength:a.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await cb({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId;no(e.dataDir,{messageId:e.messageId,sessionId:u,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,u,X(e))});let d=l.isNewSession,f=l.workspaceDir,m=l.hookContext,h=l.hookRegistry,g=l.pluginContext,_=l.runContext,v=l.runtimeBridge,y=0,b=!1,x=()=>{b||(b=!0,v.dispose())},S=(await F(e.dataDir,u,{storeName:e.sessionStoreName})).length;if(J.info(`agent run started`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:d,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:d,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),J.info(d?`session created`:`session resumed`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}),await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:d?`session_created`:`session_resumed`,message:d?`session created`:`session resumed`,details:{requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}}),d&&await p(e.dataDir,qf({sessionId:u,title:Z_(o),channel:e.channel}),X(e)),e.pendingGoal){let t=await oe(e.dataDir,u,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await Sn(e.dataDir,u,{goalId:t.goalId,objective:e.pendingGoal.objective},{storeName:e.sessionStoreName})}a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await _.persistInitialUserEntry(o));let C=new AbortController;e.abortSignal?.aborted?C.abort():e.abortSignal?.addEventListener(`abort`,()=>C.abort()),m.signal=C.signal,await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let w=await Pb({runParams:e,sessionId:u,pluginContext:g,eventDispatcher:i}),T=e=>_.appendTranscriptEntry(e),E=await Yv({invocation:a,skills:w.skills,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,extensionHost:g.extensionHost});if(E.kind===`completed`)return J.info(`agent run short-circuited`,{sessionId:u,durationMs:Date.now()-n,hasError:!!E.result.error,paused:!!E.result.paused,uiToolPending:!!E.result.uiToolPending,textLength:E.result.text.length}),x(),E.result;let D=E.effectivePrompt;o=E.transcriptMessage;let O=typeof D==`string`?D:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof D==`string`?`string`:`messages`,transcriptLength:o.length}}),J.info(`invocation resolved`,{sessionId:u,promptType:typeof D==`string`?`string`:`messages`,transcriptLength:o.length});let k=await zh({session:{runParams:w.runParamsWithAgentPolicy,sessionId:u,hookRegistry:h,hookContext:m,runContext:_,eventDispatcher:i},runtimeInputs:{contextFiles:w.contextFiles,bootstrapWarnings:w.bootstrapWarnings,skills:w.skills,autoSkillCategories:w.autoSkillCategories,effectivePromptText:O,pluginTools:g.pluginTools,pluginSkillDirs:g.pluginSkillDirs,skillsLoadPaths:w.skillsLoadPaths,presetSystemPrompt:w.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Bb(e,new rm),createModel:fa,abortSignal:C.signal}}),A=k.agent,j=k.resolvedModelId;v.bindAgent(A),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:j,historyMessageCount:k.historyMessages.length,pluginToolCount:g.pluginTools.length}}),J.info(`agent runtime created`,{sessionId:u,modelId:j,historyMessageCount:k.historyMessages.length,pluginToolCount:g.pluginTools.length});let M=Kb(e.timeoutMs),N=!1,ee=M===void 0?void 0:setTimeout(()=>{N=!0,C.abort(),A.abort(),i.dispatchDiagnostic(u,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:M}}),J.warn(`agent run timed out`,{sessionId:u,timeoutMs:M})},M);C.signal.addEventListener(`abort`,()=>A.abort());let P=new Ib,I=``,L,R=!1,te=new Ct;await vb(e.dataDir,u,te,{storeName:e.sessionStoreName}),C.signal;try{if(bb(e)){let t=await xb({params:e,agent:A,sessionId:u,eventDispatcher:i,appendEntry:T,abortSignal:C.signal});return I=t.text,x(),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await _.persistInitialUserEntry(o);R=t,s=t||s;try{await un(e.dataDir,u,{storeName:e.sessionStoreName},()=>xr(e.dataDir,u,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof sn))throw e}}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await H(e.dataDir,u,{storeName:e.sessionStoreName}),a=!1,c=null;if(r?.status===`active`)try{c=await hr(e.dataDir,u,{storeName:e.sessionStoreName})}catch(e){if(e instanceof sn)a=!0;else throw e}let l=!!(a||c&&Er(c)),f=kr({hookRegistry:h,isGateActive:()=>l}),p=await Cr(e.dataDir,u,D,{storeName:e.sessionStoreName}),g;if(a){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Call goal_repair_workflow_state with confirm:true to reinitialize from the saved objective before other goal workflow tools.`,`</goal_context>`,``].join(`
|
|
149
|
-
`);g={prompt:typeof p.prompt==`string`?e+p.prompt:[{type:`text`,text:e},...p.prompt],hadFirstGoalWorkflowSteering:!0}}else g=await Sr(e.dataDir,u,p.prompt,{storeName:e.sessionStoreName});J.info(`first agent turn started`,{sessionId:u,modelId:j});let b=await tg({agent:A,message:g.prompt,continueFromHistory:!!e.uiToolResume,sessionId:u,channel:e.channel,modelId:j,historyMessages:k.historyMessages,eventDispatcher:i,hooks:h,hookCtx:m,abortSignal:C.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await T(e);for(let e of t)await T(e)}});f(),I=b.text,P.add(b.inputTokens,b.outputTokens),b.error&&(L=b.error),p.hadObjectiveUpdatedSteering&&!b.error&&await wr(e.dataDir,u,{storeName:e.sessionStoreName}),await i.dispatchDiagnostic(u,{level:b.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!b.error,error:b.error,inputTokens:b.inputTokens,outputTokens:b.outputTokens}});let S={sessionId:u,hasError:!!b.error,error:b.error,inputTokens:b.inputTokens,outputTokens:b.outputTokens};b.error?J.warn(`first agent turn completed with error`,S):J.info(`first agent turn completed`,S);let w=await yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`});w.budgetLimited&&await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),J.info(`announce loop started`,{sessionId:u});let E=await ty({agent:A,registry:t,sessionId:u,resolvedModelId:j,eventDispatcher:i,hookRegistry:h,hookContext:m,abortSignal:C.signal,retry:e.llmRetry,appendEntry:T});if(E.text&&(I=E.text),P.add(E.inputTokens,E.outputTokens),E.error&&!L&&(L=E.error),await i.dispatchDiagnostic(u,{level:E.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!E.error,error:E.error,inputTokens:E.inputTokens,outputTokens:E.outputTokens}}),w=await yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`}),w.budgetLimited&&await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),gr()){let n=new mr;n.reset(),b.error&&(n.lastTurnHadOutput=!1);let r=!0,a=qe;for(;r&&n.continuationCount<a&&!C.signal.aborted;)if(r=await yr({agent:A,dataDir:e.dataDir,sessionId:u,sessionStoreName:e.sessionStoreName,state:n,accounting:te,abortSignal:C.signal,executeTurn:async t=>{let n=await tg({agent:A,message:t,continueFromHistory:!1,sessionId:u,channel:e.channel,modelId:j,historyMessages:k.historyMessages,eventDispatcher:i,hooks:h,hookCtx:m,abortSignal:C.signal,onTurnRecordProduced:async(e,t)=>{await br(T,e,t)}});P.add(n.inputTokens,n.outputTokens),I=n.text||I,n.error&&!L&&(L=n.error);let r=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:r}},flushAccountingAfterTurn:async()=>{(await yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),r){let e=await ty({agent:A,registry:t,sessionId:u,resolvedModelId:j,eventDispatcher:i,hookRegistry:h,hookContext:m,abortSignal:C.signal,appendEntry:T});P.add(e.inputTokens,e.outputTokens),e.text&&(I=e.text),e.error&&!L&&(L=e.error)}}do{if(C.signal.aborted)break;if(y++,y>8){i.dispatchDiagnostic(u,{level:`warn`,scope:`runner`,phase:`bridge_cycle_limit`,message:`SessionRuntimeBridge exceeded max cycles (8)`}).catch(()=>{});break}await $_({sessionId:u,result:{sessionId:u,text:I??``,usage:P.snapshot(),durationMs:Date.now()-n,error:L},runParams:e,hookRegistry:h,hookContext:m,eventDispatcher:i});let r=await zb({runtimeBridge:v,agent:k.agent,runtime:k,sessionId:u,channel:e.channel,resolvedModelId:j,eventDispatcher:i,hookRegistry:h,hookContext:m,abortSignal:C.signal,retry:e.llmRetry,appendEntry:T,runParams:e,registry:t});P.add(r.inputTokens,r.outputTokens),r.lastResponseText&&(I=r.lastResponseText),r.error&&!L&&(L=r.error)}while(!C.signal.aborted&&(v.hasPendingMessages()||v.hasPendingCompact()));x();let O={sessionId:u,hasError:!!E.error,error:E.error,inputTokens:E.inputTokens,outputTokens:E.outputTokens};E.error?J.warn(`announce loop completed with error`,O):J.info(`announce loop completed`,O)}catch(t){if(vo(t)){let r=t,a=e.subagentContext?.parentSessionId??u,s=a===r.request.sessionId?r.request:{...r.request,sessionId:a};await we(e.dataDir,a,s,r.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},r.toolContext),await i.dispatchProgress(a,{type:`hitl_requested`,request:s}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),J.info(`agent paused for HITL`,{sessionId:u,requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={...P.snapshot()};return await Vb({runtime:k,resolvedModelId:j,usage:c,currentUserEntryCoveredByUsage:R}),x(),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(bo(t)){let r=t,a=r.request.outputSchema.properties??{};await hb(e.dataDir,u,r.request,X(e)),await i.dispatchProgress(u,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length}}),J.info(`agent paused for UI tool input`,{sessionId:u,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length});let s={...P.snapshot()};return await Vb({runtime:k,resolvedModelId:j,usage:s,currentUserEntryCoveredByUsage:R}),x(),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I||``,usage:s,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}if(N&&qb(t))L=`Run timed out after ${M}ms`;else throw await db({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),J.error(`agent run failed`,{sessionId:u,channel:e.channel,isNewSession:d,error:t instanceof Error?t.message:String(t)}),t}finally{ee!==void 0&&clearTimeout(ee);try{await yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}te.clearActiveGoal(),kh(u);try{k.processRegistry.disposeAll()}catch{}_.stop(),x()}let z=P.snapshot();N&&(L=`Run timed out after ${M}ms`),await i.dispatchDiagnostic(u,{level:L?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L}});let ne={sessionId:u,durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L};return L?J.warn(`agent run completed with error`,ne):J.info(`agent run completed`,ne),await Vb({runtime:k,resolvedModelId:j,usage:z,currentUserEntryCoveredByUsage:R}),await w_({sessionId:u,runParams:w.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:S,result:{text:I,usage:z,durationMs:Date.now()-n,error:L}}),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I,usage:z,error:L,sessionEndOnly:y>0})}async function Vb(e){let{runtime:t,resolvedModelId:n,usage:r,currentUserEntryCoveredByUsage:i}=e;r.input<=0&&r.total<=0||await t.contextManager.recordModelUsage({model:n,inputTokens:r.input,outputTokens:r.output,totalTokens:r.total,coveredTranscriptEntryCount:t.usageBaselineTranscriptEntryCount+(i?1:0)})}async function Hb(e){let t=Date.now(),i=new io(e),a=qv(e),o=a.transcriptMessage.trim()||`CRON task`,c=e.sessionStoreName;J.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...Rb(e)});let l=a.requestedSessionId,d=!l;l?(await n(e.dataDir,l,{storeName:c})||(d=!0),await v(e.dataDir,l,{storeName:c})):l=await T(e.dataDir,e.channel,{storeName:c}),d&&await p(e.dataDir,qf({sessionId:l,title:Z_(o),channel:e.channel}),{storeName:c});let f=await T(e.dataDir,e.channel,{storeName:Lb});no(e.dataDir,{messageId:e.messageId,sessionId:f,sessionStoreName:Lb,sessionDir:r(e.dataDir,f,{storeName:Lb})}),await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:f,task:o}),J.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:f,taskLength:o.length,taskPreview:ro(o)});let m={...e,sessionId:f,sessionStoreName:Lb,subagentContext:{depth:1,parentSessionId:l}},g,y=`done`;try{g=await Bb(m,new rm),g.error&&(y=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);g={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,f,{storeName:Lb}),toolResultsDir:s(e.dataDir,f,{storeName:Lb})}},y=`error`,J.error(`cron child run failed`,{parentSessionId:l,childSessionId:f,error:r})}await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:f,task:o,status:y}),J.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:f,status:y,durationMs:Date.now()-t,hasError:!!g.error});let b=sm({task:o,status:y,result:g.text,error:g.error}),x=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:b,timestamp:x,source:`cron`},{storeName:c});let C={task:o,status:y,content:b,childSessionId:f,createdAt:x};return await S(e.dataDir,l,C,{storeName:c}),await P(e.dataDir,l,e=>Ub(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...g,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function Ub(e,t){if(t<=0)return e.filter(e=>!Wb(e));let n=e.reduce((e,t,n)=>(Wb(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Wb(e)||r.has(t))}function Wb(e){return`source`in e&&e.source===`cron`}async function Gb(e,t){let n=async()=>{if(J.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...Rb(e)}),e.channel===`CRON`&&!e.subagentContext)return Hb(e);let n=t??new rm;try{return await Bb(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:ub(t)}),J.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};return e.onLog?Ua(e.onLog,n):n()}function Kb(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function qb(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const Jb={"AGENTS.md":`---
|
|
151
|
+
`),truncated:!0,originalLength:r.length}}function sx(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function cx(e,t){let n=t?.maxChars??tx,r=Math.max(1,t?.totalMaxChars??Math.max(n,nx)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=sx(`[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}=ox(a.content??``,a.name,e),l=sx(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 lx=`You are a personal assistant running inside AiMax.`;async function ux(e){try{return{presetSystemPrompt:at(await W.readFile(e,`utf-8`)).content.trim()||lx}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:lx};throw e}}async function dx(){return ux(`/aimax_pvc/system_prompt.md`)}async function fx(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await ax(t.dataDir),o=[],s=cx(a,{warn:e=>o.push(e)}),c=await dx();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}}),Y.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await sp(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}))}}),Y.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}))}}),Y.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 px({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function px(e){if(!e.enabled)return[];try{let t=await new ji({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var mx=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const hx={Inferred:1,Child:2,Own:3};var gx=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=vx(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,hx.Own)}addInferred(e){this.add(e,hx.Inferred)}addChild(e){e&&e.length>0&&this.add(e,hx.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=_x(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=yx(e.url);return t?this.urlWhitelist.has(t):!1}};function _x(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function vx(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function yx(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const bx=`crons`;function xx(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:no(e.message)}}async function Sx(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 jg({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 Ny({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 hy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,Z(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{apiFormat:e.runParams.llm.apiFormat,baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:a.customInstructions,signal:e.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});t.status===`compacted`&&await e.appendEntry(t.entry),a.onComplete?.(t)}catch(e){a.onError?.(e instanceof Error?e:Error(String(e)))}return{lastResponseText:t,inputTokens:n,outputTokens:r,error:i}}async function Cx(e,t){xv();let n=Date.now(),i=new ro(e),a=new gx({urlWhitelist:e.artifactsUrlWhitelist}),o=Ty(e);Y.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;to(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,Z(e))});let f=u.isNewSession,m=u.workspaceDir,h=u.hookContext,g=u.hookRegistry,_=u.pluginContext,v=u.runContext,y=u.runtimeBridge,b=0,x=!1,S=()=>{x||(x=!0,y.dispose())},C=(await F(e.dataDir,d,{storeName:e.sessionStoreName})).length;if(Y.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}}),Y.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,Tp({sessionId:d,title:Ov(s),channel:e.channel}),Z(e)),e.pendingGoal){let t=await ae(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await xn(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 fx({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await Dy({invocation:o,skills:T.skills,sessionId:d,isNewSession:f,initialUserEntryPersisted:c,runParams:e,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,extensionHost:_.extensionHost});if(D.kind===`completed`)return Y.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}}),Y.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await hg({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=>Cx(e,new Mm),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}}),Y.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=kx(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}}),Y.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let I=new mx,L=``,R,te=!1,z=new St;await Xb(e.dataDir,d,z,{storeName:e.sessionStoreName}),w.signal;try{if(Qb(e)){let t=await $b({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return L=t.text,S(),Fv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,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 ln(e.dataDir,d,{storeName:e.sessionStoreName},()=>br(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof on))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await U(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await mr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof on)o=!0;else throw e}let u=!!(o||l&&Tr(l)),p=Or({hookRegistry:g,isGateActive:()=>u}),m=await Sr(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Call goal_repair_workflow_state with confirm:true to reinitialize from the saved objective before other goal workflow tools.`,`</goal_context>`,``].join(`
|
|
152
|
+
`);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await xr(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});Y.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await jg({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 Cr(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?Y.warn(`first agent turn completed with error`,C):Y.info(`first agent turn completed`,C);let T=await Zb(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`}),Y.info(`announce loop started`,{sessionId:d});let D=await Ny({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 Zb(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`}),hr()){let n=new pr;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=Ke;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await vr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:z,abortSignal:w.signal,executeTurn:async t=>{let n=await jg({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 yr(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 Zb(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 Ny({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 Av({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 Sx({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?Y.warn(`announce loop completed with error`,k):Y.info(`announce loop completed`,k)}catch(t){if(Qo(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await Ce(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}}),Y.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 wx({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:te}),S(),Fv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,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(es(t)){let r=t,o=r.request.outputSchema.properties??{};await qb(e.dataDir,d,r.request,Z(e)),await i.dispatchProgress(d,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(d,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length}}),Y.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 wx({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:te}),S(),Fv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,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&&Ax(t))R=`Run timed out after ${N}ms`;else throw await Ub({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),Y.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 Zb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}z.clearActiveGoal(),ag(d);try{A.processRegistry.disposeAll()}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?Y.warn(`agent run completed with error`,V):Y.info(`agent run completed`,V),await wx({runtime:A,resolvedModelId:M,usage:B,currentUserEntryCoveredByUsage:te}),await tv({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:L,usage:B,durationMs:Date.now()-n,error:R}}),Fv({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),transcriptStartIndex:C,text:L,usage:B,error:R,sessionEndOnly:b>0})}async function wx(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 Tx(e){let t=Date.now(),i=new ro(e),a=Ty(e),o=a.transcriptMessage.trim()||`CRON task`,c=e.sessionStoreName;Y.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...xx(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,Tp({sessionId:l,title:Ov(o),channel:e.channel}),{storeName:c});let f=await T(e.dataDir,e.channel,{storeName:bx});to(e.dataDir,{messageId:e.messageId,sessionId:f,sessionStoreName:bx,sessionDir:r(e.dataDir,f,{storeName:bx})}),await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:f,task:o}),Y.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:f,taskLength:o.length,taskPreview:no(o)});let m={...e,sessionId:f,sessionStoreName:bx,subagentContext:{depth:1,parentSessionId:l}},g,y=`done`;try{g=await Cx(m,new Mm),g.error&&(y=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);g={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,f,{storeName:bx}),toolResultsDir:s(e.dataDir,f,{storeName:bx})}},y=`error`,Y.error(`cron child run failed`,{parentSessionId:l,childSessionId:f,error:r})}await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:f,task:o,status:y}),Y.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:f,status:y,durationMs:Date.now()-t,hasError:!!g.error});let b=Im({task:o,status:y,result:g.text,error:g.error}),x=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:b,timestamp:x,source:`cron`},{storeName:c});let C={task:o,status:y,content:b,childSessionId:f,createdAt:x};return await S(e.dataDir,l,C,{storeName:c}),await ee(e.dataDir,l,e=>Ex(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...g,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function Ex(e,t){if(t<=0)return e.filter(e=>!Dx(e));let n=e.reduce((e,t,n)=>(Dx(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Dx(e)||r.has(t))}function Dx(e){return`source`in e&&e.source===`cron`}async function Ox(e,t){let n=async()=>{if(Y.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,...xx(e)}),e.channel===`CRON`&&!e.subagentContext)return Tx(e);let n=t??new Mm;try{return await Cx(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:Hb(t)}),Y.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};return e.onLog?Ha(e.onLog,n):n()}function kx(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Ax(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 jx={"AGENTS.md":`---
|
|
150
153
|
title: "AGENTS.md Template"
|
|
151
154
|
summary: ".aimax template for AGENTS.md"
|
|
152
155
|
read_when:
|
|
@@ -439,7 +442,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
|
|
|
439
442
|
This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
|
|
440
443
|
|
|
441
444
|
Add whatever helps you do your job. This is your cheat sheet.
|
|
442
|
-
`},
|
|
445
|
+
`},Mx=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Nx(e,t){try{if(!(await W.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Px(e,t,n){try{if(!(await W.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(G.dirname(e),{recursive:!0});try{await W.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function Fx(e){let t=ix(e);return[e,t,G.join(t,`skills`),G.join(t,`sessions`),G.join(t,`memory`),G.join(e,`workspace`)]}function Ix(e){let t=ix(e);return[...Mx.filter(e=>e!==`BOOTSTRAP.md`).map(e=>G.join(t,e)),G.join(t,`MEMORY.md`)]}function Lx(e){return G.join(ix(e),`.bootstrapped`)}async function Rx(e){try{return(await W.stat(Lx(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function zx(e){let t=Lx(e);await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,``,{encoding:`utf-8`})}async function Bx(e){let t=[],n=[];for(let n of Fx(e))try{(await W.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Ix(e))try{(await W.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function Vx(e){return(await Bx(e)).ready}async function Hx(e){if(await Rx(e))return{ready:!0,performedBootstrap:!1};if((await Bx(e)).ready)return await zx(e),{ready:!0,performedBootstrap:!1};let t=await Ux(e);return await zx(e),{ready:!0,performedBootstrap:!0,result:t}}async function Ux(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=ix(e),r=G.join(e,`workspace`),i=G.join(n,`skills`),a=G.join(n,`sessions`),o=G.join(n,`memory`);await Nx(e,t),await Nx(n,t),await Nx(i,t),await Nx(a,t),await Nx(o,t),await Nx(r,t);for(let e of Mx){let r=jx[e]??``;await Px(G.join(n,e),r,t)}return await Px(G.join(n,`MEMORY.md`),``,t),t}async function Wx(e){let t=G.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await W.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function Gx(e,t){let n=G.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await W.mkdir(G.dirname(n),{recursive:!0}),await W.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Kx(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 qx(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 Gx(e,n),i}var Jx=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function Yx(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function Xx(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await U(t,n,s);if(!l){let e=await ae(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await xn(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 Jx(`A different goal already exists for this session. Use --force to replace it.`,Yx(u));let e=await ae(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await xn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new Jx(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,Yx(u));if(a){let e=await ae(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await xn(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 Zx(e,t,n,r){let i=await Ee(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Je(i.request)?(await Se(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 Qx(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Te(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 Zx(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Se(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 $x={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 eS(e){return e.action===`timeout`?$x.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?$x.approval.summary.approved:$x.approval.summary.denied}function tS(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:eS(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function nS(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 rS(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 iS(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
|
|
443
446
|
`)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
|
|
444
447
|
`)):(n.push(`动作:用户已提交结果。`),e.values?.selectedChoiceIds&&e.values.selectedChoiceIds.length>0&&n.push(`已选项:${e.values.selectedChoiceIds.join(`, `)}`),e.values?.text&&n.push(`用户文本:${e.values.text}`),e.values?.form&&n.push(`表单数据:${JSON.stringify(e.values.form)}`),n.join(`
|
|
445
|
-
`))}export{
|
|
448
|
+
`))}export{ji as AutoSkillsLoader,rx as BOOTSTRAP_FILE_NAMES,tx as BOOTSTRAP_MAX_CHARS,nx as BOOTSTRAP_TOTAL_MAX_CHARS,Tt as CLARIFY_ACCEPTANCE_TEXT,wr as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,wt as CLARIFY_TASK_TITLE,pr as ContinuationState,on as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,fr as ENV_GOAL_CONTINUATION,ar as FIRST_TURN_GOAL_WORKFLOW_INTRO,zv as GOAL_MULTILINE_TEMPLATE_EXAMPLE,nn as GOAL_WORKFLOW_STATE_VERSION,St as GoalAccounting,Jx as GoalConflictError,$x as HITL_MESSAGES,Zo as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,jm as MAX_CHILDREN_PER_SESSION,Am as MAX_SUBAGENT_DEPTH,fe as MemoryIndexManager,hb as PLUGIN_MANIFEST_FILENAME,gb as PLUGIN_MANIFEST_FILENAMES,La as PluginHookRegistry,Ch as PluginToolRegistry,fa as SYSTEM_AGENTS_DIR,Mm as SubagentRegistry,$o as UiToolPauseSignal,He as addAgent,Re as addBinding,ma as agentDirCandidates,Sa as agentVisibility,ix as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,te as appendGoalEvent,uf as appendRecentToMemory,i as appendSessionFile,lf as appendToMemory,h as appendTranscriptEntry,Xx as applyCliGoalBeforeRun,eS as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,di as autoSkillsDir,Ux as bootstrapMountLayout,Ea as buildAgentDelegationPrompt,Da as buildAgentTaskPrompt,Vv as buildAimaxGoalCliHelpExtra,cx as buildBootstrapContextFiles,cr as buildBudgetLimitPrompt,sr as buildContinuationPrompt,or as buildFirstTurnGoalWorkflowPrompt,ur as buildGoalContextItem,Bv as buildGoalSlashHelpText,lr as buildObjectiveUpdatedPrompt,iS as buildResumeNarration,fp as buildSkillsPrompt,Im as buildSubagentAnnounceMessage,xh as buildSystemPrompt,qx as cleanupOldSubagentRecords,De as clearPendingHitl,Yb as clearPendingUiTool,j as collapseLogPath,Cr as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,_r as continuationTurnHadMeaningfulOutput,ga as createAgentDefinitionsContext,Ym as createAgentTools,Vd as createApplyPatchTool,Sm as createAutoSkillCategoriesTool,Cm as createAutoSkillListTool,wm as createAutoSkillSearchTool,Tm as createAutoSkillViewTool,ki as createAutoSkillsLoader,Sd as createBashTool,Bm as createBatchSubagentSpawnTool,ue as createBuiltinMemoryProvider,ad as createContextManager,Md as createEditFileTool,_d as createExecTool,Km as createImageTool,Pd as createListDirTool,vf as createMemoryAppendTool,Mf as createMemoryForgetTool,gf as createMemoryGetTool,Af as createMemoryListTool,Of as createMemoryLogTool,mf as createMemorySearchTool,Pf as createMemoryUpdateTool,bf as createMemoryWriteTool,Ce as createPendingHitl,qb as createPendingUiTool,Fa as createPluginProgressEmitter,Sb as createPluginRuntime,xd as createProcessTool,Od as createReadFileTool,T as createSession,Mu as createSessionContextStore,If as createSessionSearchTool,gp as createSkillListTool,_p as createSkillLoadTool,zm as createSubagentSpawnTool,Wm as createSubagentsTool,Jm as createUiTool,Ad as createWriteFileTool,N as cronExecutionsPath,qm as defaultUiToolInputSchema,ie as deleteGoal,bn as deleteGoalWorkflow,ff as deleteMemoryFile,pb as discoverAIMaxPlugins,Cy as emitGoalUpdatedProgress,Hx as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,Rt as extractWorkflowPlanFromObjective,wa as filterSkillsForAgent,Ta as filterToolsForAgent,xa as findAgentDefinition,lp as findSkillByName,Ct as flushAccounting,tS as formatApprovalResolution,nS as formatClarifyResolution,rS as formatReviewResolution,Cv as generateSessionTitle,Fe as getAgentConfig,cf as getMemoryLines,Pb as getPluginSystem,fn as goalArtifactsDir,H as goalDir,R as goalEventsPath,re as goalObjectiveMdPath,B as goalPath,dn as goalWorkflowPlanPath,un as goalWorkflowStatePath,Rx as hasBootstrapSentinel,xe as hitlHistoryPath,xn as initializeGoalWorkflow,Fb as initializePluginSystem,Bx as inspectBootstrapMountLayout,k as inspectSession,Or as installClarifyFirstTurnGate,Vx as isBootstrapMountLayoutReady,Er as isClarifyFirstTurnBlockedTool,Tr as isClarifyWorkflowTask,hr as isContinuationEnabled,dr as isGoalContext,Qo as isHitlPauseSignal,es as isUiToolPauseSignal,ke as listAgents,ty as listAvailableSlashCommands,ze as listBindings,rf as listMemoryFiles,E as listSessionSummaries,x as listSessions,Kx as listSubagentRunsFromDisk,ya as loadAgentDefinitionsFromDir,Ve as loadAgentsConfig,b as loadArtifactOperations,ax as loadBootstrapFiles,m as loadCronExecutionRecords,Ee as loadPendingHitl,Ee as readPendingHitl,Kb as loadPendingUiTool,Kb as readPendingUiTool,vb as loadPluginManifest,yb as loadPluginManifestRegistry,Db as loadPlugins,P as loadSessionContextSnapshot,dc as loadSessionExportSnapshots,I as loadSessionMetadata,dp as loadSkillView,op as loadSkills,cp as loadSkillsFromDirs,sp as loadSkillsWithPluginDirs,Wx as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,mr as loadWorkflowPromptContext,vr as maybeContinueGoalIfIdle,$d as memoryDir,f as metadataPath,ne as mirrorGoalStatusToSession,Ae as normalizeAgentId,Uy as normalizePluginsConfig,t as normalizeSessionStoreName,ba as parseAgentDefinition,be as pendingHitlPath,Wb as pendingUiToolPath,uc as persistSessionExportSnapshots,Nb as preloadPluginSystem,xr as prependFirstGoalWorkflowSteeringIfNeeded,Sr as prependObjectiveUpdatedSteeringIfNeeded,ef as primaryMemoryPath,Ca as publicAgentDefinitions,U as readGoal,gn as readGoalWorkflowState,vn as readGoalWorkflowSummary,we as readHitlHistory,af as readMemoryFile,of as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,br as recoverBlockedWorkflowOnUserTurn,ce as registerEmbeddingProvider,ge as registerMemoryProvider,Ie as removeAgent,Ue as removeBindings,Vt as renderGoalPlanMarkdown,_n as repairGoalWorkflowState,df as replaceMemoryFile,oe as resetEmbeddingProviderRegistryForTests,_e as resetMemoryProviderRegistryForTests,va as resolveAgentDefinitionsContext,je as resolveAgentDir,Me as resolveAgentIdByBinding,Be as resolveAgentsConfigPath,Le as resolveDefaultAgentId,de as resolveEmbeddingProvider,z as resolveGoalObjective,yn as resolveGoalToolWorkflowView,Qx as resolveHitlRequest,Qx as resolvePendingHitl,he as resolveMemoryProvider,Pe as resolveModelFallbacks,Ne as resolveModelString,Jb as resolvePendingUiTool,_b as resolvePluginManifestPath,ee as rewriteTranscript,Ox as runAgent,Oe as saveAgentsConfig,p as saveSessionMetadata,Gx as saveSubagentRegistryToDisk,ha as scanAgentDefinitions,sf as searchMemory,cc as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,sc as sessionToolsSnapshotPath,e as sessionsDir,gr as shouldContinueGoal,ep as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,Se as transitionHitlStatus,We as updateAgent,Ge as updateAgentIdentity,V as updateGoal,u as updateSessionMetadata,Wy as validatePluginsConfig,Zx as validateResume,ln as withGoalWorkflowLock,Th as wrapToolsWithHooks,ae as writeGoal,L as writeSessionFile};
|