@gencode/agents 0.1.2 → 0.2.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 CHANGED
@@ -1,6 +1,16 @@
1
1
  # @gencode/agents
2
2
 
3
- ## 0.1.2
3
+ ## 0.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 5d8068e: Updated summarization prompt to preserve skill locations alongside names; added parseSkillLoadInfo() and parseSkillLoadPayload() functions to extract both name and path from skill_load results; updated buildSkillLoadSummaryHint() to include location info in folded content hints.
8
+
9
+ ## 0.2.0
10
+
11
+ ### Minor Changes
12
+
13
+ - Add CLI support for loading additional absolute skill directories and pass them through run and resume flows into the agent skill registry.
4
14
 
5
15
  ### Patch Changes
6
16
 
package/dist/index.js CHANGED
@@ -14,76 +14,76 @@ import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,P as s,S as c,T as l,_ a
14
14
  `)}}function vn(e,t){let n=t.trim().toLowerCase();return n&&sn(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function yn(e){let t=vn(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(`
15
15
 
16
16
  `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function bn(e){let t=fn(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?_n(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?yn({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:{kind:`pass`,message:e.message}}function G(e){return Math.ceil(e.length/4*1.2)}function xn(e){if(e.role===`user`)return G(e.content);if(e.role===`assistant`){let t=G(e.content);for(let n of e.toolCalls??[])t+=G(n.name)+G(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
17
- `):e.content;return G(e.toolName)+G(t)}function K(e){return e.reduce((e,t)=>e+xn(t),0)}const Sn=[`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 mentioned or loaded in the compressed content, especially skill_load names`,`- 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(`
17
+ `):e.content;return G(e.toolName)+G(t)}function K(e){return e.reduce((e,t)=>e+xn(t),0)}const Sn=[`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(`
18
18
  `);async function Cn(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Tn(t,r,i),l,u=vt({baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:o,hookCtx:s});for(let e=1;e<=3;e++)try{let e=(await u.chat({system:Sn,user:c,temperature:0,maxTokens:2048,signal:a})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;l=t,e<3&&await wn(500*e)}throw l}function wn(e){return new Promise(t=>setTimeout(t,e))}function Tn(e,t,n){let r=[];n?.trim()&&r.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(r.push(`[Prior summary]\n${t.trim()}\n`),r.push(`[Conversation to incorporate]`)):r.push(`[Conversation to summarise]`);for(let t of e)if(t.role===`user`)r.push(`User: ${t.content}`);else if(t.role===`assistant`){let e=t.toolCalls&&t.toolCalls.length>0?` [called tools: ${t.toolCalls.map(e=>e.name).join(`, `)}]`:``;r.push(`Assistant:${e} ${t.content}`.trimEnd())}else if(t.role===`tool_result`){let e=t.isError?`error`:`ok`,n=t.toolName===`skill_load`?En(t):t.toolResultRef?[`[tool result persisted] ${t.toolResultRef.toolName} (${t.toolResultRef.originalChars} chars).`,`Full output: ${t.toolResultRef.storagePath}`,t.toolResultRef.preview.trim()?`Preview:\n${t.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
19
19
  `):t.content,i=n.length>2e3?`${n.slice(0,2e3)}… [truncated]`:n;r.push(`Tool(${t.toolName})[${e}]: ${i}`)}return r.join(`
20
- `)}function En(e){let t=e.content.match(/^Original path: (.+)$/m)?.[1]?.trim(),n=Dn(e.content)??`<skill-name>`,r=t?`skill_load(name="${n}", skillPath="${t}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,`If this skill is needed later, call ${r} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].join(`
21
- `)}function Dn(e){try{let t=JSON.parse(e);return t.success===!0&&typeof t.name==`string`?t.name:void 0}catch{return e.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1]??e.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1]}}function On(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=xn(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function kn(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}async function An(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=jn(t),l=c>=0?t[c].content:void 0,u=kn(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}=On(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:K(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Cn({entries:f,llm:r,previousSummary:l,instructions:i,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:K(d)}}function jn(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Mn=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
22
- `),Nn=[`.aimax/new.txt`];async function Pn(e){try{return(await be(e,`utf-8`)).trim()||null}catch{return null}}async function Fn(e){for(let t of Nn){let n=await Pn(xe(e,t));if(n)return n}return await Pn(`/aimax/new.txt`)||Mn}async function In(e){return{kind:`reply`,text:await Fn(e)}}function Ln(){return{kind:`reply`,text:`✅ Session reset.`}}function Rn(e){let t=Vn(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Hn(r):null,a=n??i?.text,o=a?dn(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Un(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Wn(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function zn(e,t){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 n=bn({message:e.messageForRun??``,skills:t});if(n.kind===`reply`)return{kind:`reply`,replyText:n.text,transcriptMessage:e.transcriptMessage};if(n.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:n.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(n.kind===`rewrite`){let t=e.inputMode===`text`?n.message:Un(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Wn(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Bn(e){let n=zn(e.invocation,e.skills);if(n.kind===`run`)return{kind:`continue`,effectivePrompt:n.effectivePrompt,transcriptMessage:n.transcriptMessage};if(n.kind===`reset_reply`)return{kind:`completed`,result:await tn({replyText:(n.action===`reset`?Ln():await In(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(n.kind===`reply`)return{kind:`completed`,result:await tn({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let r=await An({entries:e.runParams.channel===`CRON`?[]:await t(e.runParams.dataDir,e.sessionId),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:n.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await tn({replyText:r.status===`compacted`?`⚙️ Compacted (kept ${r.keptCount}, dropped ${r.droppedCount}).`:`⚙️ Compaction skipped: ${r.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:r.status===`compacted`?r.entry:void 0,eventDispatcher:e.eventDispatcher})}}function Vn(e){return typeof e.message==`string`}function Hn(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 Un(e,t){let n=Hn(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 Wn(e){return typeof e==`string`?e:JSON.stringify(e)}function Gn(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}const Kn={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function qn(e,t){return e.map(e=>Jn(e,t))}function Jn(e,t){let n=new Date(e.timestamp).getTime();if(Yn(e))return{role:`user`,content:e.content,timestamp:n};if(Xn(e)){let r=[];e.content&&r.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])r.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:r,api:t.api,provider:`openai`,model:t.model,usage:Kn,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:Zn(r)}],isError:r.isError,timestamp:n}}function Yn(e){return e.role===`user`}function Xn(e){return e.role===`assistant`}function Zn(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}`];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
23
- `)}async function Qn(e){let t=h(e.dataDir,e.sessionId,e),n=new Map,r=new Map,a=[],o=[],s=[],c,l,u=0,d,f,p=await rr(t);for(let e of p.readStates)n.set($n(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);a.push(...p.compaction.budgets),o.push(...p.compaction.snips),s.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 e={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await L.mkdir(R.dirname(t),{recursive:!0}),await L.writeFile(t,JSON.stringify(e,null,2),`utf-8`)};return{async findReusableRead(e,t,r){let i=$n(e,t,r),a=n.get(i);if(!a)return null;let o=await tr(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:nr(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await tr(e.path)??Date.now()};return n.set($n(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())er(i.path)===er(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 o=t.previewChars??2e3,s=i(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=R.join(s,c);await L.mkdir(s,{recursive:!0}),await L.writeFile(l,t.content,`utf-8`);let u=R.relative(e.dataDir,l).split(R.sep).join(`/`),p=sr(t.content,o),h={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:u,preview:p,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(h.toolCallId,h),a.push({toolCallId:h.toolCallId,toolName:h.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:p.length,strategy:`persist`,createdAt:h.createdAt}),d=h.createdAt,f=`L2`,await m(),{content:or(h),reference:h}},async recordSnip(e){o.push(e),d=e.createdAt,f=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await m()},async recordCollapse(e){s.push(e),d=e.createdAt,f=e.layer,await m()},async setSessionMemory(t){c=t,await cr(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:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function $n(e,t,n){return`${er(e)}::${t??``}::${n??``}`}function er(e){return R.normalize(e)}async function tr(e){try{return(await L.stat(e)).mtimeMs}catch{return null}}function nr(e){return Ie(`sha1`).update(e).digest(`hex`)}async function rr(e){try{let t=await L.readFile(e,`utf-8`),n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?ir():{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:ar(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 ir()}}function ir(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function ar(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 or(e){let t=e.preview.length<e.originalChars?`
20
+ `)}function En(e){let t=Dn(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(`
21
+ `)}function Dn(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=On(t);if(e.name||e.path)return e}return{}}function On(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 kn(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=xn(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function An(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}async function jn(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Mn(t),l=c>=0?t[c].content:void 0,u=An(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}=kn(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:K(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Cn({entries:f,llm:r,previousSummary:l,instructions:i,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:K(d)}}function Mn(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Nn=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
22
+ `),Pn=[`.aimax/new.txt`];async function Fn(e){try{return(await be(e,`utf-8`)).trim()||null}catch{return null}}async function In(e){for(let t of Pn){let n=await Fn(xe(e,t));if(n)return n}return await Fn(`/aimax/new.txt`)||Nn}async function Ln(e){return{kind:`reply`,text:await In(e)}}function Rn(){return{kind:`reply`,text:`✅ Session reset.`}}function zn(e){let t=Hn(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Un(r):null,a=n??i?.text,o=a?dn(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Wn(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Gn(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Bn(e,t){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 n=bn({message:e.messageForRun??``,skills:t});if(n.kind===`reply`)return{kind:`reply`,replyText:n.text,transcriptMessage:e.transcriptMessage};if(n.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:n.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(n.kind===`rewrite`){let t=e.inputMode===`text`?n.message:Wn(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Gn(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Vn(e){let n=Bn(e.invocation,e.skills);if(n.kind===`run`)return{kind:`continue`,effectivePrompt:n.effectivePrompt,transcriptMessage:n.transcriptMessage};if(n.kind===`reset_reply`)return{kind:`completed`,result:await tn({replyText:(n.action===`reset`?Rn():await Ln(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(n.kind===`reply`)return{kind:`completed`,result:await tn({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let r=await jn({entries:e.runParams.channel===`CRON`?[]:await t(e.runParams.dataDir,e.sessionId),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:n.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await tn({replyText:r.status===`compacted`?`⚙️ Compacted (kept ${r.keptCount}, dropped ${r.droppedCount}).`:`⚙️ Compaction skipped: ${r.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:r.status===`compacted`?r.entry:void 0,eventDispatcher:e.eventDispatcher})}}function Hn(e){return typeof e.message==`string`}function Un(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 Wn(e,t){let n=Un(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 Gn(e){return typeof e==`string`?e:JSON.stringify(e)}function Kn(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}const qn={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Jn(e,t){return e.map(e=>Yn(e,t))}function Yn(e,t){let n=new Date(e.timestamp).getTime();if(Xn(e))return{role:`user`,content:e.content,timestamp:n};if(Zn(e)){let r=[];e.content&&r.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])r.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:r,api:t.api,provider:`openai`,model:t.model,usage:qn,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:Qn(r)}],isError:r.isError,timestamp:n}}function Xn(e){return e.role===`user`}function Zn(e){return e.role===`assistant`}function Qn(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}`];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
23
+ `)}async function $n(e){let t=h(e.dataDir,e.sessionId,e),n=new Map,r=new Map,a=[],o=[],s=[],c,l,u=0,d,f,p=await ir(t);for(let e of p.readStates)n.set(er(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);a.push(...p.compaction.budgets),o.push(...p.compaction.snips),s.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 e={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await L.mkdir(R.dirname(t),{recursive:!0}),await L.writeFile(t,JSON.stringify(e,null,2),`utf-8`)};return{async findReusableRead(e,t,r){let i=er(e,t,r),a=n.get(i);if(!a)return null;let o=await nr(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:rr(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await nr(e.path)??Date.now()};return n.set(er(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())tr(i.path)===tr(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 o=t.previewChars??2e3,s=i(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=R.join(s,c);await L.mkdir(s,{recursive:!0}),await L.writeFile(l,t.content,`utf-8`);let u=R.relative(e.dataDir,l).split(R.sep).join(`/`),p=cr(t.content,o),h={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:u,preview:p,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(h.toolCallId,h),a.push({toolCallId:h.toolCallId,toolName:h.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:p.length,strategy:`persist`,createdAt:h.createdAt}),d=h.createdAt,f=`L2`,await m(),{content:sr(h),reference:h}},async recordSnip(e){o.push(e),d=e.createdAt,f=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await m()},async recordCollapse(e){s.push(e),d=e.createdAt,f=e.layer,await m()},async setSessionMemory(t){c=t,await lr(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:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function er(e,t,n){return`${tr(e)}::${t??``}::${n??``}`}function tr(e){return R.normalize(e)}async function nr(e){try{return(await L.stat(e)).mtimeMs}catch{return null}}function rr(e){return Ie(`sha1`).update(e).digest(`hex`)}async function ir(e){try{let t=await L.readFile(e,`utf-8`),n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?ar():{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:or(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 ar()}}function ar(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function or(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 sr(e){let t=e.preview.length<e.originalChars?`
24
24
  ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,``,`Preview:`,e.preview+t].join(`
25
- `)}function sr(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
26
- `),r=n>t*.5?n:t;return e.slice(0,r)}async function cr(t,n,r,i){let a=e(t,n,i);await L.mkdir(R.dirname(a),{recursive:!0}),await L.writeFile(a,JSON.stringify(r,null,2),`utf-8`)}const lr=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function ur(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,signal:c,hooks:l,hookCtx:u,contextStore:d,dataDir:f,sessionId:p,sessionStoreName:m}=e,h,g=Sr(t),_=g>=0?t.slice(g+1):t;g>=0&&(h=t[g].content);let v=t.length,y=kn(Gn(_,a)),b=[];d&&(h=await dr({entries:y,existingSummary:h,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let x=y;if(x=await fr({entries:x,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:b}),x=await pr({entries:x,contextStore:d,compactionEvents:b}),x=await mr({entries:x,contextStore:d,compactionEvents:b,dataDir:f,sessionId:p,sessionStoreName:m}),!o)return{messages:qn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let S=d?.getSnapshot(),C=Math.max(1e3,Math.floor(r*.7)),w=Cr({entries:t,workingEntries:x,pendingUserMessage:s,checkpoint:S?.compaction.modelUsage}).projectedInputTokens>=C,T=S?.compaction.consecutiveAutocompactFailures??0;if(!w||T>=3)return{messages:qn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let{toKeep:E,toSummarise:D}=On(x,r);if(D.length===0)return{messages:qn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let O=new Date().toISOString();try{let e=S?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Cn({entries:D,llm:i,previousSummary:h,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:E.length,droppedCount:D.length,timestamp:O};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:O}),b.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${D.length} entries with session memory`:`Autocompact summarised ${D.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,K(D)),affectedEntries:D.length,snapshotVersion:2}),{messages:qn(kn(E),n),priorSummary:t,compactionEntry:r,stats:{originalCount:v,keptCount:E.length,estimatedTokens:K(E),compacted:!0},compactionEvents:b}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:O}),{messages:qn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:[...b,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function dr(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=K(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&xr(t)>=3;if(!u&&!d)return n??l?.summary;let f=await Cn({entries:t,llm:r,previousSummary:n??l?.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(` `),signal:a,hooks:o,hookCtx:s}),p={version:1,summary:f,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:c,trigger:u?`threshold`:`autocompact`};return await i.setSessionMemory(p),f}async function fr(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(gr).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(!gr(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=_r(n)?vr(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
27
- `);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}),kn(l.reverse())}async function pr(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!gr(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=_r(e)?vr(e):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${e.toolName}`,`Preview:\n${e.toolResultRef?.preview?.trim()||e.content.slice(0,400).trim()}`].join(`
28
- `);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),fr({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function mr(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o}=e,s=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(s.length<=2)return t;let c=s[s.length-2]??t.length,l=[],u=0,d=0,f=0;for(;u<t.length;){if(u>=c||t[u]?.role===`user`){l.push(t[u]),u+=1;continue}let e=u;for(;u<c&&t[u]?.role!==`user`;)u+=1;let r=t.slice(e,u),s=r.filter(gr).filter(e=>lr.has(e.toolName)),p=s.reduce((e,t)=>e+t.content.length,0);if(s.length<3||p<1500){l.push(...r);continue}let m=hr(r,s),h=new Date().toISOString(),g={role:`assistant`,content:m,timestamp:h};l.push(g),d+=r.length,f+=Math.max(0,Math.floor(K(r)-K([g])));let _={id:Le(),layer:`L5`,startEntryIndex:e,endEntryIndex:u-1,toolNames:[...new Set(s.map(e=>e.toolName))],summary:m,sourceCount:r.length,estimatedTokensFreed:f,createdAt:h};await n?.recordCollapse(_),i&&a&&await wr(i,a,_,o)}return d>0&&r.push({type:`compaction`,reason:`Collapsed ${d} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:f,affectedEntries:d,snapshotVersion:2}),l}function hr(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(`
25
+ `)}function cr(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
26
+ `),r=n>t*.5?n:t;return e.slice(0,r)}async function lr(t,n,r,i){let a=e(t,n,i);await L.mkdir(R.dirname(a),{recursive:!0}),await L.writeFile(a,JSON.stringify(r,null,2),`utf-8`)}const ur=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function dr(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,signal:c,hooks:l,hookCtx:u,contextStore:d,dataDir:f,sessionId:p,sessionStoreName:m}=e,h,g=Cr(t),_=g>=0?t.slice(g+1):t;g>=0&&(h=t[g].content);let v=t.length,y=An(Kn(_,a)),b=[];d&&(h=await fr({entries:y,existingSummary:h,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let x=y;if(x=await pr({entries:x,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:b}),x=await mr({entries:x,contextStore:d,compactionEvents:b}),x=await hr({entries:x,contextStore:d,compactionEvents:b,dataDir:f,sessionId:p,sessionStoreName:m}),!o)return{messages:Jn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let S=d?.getSnapshot(),C=Math.max(1e3,Math.floor(r*.7)),w=wr({entries:t,workingEntries:x,pendingUserMessage:s,checkpoint:S?.compaction.modelUsage}).projectedInputTokens>=C,T=S?.compaction.consecutiveAutocompactFailures??0;if(!w||T>=3)return{messages:Jn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let{toKeep:E,toSummarise:D}=kn(x,r);if(D.length===0)return{messages:Jn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let O=new Date().toISOString();try{let e=S?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Cn({entries:D,llm:i,previousSummary:h,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:E.length,droppedCount:D.length,timestamp:O};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:O}),b.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${D.length} entries with session memory`:`Autocompact summarised ${D.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,K(D)),affectedEntries:D.length,snapshotVersion:2}),{messages:Jn(An(E),n),priorSummary:t,compactionEntry:r,stats:{originalCount:v,keptCount:E.length,estimatedTokens:K(E),compacted:!0},compactionEvents:b}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:O}),{messages:Jn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:[...b,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function fr(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=K(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&Sr(t)>=3;if(!u&&!d)return n??l?.summary;let f=await Cn({entries:t,llm:r,previousSummary:n??l?.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(` `),signal:a,hooks:o,hookCtx:s}),p={version:1,summary:f,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:c,trigger:u?`threshold`:`autocompact`};return await i.setSessionMemory(p),f}async function pr(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(_r).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(!_r(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=vr(n)?yr(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
27
+ `);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}),An(l.reverse())}async function mr(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!_r(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=vr(e)?yr(e):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${e.toolName}`,`Preview:\n${e.toolResultRef?.preview?.trim()||e.content.slice(0,400).trim()}`].join(`
28
+ `);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),pr({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function hr(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o}=e,s=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(s.length<=2)return t;let c=s[s.length-2]??t.length,l=[],u=0,d=0,f=0;for(;u<t.length;){if(u>=c||t[u]?.role===`user`){l.push(t[u]),u+=1;continue}let e=u;for(;u<c&&t[u]?.role!==`user`;)u+=1;let r=t.slice(e,u),s=r.filter(_r).filter(e=>ur.has(e.toolName)),p=s.reduce((e,t)=>e+t.content.length,0);if(s.length<3||p<1500){l.push(...r);continue}let m=gr(r,s),h=new Date().toISOString(),g={role:`assistant`,content:m,timestamp:h};l.push(g),d+=r.length,f+=Math.max(0,Math.floor(K(r)-K([g])));let _={id:Le(),layer:`L5`,startEntryIndex:e,endEntryIndex:u-1,toolNames:[...new Set(s.map(e=>e.toolName))],summary:m,sourceCount:r.length,estimatedTokensFreed:f,createdAt:h};await n?.recordCollapse(_),i&&a&&await Tr(i,a,_,o)}return d>0&&r.push({type:`compaction`,reason:`Collapsed ${d} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:f,affectedEntries:d,snapshotVersion:2}),l}function gr(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(`
29
29
  `),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
30
30
  `);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
31
31
 
32
- `)}function gr(e){return e.role===`tool_result`}function _r(e){return e.toolName===`skill_load`}function vr(e){let t=yr(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(`
33
- `)}function yr(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=br(t);if(e.name||e.path)return e}return{}}function br(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 xr(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Sr(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Cr(e){let t=e.pendingUserMessage?.trim()?K([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=K(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=K(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 wr(e,t,n,r){let i=m(e,t,{storeName:r});await L.mkdir(R.dirname(i),{recursive:!0}),await L.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Tr(e){let t=await Qn({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName});return{async getReusableRead(e,n,r){let i=await t.findReusableRead(e,n,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await t.recordRead(e)},async invalidateReadPath(e){await t.invalidatePath(e)},persistToolResult(e){return t.persistToolResult(e)},async recordModelUsage(e){await t.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(n){return ur({...n,contextStore:t,sessionStoreName:e.sessionStoreName})},getSnapshot:t.getSnapshot}}async function Er(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,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName}):ur({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName})}var Dr=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 q(e){return!!(e instanceof Dr||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const Or=z.Object({command:z.String({description:`Shell command to execute`}),workdir:z.Optional(z.String({description:`Working directory (relative to workspace root)`})),env:z.Optional(z.Record(z.String(),z.String())),timeout:z.Optional(z.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:z.Optional(z.Number({description:`Wait this many milliseconds before returning running state`})),background:z.Optional(z.Boolean({description:`Return immediately with running session`}))});function kr(e,t,n){return Math.max(t,Math.min(n,e))}function Ar(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function jr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:kr(Math.floor(e),0,12e4)}function Mr(e,t){if(!t?.trim())return e;let n=R.isAbsolute(t)?R.normalize(t):R.normalize(R.join(e,t));if(!n.startsWith(e+R.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Nr(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 Pr(e){return Ir({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
34
- `)}function Fr(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Ir(e){let t=Fr(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 Lr(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:Or,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=Mr(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Ar(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,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&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,jr(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Nr(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?Ir({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Pr(l)],p=Fr(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(`
35
- `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Rr=z.Object({action:z.String({description:`Process action: list | poll | log | kill`}),sessionId:z.Optional(z.String({description:`Session id for non-list actions`})),offset:z.Optional(z.Number({description:`Log line offset (0-based)`})),limit:z.Optional(z.Number({description:`Maximum lines to return`})),timeout:z.Optional(z.Number({description:`Poll wait time in milliseconds`}))});function zr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Br(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Vr(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:Rr,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(`
36
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Br(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,zr(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`}}:Br(`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}}:Br(`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}}:Br(`No session found for ${i}`)}return Br(`Unsupported action: ${n.action}`)}}}const Hr=2e5;function Ur(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Wr(e,t){let n=e+t;return n.length<=Hr?{text:n,truncated:!1}:{text:n.slice(-Hr),truncated:!0}}function Gr(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Wr(e.output,r);e.output=i.text;let a=Wr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function J(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:Ur(e.output),stdoutTail:Ur(e.stdout),stderrTail:Ur(e.stderr),outputTruncated:e.outputTruncated}}function Y(e,t){return t?e.scopeKey===t:!0}function Kr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function qr(e){return e?e.split(/\r?\n/):[]}function Jr(e){let t=qr(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Kr(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(`
37
- `);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 Yr(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Xr(){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),Yr(e))};return{start(t){let n=Be(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:Le(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Gr(o,`stdout`,e)),n.stderr.on(`data`,e=>Gr(o,`stderr`,e));let s=Kr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Gr(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),Gr(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),J(o)},get(e,t){let n=r(e);return!n||!Y(n,t)?null:J(n)},list(n){return[...e.values(),...t.values()].filter(e=>Y(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>J(e))},async wait(e,t,n){let i=r(e);if(!i||!Y(i,t))return null;if(i.status!==`running`)return J(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||!Y(a,t)?null:J(a)},readLog(e){let t=r(e.sessionId);return!t||!Y(t,e.scopeKey)?null:Jr({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Y(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||!Y(n,t))return null;if(n.status!==`running`)return J(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?J(i):null}}}function Zr(e){return Lr({workspaceDir:e,registry:Xr(),scopeKey:e})}const Qr=5*1024*1024,$r=2e3;function ei(e,t){return R.isAbsolute(e)?R.normalize(e):R.normalize(R.join(t,e))}const ti=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),offset:z.Optional(z.Number({description:`Line offset (1-based, default: 1)`})),limit:z.Optional(z.Number({description:`Maximum lines to read (default: 2000)`}))});function ni(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:ti,async execute(n,r){let i;try{i=ei(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 L.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 Ve(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>Qr){let e=o.slice(0,Qr).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Qr} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
38
- `),l=Math.max(1,r.offset??1),u=Math.min($r,r.limit??$r),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(`
32
+ `)}function _r(e){return e.role===`tool_result`}function vr(e){return e.toolName===`skill_load`}function yr(e){let t=br(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(`
33
+ `)}function br(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=xr(t);if(e.name||e.path)return e}return{}}function xr(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 Sr(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Cr(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function wr(e){let t=e.pendingUserMessage?.trim()?K([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=K(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=K(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 Tr(e,t,n,r){let i=m(e,t,{storeName:r});await L.mkdir(R.dirname(i),{recursive:!0}),await L.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Er(e){let t=await $n({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName});return{async getReusableRead(e,n,r){let i=await t.findReusableRead(e,n,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await t.recordRead(e)},async invalidateReadPath(e){await t.invalidatePath(e)},persistToolResult(e){return t.persistToolResult(e)},async recordModelUsage(e){await t.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(n){return dr({...n,contextStore:t,sessionStoreName:e.sessionStoreName})},getSnapshot:t.getSnapshot}}async function Dr(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,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName}):dr({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName})}var Or=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 q(e){return!!(e instanceof Or||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const kr=z.Object({command:z.String({description:`Shell command to execute`}),workdir:z.Optional(z.String({description:`Working directory (relative to workspace root)`})),env:z.Optional(z.Record(z.String(),z.String())),timeout:z.Optional(z.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:z.Optional(z.Number({description:`Wait this many milliseconds before returning running state`})),background:z.Optional(z.Boolean({description:`Return immediately with running session`}))});function Ar(e,t,n){return Math.max(t,Math.min(n,e))}function jr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Mr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Ar(Math.floor(e),0,12e4)}function Nr(e,t){if(!t?.trim())return e;let n=R.isAbsolute(t)?R.normalize(t):R.normalize(R.join(e,t));if(!n.startsWith(e+R.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Pr(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 Fr(e){return Lr({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
34
+ `)}function Ir(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Lr(e){let t=Ir(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 Rr(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:kr,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=Nr(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=jr(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,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&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,Mr(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Pr(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?Lr({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Fr(l)],p=Ir(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(`
35
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const zr=z.Object({action:z.String({description:`Process action: list | poll | log | kill`}),sessionId:z.Optional(z.String({description:`Session id for non-list actions`})),offset:z.Optional(z.Number({description:`Log line offset (0-based)`})),limit:z.Optional(z.Number({description:`Maximum lines to return`})),timeout:z.Optional(z.Number({description:`Poll wait time in milliseconds`}))});function Br(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Vr(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Hr(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:zr,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(`
36
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Vr(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Br(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`}}:Vr(`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}}:Vr(`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}}:Vr(`No session found for ${i}`)}return Vr(`Unsupported action: ${n.action}`)}}}const Ur=2e5;function Wr(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Gr(e,t){let n=e+t;return n.length<=Ur?{text:n,truncated:!1}:{text:n.slice(-Ur),truncated:!0}}function Kr(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Gr(e.output,r);e.output=i.text;let a=Gr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function J(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:Wr(e.output),stdoutTail:Wr(e.stdout),stderrTail:Wr(e.stderr),outputTruncated:e.outputTruncated}}function Y(e,t){return t?e.scopeKey===t:!0}function qr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Jr(e){return e?e.split(/\r?\n/):[]}function Yr(e){let t=Jr(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=qr(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(`
37
+ `);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 Xr(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Zr(){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),Xr(e))};return{start(t){let n=Be(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:Le(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Kr(o,`stdout`,e)),n.stderr.on(`data`,e=>Kr(o,`stderr`,e));let s=qr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Kr(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),Kr(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),J(o)},get(e,t){let n=r(e);return!n||!Y(n,t)?null:J(n)},list(n){return[...e.values(),...t.values()].filter(e=>Y(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>J(e))},async wait(e,t,n){let i=r(e);if(!i||!Y(i,t))return null;if(i.status!==`running`)return J(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||!Y(a,t)?null:J(a)},readLog(e){let t=r(e.sessionId);return!t||!Y(t,e.scopeKey)?null:Yr({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Y(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||!Y(n,t))return null;if(n.status!==`running`)return J(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?J(i):null}}}function Qr(e){return Rr({workspaceDir:e,registry:Zr(),scopeKey:e})}const $r=5*1024*1024,ei=2e3;function ti(e,t){return R.isAbsolute(e)?R.normalize(e):R.normalize(R.join(t,e))}const ni=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),offset:z.Optional(z.Number({description:`Line offset (1-based, default: 1)`})),limit:z.Optional(z.Number({description:`Maximum lines to read (default: 2000)`}))});function ri(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:ni,async execute(n,r){let i;try{i=ti(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 L.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 Ve(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>$r){let e=o.slice(0,$r).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${$r} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
38
+ `),l=Math.max(1,r.offset??1),u=Math.min(ei,r.limit??ei),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(`
39
39
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
40
40
  `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
41
- `),lines:d.length,truncated:f}}}}}const ri=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),content:z.String({description:`File content to write`})});function ii(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:ri,async execute(n,r){let i;try{i=ei(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await L.mkdir(R.dirname(i),{recursive:!0}),await L.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const ai=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),old_string:z.String({description:`Exact text to replace`}),new_string:z.String({description:`Replacement text`})});function oi(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:ai,async execute(n,r){let i;try{i=ei(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await L.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await L.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const si=z.Object({path:z.Optional(z.String({description:`Directory path (default: workspace root)`}))});function ci(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:si,async execute(t,n){let r=n.path??`.`,i;try{i=ei(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await L.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(`
42
- `)||`(empty directory)`}],details:{entries:a}}}}}const li=z.Object({input:z.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function ui(e,t){let n=R.isAbsolute(e)?R.normalize(e):R.normalize(R.join(t,e));if(!n.startsWith(t+R.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function di(e,t){let n=R.relative(t,e);return!n||n===``?R.basename(e):n.startsWith(`..`)||R.isAbsolute(n)?e:n}async function fi(e){await L.mkdir(R.dirname(e),{recursive:!0})}function pi(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(`
43
- `)}function mi(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:li,async execute(t,n){try{let t=n.input?.trim();if(!t)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let r=gi(t);if(r.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let i={added:[],modified:[],deleted:[]},a={added:new Set,modified:new Set,deleted:new Set};for(let t of r.hunks){if(t.kind===`add`){let n=ui(t.path,e);await fi(n),await L.writeFile(n,t.contents,`utf-8`),hi(i,a,`added`,di(n,e));continue}if(t.kind===`delete`){let n=ui(t.path,e);await L.rm(n,{force:!0,recursive:!1}),hi(i,a,`deleted`,di(n,e));continue}let n=ui(t.path,e),r=await bi(n,t.chunks);if(t.movePath){let o=ui(t.movePath,e);await fi(o),await L.writeFile(o,r,`utf-8`),await L.rm(n,{force:!0,recursive:!1}),hi(i,a,`modified`,di(o,e))}else await L.writeFile(n,r,`utf-8`),hi(i,a,`modified`,di(n,e))}return{content:[{type:`text`,text:pi(i)}],details:{summary:i}}}catch(e){if(q(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function hi(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function gi(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);_i(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=vi(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function _i(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 vi(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}=yi(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 yi(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 bi(e,t){let n=(await L.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
44
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Si(n,xi(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
45
- `)}function xi(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Ci(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=Ci(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=Ci(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
46
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Si(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 Ci(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(wi(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(wi(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(wi(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(wi(e,t,n,e=>Ti(e.trim())))return n;return null}function wi(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 Ti(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 Ei(e){return R.join(e,`.aimax`)}function Di(e){return R.join(Ei(e),`MEMORY.md`)}async function Oi(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function X(e,t){let n=Ei(e),r=N({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:C({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function ki(e){return D(Ei(e))}async function Ai(e){try{return await L.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ji(e){return Ai(Di(e))}async function Mi(e,t,n){return await X(e,n).search(t)}async function Ni(e,t,n,r,i){try{return await X(e,i).getLines(t,n,r)}catch{return null}}async function Pi(e,t,n){let r=X(e,n);await r.append(t),await Oi(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function Fi(e,t,n,r){let i=X(e,r);if(i.appendRecent){await i.appendRecent(t,n),await Oi(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()});return}let a=new Date().toISOString().slice(0,10);await Pi(e,`${n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${a}]`} ${t}\n`,r)}async function Ii(e,t,n,r){let i=X(e,r);await i.updateFile(t,n),await Oi(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function Li(e,t,n){let r=X(e,n);await r.deleteFile(t),await Oi(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const Ri=z.Object({query:z.String({description:`Search query (case-insensitive substring match)`})});function zi(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memories to find relevant entries before reading, updating, or deleting`,parameters:Ri,async execute(n,r){let i=(await Mi(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({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.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
47
- `)}],details:{matches:i}}}}}const Bi=z.Object({file:z.String({description:`Memory file path (from memory_search results)`}),start_line:z.Number({description:`Start line number (1-based)`}),end_line:z.Number({description:`End line number (1-based)`})});function Vi(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:Bi,async execute(n,r){let i=await Ni(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(`
48
- `)||`(empty)`}],details:{lines:i}}}}}const Hi=z.Object({content:z.String({description:`Content to write to memory`})});function Ui(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:Hi,async execute(n,r){try{return await Pi(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 Wi=z.Object({section:z.Optional(z.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:z.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:z.Union([z.Literal(`append`),z.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Gi(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:Wi,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Pi(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 Ii(e,`MEMORY.md`,Ki(await ji(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Pi(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 Ki(e,t,n){let r=e.split(`
41
+ `),lines:d.length,truncated:f}}}}}const ii=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),content:z.String({description:`File content to write`})});function ai(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:ii,async execute(n,r){let i;try{i=ti(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await L.mkdir(R.dirname(i),{recursive:!0}),await L.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const oi=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),old_string:z.String({description:`Exact text to replace`}),new_string:z.String({description:`Replacement text`})});function si(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:oi,async execute(n,r){let i;try{i=ti(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await L.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await L.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const ci=z.Object({path:z.Optional(z.String({description:`Directory path (default: workspace root)`}))});function li(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:ci,async execute(t,n){let r=n.path??`.`,i;try{i=ti(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await L.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(`
42
+ `)||`(empty directory)`}],details:{entries:a}}}}}const ui=z.Object({input:z.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function di(e,t){let n=R.isAbsolute(e)?R.normalize(e):R.normalize(R.join(t,e));if(!n.startsWith(t+R.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function fi(e,t){let n=R.relative(t,e);return!n||n===``?R.basename(e):n.startsWith(`..`)||R.isAbsolute(n)?e:n}async function pi(e){await L.mkdir(R.dirname(e),{recursive:!0})}function mi(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(`
43
+ `)}function hi(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:ui,async execute(t,n){try{let t=n.input?.trim();if(!t)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let r=_i(t);if(r.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let i={added:[],modified:[],deleted:[]},a={added:new Set,modified:new Set,deleted:new Set};for(let t of r.hunks){if(t.kind===`add`){let n=di(t.path,e);await pi(n),await L.writeFile(n,t.contents,`utf-8`),gi(i,a,`added`,fi(n,e));continue}if(t.kind===`delete`){let n=di(t.path,e);await L.rm(n,{force:!0,recursive:!1}),gi(i,a,`deleted`,fi(n,e));continue}let n=di(t.path,e),r=await xi(n,t.chunks);if(t.movePath){let o=di(t.movePath,e);await pi(o),await L.writeFile(o,r,`utf-8`),await L.rm(n,{force:!0,recursive:!1}),gi(i,a,`modified`,fi(o,e))}else await L.writeFile(n,r,`utf-8`),gi(i,a,`modified`,fi(n,e))}return{content:[{type:`text`,text:mi(i)}],details:{summary:i}}}catch(e){if(q(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function gi(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function _i(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);vi(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=yi(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function vi(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 yi(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}=bi(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 bi(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 xi(e,t){let n=(await L.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
44
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Ci(n,Si(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
45
+ `)}function Si(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=wi(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=wi(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=wi(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
46
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Ci(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 wi(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(Ti(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Ti(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Ti(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Ti(e,t,n,e=>Ei(e.trim())))return n;return null}function Ti(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 Ei(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 Di(e){return R.join(e,`.aimax`)}function Oi(e){return R.join(Di(e),`MEMORY.md`)}async function ki(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function X(e,t){let n=Di(e),r=N({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:C({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function Ai(e){return D(Di(e))}async function ji(e){try{return await L.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Mi(e){return ji(Oi(e))}async function Ni(e,t,n){return await X(e,n).search(t)}async function Pi(e,t,n,r,i){try{return await X(e,i).getLines(t,n,r)}catch{return null}}async function Fi(e,t,n){let r=X(e,n);await r.append(t),await ki(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function Ii(e,t,n,r){let i=X(e,r);if(i.appendRecent){await i.appendRecent(t,n),await ki(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()});return}let a=new Date().toISOString().slice(0,10);await Fi(e,`${n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${a}]`} ${t}\n`,r)}async function Li(e,t,n,r){let i=X(e,r);await i.updateFile(t,n),await ki(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function Ri(e,t,n){let r=X(e,n);await r.deleteFile(t),await ki(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const zi=z.Object({query:z.String({description:`Search query (case-insensitive substring match)`})});function Bi(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memories to find relevant entries before reading, updating, or deleting`,parameters:zi,async execute(n,r){let i=(await Ni(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({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.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
47
+ `)}],details:{matches:i}}}}}const Vi=z.Object({file:z.String({description:`Memory file path (from memory_search results)`}),start_line:z.Number({description:`Start line number (1-based)`}),end_line:z.Number({description:`End line number (1-based)`})});function Hi(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:Vi,async execute(n,r){let i=await Pi(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(`
48
+ `)||`(empty)`}],details:{lines:i}}}}}const Ui=z.Object({content:z.String({description:`Content to write to memory`})});function Wi(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:Ui,async execute(n,r){try{return await Fi(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 Gi=z.Object({section:z.Optional(z.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:z.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:z.Union([z.Literal(`append`),z.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Ki(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:Gi,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Fi(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 Li(e,`MEMORY.md`,qi(await Mi(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Fi(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 qi(e,t,n){let r=e.split(`
49
49
  `),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(`
50
50
  `).trimEnd(),a,r.slice(s).join(`
51
51
  `).trimStart()].filter(e=>e.length>0).join(`
52
- `)}\n`}const qi=z.Object({content:z.String({description:`Note to append to today's daily log`}),scope:z.Optional(z.Union([z.Literal(`daily`),z.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Ji(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:qi,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Fi(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 Yi=z.Object({scope:z.Optional(z.Union([z.Literal(`long-term`),z.Literal(`recent`),z.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Xi(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:Yi,async execute(n,r){try{let n=r.scope??`all`,i=await ki(e),a=[];for(let n of i.slice(0,30)){let r=await Ni(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});r&&r.length>0&&a.push({file:n,content:r.join(`
52
+ `)}\n`}const Ji=z.Object({content:z.String({description:`Note to append to today's daily log`}),scope:z.Optional(z.Union([z.Literal(`daily`),z.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Yi(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:Ji,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Ii(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 Xi=z.Object({scope:z.Optional(z.Union([z.Literal(`long-term`),z.Literal(`recent`),z.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Zi(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:Xi,async execute(n,r){try{let n=r.scope??`all`,i=await Ai(e),a=[];for(let n of i.slice(0,30)){let r=await Pi(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});r&&r.length>0&&a.push({file:n,content:r.join(`
53
53
  `)})}return{content:[{type:`text`,text:a.map(e=>`--- ${e.file} ---\n${e.content.slice(0,500)}`).join(`
54
54
 
55
- `)||`(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 Zi=z.Object({id:z.Optional(z.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:z.Optional(z.String({description:`Search query used to find memories to delete`})),limit:z.Optional(z.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:z.Optional(z.Union([z.Literal(`long-term`),z.Literal(`recent`),z.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Qi(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. Prefer memory_list or memory_search first so you know the target.`,parameters:Zi,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id)return await Li(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 Mi(e,r.query,i),a=0;for(let r of n.slice(0,t))await Li(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 $i=z.Object({id:z.String({description:`The entry ID of the memory to update (from memory_list or memory_search results)`}),content:z.String({description:`New content to replace the existing memory with`})});function ea(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.`,parameters:$i,async execute(n,r){try{return await Ii(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 ta=z.Object({category:z.Optional(z.String({description:`Reserved category filter field. Not used yet.`}))}),na=z.Object({name:z.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:z.Optional(z.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function ra(e,t,n=[]){return[...n,...t,tt(e)]}function ia(e,t,n=[]){let r=ra(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:ta,async execute(e,t){let n=await st(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 aa(e){let t=ra(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:na,async execute(r,i){let a=await ut(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,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}}):{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:``}}}}}const oa=z.Object({task:z.String({description:`The task description for the subagent to execute`}),label:z.Optional(z.String({description:`Optional short label to identify this subagent`}))});function sa(e){let t=e.label?`"${e.label}"`:`task: ${ge(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${e.result??`(no output)`}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function ca(e,t,n,r,i,a,o,s,c){return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. 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. Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:oa,async execute(l,u){let d=u.task.trim(),f=u.label?.trim();if(!d){let e={status:`error`,error:`task must not be empty`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let p=e.checkSpawnAllowed(t,n+1);if(!p.allowed){let e={status:`forbidden`,error:p.reason};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=Le(),h=new AbortController,g;try{g=await T(r,i,{storeName:s.sessionStoreName})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}let _={runId:m,childSessionId:g,parentSessionId:t,task:d,label:f,depth:n+1,status:`running`,startedAt:Date.now(),abortController:h};await s.onProgress?.({type:`subagent_spawn`,childSessionId:g,task:d,label:f,sessionId:t,messageId:s.messageId,depth:n+1});let v=c({dataDir:r,sessionId:g,message:d,channel:i,llm:a,...s,loopDetection:o,abortSignal:h.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(m,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(m,n)});e.register(_,v),await v,e.markAnnounced(m),await s.onProgress?.({type:`subagent_complete`,childSessionId:g,task:d,status:_.status,sessionId:t,messageId:s.messageId,depth:n+1});let y=sa({task:d,label:f,status:_.status,result:_.result,error:_.error});if(_.status===`done`){let e={status:`done`,childSessionId:g,runId:m,result:_.result??``};return{content:[{type:`text`,text:y}],details:e}}let b=_.status===`killed`?{status:`killed`,childSessionId:g,runId:m,error:`subagent killed`}:{status:`error`,childSessionId:g,runId:m,error:_.error??`unknown error`};return{content:[{type:`text`,text:y}],details:b}}}}const la=z.Object({action:z.Union([`list`,`kill`].map(e=>z.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:z.Optional(z.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function ua(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 da(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 fa(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:la,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} (${ua(e.runtimeMs)})${n}`})).join(`
56
- `)};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=da(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 pa=z.Object({image:z.String({description:`Image path or URL`}),prompt:z.Optional(z.String({description:`Prompt for image analysis`})),model:z.Optional(z.String({description:`Optional model override`})),maxBytesMb:z.Optional(z.Number({description:`Optional size cap in MB`}))});function ma(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:pa,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}}}}var ha=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 ga(e){return!!(e instanceof ha||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const _a=new He;function va(){return{}}async function ya(e,t){return await _a.run(e,t)}function ba(e){let t=_a.getStore();!t||t.signal||(t.signal=e)}const xa=z.Object({reason:z.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Sa(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??xa,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=ye(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 ha(e,i,t,e,o,s,n);throw ba(r),r}}}function Ca(e,t){let n=R.join(e,`workspace`),r=t?.memoryOptions,i=Xr(),a=[Lr({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Vr({registry:i,scopeKey:n}),ni(n,t?.contextManager),ii(n,t?.contextManager),oi(n,t?.contextManager),ci(n),mi(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),zi(e,r),Vi(e,r),Gi(e,r),Ji(e,r),Xi(e,r),Qi(e,r),ea(e,r),ia(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),aa({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return t&&a.push(ca(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),fa(t.registry,t.parentSessionId)),a}const wa={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`,memory_search:`Search long-term memory and daily logs using Markdown chunk retrieval`,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`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Ta=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`subagent_spawn`,`subagents`];function Ea(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:[...Ta.filter(e=>t.has(e)),...n.filter(e=>!Ta.includes(e)).sort()],displayName:t}}function Da(e){let{ordered:t,displayName:n}=Ea(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)??wa[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
55
+ `)||`(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 Qi=z.Object({id:z.Optional(z.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:z.Optional(z.String({description:`Search query used to find memories to delete`})),limit:z.Optional(z.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:z.Optional(z.Union([z.Literal(`long-term`),z.Literal(`recent`),z.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function $i(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. Prefer memory_list or memory_search first so you know the target.`,parameters:Qi,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id)return await Ri(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 Ni(e,r.query,i),a=0;for(let r of n.slice(0,t))await Ri(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 ea=z.Object({id:z.String({description:`The entry ID of the memory to update (from memory_list or memory_search results)`}),content:z.String({description:`New content to replace the existing memory with`})});function ta(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.`,parameters:ea,async execute(n,r){try{return await Li(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 na=z.Object({category:z.Optional(z.String({description:`Reserved category filter field. Not used yet.`}))}),ra=z.Object({name:z.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:z.Optional(z.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function ia(e,t,n=[]){return[...n,...t,tt(e)]}function aa(e,t,n=[]){let r=ia(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:na,async execute(e,t){let n=await st(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 oa(e){let t=ia(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:ra,async execute(r,i){let a=await ut(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,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}}):{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:``}}}}}const sa=z.Object({task:z.String({description:`The task description for the subagent to execute`}),label:z.Optional(z.String({description:`Optional short label to identify this subagent`}))});function ca(e){let t=e.label?`"${e.label}"`:`task: ${ge(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${e.result??`(no output)`}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function la(e,t,n,r,i,a,o,s,c){return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. 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. Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:sa,async execute(l,u){let d=u.task.trim(),f=u.label?.trim();if(!d){let e={status:`error`,error:`task must not be empty`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let p=e.checkSpawnAllowed(t,n+1);if(!p.allowed){let e={status:`forbidden`,error:p.reason};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=Le(),h=new AbortController,g;try{g=await T(r,i,{storeName:s.sessionStoreName})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}let _={runId:m,childSessionId:g,parentSessionId:t,task:d,label:f,depth:n+1,status:`running`,startedAt:Date.now(),abortController:h};await s.onProgress?.({type:`subagent_spawn`,childSessionId:g,task:d,label:f,sessionId:t,messageId:s.messageId,depth:n+1});let v=c({dataDir:r,sessionId:g,message:d,channel:i,llm:a,...s,loopDetection:o,abortSignal:h.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(m,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(m,n)});e.register(_,v),await v,e.markAnnounced(m),await s.onProgress?.({type:`subagent_complete`,childSessionId:g,task:d,status:_.status,sessionId:t,messageId:s.messageId,depth:n+1});let y=ca({task:d,label:f,status:_.status,result:_.result,error:_.error});if(_.status===`done`){let e={status:`done`,childSessionId:g,runId:m,result:_.result??``};return{content:[{type:`text`,text:y}],details:e}}let b=_.status===`killed`?{status:`killed`,childSessionId:g,runId:m,error:`subagent killed`}:{status:`error`,childSessionId:g,runId:m,error:_.error??`unknown error`};return{content:[{type:`text`,text:y}],details:b}}}}const ua=z.Object({action:z.Union([`list`,`kill`].map(e=>z.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:z.Optional(z.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function da(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 fa(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 pa(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:ua,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} (${da(e.runtimeMs)})${n}`})).join(`
56
+ `)};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=fa(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 ma=z.Object({image:z.String({description:`Image path or URL`}),prompt:z.Optional(z.String({description:`Prompt for image analysis`})),model:z.Optional(z.String({description:`Optional model override`})),maxBytesMb:z.Optional(z.Number({description:`Optional size cap in MB`}))});function ha(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:ma,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}}}}var ga=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 _a(e){return!!(e instanceof ga||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const va=new He;function ya(){return{}}async function ba(e,t){return await va.run(e,t)}function xa(e){let t=va.getStore();!t||t.signal||(t.signal=e)}const Sa=z.Object({reason:z.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Ca(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??Sa,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=ye(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 ga(e,i,t,e,o,s,n);throw xa(r),r}}}function wa(e,t){let n=R.join(e,`workspace`),r=t?.memoryOptions,i=Zr(),a=[Rr({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Hr({registry:i,scopeKey:n}),ri(n,t?.contextManager),ai(n,t?.contextManager),si(n,t?.contextManager),li(n),hi(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),Bi(e,r),Hi(e,r),Ki(e,r),Yi(e,r),Zi(e,r),$i(e,r),ta(e,r),aa(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),oa({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return t&&a.push(la(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),pa(t.registry,t.parentSessionId)),a}const Ta={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`,memory_search:`Search long-term memory and daily logs using Markdown chunk retrieval`,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`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Ea=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`subagent_spawn`,`subagents`];function Da(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:[...Ea.filter(e=>t.has(e)),...n.filter(e=>!Ea.includes(e)).sort()],displayName:t}}function Oa(e){let{ordered:t,displayName:n}=Da(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)??Ta[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
57
57
  `),``].join(`
58
- `)}function Oa(){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(`
59
- `)}function ka(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(`
60
- `)}function Aa(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.`,`- 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>`,` </skill>`].join(`
58
+ `)}function ka(){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(`
59
+ `)}function Aa(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(`
60
+ `)}function ja(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.`,`- 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>`,` </skill>`].join(`
61
61
  `)).join(`
62
62
  `)}\n</available_skills>`,``].join(`
63
- `)}function ja(){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=/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 `/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(`
64
- `)}function Ma(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: add or replace structured long-term memory (omit section for flat append).`,`- memory_log: append a daily or session note.`,`- 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(`
65
- `)}function Na(e){return[`## Memory Recall`,`Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search to find relevant entries, then use memory_get to read the full content. Do not guess entry IDs or file paths.`,`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 examples: memory_search -> memory_get; memory_list -> memory_update; memory_search -> memory_forget.`,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(`
66
- `)}function Pa(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.`;return[`## Workspace`,`Your cloud working directory is: ${r}`,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.`,``].join(`
67
- `)}function Fa(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(`
68
- `)}function Ia(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=La(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
69
- `)}function La(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 Ra(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(`
70
- `)}function za(e){if(!e)return``;let t=[e.hostname?`host=${e.hostname}`:``,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(`
71
- `)}function Ba(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(`
72
- `)}function Va(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(`
73
- `)}function Ha(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(`
74
- `):``}function Ua(e){let t=e.promptMode??`full`,n=t===`minimal`,r=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:[...Ta],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Da({toolNames:i,toolSummaries:e.toolSummaries}),ka(n),Oa(),Aa(a),ja(),Ma(),Na(e.memoryCitationsMode??`off`),Pa({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),Fa(e.sandboxInfo),Ia({currentDate:e.currentDate,timezone:e.timezone}),Ra({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Ba({isMinimal:n}),za(e.runtimeInfo),Va({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Ha(e.priorConversationSummary)].filter(Boolean).join(`
75
- `)}const Wa=new He;async function Ga(e,t){return await Wa.run(e,t)}function Ka(e){return{async emit(t){let n=Wa.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 qa=Symbol(`pluginToolOwner`);var Ja=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,qa,{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=Sa({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,qa,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Ya(e){return e[qa]}const Xa=new He;function Za(){return{}}async function Qa(e,t){return await Xa.run(e,t)}function $a(e){let t=Xa.getStore();!t||t.signal||(t.signal=e)}function eo(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Ya(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Ga({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h;try{h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r)}catch(e){if(q(e))return $a(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(q(i)){$a(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var to=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}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 Ga({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const Z={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function no(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function ro(e){let t=no(e?.warningThreshold,Z.warningThreshold),n=no(e?.criticalThreshold,Z.criticalThreshold),r=no(e?.globalCircuitBreakerThreshold,Z.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Z.enabled,historySize:no(e?.historySize,Z.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Z.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Z.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Z.detectors.pingPong}}}function Q(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function io(e,t){return`${e}:${$(t)}`}function ao(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(ao).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${ao(t[e])}`).join(`,`)}}`}function oo(e){try{return ao(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 $(e){let t=oo(e);return Ie(`sha256`).update(t).digest(`hex`)}function so(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Q(t))return!1;let n=t.action;return n===`poll`||n===`log`}function co(e){return!Q(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Q(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
76
- `).trim()}function lo(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:ao(e)}function uo(e,t,n,r){if(r!==void 0)return`error:${$(lo(r))}`;if(!Q(n))return n===void 0?void 0:$(n);let i=Q(n.details)?n.details:{},a=co(n);if(so(e,t)&&e===`process`&&Q(t)){let e=t.action;if(e===`poll`)return $({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return $({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 $({details:i,text:a})}function fo(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 po(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 mo(e,t){return[e,t].toSorted().join(`|`)}function ho(e,t,n,r){let i=ro(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=io(t,n),s=fo(a,t,o),c=s.count,l=so(t,n),u=po(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:${mo(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 go(e,t,n,r,i){let a=ro(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:io(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function _o(e,t){let n=ro(t.config),r=uo(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=io(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 vo(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 yo(e){return e&&e.trim()||`tool`}function bo(e,t,n){if(!e.execute)return e;let r=yo(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=ho(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);vo(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}go(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return _o(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw _o(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function xo(e,t,n){return e.map(e=>bo(e,t,n))}async function So(e){let{session:{runParams:n,sessionId:r,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:l,skills:u,effectivePromptText:d,pluginTools:f,pluginSkillDirs:p,skillsLoadPaths:m,presetSystemPrompt:h},dependencies:{registry:g,spawnFn:_,createModel:v,abortSignal:y}}=e,b=n.channel===`CRON`,x=b?[]:await t(n.dataDir,r,{storeName:n.sessionStoreName}),S={model:n.llm.model,api:`openai-completions`},C=await Tr({dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName}),w=b?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Er({entries:x,modelInfo:S,contextWindowTokens:n.llm.contextWindow??2e5,llm:{baseUrl:n.llm.baseUrl,apiKey:n.llm.apiKey,model:n.llm.model},historyLimit:n.historyLimit,compactionEnabled:!0,pendingUserMessage:d,signal:y,hooks:i,hookCtx:a,contextManager:C,dataDir:n.dataDir,sessionId:r});await wo({sessionId:r,historyResult:w,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let T=n.subagentContext?.depth??0,E=[...Ca(n.dataDir,{sessionId:n.subagentContext?.parentSessionId??r,registry:g,parentSessionId:r,depth:T,channel:n.channel,llm:n.llm,inheritedRunParams:{sessionStoreName:n.sessionStoreName,plugins:n.plugins,skillsLoadPaths:m,memory:n.memory,messaging:n.messaging,historyLimit:n.historyLimit,onProgress:n.onProgress,messageId:n.messageId},loopDetection:n.loopDetection,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:r,onMemoryChanged:async()=>{}},pluginSkillDirs:p,skillsLoadPaths:m,reportSkillUsed:async e=>{await s.dispatchProgress(r,e)},contextManager:C,hitlResume:n.hitlResume,spawnFn:_}),...f],D=E.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),O={};for(let e of E){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||O[t]||(O[t]=n)}let k=n.messaging?.enabled??n.channel!==`CRON`,A=n.messaging?.channels&&n.messaging.channels.length>0?n.messaging.channels:[n.channel],j=Ua({dataDir:n.dataDir,skills:u,contextFiles:c,toolNames:D,toolSummaries:O,promptMode:T>0?`minimal`:`full`,bootstrapWarnings:l,memoryCitationsMode:n.memory?.citationsMode??`off`,messaging:{enabled:k,channels:A},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:n.llm.model,hostname:ze.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:h,priorConversationSummary:w.priorSummary});j=await Co({systemPrompt:j,dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName});let M=await i.dispatch(`before_prompt_build`,{prompt:d},a,{eventDispatcher:s});for(let e of M)e&&(e.systemPrompt&&(j=e.systemPrompt),e.prependContext&&(j=`${e.prependContext}\n\n${j}`));await i.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:j},a,{eventDispatcher:s});let N=xo(eo(E,i,a,{eventDispatcher:s}),{sessionId:r,config:n.loopDetection},gt),P=n.llm.model,F=await i.dispatch(`before_model_resolve`,{prompt:d},a,{eventDispatcher:s});for(let e of F)e&&e.modelOverride&&(P=e.modelOverride);let I=v({...n.llm,model:P},r,n.messageId,n.channel),ee=new Re({initialState:{systemPrompt:j,model:I,tools:N,messages:[]},getApiKey:e=>n.llm.apiKey});return w.messages.length>0&&ee.replaceMessages(w.messages),{agent:ee,resolvedModelId:P,historyMessages:w.messages,historyResult:w,contextManager:C,usageBaselineTranscriptEntryCount:x.length,workspaceDir:o.workspaceDir}}async function Co(e){if((await f(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 ${S(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 wo(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=To(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 To(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(`
77
-
78
- `):void 0}}async function Eo(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=0,x=[],S=new Map,C=new Set,w=!1,T=``,E=Za(),D=va(),O=t.subscribe(async e=>{let n=()=>!!D.signal||E.signal?.transparentPause===!0||w;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(b===0&&(t.type===`text_delta`||t.type===`done`)&&(b=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=Po(`partial`in t?t.partial:void 0)??Po(`message`in t?t.message:void 0)??Po(`message`in e?e.message:void 0),a=Fo(t.delta,r,p);r?(p=r,m=r):a&&(m+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){f=``,p=``,m=``,e.usage&&(h=e.usage.input,g=e.usage.output);return}f=No(e);let r=Fo(``,f,m||p);p=f,m=f,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=No(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(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:jo(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),r=n.find(e=>e.toolName===`subagent_spawn`);if(r&&(w=!0,T=r.content),x.push({message:t,toolResults:n}),d){let e=!!E.signal,r=!!D.signal;if(!(e&&E.signal.transparentPause)){let i=Oo(Do(t),e||r);await d(Ao(i,w)?null:i,r?[]:n.map(ko))}if(e||r)return}return}if(e.type===`tool_execution_start`){m=``,S.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=S.get(e.toolCallId);if(S.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){C.has(e.toolCallId)||(C.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:r}));return}C.has(e.toolCallId)||(C.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:r})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:r,output:n,isError:e.isError}),e.toolName===`subagent_spawn`&&(w=!0)}});try{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=Date.now(),await Qa(E,async()=>{await ya(D,async()=>{r?await t.continue():await t.prompt(n)})});let e=E.signal;if(e)throw e;let d=D.signal;if(d)throw d;if(!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Io(n),await s.dispatchProgress(i,{type:`error`,message:_}))}}catch(e){if(q(e)||ga(e))throw e;_=Io(e),await s.dispatchProgress(i,{type:`error`,message:_})}finally{O()}let k=x.length>0?x[x.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:f?[f]:[],lastAssistant:k,durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:{input:h,output:g,total:h+g}},l);let A=D.signal?``:x.length>0?No(x[x.length-1].message):``,j=T||(w?``:A||f);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return d&&x.length===0&&!w&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:j,inputTokens:h,outputTokens:g,error:_,turnRecords:x}}function Do(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function Oo(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function ko(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 Ao(e,t){return!e||e.toolCalls&&e.toolCalls.length>0?!1:t}function jo(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:Mo(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Mo(e){let t=e.indexOf(`
63
+ `)}function Ma(){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=/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 `/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(`
64
+ `)}function Na(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: add or replace structured long-term memory (omit section for flat append).`,`- memory_log: append a daily or session note.`,`- 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(`
65
+ `)}function Pa(e){return[`## Memory Recall`,`Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search to find relevant entries, then use memory_get to read the full content. Do not guess entry IDs or file paths.`,`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 examples: memory_search -> memory_get; memory_list -> memory_update; memory_search -> memory_forget.`,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(`
66
+ `)}function Fa(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.`;return[`## Workspace`,`Your cloud working directory is: ${r}`,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.`,``].join(`
67
+ `)}function Ia(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(`
68
+ `)}function La(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Ra(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
69
+ `)}function Ra(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 za(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(`
70
+ `)}function Ba(e){if(!e)return``;let t=[e.hostname?`host=${e.hostname}`:``,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(`
71
+ `)}function Va(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(`
72
+ `)}function Ha(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(`
73
+ `)}function Ua(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(`
74
+ `):``}function Wa(e){let t=e.promptMode??`full`,n=t===`minimal`,r=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:[...Ea],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Oa({toolNames:i,toolSummaries:e.toolSummaries}),Aa(n),ka(),ja(a),Ma(),Na(),Pa(e.memoryCitationsMode??`off`),Fa({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),Ia(e.sandboxInfo),La({currentDate:e.currentDate,timezone:e.timezone}),za({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Va({isMinimal:n}),Ba(e.runtimeInfo),Ha({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Ua(e.priorConversationSummary)].filter(Boolean).join(`
75
+ `)}const Ga=new He;async function Ka(e,t){return await Ga.run(e,t)}function qa(e){return{async emit(t){let n=Ga.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 Ja=Symbol(`pluginToolOwner`);var Ya=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,Ja,{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=Ca({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,Ja,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Xa(e){return e[Ja]}const Za=new He;function Qa(){return{}}async function $a(e,t){return await Za.run(e,t)}function eo(e){let t=Za.getStore();!t||t.signal||(t.signal=e)}function to(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Xa(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Ka({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h;try{h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r)}catch(e){if(q(e))return eo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(q(i)){eo(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var no=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}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 Ka({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const Z={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function ro(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function io(e){let t=ro(e?.warningThreshold,Z.warningThreshold),n=ro(e?.criticalThreshold,Z.criticalThreshold),r=ro(e?.globalCircuitBreakerThreshold,Z.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Z.enabled,historySize:ro(e?.historySize,Z.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Z.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Z.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Z.detectors.pingPong}}}function Q(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ao(e,t){return`${e}:${$(t)}`}function oo(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(oo).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${oo(t[e])}`).join(`,`)}}`}function so(e){try{return oo(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 $(e){let t=so(e);return Ie(`sha256`).update(t).digest(`hex`)}function co(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Q(t))return!1;let n=t.action;return n===`poll`||n===`log`}function lo(e){return!Q(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Q(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
76
+ `).trim()}function uo(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:oo(e)}function fo(e,t,n,r){if(r!==void 0)return`error:${$(uo(r))}`;if(!Q(n))return n===void 0?void 0:$(n);let i=Q(n.details)?n.details:{},a=lo(n);if(co(e,t)&&e===`process`&&Q(t)){let e=t.action;if(e===`poll`)return $({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return $({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 $({details:i,text:a})}function po(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 mo(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 ho(e,t){return[e,t].toSorted().join(`|`)}function go(e,t,n,r){let i=io(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ao(t,n),s=po(a,t,o),c=s.count,l=co(t,n),u=mo(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:${ho(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 _o(e,t,n,r,i){let a=io(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ao(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function vo(e,t){let n=io(t.config),r=fo(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ao(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 yo(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 bo(e){return e&&e.trim()||`tool`}function xo(e,t,n){if(!e.execute)return e;let r=bo(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=go(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);yo(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}_o(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return vo(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw vo(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function So(e,t,n){return e.map(e=>xo(e,t,n))}async function Co(e){let{session:{runParams:n,sessionId:r,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:l,skills:u,effectivePromptText:d,pluginTools:f,pluginSkillDirs:p,skillsLoadPaths:m,presetSystemPrompt:h},dependencies:{registry:g,spawnFn:_,createModel:v,abortSignal:y}}=e,b=n.channel===`CRON`,x=b?[]:await t(n.dataDir,r,{storeName:n.sessionStoreName}),S={model:n.llm.model,api:`openai-completions`},C=await Er({dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName}),w=b?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Dr({entries:x,modelInfo:S,contextWindowTokens:n.llm.contextWindow??2e5,llm:{baseUrl:n.llm.baseUrl,apiKey:n.llm.apiKey,model:n.llm.model},historyLimit:n.historyLimit,compactionEnabled:!0,pendingUserMessage:d,signal:y,hooks:i,hookCtx:a,contextManager:C,dataDir:n.dataDir,sessionId:r});await To({sessionId:r,historyResult:w,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let T=n.subagentContext?.depth??0,E=[...wa(n.dataDir,{sessionId:n.subagentContext?.parentSessionId??r,registry:g,parentSessionId:r,depth:T,channel:n.channel,llm:n.llm,inheritedRunParams:{sessionStoreName:n.sessionStoreName,plugins:n.plugins,skillsLoadPaths:m,memory:n.memory,messaging:n.messaging,historyLimit:n.historyLimit,onProgress:n.onProgress,messageId:n.messageId},loopDetection:n.loopDetection,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:r,onMemoryChanged:async()=>{}},pluginSkillDirs:p,skillsLoadPaths:m,reportSkillUsed:async e=>{await s.dispatchProgress(r,e)},contextManager:C,hitlResume:n.hitlResume,spawnFn:_}),...f],D=E.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),O={};for(let e of E){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||O[t]||(O[t]=n)}let k=n.messaging?.enabled??n.channel!==`CRON`,A=n.messaging?.channels&&n.messaging.channels.length>0?n.messaging.channels:[n.channel],j=Wa({dataDir:n.dataDir,skills:u,contextFiles:c,toolNames:D,toolSummaries:O,promptMode:T>0?`minimal`:`full`,bootstrapWarnings:l,memoryCitationsMode:n.memory?.citationsMode??`off`,messaging:{enabled:k,channels:A},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:n.llm.model,hostname:ze.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:h,priorConversationSummary:w.priorSummary});j=await wo({systemPrompt:j,dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName});let M=await i.dispatch(`before_prompt_build`,{prompt:d},a,{eventDispatcher:s});for(let e of M)e&&(e.systemPrompt&&(j=e.systemPrompt),e.prependContext&&(j=`${e.prependContext}\n\n${j}`));await i.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:j},a,{eventDispatcher:s});let N=So(to(E,i,a,{eventDispatcher:s}),{sessionId:r,config:n.loopDetection},gt),P=n.llm.model,F=await i.dispatch(`before_model_resolve`,{prompt:d},a,{eventDispatcher:s});for(let e of F)e&&e.modelOverride&&(P=e.modelOverride);let I=v({...n.llm,model:P},r,n.messageId,n.channel),ee=new Re({initialState:{systemPrompt:j,model:I,tools:N,messages:[]},getApiKey:e=>n.llm.apiKey});return w.messages.length>0&&ee.replaceMessages(w.messages),{agent:ee,resolvedModelId:P,historyMessages:w.messages,historyResult:w,contextManager:C,usageBaselineTranscriptEntryCount:x.length,workspaceDir:o.workspaceDir}}async function wo(e){if((await f(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 ${S(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 To(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=Eo(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 Eo(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(`
77
+
78
+ `):void 0}}async function Do(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=0,x=[],S=new Map,C=new Set,w=!1,T=``,E=Qa(),D=ya(),O=t.subscribe(async e=>{let n=()=>!!D.signal||E.signal?.transparentPause===!0||w;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(b===0&&(t.type===`text_delta`||t.type===`done`)&&(b=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=Fo(`partial`in t?t.partial:void 0)??Fo(`message`in t?t.message:void 0)??Fo(`message`in e?e.message:void 0),a=Io(t.delta,r,p);r?(p=r,m=r):a&&(m+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){f=``,p=``,m=``,e.usage&&(h=e.usage.input,g=e.usage.output);return}f=Po(e);let r=Io(``,f,m||p);p=f,m=f,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Po(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(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:Mo(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),r=n.find(e=>e.toolName===`subagent_spawn`);if(r&&(w=!0,T=r.content),x.push({message:t,toolResults:n}),d){let e=!!E.signal,r=!!D.signal;if(!(e&&E.signal.transparentPause)){let i=ko(Oo(t),e||r);await d(jo(i,w)?null:i,r?[]:n.map(Ao))}if(e||r)return}return}if(e.type===`tool_execution_start`){m=``,S.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=S.get(e.toolCallId);if(S.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){C.has(e.toolCallId)||(C.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:r}));return}C.has(e.toolCallId)||(C.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:r})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:r,output:n,isError:e.isError}),e.toolName===`subagent_spawn`&&(w=!0)}});try{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=Date.now(),await $a(E,async()=>{await ba(D,async()=>{r?await t.continue():await t.prompt(n)})});let e=E.signal;if(e)throw e;let d=D.signal;if(d)throw d;if(!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Lo(n),await s.dispatchProgress(i,{type:`error`,message:_}))}}catch(e){if(q(e)||_a(e))throw e;_=Lo(e),await s.dispatchProgress(i,{type:`error`,message:_})}finally{O()}let k=x.length>0?x[x.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:f?[f]:[],lastAssistant:k,durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:{input:h,output:g,total:h+g}},l);let A=D.signal?``:x.length>0?Po(x[x.length-1].message):``,j=T||(w?``:A||f);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return d&&x.length===0&&!w&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:j,inputTokens:h,outputTokens:g,error:_,turnRecords:x}}function Oo(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function ko(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Ao(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 jo(e,t){return!e||e.toolCalls&&e.toolCalls.length>0?!1:t}function Mo(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:No(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function No(e){let t=e.indexOf(`
79
79
  Preview:
80
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function No(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Po(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 Fo(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Io(e){let t=Lo(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 Lo(e){if(e instanceof U)return e;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 Ro(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,appendEntry:l}=e,u=0,d=``,f=0,p=0,m;for(;!c?.aborted&&n.needsAnnounce(r)&&u<10;){u++,await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let h=zo(e);await l({role:`assistant`,content:h,timestamp:new Date().toISOString()});let g=await Eo({agent:t,message:h,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,onTurnRecordProduced:async(e,t)=>{e&&await l(e);for(let e of t)await l(e)}});d=g.text,f+=g.inputTokens,p+=g.outputTokens,g.error&&!m&&(m=g.error),n.markAnnounced(e.map(e=>e.runId))}return{text:d,inputTokens:f,outputTokens:p,error:m}}function zo(e){if(e.length===1){let t=e[0];return sa({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>sa({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
80
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Po(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Fo(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 Io(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Lo(e){let t=Ro(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 Ro(e){if(e instanceof U)return e;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 zo(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,appendEntry:l}=e,u=0,d=``,f=0,p=0,m;for(;!c?.aborted&&n.needsAnnounce(r)&&u<10;){u++,await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let h=Bo(e);await l({role:`assistant`,content:h,timestamp:new Date().toISOString()});let g=await Do({agent:t,message:h,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,onTurnRecordProduced:async(e,t)=>{e&&await l(e);for(let e of t)await l(e)}});d=g.text,f+=g.inputTokens,p+=g.outputTokens,g.error&&!m&&(m=g.error),n.markAnnounced(e.map(e=>e.runId))}return{text:d,inputTokens:f,outputTokens:p,error:m}}function Bo(e){if(e.length===1){let t=e[0];return ca({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>ca({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
81
81
 
82
82
  ---
83
83
 
84
- `)}`}function Bo(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 Vo(e){let t=Bo(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=R.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 Ho(e){let t=e.watchFactory??((e,t,n)=>V.watch(e,t,n)),n=R.join(e.dataDir,`.aimax`),r=[{target:R.join(n,`MEMORY.md`),kind:`memory-file`},{target:R.join(n,`memory.md`),kind:`memory-file-lower`},{target:R.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=Vo({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{}}}async function Uo(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=R.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),o=Ko(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)l.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(c)??0)<1e3)return;u.set(c,t);let d={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:d.reason,files:d.files,source:d.source,providerId:d.providerId,timestamp:d.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,d,{...a,sessionId:d.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=R.join(t.dataDir,`.aimax`),m=N({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName})?.provider??C({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=Ho({dataDir:t.dataDir,sessionId:i,providerId:o??s??m.id,provider:m,onMemoryChanged:f});m.sync&&m.sync(`session-start`).catch(()=>{});let g=async e=>{await O(t.dataDir,i,e,Go({sessionStoreName:t.sessionStoreName,providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:g,persistInitialUserEntry:async e=>d?!1:(await g({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{h()}}}function Wo(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Go(e){return e.sessionStoreName||e.providerId||e.pluginId?{storeName:e.sessionStoreName,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function Ko(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 qo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jo(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Yo(){let e=ze.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Xo(e){let t=e.trim(),n=Yo();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?R.join(n,t.slice(2)):void 0:R.resolve(t)}const Zo=new Ue({allErrors:!0,strict:!1}),Qo=new Map;function $o(e,t){let n=Qo.get(t);if(n)return n;let r=Zo.compile(e);return Qo.set(t,r),r}function es(e){let t=e.cacheKey??JSON.stringify(e.schema),n=$o(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function ts(e){let t=Jo(e?.allow),n=Jo(e?.deny),r=Jo(e?.load?.paths),i=e?.entries??{},a=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)),entries:i,slots:a}}function ns(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=es({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 rs(e){try{return V.realpathSync(e)}catch{return null}}function is(e){try{return V.statSync(e)}catch{return null}}function as(e,t){let n=R.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!R.isAbsolute(n)}function os(e){return`0o${e.toString(8).padStart(3,`0`)}`}const ss=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),cs=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function ls(e){let t=R.join(e,`package.json`);if(V.existsSync(t))try{let e=JSON.parse(V.readFileSync(t,`utf-8`));return qo(e)?e:void 0}catch{return}}function us(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 ds(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function fs(e){let t=rs(e.source),n=rs(e.rootDir);return!t||!n||as(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function ps(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=R.resolve(r);if(n.has(t))continue;n.add(t);let i=is(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 ms(e){return fs({source:e.source,rootDir:e.rootDir})||ps({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:ds(e.ownershipUid)})}function hs(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=${os(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function gs(e){let t=ms({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:hs(t),source:e.source}),!0):!1}function _s(e){return R.basename(e,R.extname(e))}function vs(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 ys(e){for(let t of cs){let n=R.join(e,t);if(V.existsSync(n))return n}return null}function bs(e){let t;try{t=V.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=R.join(e.rootDir,n.name);if(n.isFile()){if(!ss.has(R.extname(n.name)))continue;let r=R.dirname(t);if(gs({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(vs({idHint:_s(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=ls(t),i=us(r);if(i.status===`ok`){for(let n of i.entries){let i=R.resolve(t,n);if(!as(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!V.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!ss.has(R.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(gs({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${_s(i)}`:_s(i);e.candidates.push(vs({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=ys(t);a&&(gs({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(vs({idHint:R.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function xs(e){return e?e.map(Xo).filter(e=>typeof e==`string`&&e.length>0):[]}function Ss(){let e=Yo();if(e)return R.join(e,`.aimax`,`extensions`)}function Cs(e){return R.join(e,`.aimax`,`extensions`)}function ws(e){return R.join(e,`.aimax`,`extensions`)}function Ts(e={}){let t=[],n=[],r=xs(e.extraPaths);for(let i of r){if(!V.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=is(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!ss.has(R.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=R.dirname(i);if(gs({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(vs({idHint:_s(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&bs({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?bs({rootDir:Cs(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&bs({rootDir:ws(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Ss();return i?bs({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&&bs({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Es(e){let t=e.rejectHardlinks??!0,n=rs(e.rootPath),r=rs(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!as(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=V.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:V.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ds=`aimax.plugin.json`,Os=[Ds];function ks(e){for(let t of Os){let n=R.join(e,t);if(V.existsSync(n))return n}return R.join(e,Ds)}function As(e,t=!0){let n=ks(e),r=Es({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(V.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{V.closeSync(r.fd)}if(!qo(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=qo(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=Jo(i.skills),f;return qo(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 js(e){let t=new Map,n=[];for(let r of e){let e=As(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 Ms=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Ns(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Ps(e,t,n,r){process.stderr.write(`[${Ns()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Fs(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Ps(Ms.INFO,e.pluginId,t,n),warn:n=>Ps(Ms.WARN,e.pluginId,t,n),error:n=>Ps(Ms.ERROR,e.pluginId,t,n)})}}}function Is(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 Ls(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 Rs(e){let t=[...e.registry.diagnostics],n=new Ja,r=new to,i=[],a=[],o=e.runtime?.llm?vt({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=zs(e.runtime?.llmAllowlist),c=We(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Is({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Ls({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;try{f=c(l.source)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let p=f&&typeof f==`object`&&`default`in f?f.default:f,m=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!m){d.status=`error`,d.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let h=Fs({pluginId:l.id}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Bs(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`);v({pluginId:l.id,id:e.id,create:e.create,config:g,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`);P({pluginId:l.id,id:e.id,create:e.create,config:g,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=R.isAbsolute(e)?e:R.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Ka(l.id)};try{m(_)}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=R.isAbsolute(e)?e:R.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function zs(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Bs(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Vs(e={}){let t=ts(e.config),n=Ts({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=js(n.candidates),i=ns({config:t,registry:r}),a=Rs({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t}}function Hs(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Vs({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({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,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new to,pluginSkillDirs:o?.registry.skills??[],pluginTools:[...o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...o?.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function Us(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=R.join(t.dataDir,`workspace`),a=n,o=!a;a?(await b(t.dataDir,a,{storeName:t.sessionStoreName})||(o=!0),await _(t.dataDir,a,{storeName:t.sessionStoreName})):a=await T(t.dataDir,t.channel,{storeName:t.sessionStoreName});let s={sessionId:a,workspaceDir:i,channel:t.channel},c=Hs({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),l=c.hookRegistry,u=await Uo({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:l});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:l,pluginContext:c,runContext:u,start:e=>$t({sessionId:a,runParams:t,hookRegistry:l,hookContext:s,eventDispatcher:r,...e})}}function Ws(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Gs(e){if(!(e instanceof Error))return{errorValue:Ws(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]=Ws(n[e]));return t}async function Ks(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Gs(e.error)}})}function qs(e,t,n){return R.join(o(e,t,n),`pending-hitl.json`)}function Js(e,t,n){return R.join(o(e,t,n),`hitl-history.jsonl`)}async function Ys(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0});let a=qs(e,t,r);await L.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function Xs(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0});let a=Js(e,t,r),s=JSON.stringify(n)+`
85
- `;await L.appendFile(a,s,`utf-8`)}async function Zs(e,t,n){let r=qs(e,t,n);try{let e=await L.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Qs(e,t,n){let r=Js(e,t,n);try{let e=await L.readFile(r,`utf-8`),t=[];for(let n of e.split(`
86
- `)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function $s(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await Ys(e,t,c,o),await Xs(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function ec(e,t,n,r,i,a){let o=await Zs(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await Ys(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await Xs(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function tc(e,t,n,r){let i=await Zs(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function nc(e,t,n){let r=qs(e,t,n);try{await L.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function rc(e,t,n){return R.join(o(e,t,n),`pending-ui-tool.json`)}async function ic(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0}),await L.writeFile(rc(e,t,r),JSON.stringify(n,null,2),`utf-8`)}async function ac(e,t,n){try{let r=await L.readFile(rc(e,t,n),`utf-8`);return JSON.parse(r)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function oc(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await ic(e,t,a,r),a}async function sc(e,t,n,r,i){let a=await ac(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 ic(e,t,o,i),o}async function cc(e,t,n){try{await L.unlink(rc(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const lc=`crons`;function uc(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function dc(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!ve(t))}async function fc(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=Za();if(i=await Qa(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(q(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=pc(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 pc(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)}async function mc(e,t){qt();let r=Date.now(),i=new Jt(e),a=Rn(e),o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await Us({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId,d=l.isNewSession,f=l.workspaceDir,p=l.hookContext,m=l.hookRegistry,h=l.pluginContext,g=l.runContext;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}}),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 n(e.dataDir,Wo({sessionId:u,title:Qt(o),channel:e.channel}),{storeName:e.sessionStoreName}),a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await g.persistInitialUserEntry(o)),await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let _=new AbortController;e.abortSignal?.aborted?_.abort():e.abortSignal?.addEventListener(`abort`,()=>_.abort());let v=await Je(e.dataDir),y=[],b=Ze(v,{warn:e=>y.push(e)}),x=await et();await i.dispatchDiagnostic(u,{level:y.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:v.length,contextFileCount:b.length,warningCount:y.length}});let S=e.skillsLoadPaths??[],C=await ot(e.dataDir,h.pluginSkillDirs,S);await i.dispatchDiagnostic(u,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:C.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:S.length,skills:C.map(e=>({name:e.name,description:e.description,location:e.location}))}});let w=e=>g.appendTranscriptEntry(e),T=await Bn({invocation:a,skills:C,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i});if(T.kind===`completed`)return T.result;let E=T.effectivePrompt;o=T.transcriptMessage;let D=typeof E==`string`?E:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof E==`string`?`string`:`messages`,transcriptLength:o.length}});let O=await So({session:{runParams:e,sessionId:u,hookRegistry:m,hookContext:p,runContext:g,eventDispatcher:i},runtimeInputs:{contextFiles:b,bootstrapWarnings:y,skills:C,effectivePromptText:D,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:S,presetSystemPrompt:x.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>mc(e,new mt),createModel:uc,abortSignal:_.signal}}),k=O.agent,A=O.resolvedModelId;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:A,historyMessageCount:O.historyMessages.length,pluginToolCount:h.pluginTools.length}}),_.signal.addEventListener(`abort`,()=>k.abort());let j=0,M=0,N=``,P,F=!1;try{if(dc(e)){let t=await fc({params:e,agent:k,sessionId:u,eventDispatcher:i,appendEntry:w,abortSignal:_.signal});return N=t.text,nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(o);F=e,s=e||s}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let n=await Eo({agent:k,message:E,continueFromHistory:!!e.uiToolResume,sessionId:u,modelId:A,historyMessages:O.historyMessages,eventDispatcher:i,hooks:m,hookCtx:p,abortSignal:_.signal,onTurnRecordProduced:async(e,t)=>{e&&await w(e);for(let e of t)await w(e)}});N=n.text,j+=n.inputTokens,M+=n.outputTokens,n.error&&(P=n.error),await i.dispatchDiagnostic(u,{level:n.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let a=await Ro({agent:k,registry:t,sessionId:u,resolvedModelId:A,eventDispatcher:i,hookRegistry:m,hookContext:p,abortSignal:_.signal,appendEntry:w});a.text&&(N=a.text),j+=a.inputTokens,M+=a.outputTokens,a.error&&!P&&(P=a.error),await i.dispatchDiagnostic(u,{level:a.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!a.error,error:a.error,inputTokens:a.inputTokens,outputTokens:a.outputTokens}})}catch(t){if(q(t)){let n=t,a=e.subagentContext?.parentSessionId??u,s=a===n.request.sessionId?n.request:{...n.request,sessionId:a};await $s(e.dataDir,a,s,n.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},n.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: ${n.request.kind} — ${n.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:n.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}});let c={input:j,output:M,total:j+M};return await hc({runtime:O,resolvedModelId:A,usage:c,currentUserEntryCoveredByUsage:F}),nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N||`[HITL paused] ${n.request.title}: ${n.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(ga(t)){let n=t,a=n.request.outputSchema.properties??{};await oc(e.dataDir,u,n.request,{storeName:e.sessionStoreName}),await i.dispatchProgress(u,{type:`ui_tool_request`,request:n.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${n.request.toolName}`,details:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchemaTitle:n.request.outputSchema.title,propertyCount:Object.keys(a).length}});let s={input:j,output:M,total:j+M};return await hc({runtime:O,resolvedModelId:A,usage:s,currentUserEntryCoveredByUsage:F}),nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N||`[UI Tool] Waiting for user input: ${n.request.outputSchema.title}`,usage:s,error:void 0,uiToolPending:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchema:n.request.outputSchema,extra:n.request.extra}})}throw await Ks({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),t}finally{_t(u),g.stop()}let I={input:j,output:M,total:j+M};return await i.dispatchDiagnostic(u,{level:P?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-r,inputTokens:I.input,outputTokens:I.output,totalTokens:I.total,hasError:!!P,error:P}}),await hc({runtime:O,resolvedModelId:A,usage:I,currentUserEntryCoveredByUsage:F}),nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N,usage:I,error:P})}async function hc(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 gc(e){let t=Date.now(),a=new Jt(e),o=Rn(e),c=o.transcriptMessage.trim()||`CRON task`,l=e.sessionStoreName,u=o.requestedSessionId,d=!u;u?(await b(e.dataDir,u,{storeName:l})||(d=!0),await _(e.dataDir,u,{storeName:l})):u=await T(e.dataDir,e.channel,{storeName:l}),d&&await n(e.dataDir,Wo({sessionId:u,title:Qt(c),channel:e.channel}),{storeName:l});let f=await T(e.dataDir,e.channel,{storeName:lc});await a.dispatchProgress(u,{type:`subagent_spawn`,childSessionId:f,task:c});let p={...e,sessionId:f,sessionStoreName:lc,subagentContext:{depth:1,parentSessionId:u}},m,g=`done`;try{m=await mc(p,new mt),m.error&&(g=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);m={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:h(e.dataDir,f,{storeName:lc}),toolResultsDir:i(e.dataDir,f,{storeName:lc})}},g=`error`}await a.dispatchProgress(u,{type:`subagent_complete`,childSessionId:f,task:c,status:g});let v=sa({task:c,status:g,result:m.text,error:m.error}),y=new Date().toISOString();await O(e.dataDir,u,{role:`assistant`,content:v,timestamp:y,source:`cron`},{storeName:l});let S={task:c,status:g,content:v,childSessionId:f,createdAt:y};return await x(e.dataDir,u,S,{storeName:l}),await r(e.dataDir,u,e=>_c(e,8),{storeName:l}),await s(e.dataDir,u,{},{storeName:l}),{...m,sessionId:u,context:{snapshotPath:h(e.dataDir,u,{storeName:l}),toolResultsDir:i(e.dataDir,u,{storeName:l})}}}function _c(e,t){if(t<=0)return e.filter(e=>!vc(e));let n=e.reduce((e,t,n)=>(vc(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!vc(e)||r.has(t))}function vc(e){return`source`in e&&e.source===`cron`}async function yc(e,t){if(e.channel===`CRON`&&!e.subagentContext)return gc(e);let n=t??new mt;try{return await mc(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:Gs(t)}),t}}const bc={"AGENTS.md":`---
84
+ `)}`}function Vo(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 Ho(e){let t=Vo(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=R.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 Uo(e){let t=e.watchFactory??((e,t,n)=>V.watch(e,t,n)),n=R.join(e.dataDir,`.aimax`),r=[{target:R.join(n,`MEMORY.md`),kind:`memory-file`},{target:R.join(n,`memory.md`),kind:`memory-file-lower`},{target:R.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=Ho({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{}}}async function Wo(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=R.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),o=qo(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)l.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(c)??0)<1e3)return;u.set(c,t);let d={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:d.reason,files:d.files,source:d.source,providerId:d.providerId,timestamp:d.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,d,{...a,sessionId:d.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=R.join(t.dataDir,`.aimax`),m=N({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName})?.provider??C({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=Uo({dataDir:t.dataDir,sessionId:i,providerId:o??s??m.id,provider:m,onMemoryChanged:f});m.sync&&m.sync(`session-start`).catch(()=>{});let g=async e=>{await O(t.dataDir,i,e,Ko({sessionStoreName:t.sessionStoreName,providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:g,persistInitialUserEntry:async e=>d?!1:(await g({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{h()}}}function Go(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Ko(e){return e.sessionStoreName||e.providerId||e.pluginId?{storeName:e.sessionStoreName,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function qo(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 Jo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yo(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Xo(){let e=ze.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Zo(e){let t=e.trim(),n=Xo();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?R.join(n,t.slice(2)):void 0:R.resolve(t)}const Qo=new Ue({allErrors:!0,strict:!1}),$o=new Map;function es(e,t){let n=$o.get(t);if(n)return n;let r=Qo.compile(e);return $o.set(t,r),r}function ts(e){let t=e.cacheKey??JSON.stringify(e.schema),n=es(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function ns(e){let t=Yo(e?.allow),n=Yo(e?.deny),r=Yo(e?.load?.paths),i=e?.entries??{},a=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)),entries:i,slots:a}}function rs(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=ts({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 is(e){try{return V.realpathSync(e)}catch{return null}}function as(e){try{return V.statSync(e)}catch{return null}}function os(e,t){let n=R.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!R.isAbsolute(n)}function ss(e){return`0o${e.toString(8).padStart(3,`0`)}`}const cs=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),ls=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function us(e){let t=R.join(e,`package.json`);if(V.existsSync(t))try{let e=JSON.parse(V.readFileSync(t,`utf-8`));return Jo(e)?e:void 0}catch{return}}function ds(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 fs(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function ps(e){let t=is(e.source),n=is(e.rootDir);return!t||!n||os(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function ms(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=R.resolve(r);if(n.has(t))continue;n.add(t);let i=as(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 hs(e){return ps({source:e.source,rootDir:e.rootDir})||ms({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:fs(e.ownershipUid)})}function gs(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=${ss(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function _s(e){let t=hs({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:gs(t),source:e.source}),!0):!1}function vs(e){return R.basename(e,R.extname(e))}function ys(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 bs(e){for(let t of ls){let n=R.join(e,t);if(V.existsSync(n))return n}return null}function xs(e){let t;try{t=V.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=R.join(e.rootDir,n.name);if(n.isFile()){if(!cs.has(R.extname(n.name)))continue;let r=R.dirname(t);if(_s({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(ys({idHint:vs(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=us(t),i=ds(r);if(i.status===`ok`){for(let n of i.entries){let i=R.resolve(t,n);if(!os(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!V.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!cs.has(R.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(_s({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${vs(i)}`:vs(i);e.candidates.push(ys({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=bs(t);a&&(_s({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(ys({idHint:R.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Ss(e){return e?e.map(Zo).filter(e=>typeof e==`string`&&e.length>0):[]}function Cs(){let e=Xo();if(e)return R.join(e,`.aimax`,`extensions`)}function ws(e){return R.join(e,`.aimax`,`extensions`)}function Ts(e){return R.join(e,`.aimax`,`extensions`)}function Es(e={}){let t=[],n=[],r=Ss(e.extraPaths);for(let i of r){if(!V.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=as(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!cs.has(R.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=R.dirname(i);if(_s({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(ys({idHint:vs(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&xs({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?xs({rootDir:ws(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&xs({rootDir:Ts(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Cs();return i?xs({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&&xs({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Ds(e){let t=e.rejectHardlinks??!0,n=is(e.rootPath),r=is(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!os(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=V.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:V.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Os=`aimax.plugin.json`,ks=[Os];function As(e){for(let t of ks){let n=R.join(e,t);if(V.existsSync(n))return n}return R.join(e,Os)}function js(e,t=!0){let n=As(e),r=Ds({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(V.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{V.closeSync(r.fd)}if(!Jo(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=Jo(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=Yo(i.skills),f;return Jo(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 Ms(e){let t=new Map,n=[];for(let r of e){let e=js(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 Ns=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Ps(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Fs(e,t,n,r){process.stderr.write(`[${Ps()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Is(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Fs(Ns.INFO,e.pluginId,t,n),warn:n=>Fs(Ns.WARN,e.pluginId,t,n),error:n=>Fs(Ns.ERROR,e.pluginId,t,n)})}}}function Ls(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 Rs(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 zs(e){let t=[...e.registry.diagnostics],n=new Ya,r=new no,i=[],a=[],o=e.runtime?.llm?vt({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Bs(e.runtime?.llmAllowlist),c=We(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Ls({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Rs({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;try{f=c(l.source)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let p=f&&typeof f==`object`&&`default`in f?f.default:f,m=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!m){d.status=`error`,d.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let h=Is({pluginId:l.id}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Vs(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`);v({pluginId:l.id,id:e.id,create:e.create,config:g,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`);P({pluginId:l.id,id:e.id,create:e.create,config:g,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=R.isAbsolute(e)?e:R.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>qa(l.id)};try{m(_)}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=R.isAbsolute(e)?e:R.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Bs(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Vs(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Hs(e={}){let t=ns(e.config),n=Es({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Ms(n.candidates),i=rs({config:t,registry:r}),a=zs({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t}}function Us(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Hs({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({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,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new no,pluginSkillDirs:o?.registry.skills??[],pluginTools:[...o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...o?.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function Ws(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=R.join(t.dataDir,`workspace`),a=n,o=!a;a?(await b(t.dataDir,a,{storeName:t.sessionStoreName})||(o=!0),await _(t.dataDir,a,{storeName:t.sessionStoreName})):a=await T(t.dataDir,t.channel,{storeName:t.sessionStoreName});let s={sessionId:a,workspaceDir:i,channel:t.channel},c=Us({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),l=c.hookRegistry,u=await Wo({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:l});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:l,pluginContext:c,runContext:u,start:e=>$t({sessionId:a,runParams:t,hookRegistry:l,hookContext:s,eventDispatcher:r,...e})}}function Gs(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Ks(e){if(!(e instanceof Error))return{errorValue:Gs(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]=Gs(n[e]));return t}async function qs(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Ks(e.error)}})}function Js(e,t,n){return R.join(o(e,t,n),`pending-hitl.json`)}function Ys(e,t,n){return R.join(o(e,t,n),`hitl-history.jsonl`)}async function Xs(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0});let a=Js(e,t,r);await L.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function Zs(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0});let a=Ys(e,t,r),s=JSON.stringify(n)+`
85
+ `;await L.appendFile(a,s,`utf-8`)}async function Qs(e,t,n){let r=Js(e,t,n);try{let e=await L.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function $s(e,t,n){let r=Ys(e,t,n);try{let e=await L.readFile(r,`utf-8`),t=[];for(let n of e.split(`
86
+ `)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function ec(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await Xs(e,t,c,o),await Zs(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function tc(e,t,n,r,i,a){let o=await Qs(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await Xs(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await Zs(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function nc(e,t,n,r){let i=await Qs(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function rc(e,t,n){let r=Js(e,t,n);try{await L.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function ic(e,t,n){return R.join(o(e,t,n),`pending-ui-tool.json`)}async function ac(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0}),await L.writeFile(ic(e,t,r),JSON.stringify(n,null,2),`utf-8`)}async function oc(e,t,n){try{let r=await L.readFile(ic(e,t,n),`utf-8`);return JSON.parse(r)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function sc(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await ac(e,t,a,r),a}async function cc(e,t,n,r,i){let a=await oc(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 ac(e,t,o,i),o}async function lc(e,t,n){try{await L.unlink(ic(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const uc=`crons`;function dc(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function fc(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!ve(t))}async function pc(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=Qa();if(i=await $a(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(q(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=mc(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 mc(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)}async function hc(e,t){qt();let r=Date.now(),i=new Jt(e),a=zn(e),o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await Ws({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId,d=l.isNewSession,f=l.workspaceDir,p=l.hookContext,m=l.hookRegistry,h=l.pluginContext,g=l.runContext;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}}),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 n(e.dataDir,Go({sessionId:u,title:Qt(o),channel:e.channel}),{storeName:e.sessionStoreName}),a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await g.persistInitialUserEntry(o)),await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let _=new AbortController;e.abortSignal?.aborted?_.abort():e.abortSignal?.addEventListener(`abort`,()=>_.abort());let v=await Je(e.dataDir),y=[],b=Ze(v,{warn:e=>y.push(e)}),x=await et();await i.dispatchDiagnostic(u,{level:y.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:v.length,contextFileCount:b.length,warningCount:y.length}});let S=e.skillsLoadPaths??[],C=await ot(e.dataDir,h.pluginSkillDirs,S);await i.dispatchDiagnostic(u,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:C.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:S.length,skills:C.map(e=>({name:e.name,description:e.description,location:e.location}))}});let w=e=>g.appendTranscriptEntry(e),T=await Vn({invocation:a,skills:C,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i});if(T.kind===`completed`)return T.result;let E=T.effectivePrompt;o=T.transcriptMessage;let D=typeof E==`string`?E:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof E==`string`?`string`:`messages`,transcriptLength:o.length}});let O=await Co({session:{runParams:e,sessionId:u,hookRegistry:m,hookContext:p,runContext:g,eventDispatcher:i},runtimeInputs:{contextFiles:b,bootstrapWarnings:y,skills:C,effectivePromptText:D,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:S,presetSystemPrompt:x.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>hc(e,new mt),createModel:dc,abortSignal:_.signal}}),k=O.agent,A=O.resolvedModelId;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:A,historyMessageCount:O.historyMessages.length,pluginToolCount:h.pluginTools.length}}),_.signal.addEventListener(`abort`,()=>k.abort());let j=0,M=0,N=``,P,F=!1;try{if(fc(e)){let t=await pc({params:e,agent:k,sessionId:u,eventDispatcher:i,appendEntry:w,abortSignal:_.signal});return N=t.text,nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(o);F=e,s=e||s}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let n=await Do({agent:k,message:E,continueFromHistory:!!e.uiToolResume,sessionId:u,modelId:A,historyMessages:O.historyMessages,eventDispatcher:i,hooks:m,hookCtx:p,abortSignal:_.signal,onTurnRecordProduced:async(e,t)=>{e&&await w(e);for(let e of t)await w(e)}});N=n.text,j+=n.inputTokens,M+=n.outputTokens,n.error&&(P=n.error),await i.dispatchDiagnostic(u,{level:n.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let a=await zo({agent:k,registry:t,sessionId:u,resolvedModelId:A,eventDispatcher:i,hookRegistry:m,hookContext:p,abortSignal:_.signal,appendEntry:w});a.text&&(N=a.text),j+=a.inputTokens,M+=a.outputTokens,a.error&&!P&&(P=a.error),await i.dispatchDiagnostic(u,{level:a.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!a.error,error:a.error,inputTokens:a.inputTokens,outputTokens:a.outputTokens}})}catch(t){if(q(t)){let n=t,a=e.subagentContext?.parentSessionId??u,s=a===n.request.sessionId?n.request:{...n.request,sessionId:a};await ec(e.dataDir,a,s,n.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},n.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: ${n.request.kind} — ${n.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:n.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}});let c={input:j,output:M,total:j+M};return await gc({runtime:O,resolvedModelId:A,usage:c,currentUserEntryCoveredByUsage:F}),nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N||`[HITL paused] ${n.request.title}: ${n.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(_a(t)){let n=t,a=n.request.outputSchema.properties??{};await sc(e.dataDir,u,n.request,{storeName:e.sessionStoreName}),await i.dispatchProgress(u,{type:`ui_tool_request`,request:n.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${n.request.toolName}`,details:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchemaTitle:n.request.outputSchema.title,propertyCount:Object.keys(a).length}});let s={input:j,output:M,total:j+M};return await gc({runtime:O,resolvedModelId:A,usage:s,currentUserEntryCoveredByUsage:F}),nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N||`[UI Tool] Waiting for user input: ${n.request.outputSchema.title}`,usage:s,error:void 0,uiToolPending:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchema:n.request.outputSchema,extra:n.request.extra}})}throw await qs({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),t}finally{_t(u),g.stop()}let I={input:j,output:M,total:j+M};return await i.dispatchDiagnostic(u,{level:P?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-r,inputTokens:I.input,outputTokens:I.output,totalTokens:I.total,hasError:!!P,error:P}}),await gc({runtime:O,resolvedModelId:A,usage:I,currentUserEntryCoveredByUsage:F}),nn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N,usage:I,error:P})}async function gc(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 _c(e){let t=Date.now(),a=new Jt(e),o=zn(e),c=o.transcriptMessage.trim()||`CRON task`,l=e.sessionStoreName,u=o.requestedSessionId,d=!u;u?(await b(e.dataDir,u,{storeName:l})||(d=!0),await _(e.dataDir,u,{storeName:l})):u=await T(e.dataDir,e.channel,{storeName:l}),d&&await n(e.dataDir,Go({sessionId:u,title:Qt(c),channel:e.channel}),{storeName:l});let f=await T(e.dataDir,e.channel,{storeName:uc});await a.dispatchProgress(u,{type:`subagent_spawn`,childSessionId:f,task:c});let p={...e,sessionId:f,sessionStoreName:uc,subagentContext:{depth:1,parentSessionId:u}},m,g=`done`;try{m=await hc(p,new mt),m.error&&(g=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);m={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:h(e.dataDir,f,{storeName:uc}),toolResultsDir:i(e.dataDir,f,{storeName:uc})}},g=`error`}await a.dispatchProgress(u,{type:`subagent_complete`,childSessionId:f,task:c,status:g});let v=ca({task:c,status:g,result:m.text,error:m.error}),y=new Date().toISOString();await O(e.dataDir,u,{role:`assistant`,content:v,timestamp:y,source:`cron`},{storeName:l});let S={task:c,status:g,content:v,childSessionId:f,createdAt:y};return await x(e.dataDir,u,S,{storeName:l}),await r(e.dataDir,u,e=>vc(e,8),{storeName:l}),await s(e.dataDir,u,{},{storeName:l}),{...m,sessionId:u,context:{snapshotPath:h(e.dataDir,u,{storeName:l}),toolResultsDir:i(e.dataDir,u,{storeName:l})}}}function vc(e,t){if(t<=0)return e.filter(e=>!yc(e));let n=e.reduce((e,t,n)=>(yc(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!yc(e)||r.has(t))}function yc(e){return`source`in e&&e.source===`cron`}async function bc(e,t){if(e.channel===`CRON`&&!e.subagentContext)return _c(e);let n=t??new mt;try{return await hc(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:Ks(t)}),t}}const xc={"AGENTS.md":`---
87
87
  title: "AGENTS.md Template"
88
88
  summary: ".aimax template for AGENTS.md"
89
89
  read_when:
@@ -376,7 +376,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
376
376
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
377
377
 
378
378
  Add whatever helps you do your job. This is your cheat sheet.
379
- `},xc=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Sc(e,t){try{if(!(await L.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 L.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Cc(e,t,n){try{if(!(await L.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 L.mkdir(R.dirname(e),{recursive:!0});try{await L.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 wc(e){let t=H(e);return[e,t,R.join(t,`skills`),R.join(t,`sessions`),R.join(t,`memory`),R.join(e,`workspace`)]}function Tc(e){let t=H(e);return[...xc.filter(e=>e!==`BOOTSTRAP.md`).map(e=>R.join(t,e)),R.join(t,`MEMORY.md`)]}function Ec(e){return R.join(H(e),`.bootstrapped`)}async function Dc(e){try{return(await L.stat(Ec(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Oc(e){let t=Ec(e);await L.mkdir(R.dirname(t),{recursive:!0}),await L.writeFile(t,``,{encoding:`utf-8`})}async function kc(e){let t=[],n=[];for(let n of wc(e))try{(await L.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Tc(e))try{(await L.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 Ac(e){return(await kc(e)).ready}async function jc(e){if(await Dc(e))return{ready:!0,performedBootstrap:!1};if((await kc(e)).ready)return await Oc(e),{ready:!0,performedBootstrap:!1};let t=await Mc(e);return await Oc(e),{ready:!0,performedBootstrap:!0,result:t}}async function Mc(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=H(e),r=R.join(e,`workspace`),i=R.join(n,`skills`),a=R.join(n,`sessions`),o=R.join(n,`memory`);await Sc(e,t),await Sc(n,t),await Sc(i,t),await Sc(a,t),await Sc(o,t),await Sc(r,t);for(let e of xc){let r=bc[e]??``;await Cc(R.join(n,e),r,t)}return await Cc(R.join(n,`MEMORY.md`),``,t),t}async function Nc(e){let t=R.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await L.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 Pc(e,t){let n=R.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 L.mkdir(R.dirname(n),{recursive:!0}),await L.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Fc(e,t){let n=await Nc(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 Ic(e,t=7){let n=await Nc(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 Pc(e,n),i}async function Lc(e,t,n,r){let i=await Zs(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?_e(i.request)?(await ec(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 Rc(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await tc(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 Lc(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await ec(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 zc={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 Bc(e){return e.action===`timeout`?zc.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?zc.approval.summary.approved:zc.approval.summary.denied}function Vc(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Bc(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Hc(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 Uc(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 Wc(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
379
+ `},Sc=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Cc(e,t){try{if(!(await L.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 L.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function wc(e,t,n){try{if(!(await L.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 L.mkdir(R.dirname(e),{recursive:!0});try{await L.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 Tc(e){let t=H(e);return[e,t,R.join(t,`skills`),R.join(t,`sessions`),R.join(t,`memory`),R.join(e,`workspace`)]}function Ec(e){let t=H(e);return[...Sc.filter(e=>e!==`BOOTSTRAP.md`).map(e=>R.join(t,e)),R.join(t,`MEMORY.md`)]}function Dc(e){return R.join(H(e),`.bootstrapped`)}async function Oc(e){try{return(await L.stat(Dc(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function kc(e){let t=Dc(e);await L.mkdir(R.dirname(t),{recursive:!0}),await L.writeFile(t,``,{encoding:`utf-8`})}async function Ac(e){let t=[],n=[];for(let n of Tc(e))try{(await L.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Ec(e))try{(await L.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 jc(e){return(await Ac(e)).ready}async function Mc(e){if(await Oc(e))return{ready:!0,performedBootstrap:!1};if((await Ac(e)).ready)return await kc(e),{ready:!0,performedBootstrap:!1};let t=await Nc(e);return await kc(e),{ready:!0,performedBootstrap:!0,result:t}}async function Nc(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=H(e),r=R.join(e,`workspace`),i=R.join(n,`skills`),a=R.join(n,`sessions`),o=R.join(n,`memory`);await Cc(e,t),await Cc(n,t),await Cc(i,t),await Cc(a,t),await Cc(o,t),await Cc(r,t);for(let e of Sc){let r=xc[e]??``;await wc(R.join(n,e),r,t)}return await wc(R.join(n,`MEMORY.md`),``,t),t}async function Pc(e){let t=R.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await L.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 Fc(e,t){let n=R.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 L.mkdir(R.dirname(n),{recursive:!0}),await L.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Ic(e,t){let n=await Pc(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 Lc(e,t=7){let n=await Pc(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 Fc(e,n),i}async function Rc(e,t,n,r){let i=await Qs(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?_e(i.request)?(await tc(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 zc(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await nc(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 Rc(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await tc(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 Bc={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 Vc(e){return e.action===`timeout`?Bc.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Bc.approval.summary.approved:Bc.approval.summary.denied}function Hc(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Vc(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Uc(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 Wc(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 Gc(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
380
380
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
381
381
  `)):(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(`
382
- `))}export{qe as BOOTSTRAP_FILE_NAMES,Ge as BOOTSTRAP_MAX_CHARS,Ke as BOOTSTRAP_TOTAL_MAX_CHARS,p as DEFAULT_SESSION_STORE_NAME,zc as HITL_MESSAGES,Dr as HitlPauseSignal,pt as MAX_CHILDREN_PER_SESSION,ft as MAX_SUBAGENT_DEPTH,E as MemoryIndexManager,Ds as PLUGIN_MANIFEST_FILENAME,Os as PLUGIN_MANIFEST_FILENAMES,to as PluginHookRegistry,Ja as PluginToolRegistry,mt as SubagentRegistry,ha as UiToolPauseSignal,pe as addAgent,le as addBinding,H as aimaxDir,x as appendCronExecutionRecord,Fi as appendRecentToMemory,Pi as appendToMemory,O as appendTranscriptEntry,Bc as approvalSummaryFromResolution,Mc as bootstrapMountLayout,Ze as buildBootstrapContextFiles,Wc as buildResumeNarration,dt as buildSkillsPrompt,sa as buildSubagentAnnounceMessage,Ua as buildSystemPrompt,Ic as cleanupOldSubagentRecords,nc as clearPendingHitl,cc as clearPendingUiTool,m as collapseLogPath,h as contextSnapshotPath,Ca as createAgentTools,mi as createApplyPatchTool,Zr as createBashTool,C as createBuiltinMemoryProvider,Tr as createContextManager,oi as createEditFileTool,Lr as createExecTool,ma as createImageTool,ci as createListDirTool,Ui as createMemoryAppendTool,Qi as createMemoryForgetTool,Vi as createMemoryGetTool,Xi as createMemoryListTool,Ji as createMemoryLogTool,zi as createMemorySearchTool,ea as createMemoryUpdateTool,Gi as createMemoryWriteTool,$s as createPendingHitl,oc as createPendingUiTool,Ka as createPluginProgressEmitter,Fs as createPluginRuntime,Vr as createProcessTool,ni as createReadFileTool,T as createSession,Qn as createSessionContextStore,ia as createSkillListTool,aa as createSkillLoadTool,ca as createSubagentSpawnTool,fa as createSubagentsTool,Sa as createUiTool,ii as createWriteFileTool,S as cronExecutionsPath,xa as defaultUiToolInputSchema,Li as deleteMemoryFile,Ts as discoverAIMaxPlugins,jc as ensureBootstrapMountLayout,_ as ensureSession,g as exportSession,ct as findSkillByName,Vc as formatApprovalResolution,Hc as formatClarifyResolution,Uc as formatReviewResolution,Xt as generateSessionTitle,oe as getAgentConfig,Ni as getMemoryLines,Dc as hasBootstrapSentinel,Js as hitlHistoryPath,Vs as initializePluginSystem,kc as inspectBootstrapMountLayout,u as inspectSession,Ac as isBootstrapMountLayoutReady,q as isHitlPauseSignal,ga as isUiToolPauseSignal,ee as listAgents,cn as listAvailableSlashCommands,ue as listBindings,ki as listMemoryFiles,k as listSessionSummaries,M as listSessions,Fc as listSubagentRunsFromDisk,fe as loadAgentsConfig,Je as loadBootstrapFiles,f as loadCronExecutionRecords,Zs as loadPendingHitl,Zs as readPendingHitl,ac as loadPendingUiTool,ac as readPendingUiTool,As as loadPluginManifest,js as loadPluginManifestRegistry,Rs as loadPlugins,j as loadSessionContextSnapshot,c as loadSessionMetadata,ut as loadSkillView,at as loadSkills,st as loadSkillsFromDirs,ot as loadSkillsWithPluginDirs,Nc as loadSubagentRegistryFromDisk,t as loadTranscript,Ei as memoryDir,A as metadataPath,te as normalizeAgentId,ts as normalizePluginsConfig,l as normalizeSessionStoreName,qs as pendingHitlPath,rc as pendingUiToolPath,Di as primaryMemoryPath,Qs as readHitlHistory,Ai as readMemoryFile,ji as readPrimaryMemory,v as registerEmbeddingProvider,P as registerMemoryProvider,se as removeAgent,me as removeBindings,Ii as replaceMemoryFile,d as resetEmbeddingProviderRegistryForTests,F as resetMemoryProviderRegistryForTests,ne as resolveAgentDir,re as resolveAgentIdByBinding,de as resolveAgentsConfigPath,ce as resolveDefaultAgentId,w as resolveEmbeddingProvider,Rc as resolveHitlRequest,Rc as resolvePendingHitl,N as resolveMemoryProvider,ae as resolveModelFallbacks,ie as resolveModelString,sc as resolvePendingUiTool,ks as resolvePluginManifestPath,r as rewriteTranscript,yc as runAgent,I as saveAgentsConfig,n as saveSessionMetadata,Pc as saveSubagentRegistryToDisk,Mi as searchMemory,o as sessionDir,e as sessionMemoryPath,y as sessionsDir,tt as skillsDir,i as toolResultsDir,a as transcriptPath,ec as transitionHitlStatus,he as updateAgentIdentity,s as updateSessionMetadata,ns as validatePluginsConfig,Lc as validateResume,eo as wrapToolsWithHooks};
382
+ `))}export{qe as BOOTSTRAP_FILE_NAMES,Ge as BOOTSTRAP_MAX_CHARS,Ke as BOOTSTRAP_TOTAL_MAX_CHARS,p as DEFAULT_SESSION_STORE_NAME,Bc as HITL_MESSAGES,Or as HitlPauseSignal,pt as MAX_CHILDREN_PER_SESSION,ft as MAX_SUBAGENT_DEPTH,E as MemoryIndexManager,Os as PLUGIN_MANIFEST_FILENAME,ks as PLUGIN_MANIFEST_FILENAMES,no as PluginHookRegistry,Ya as PluginToolRegistry,mt as SubagentRegistry,ga as UiToolPauseSignal,pe as addAgent,le as addBinding,H as aimaxDir,x as appendCronExecutionRecord,Ii as appendRecentToMemory,Fi as appendToMemory,O as appendTranscriptEntry,Vc as approvalSummaryFromResolution,Nc as bootstrapMountLayout,Ze as buildBootstrapContextFiles,Gc as buildResumeNarration,dt as buildSkillsPrompt,ca as buildSubagentAnnounceMessage,Wa as buildSystemPrompt,Lc as cleanupOldSubagentRecords,rc as clearPendingHitl,lc as clearPendingUiTool,m as collapseLogPath,h as contextSnapshotPath,wa as createAgentTools,hi as createApplyPatchTool,Qr as createBashTool,C as createBuiltinMemoryProvider,Er as createContextManager,si as createEditFileTool,Rr as createExecTool,ha as createImageTool,li as createListDirTool,Wi as createMemoryAppendTool,$i as createMemoryForgetTool,Hi as createMemoryGetTool,Zi as createMemoryListTool,Yi as createMemoryLogTool,Bi as createMemorySearchTool,ta as createMemoryUpdateTool,Ki as createMemoryWriteTool,ec as createPendingHitl,sc as createPendingUiTool,qa as createPluginProgressEmitter,Is as createPluginRuntime,Hr as createProcessTool,ri as createReadFileTool,T as createSession,$n as createSessionContextStore,aa as createSkillListTool,oa as createSkillLoadTool,la as createSubagentSpawnTool,pa as createSubagentsTool,Ca as createUiTool,ai as createWriteFileTool,S as cronExecutionsPath,Sa as defaultUiToolInputSchema,Ri as deleteMemoryFile,Es as discoverAIMaxPlugins,Mc as ensureBootstrapMountLayout,_ as ensureSession,g as exportSession,ct as findSkillByName,Hc as formatApprovalResolution,Uc as formatClarifyResolution,Wc as formatReviewResolution,Xt as generateSessionTitle,oe as getAgentConfig,Pi as getMemoryLines,Oc as hasBootstrapSentinel,Ys as hitlHistoryPath,Hs as initializePluginSystem,Ac as inspectBootstrapMountLayout,u as inspectSession,jc as isBootstrapMountLayoutReady,q as isHitlPauseSignal,_a as isUiToolPauseSignal,ee as listAgents,cn as listAvailableSlashCommands,ue as listBindings,Ai as listMemoryFiles,k as listSessionSummaries,M as listSessions,Ic as listSubagentRunsFromDisk,fe as loadAgentsConfig,Je as loadBootstrapFiles,f as loadCronExecutionRecords,Qs as loadPendingHitl,Qs as readPendingHitl,oc as loadPendingUiTool,oc as readPendingUiTool,js as loadPluginManifest,Ms as loadPluginManifestRegistry,zs as loadPlugins,j as loadSessionContextSnapshot,c as loadSessionMetadata,ut as loadSkillView,at as loadSkills,st as loadSkillsFromDirs,ot as loadSkillsWithPluginDirs,Pc as loadSubagentRegistryFromDisk,t as loadTranscript,Di as memoryDir,A as metadataPath,te as normalizeAgentId,ns as normalizePluginsConfig,l as normalizeSessionStoreName,Js as pendingHitlPath,ic as pendingUiToolPath,Oi as primaryMemoryPath,$s as readHitlHistory,ji as readMemoryFile,Mi as readPrimaryMemory,v as registerEmbeddingProvider,P as registerMemoryProvider,se as removeAgent,me as removeBindings,Li as replaceMemoryFile,d as resetEmbeddingProviderRegistryForTests,F as resetMemoryProviderRegistryForTests,ne as resolveAgentDir,re as resolveAgentIdByBinding,de as resolveAgentsConfigPath,ce as resolveDefaultAgentId,w as resolveEmbeddingProvider,zc as resolveHitlRequest,zc as resolvePendingHitl,N as resolveMemoryProvider,ae as resolveModelFallbacks,ie as resolveModelString,cc as resolvePendingUiTool,As as resolvePluginManifestPath,r as rewriteTranscript,bc as runAgent,I as saveAgentsConfig,n as saveSessionMetadata,Fc as saveSubagentRegistryToDisk,Ni as searchMemory,o as sessionDir,e as sessionMemoryPath,y as sessionsDir,tt as skillsDir,i as toolResultsDir,a as transcriptPath,tc as transitionHitlStatus,he as updateAgentIdentity,s as updateSessionMetadata,rs as validatePluginsConfig,Rc as validateResume,to as wrapToolsWithHooks};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",