@gencode/agents 0.9.0 → 0.9.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,5 +1,11 @@
1
1
  # @gencode/agents
2
2
 
3
+ ## 0.9.1
4
+
5
+ ### Patch Changes
6
+
7
+ - f7a9b2f: 修复使用 `apiFormat: "anthropic-messages"` 连接第三方 Anthropic 兼容 API 网关时,因 SSE 事件顺序不严格(缺少 `message_start` 或 `message_delta` 先于 `message_start` 到达)导致请求失败并报 `Unexpected event order, got message_delta before "message_start"` 的问题。修复后系统会自动修正事件流顺序,无需调整 API 网关配置。
8
+
3
9
  ## 0.9.0
4
10
 
5
11
  ### Minor Changes
package/dist/index.js CHANGED
@@ -128,13 +128,20 @@ Preview:
128
128
  `)}function th(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(`
129
129
  `):``}function nh(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Pm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,eh(e.subagentDepth??0),Im({toolNames:i,toolSummaries:e.toolSummaries}),Bm(n),Lm(),Rm(),si(e.availableAgents??[]),Vm(a),Hm(e.autoSkillCategories),Um(),Wm(),Gm(e.memoryCitationsMode??`off`),Km({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),qm(e.sandboxInfo),Jm({currentDate:e.currentDate,timezone:e.timezone}),zm(),Xm({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Qm({isMinimal:n}),Zm(e.runtimeInfo),$m({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),th(e.priorConversationSummary)].filter(Boolean).join(`
130
130
  `)}const rh=Symbol(`pluginToolOwner`);var ih=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,rh,{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=Am({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,rh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function ah(e){return e[rh]}function oh(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=ah(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await hi({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(Ai(e))return Ii(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(Ai(i)){Ii(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}}}})}const sh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function ch(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function lh(e){let t=ch(e?.warningThreshold,sh.warningThreshold),n=ch(e?.criticalThreshold,sh.criticalThreshold),r=ch(e?.globalCircuitBreakerThreshold,sh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??sh.enabled,historySize:ch(e?.historySize,sh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??sh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??sh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??sh.detectors.pingPong}}}function uh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function dh(e,t){return`${e}:${mh(t)}`}function fh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(fh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${fh(t[e])}`).join(`,`)}}`}function ph(e){try{return fh(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 mh(e){let t=ph(e);return Je(`sha256`).update(t).digest(`hex`)}function hh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!uh(t))return!1;let n=t.action;return n===`poll`||n===`log`}function gh(e){return!uh(e)||!Array.isArray(e.content)?``:e.content.filter(e=>uh(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
131
- `).trim()}function _h(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:fh(e)}function vh(e,t,n,r){if(r!==void 0)return`error:${mh(_h(r))}`;if(!uh(n))return n===void 0?void 0:mh(n);let i=uh(n.details)?n.details:{},a=gh(n);if(hh(e,t)&&e===`process`&&uh(t)){let e=t.action;if(e===`poll`)return mh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return mh({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 mh({details:i,text:a})}function yh(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 bh(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 xh(e,t){return[e,t].toSorted().join(`|`)}function Sh(e,t,n,r){let i=lh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=dh(t,n),s=yh(a,t,o),c=s.count,l=hh(t,n),u=bh(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:${xh(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 Ch(e,t,n,r,i){let a=lh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:dh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function wh(e,t){let n=lh(t.config),r=vh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=dh(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 Th(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 Eh(e){return e&&e.trim()||`tool`}function Dh(e,t,n){if(!e.execute)return e;let r=Eh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Sh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Th(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Ch(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return wh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw wh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Oh(e,t,n){return e.map(e=>Dh(e,t,n))}function kh(e){let t=e.streamFn??at;return(e,n,r)=>(e.api===`anthropic-messages`&&Ah(e),t(e,n,{...r,...Fh(e,r)}))}function Ah(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>jh(Ph(e),n)?(globalThis.fetch=t,t(e,Mh(e,r))):t(e,r))}function jh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Mh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Nh(e)&&n.delete(e);return{...t,headers:n}}function Nh(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function Ph(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Fh(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function Ih(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,autoSkillCategories:u,effectivePromptText:f,pluginTools:p,pluginSkillDirs:h,skillsLoadPaths:g,presetSystemPrompt:_},dependencies:{registry:v,spawnFn:y,createModel:b,abortSignal:x}}=e,S=t.autoSkills?.load?.enabled===!0,C=t.agentPolicy?.activeAgent,w=t.channel===`CRON`,T=w?[]:await m(t.dataDir,n,Q(t)),E={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},D=await tf({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=w?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await nf({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:x,hooks:r,hookCtx:i,contextManager:D,dataDir:t.dataDir,sessionId:n});await zh({sessionId:n,historyResult:O,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let k=t.subagentContext?.depth??0,ee=d(t.dataDir,n,Q(t)),A=oi([...jm(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:ee,registry:v,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:g,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await o.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:o,spawnFn:y}),...p],C),j=A.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),M={};for(let e of A){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||M[t]||(M[t]=n)}let te=t.messaging?.enabled??t.channel!==`CRON`,ne=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],N=nh({dataDir:t.dataDir,projectDir:t.projectDir,skills:ai(l,C),autoSkillCategories:S?u:[],contextFiles:s,toolNames:j,toolSummaries:M,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:te,channels:ne},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:ht.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});N=await Lh({systemPrompt:N,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let P=await r.dispatch(`before_prompt_build`,{prompt:f},i,{eventDispatcher:o});for(let e of P)e&&(e.systemPrompt&&(N=e.systemPrompt),e.prependContext&&(N=`${e.prependContext}\n\n${N}`));await r.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:N},i,{eventDispatcher:o});let F=Oh(oh(A,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},_c),I=C?.model??t.llm.model,L=await r.dispatch(`before_model_resolve`,{prompt:f},i,{eventDispatcher:o});for(let e of L)e&&e.modelOverride&&(I=e.modelOverride);let R=b({...t.llm,model:I},n,t.messageId,t.channel),z=new Ze({initialState:{systemPrompt:N,model:R,tools:F,messages:[]},getApiKey:e=>t.llm.apiKey,streamFn:kh({})});return O.messages.length>0&&z.replaceMessages(O.messages),{agent:z,resolvedModelId:I,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:a.workspaceDir}}async function Lh(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 ${A(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 Rh(e){let{session:t,runtime:n,effectivePromptText:r,dependencies:i}=e,{runParams:a,sessionId:o,hookRegistry:s,hookContext:c,runContext:l,eventDispatcher:u}=t,{abortSignal:d}=i;if(a.channel===`CRON`)return{status:`skipped`,reason:`CRON runs do not persist transcript history.`};let f=await ml({entries:await m(a.dataDir,o,Q(a)),contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.flashModel??a.llm.model},instructions:wa,signal:d,hooks:s,hookCtx:c});if(f.status!==`compacted`)return{status:`skipped`,reason:f.reason};await zh({sessionId:o,historyResult:{messages:[],priorSummary:void 0,compactionEntry:f.entry,stats:{originalCount:f.keptCount+f.droppedCount,keptCount:f.keptCount,estimatedTokens:f.estimatedTokens,compacted:!0},compactionEvents:[{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`,estimatedTokensFreed:Math.max(0,f.droppedCount),affectedEntries:f.droppedCount,snapshotVersion:2}]},runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),await u.dispatchProgress(o,{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`});let p={model:a.llm.model,api:a.llm.apiFormat??`openai-completions`},h=await nf({entries:await m(a.dataDir,o,Q(a)),modelInfo:p,contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.model,flashModel:a.llm.flashModel},historyLimit:a.historyLimit,topicSegmentation:a.topicSegmentation,channel:a.channel,isSubagent:!!a.subagentContext,compactionEnabled:!0,pendingUserMessage:r,signal:d,hooks:s,hookCtx:c,contextManager:n.contextManager,dataDir:a.dataDir,sessionId:o});return await zh({sessionId:o,historyResult:h,runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),n.historyResult=h,n.historyMessages=h.messages,n.agent.replaceMessages(h.messages),{status:`compacted`}}async function zh(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=Bh(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 Bh(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(`
131
+ `).trim()}function _h(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:fh(e)}function vh(e,t,n,r){if(r!==void 0)return`error:${mh(_h(r))}`;if(!uh(n))return n===void 0?void 0:mh(n);let i=uh(n.details)?n.details:{},a=gh(n);if(hh(e,t)&&e===`process`&&uh(t)){let e=t.action;if(e===`poll`)return mh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return mh({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 mh({details:i,text:a})}function yh(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 bh(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 xh(e,t){return[e,t].toSorted().join(`|`)}function Sh(e,t,n,r){let i=lh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=dh(t,n),s=yh(a,t,o),c=s.count,l=hh(t,n),u=bh(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:${xh(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 Ch(e,t,n,r,i){let a=lh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:dh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function wh(e,t){let n=lh(t.config),r=vh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=dh(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 Th(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 Eh(e){return e&&e.trim()||`tool`}function Dh(e,t,n){if(!e.execute)return e;let r=Eh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Sh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Th(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Ch(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return wh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw wh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Oh(e,t,n){return e.map(e=>Dh(e,t,n))}function kh(e){let t=e.streamFn??at;return(e,n,r)=>(e.api===`anthropic-messages`&&Ah(e),t(e,n,{...r,...Lh(e,r)}))}function Ah(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Nh(Ih(e),n)?(globalThis.fetch=t,jh(await t(e,Ph(e,r)))):t(e,r))}function jh(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
132
132
 
133
- `):void 0}}async function Vh(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!c?.aborted&&n.needsAnnounce(r)&&d<10;){d++,X.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){X.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}X.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:d,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=Hh(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Ka({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),n.markAnnounced(e.map(e=>e.runId));let v={sessionId:r,announceRound:d,completedCount:e.length,inputTokens:_.inputTokens,outputTokens:_.outputTokens,hasError:!!_.error,error:_.error,responseTextLength:_.text.length};_.error?X.warn(`subagent announce round completed with error`,v):X.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&X.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function Hh(e){if(e.length===1){let t=e[0];return vm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>vm({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
133
+ `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Mh))),a.enqueue(r.encode(e+`
134
+
135
+ `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Mh=`event: message_start
136
+ data: {"type":"message_start","message":{"id":"","type":"message","role":"assistant","content":[],"model":"","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}
137
+
138
+ `;function Nh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Ph(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Fh(e)&&n.delete(e);return{...t,headers:n}}function Fh(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function Ih(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Lh(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function Rh(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,autoSkillCategories:u,effectivePromptText:f,pluginTools:p,pluginSkillDirs:h,skillsLoadPaths:g,presetSystemPrompt:_},dependencies:{registry:v,spawnFn:y,createModel:b,abortSignal:x}}=e,S=t.autoSkills?.load?.enabled===!0,C=t.agentPolicy?.activeAgent,w=t.channel===`CRON`,T=w?[]:await m(t.dataDir,n,Q(t)),E={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},D=await tf({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=w?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await nf({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:x,hooks:r,hookCtx:i,contextManager:D,dataDir:t.dataDir,sessionId:n});await Vh({sessionId:n,historyResult:O,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let k=t.subagentContext?.depth??0,ee=d(t.dataDir,n,Q(t)),A=oi([...jm(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:ee,registry:v,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:g,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await o.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:o,spawnFn:y}),...p],C),j=A.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),M={};for(let e of A){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||M[t]||(M[t]=n)}let te=t.messaging?.enabled??t.channel!==`CRON`,ne=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],N=nh({dataDir:t.dataDir,projectDir:t.projectDir,skills:ai(l,C),autoSkillCategories:S?u:[],contextFiles:s,toolNames:j,toolSummaries:M,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:te,channels:ne},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:ht.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});N=await zh({systemPrompt:N,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let P=await r.dispatch(`before_prompt_build`,{prompt:f},i,{eventDispatcher:o});for(let e of P)e&&(e.systemPrompt&&(N=e.systemPrompt),e.prependContext&&(N=`${e.prependContext}\n\n${N}`));await r.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:N},i,{eventDispatcher:o});let F=Oh(oh(A,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},_c),I=C?.model??t.llm.model,L=await r.dispatch(`before_model_resolve`,{prompt:f},i,{eventDispatcher:o});for(let e of L)e&&e.modelOverride&&(I=e.modelOverride);let R=b({...t.llm,model:I},n,t.messageId,t.channel),z=new Ze({initialState:{systemPrompt:N,model:R,tools:F,messages:[]},getApiKey:e=>t.llm.apiKey,streamFn:kh({})});return O.messages.length>0&&z.replaceMessages(O.messages),{agent:z,resolvedModelId:I,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:a.workspaceDir}}async function zh(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 ${A(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 Bh(e){let{session:t,runtime:n,effectivePromptText:r,dependencies:i}=e,{runParams:a,sessionId:o,hookRegistry:s,hookContext:c,runContext:l,eventDispatcher:u}=t,{abortSignal:d}=i;if(a.channel===`CRON`)return{status:`skipped`,reason:`CRON runs do not persist transcript history.`};let f=await ml({entries:await m(a.dataDir,o,Q(a)),contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.flashModel??a.llm.model},instructions:wa,signal:d,hooks:s,hookCtx:c});if(f.status!==`compacted`)return{status:`skipped`,reason:f.reason};await Vh({sessionId:o,historyResult:{messages:[],priorSummary:void 0,compactionEntry:f.entry,stats:{originalCount:f.keptCount+f.droppedCount,keptCount:f.keptCount,estimatedTokens:f.estimatedTokens,compacted:!0},compactionEvents:[{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`,estimatedTokensFreed:Math.max(0,f.droppedCount),affectedEntries:f.droppedCount,snapshotVersion:2}]},runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),await u.dispatchProgress(o,{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`});let p={model:a.llm.model,api:a.llm.apiFormat??`openai-completions`},h=await nf({entries:await m(a.dataDir,o,Q(a)),modelInfo:p,contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.model,flashModel:a.llm.flashModel},historyLimit:a.historyLimit,topicSegmentation:a.topicSegmentation,channel:a.channel,isSubagent:!!a.subagentContext,compactionEnabled:!0,pendingUserMessage:r,signal:d,hooks:s,hookCtx:c,contextManager:n.contextManager,dataDir:a.dataDir,sessionId:o});return await Vh({sessionId:o,historyResult:h,runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),n.historyResult=h,n.historyMessages=h.messages,n.agent.replaceMessages(h.messages),{status:`compacted`}}async function Vh(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=Hh(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 Hh(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(`
139
+
140
+ `):void 0}}async function Uh(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!c?.aborted&&n.needsAnnounce(r)&&d<10;){d++,X.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){X.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}X.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:d,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=Wh(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Ka({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),n.markAnnounced(e.map(e=>e.runId));let v={sessionId:r,announceRound:d,completedCount:e.length,inputTokens:_.inputTokens,outputTokens:_.outputTokens,hasError:!!_.error,error:_.error,responseTextLength:_.text.length};_.error?X.warn(`subagent announce round completed with error`,v):X.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&X.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function Wh(e){if(e.length===1){let t=e[0];return vm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>vm({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
134
141
 
135
142
  ---
136
143
 
137
- `)}`}function Uh(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function Wh(e){let t=Uh(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=G.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Gh(e){let t=e.watchFactory??((e,t,n)=>q.watch(e,t,n)),n=G.join(e.dataDir,`.aimax`),r=[{target:G.join(n,`MEMORY.md`),kind:`memory-file`},{target:G.join(n,`memory.md`),kind:`memory-file-lower`},{target:G.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=Wh({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 Kh(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=G.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Yh(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:h?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=G.join(t.dataDir,`.aimax`),h=de({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??se({dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),_=h?.registration.id??g.id,v=h?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:h?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!h}}).catch(()=>{});let y=Gh({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await p(t.dataDir,i,e,Jh({sessionOptions:Q(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function qh(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Jh(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function Yh(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 Xh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zh(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Qh(){let e=ht.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function $h(e){let t=e.trim(),n=Qh();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?G.join(n,t.slice(2)):void 0:G.resolve(t)}const eg=new yt({allErrors:!0,strict:!1}),tg=new Map;function ng(e,t){let n=tg.get(t);if(n)return n;let r=eg.compile(e);return tg.set(t,r),r}function rg(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ng(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function ig(e){let t=Zh(e?.allow),n=Zh(e?.deny),r=Zh(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 ag(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=rg({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 og(e){try{return q.realpathSync(e)}catch{return null}}function sg(e){try{return q.statSync(e)}catch{return null}}function cg(e,t){let n=G.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!G.isAbsolute(n)}function lg(e){return`0o${e.toString(8).padStart(3,`0`)}`}const ug=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),dg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function fg(e){let t=G.join(e,`package.json`);if(q.existsSync(t))try{let e=JSON.parse(q.readFileSync(t,`utf-8`));return Xh(e)?e:void 0}catch{return}}function pg(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 mg(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function hg(e){let t=og(e.source),n=og(e.rootDir);return!t||!n||cg(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function gg(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=G.resolve(r);if(n.has(t))continue;n.add(t);let i=sg(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 _g(e){return hg({source:e.source,rootDir:e.rootDir})||gg({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:mg(e.ownershipUid)})}function vg(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=${lg(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function yg(e){let t=_g({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:vg(t),source:e.source}),!0):!1}function bg(e){return G.basename(e,G.extname(e))}function xg(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 Sg(e){for(let t of dg){let n=G.join(e,t);if(q.existsSync(n))return n}return null}function Cg(e){let t;try{t=q.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=G.join(e.rootDir,n.name);if(n.isFile()){if(!ug.has(G.extname(n.name)))continue;let r=G.dirname(t);if(yg({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(xg({idHint:bg(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=fg(t),i=pg(r);if(i.status===`ok`){for(let n of i.entries){let i=G.resolve(t,n);if(!cg(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!q.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!ug.has(G.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(yg({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${bg(i)}`:bg(i);e.candidates.push(xg({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=Sg(t);a&&(yg({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(xg({idHint:G.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function wg(e){return e?e.map($h).filter(e=>typeof e==`string`&&e.length>0):[]}function Tg(){let e=Qh();if(e)return G.join(e,`.aimax`,`extensions`)}function Eg(e){return G.join(e,`.aimax`,`extensions`)}function Dg(e){return G.join(e,`.aimax`,`extensions`)}function Og(e={}){let t=[],n=[],r=wg(e.extraPaths);for(let i of r){if(!q.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=sg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!ug.has(G.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=G.dirname(i);if(yg({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(xg({idHint:bg(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Cg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Cg({rootDir:Eg(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Cg({rootDir:Dg(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Tg();return i?Cg({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&&Cg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function kg(e){let t=e.rejectHardlinks??!0,n=og(e.rootPath),r=og(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!cg(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=q.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:q.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ag=`aimax.plugin.json`,jg=[Ag];function Mg(e){for(let t of jg){let n=G.join(e,t);if(q.existsSync(n))return n}return G.join(e,Ag)}function Ng(e,t=!0){let n=Mg(e),r=kg({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(q.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{q.closeSync(r.fd)}if(!Xh(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=Xh(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=Zh(i.skills),f;return Xh(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 Pg(e){let t=new Map,n=[];for(let r of e){let e=Ng(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 Fg=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Ig(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Fg.ERROR){X.error(i);return}if(e===Fg.WARN){X.warn(i);return}X.info(i)}function Lg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Ig(Fg.INFO,e.pluginId,t,n),warn:n=>Ig(Fg.WARN,e.pluginId,t,n),error:n=>Ig(Fg.ERROR,e.pluginId,t,n)})}}}function Rg(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 zg(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 Bg(e){let t=[...e.registry.diagnostics],n=new ih,r=new _i,i=[],a=[],o=e.runtime?.llm?yi({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Vg(e.runtime?.llmAllowlist),c=bt(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Rg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=zg({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=Lg({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(!Hg(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`);ae({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`);fe({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=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>gi(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=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Vg(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Hg(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Ug(e={}){let t=ig(e.config),n=Og({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Pg(n.candidates),i=ag({config:t,registry:r}),a=Bg({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 Wg(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Ug({...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 _i,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 Gg(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=G.join(t.dataDir,`workspace`),o=n,s=!o,c=Q(t);o?(await r(t.dataDir,o,c)||(s=!0),await g(t.dataDir,o,c)):o=await C(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel},u=Wg({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Kh({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:i,hookRegistry:d});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:d,pluginContext:u,runContext:f,start:e=>Tc({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function Kg(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function qg(e){if(!(e instanceof Error))return{errorValue:Kg(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]=Kg(n[e]));return t}async function Jg(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...qg(e.error)}})}function Yg(e,t,n){return G.join(d(e,t,n),`pending-ui-tool.json`)}async function Xg(e,t,n,r){let i=d(e,t,r);await W.mkdir(i,{recursive:!0}),await a(Yg(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function Zg(e,t,n){let r=await l(Yg(e,t,n));return r===null?null:JSON.parse(r)}async function Qg(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Xg(e,t,a,r),a}async function $g(e,t,n,r,i){let a=await Zg(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 Xg(e,t,o,i),o}async function e_(e,t,n){try{await W.unlink(Yg(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const t_=`crons`;function n_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:Ga(e.message)}}function r_(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ue(t))}async function i_(e,t,n,r){let i=await z(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function a_(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await i_(e,t,n,a);let s=await Kt(e,t,n,r,a);return s.goal&&await un(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}async function o_(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=Pi();if(i=await Fi(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Ai(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=s_(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 s_(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 c_(e,t){Wa(e.dataDir),bc();let n=Date.now(),r=new vi(e),i=Sl(e);X.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await Gg({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,h=c.pluginContext,g=c.runContext,_=(await m(e.dataDir,l,{storeName:e.sessionStoreName})).length;X.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),X.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await M(e.dataDir,qh({sessionId:l,title:wc(a),channel:e.channel}),Q(e)),e.pendingGoal&&await L(e.dataDir,l,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await g.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await Tt(e.dataDir),b=[],x=Ot(y,{warn:e=>b.push(e)}),S=await jt();await r.dispatchDiagnostic(l,{level:b.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length}}),X.info(`bootstrap context loaded`,{sessionId:l,bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length});let C=e.skillsLoadPaths??[],w=await zt(e.dataDir,h.pluginSkillDirs,C),T=await $r({dataDir:e.dataDir,projectDir:e.projectDir,systemAgentsDir:e.systemAgentsDir,agentPolicy:e.agentPolicy}),E=T.stats(),D=e.agentPolicy?.activeAgent??T.findPublic(e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!D)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let O={...T,...D?{activeAgent:D}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},k={...e,agentPolicy:O};await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length,skills:w.map(e=>({name:e.name,description:e.description,location:e.location}))}}),X.info(`skills loaded`,{sessionId:l,skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,agents:T.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),X.info(`custom agents loaded`,{sessionId:l,agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,requestedAgentName:O.requestedAgentName});let ee=await l_({dataDir:e.dataDir,sessionId:l,eventDispatcher:r,enabled:e.autoSkills?.load?.enabled===!0}),A=e=>g.appendTranscriptEntry(e),j=await wl({invocation:i,skills:w,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(j.kind===`completed`)return X.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!j.result.error,paused:!!j.result.paused,uiToolPending:!!j.result.uiToolPending,textLength:j.result.text.length}),j.result;let te=j.effectivePrompt;a=j.transcriptMessage;let ne=typeof te==`string`?te:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof te==`string`?`string`:`messages`,transcriptLength:a.length}}),X.info(`invocation resolved`,{sessionId:l,promptType:typeof te==`string`?`string`:`messages`,transcriptLength:a.length});let N=await Ih({session:{runParams:k,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},runtimeInputs:{contextFiles:x,bootstrapWarnings:b,skills:w,autoSkillCategories:ee,effectivePromptText:ne,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:C,presetSystemPrompt:S.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>c_(e,new hc),createModel:Kr,abortSignal:v.signal}}),P=N.agent,F=N.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:F,historyMessageCount:N.historyMessages.length,pluginToolCount:h.pluginTools.length}}),X.info(`agent runtime created`,{sessionId:l,modelId:F,historyMessageCount:N.historyMessages.length,pluginToolCount:h.pluginTools.length}),v.signal.addEventListener(`abort`,()=>P.abort());let I=0,R=0,z=``,B,V=!1,H=new Gt;await i_(e.dataDir,l,H,{storeName:e.sessionStoreName});let re=()=>({input:I,output:R,total:I+R}),ie=new Ta,ae={runParams:k,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},oe={registry:t,spawnFn:e=>c_(e,new hc),createModel:Kr,abortSignal:v.signal},se=(e,t,n)=>({turnKind:e,budget:ie,reloadHistory:()=>Rh({session:ae,runtime:n,effectivePromptText:t,dependencies:oe}),onPhase:async(e,t)=>{await r.dispatchDiagnostic(l,{level:e.includes(`failed`)||e.includes(`skipped`)?`warn`:`info`,scope:`runner`,phase:e,message:e.replace(/_/g,` `),details:t})}});try{if(r_(e)){let t=await o_({params:e,agent:P,sessionId:l,eventDispatcher:r,appendEntry:A,abortSignal:v.signal});return z=t.text,Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);V=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await sn(e.dataDir,l,te,{storeName:e.sessionStoreName});X.info(`first agent turn started`,{sessionId:l,modelId:F});let s=typeof i.prompt==`string`?i.prompt:ne,c=await Ka({agent:P,message:i.prompt,continueFromHistory:!!e.uiToolResume,sessionId:l,channel:e.channel,modelId:F,historyMessages:N.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,retry:e.llmRetry,contextLimitRecovery:se(`first`,s,N),onTurnRecordProduced:async(e,t)=>{e&&await A(e);for(let e of t)await A(e)}});z=c.text,I+=c.inputTokens,R+=c.outputTokens,c.error&&(B=c.error);let d=!!c.contextLimitRecoverySucceeded;i.hadObjectiveUpdatedSteering&&!c.error&&await cn(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let m={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?X.warn(`first agent turn completed with error`,m):X.info(`first agent turn completed`,m);let h=await a_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`});h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),X.info(`announce loop started`,{sessionId:l});let _=await Vh({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:A});if(_.text&&(z=_.text),I+=_.inputTokens,R+=_.outputTokens,_.error&&!B&&(B=_.error),await r.dispatchDiagnostic(l,{level:_.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens}}),h=await a_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),tn()){let n=new en;n.reset(),c.error&&!d&&(n.lastTurnHadOutput=!1);let i=!0,a=Be;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await an({agent:P,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:H,abortSignal:v.signal,executeTurn:async t=>{let n=await Ka({agent:P,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:F,historyMessages:N.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,contextLimitRecovery:se(`continuation`,t,N),onTurnRecordProduced:async(e,t)=>{await on(A,e,t)}});I+=n.inputTokens,R+=n.outputTokens,z=n.text||z,n.error&&!B&&(B=n.error);let i=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:i}},flushAccountingAfterTurn:async()=>{(await a_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),i){let e=await Vh({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:A});I+=e.inputTokens,R+=e.outputTokens,e.text&&(z=e.text),e.error&&!B&&(B=e.error)}}let y={sessionId:l,hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens};_.error?X.warn(`announce loop completed with error`,y):X.info(`announce loop completed`,y)}catch(t){if(Ai(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await _e(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),X.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:I,output:R,total:I+R};return await u_({runtime:N,resolvedModelId:F,usage:c,currentUserEntryCoveredByUsage:V}),Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Mi(t)){let i=t,o=i.request.outputSchema.properties??{};await Qg(e.dataDir,l,i.request,Q(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),X.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={input:I,output:R,total:I+R};return await u_({runtime:N,resolvedModelId:F,usage:s,currentUserEntryCoveredByUsage:V}),Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}throw await Jg({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),X.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{try{await a_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}H.clearActiveGoal(),vc(l),g.stop()}let U={input:I,output:R,total:I+R};await r.dispatchDiagnostic(l,{level:B?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:U.input,outputTokens:U.output,totalTokens:U.total,hasError:!!B,error:B}});let ce={sessionId:l,durationMs:Date.now()-n,inputTokens:U.input,outputTokens:U.output,totalTokens:U.total,hasError:!!B,error:B};return B?X.warn(`agent run completed with error`,ce):X.info(`agent run completed`,ce),await u_({runtime:N,resolvedModelId:F,usage:U,currentUserEntryCoveredByUsage:V}),await Js({sessionId:l,runParams:k,eventDispatcher:r,transcriptStartIndex:_,result:{text:z,usage:U,durationMs:Date.now()-n,error:B}}),Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z,usage:U,error:B})}async function l_(e){if(!e.enabled)return[];try{let t=await new fr({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}async function u_(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 d_(e){Wa(e.dataDir);let n=Date.now(),i=new vi(e),a=Sl(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;X.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...n_(e)});let c=a.requestedSessionId,l=!c;c?(await r(e.dataDir,c,{storeName:s})||(l=!0),await g(e.dataDir,c,{storeName:s})):c=await C(e.dataDir,e.channel,{storeName:s}),l&&await M(e.dataDir,qh({sessionId:c,title:wc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:t_});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),X.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:Ga(o)});let d={...e,sessionId:u,sessionStoreName:t_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await c_(d,new hc),f.error&&(m=`error`)}catch(t){let r=t instanceof Error?t.message:String(t);f={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:h(e.dataDir,u,{storeName:t_}),toolResultsDir:S(e.dataDir,u,{storeName:t_})}},m=`error`,X.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),X.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=vm({task:o,status:m,result:f.text,error:f.error}),v=new Date().toISOString();await p(e.dataDir,c,{role:`assistant`,content:_,timestamp:v,source:`cron`},{storeName:s});let y={task:o,status:m,content:_,childSessionId:u,createdAt:v};return await b(e.dataDir,c,y,{storeName:s}),await t(e.dataDir,c,e=>f_(e,8),{storeName:s}),await x(e.dataDir,c,{},{storeName:s}),{...f,sessionId:c,context:{snapshotPath:h(e.dataDir,c,{storeName:s}),toolResultsDir:S(e.dataDir,c,{storeName:s})}}}function f_(e,t){if(t<=0)return e.filter(e=>!p_(e));let n=e.reduce((e,t,n)=>(p_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!p_(e)||r.has(t))}function p_(e){return`source`in e&&e.source===`cron`}async function m_(e,t){if(Wa(e.dataDir),X.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...n_(e)}),e.channel===`CRON`&&!e.subagentContext)return d_(e);let n=t??new hc;try{return await c_(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:qg(t)}),X.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}const h_={"AGENTS.md":`---
144
+ `)}`}function Gh(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 Kh(e){let t=Gh(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=G.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function qh(e){let t=e.watchFactory??((e,t,n)=>q.watch(e,t,n)),n=G.join(e.dataDir,`.aimax`),r=[{target:G.join(n,`MEMORY.md`),kind:`memory-file`},{target:G.join(n,`memory.md`),kind:`memory-file-lower`},{target:G.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=Kh({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 Jh(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=G.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Zh(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:h?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=G.join(t.dataDir,`.aimax`),h=de({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??se({dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),_=h?.registration.id??g.id,v=h?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:h?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!h}}).catch(()=>{});let y=qh({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await p(t.dataDir,i,e,Xh({sessionOptions:Q(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function Yh(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Xh(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function Zh(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 Qh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $h(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function eg(){let e=ht.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function tg(e){let t=e.trim(),n=eg();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?G.join(n,t.slice(2)):void 0:G.resolve(t)}const ng=new yt({allErrors:!0,strict:!1}),rg=new Map;function ig(e,t){let n=rg.get(t);if(n)return n;let r=ng.compile(e);return rg.set(t,r),r}function ag(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ig(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function og(e){let t=$h(e?.allow),n=$h(e?.deny),r=$h(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 sg(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=ag({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 cg(e){try{return q.realpathSync(e)}catch{return null}}function lg(e){try{return q.statSync(e)}catch{return null}}function ug(e,t){let n=G.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!G.isAbsolute(n)}function dg(e){return`0o${e.toString(8).padStart(3,`0`)}`}const fg=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),pg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function mg(e){let t=G.join(e,`package.json`);if(q.existsSync(t))try{let e=JSON.parse(q.readFileSync(t,`utf-8`));return Qh(e)?e:void 0}catch{return}}function hg(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 gg(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function _g(e){let t=cg(e.source),n=cg(e.rootDir);return!t||!n||ug(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function vg(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=G.resolve(r);if(n.has(t))continue;n.add(t);let i=lg(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 yg(e){return _g({source:e.source,rootDir:e.rootDir})||vg({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:gg(e.ownershipUid)})}function bg(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=${dg(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function xg(e){let t=yg({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:bg(t),source:e.source}),!0):!1}function Sg(e){return G.basename(e,G.extname(e))}function Cg(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 wg(e){for(let t of pg){let n=G.join(e,t);if(q.existsSync(n))return n}return null}function Tg(e){let t;try{t=q.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=G.join(e.rootDir,n.name);if(n.isFile()){if(!fg.has(G.extname(n.name)))continue;let r=G.dirname(t);if(xg({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Cg({idHint:Sg(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=mg(t),i=hg(r);if(i.status===`ok`){for(let n of i.entries){let i=G.resolve(t,n);if(!ug(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!q.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!fg.has(G.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(xg({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Sg(i)}`:Sg(i);e.candidates.push(Cg({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=wg(t);a&&(xg({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Cg({idHint:G.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Eg(e){return e?e.map(tg).filter(e=>typeof e==`string`&&e.length>0):[]}function Dg(){let e=eg();if(e)return G.join(e,`.aimax`,`extensions`)}function Og(e){return G.join(e,`.aimax`,`extensions`)}function kg(e){return G.join(e,`.aimax`,`extensions`)}function Ag(e={}){let t=[],n=[],r=Eg(e.extraPaths);for(let i of r){if(!q.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=lg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!fg.has(G.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=G.dirname(i);if(xg({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Cg({idHint:Sg(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Tg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Tg({rootDir:Og(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Tg({rootDir:kg(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Dg();return i?Tg({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&&Tg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function jg(e){let t=e.rejectHardlinks??!0,n=cg(e.rootPath),r=cg(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!ug(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=q.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:q.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Mg=`aimax.plugin.json`,Ng=[Mg];function Pg(e){for(let t of Ng){let n=G.join(e,t);if(q.existsSync(n))return n}return G.join(e,Mg)}function Fg(e,t=!0){let n=Pg(e),r=jg({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(q.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{q.closeSync(r.fd)}if(!Qh(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=Qh(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=$h(i.skills),f;return Qh(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 Ig(e){let t=new Map,n=[];for(let r of e){let e=Fg(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 Lg=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Rg(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Lg.ERROR){X.error(i);return}if(e===Lg.WARN){X.warn(i);return}X.info(i)}function zg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Rg(Lg.INFO,e.pluginId,t,n),warn:n=>Rg(Lg.WARN,e.pluginId,t,n),error:n=>Rg(Lg.ERROR,e.pluginId,t,n)})}}}function Bg(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 Vg(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 Hg(e){let t=[...e.registry.diagnostics],n=new ih,r=new _i,i=[],a=[],o=e.runtime?.llm?yi({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Ug(e.runtime?.llmAllowlist),c=bt(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Bg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Vg({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=zg({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(!Wg(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`);ae({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`);fe({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=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>gi(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=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Ug(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Wg(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Gg(e={}){let t=og(e.config),n=Ag({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Ig(n.candidates),i=sg({config:t,registry:r}),a=Hg({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 Kg(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Gg({...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 _i,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 qg(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=G.join(t.dataDir,`workspace`),o=n,s=!o,c=Q(t);o?(await r(t.dataDir,o,c)||(s=!0),await g(t.dataDir,o,c)):o=await C(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel},u=Kg({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Jh({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:i,hookRegistry:d});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:d,pluginContext:u,runContext:f,start:e=>Tc({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function Jg(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Yg(e){if(!(e instanceof Error))return{errorValue:Jg(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]=Jg(n[e]));return t}async function Xg(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Yg(e.error)}})}function Zg(e,t,n){return G.join(d(e,t,n),`pending-ui-tool.json`)}async function Qg(e,t,n,r){let i=d(e,t,r);await W.mkdir(i,{recursive:!0}),await a(Zg(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function $g(e,t,n){let r=await l(Zg(e,t,n));return r===null?null:JSON.parse(r)}async function e_(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Qg(e,t,a,r),a}async function t_(e,t,n,r,i){let a=await $g(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 Qg(e,t,o,i),o}async function n_(e,t,n){try{await W.unlink(Zg(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const r_=`crons`;function i_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:Ga(e.message)}}function a_(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ue(t))}async function o_(e,t,n,r){let i=await z(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function s_(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await o_(e,t,n,a);let s=await Kt(e,t,n,r,a);return s.goal&&await un(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}async function c_(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=Pi();if(i=await Fi(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Ai(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=l_(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 l_(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 u_(e,t){Wa(e.dataDir),bc();let n=Date.now(),r=new vi(e),i=Sl(e);X.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await qg({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,h=c.pluginContext,g=c.runContext,_=(await m(e.dataDir,l,{storeName:e.sessionStoreName})).length;X.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),X.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await M(e.dataDir,Yh({sessionId:l,title:wc(a),channel:e.channel}),Q(e)),e.pendingGoal&&await L(e.dataDir,l,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await g.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await Tt(e.dataDir),b=[],x=Ot(y,{warn:e=>b.push(e)}),S=await jt();await r.dispatchDiagnostic(l,{level:b.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length}}),X.info(`bootstrap context loaded`,{sessionId:l,bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length});let C=e.skillsLoadPaths??[],w=await zt(e.dataDir,h.pluginSkillDirs,C),T=await $r({dataDir:e.dataDir,projectDir:e.projectDir,systemAgentsDir:e.systemAgentsDir,agentPolicy:e.agentPolicy}),E=T.stats(),D=e.agentPolicy?.activeAgent??T.findPublic(e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!D)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let O={...T,...D?{activeAgent:D}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},k={...e,agentPolicy:O};await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length,skills:w.map(e=>({name:e.name,description:e.description,location:e.location}))}}),X.info(`skills loaded`,{sessionId:l,skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,agents:T.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),X.info(`custom agents loaded`,{sessionId:l,agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,requestedAgentName:O.requestedAgentName});let ee=await d_({dataDir:e.dataDir,sessionId:l,eventDispatcher:r,enabled:e.autoSkills?.load?.enabled===!0}),A=e=>g.appendTranscriptEntry(e),j=await wl({invocation:i,skills:w,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(j.kind===`completed`)return X.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!j.result.error,paused:!!j.result.paused,uiToolPending:!!j.result.uiToolPending,textLength:j.result.text.length}),j.result;let te=j.effectivePrompt;a=j.transcriptMessage;let ne=typeof te==`string`?te:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof te==`string`?`string`:`messages`,transcriptLength:a.length}}),X.info(`invocation resolved`,{sessionId:l,promptType:typeof te==`string`?`string`:`messages`,transcriptLength:a.length});let N=await Rh({session:{runParams:k,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},runtimeInputs:{contextFiles:x,bootstrapWarnings:b,skills:w,autoSkillCategories:ee,effectivePromptText:ne,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:C,presetSystemPrompt:S.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>u_(e,new hc),createModel:Kr,abortSignal:v.signal}}),P=N.agent,F=N.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:F,historyMessageCount:N.historyMessages.length,pluginToolCount:h.pluginTools.length}}),X.info(`agent runtime created`,{sessionId:l,modelId:F,historyMessageCount:N.historyMessages.length,pluginToolCount:h.pluginTools.length}),v.signal.addEventListener(`abort`,()=>P.abort());let I=0,R=0,z=``,B,V=!1,H=new Gt;await o_(e.dataDir,l,H,{storeName:e.sessionStoreName});let re=()=>({input:I,output:R,total:I+R}),ie=new Ta,ae={runParams:k,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},oe={registry:t,spawnFn:e=>u_(e,new hc),createModel:Kr,abortSignal:v.signal},se=(e,t,n)=>({turnKind:e,budget:ie,reloadHistory:()=>Bh({session:ae,runtime:n,effectivePromptText:t,dependencies:oe}),onPhase:async(e,t)=>{await r.dispatchDiagnostic(l,{level:e.includes(`failed`)||e.includes(`skipped`)?`warn`:`info`,scope:`runner`,phase:e,message:e.replace(/_/g,` `),details:t})}});try{if(a_(e)){let t=await c_({params:e,agent:P,sessionId:l,eventDispatcher:r,appendEntry:A,abortSignal:v.signal});return z=t.text,Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);V=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await sn(e.dataDir,l,te,{storeName:e.sessionStoreName});X.info(`first agent turn started`,{sessionId:l,modelId:F});let s=typeof i.prompt==`string`?i.prompt:ne,c=await Ka({agent:P,message:i.prompt,continueFromHistory:!!e.uiToolResume,sessionId:l,channel:e.channel,modelId:F,historyMessages:N.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,retry:e.llmRetry,contextLimitRecovery:se(`first`,s,N),onTurnRecordProduced:async(e,t)=>{e&&await A(e);for(let e of t)await A(e)}});z=c.text,I+=c.inputTokens,R+=c.outputTokens,c.error&&(B=c.error);let d=!!c.contextLimitRecoverySucceeded;i.hadObjectiveUpdatedSteering&&!c.error&&await cn(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let m={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?X.warn(`first agent turn completed with error`,m):X.info(`first agent turn completed`,m);let h=await s_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`});h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),X.info(`announce loop started`,{sessionId:l});let _=await Uh({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:A});if(_.text&&(z=_.text),I+=_.inputTokens,R+=_.outputTokens,_.error&&!B&&(B=_.error),await r.dispatchDiagnostic(l,{level:_.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens}}),h=await s_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),tn()){let n=new en;n.reset(),c.error&&!d&&(n.lastTurnHadOutput=!1);let i=!0,a=Be;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await an({agent:P,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:H,abortSignal:v.signal,executeTurn:async t=>{let n=await Ka({agent:P,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:F,historyMessages:N.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,contextLimitRecovery:se(`continuation`,t,N),onTurnRecordProduced:async(e,t)=>{await on(A,e,t)}});I+=n.inputTokens,R+=n.outputTokens,z=n.text||z,n.error&&!B&&(B=n.error);let i=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:i}},flushAccountingAfterTurn:async()=>{(await s_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),i){let e=await Uh({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:A});I+=e.inputTokens,R+=e.outputTokens,e.text&&(z=e.text),e.error&&!B&&(B=e.error)}}let y={sessionId:l,hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens};_.error?X.warn(`announce loop completed with error`,y):X.info(`announce loop completed`,y)}catch(t){if(Ai(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await _e(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),X.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:I,output:R,total:I+R};return await f_({runtime:N,resolvedModelId:F,usage:c,currentUserEntryCoveredByUsage:V}),Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Mi(t)){let i=t,o=i.request.outputSchema.properties??{};await e_(e.dataDir,l,i.request,Q(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),X.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={input:I,output:R,total:I+R};return await f_({runtime:N,resolvedModelId:F,usage:s,currentUserEntryCoveredByUsage:V}),Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}throw await Xg({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),X.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{try{await s_(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}H.clearActiveGoal(),vc(l),g.stop()}let U={input:I,output:R,total:I+R};await r.dispatchDiagnostic(l,{level:B?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:U.input,outputTokens:U.output,totalTokens:U.total,hasError:!!B,error:B}});let ce={sessionId:l,durationMs:Date.now()-n,inputTokens:U.input,outputTokens:U.output,totalTokens:U.total,hasError:!!B,error:B};return B?X.warn(`agent run completed with error`,ce):X.info(`agent run completed`,ce),await f_({runtime:N,resolvedModelId:F,usage:U,currentUserEntryCoveredByUsage:V}),await Js({sessionId:l,runParams:k,eventDispatcher:r,transcriptStartIndex:_,result:{text:z,usage:U,durationMs:Date.now()-n,error:B}}),Oc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z,usage:U,error:B})}async function d_(e){if(!e.enabled)return[];try{let t=await new fr({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}async function f_(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 p_(e){Wa(e.dataDir);let n=Date.now(),i=new vi(e),a=Sl(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;X.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...i_(e)});let c=a.requestedSessionId,l=!c;c?(await r(e.dataDir,c,{storeName:s})||(l=!0),await g(e.dataDir,c,{storeName:s})):c=await C(e.dataDir,e.channel,{storeName:s}),l&&await M(e.dataDir,Yh({sessionId:c,title:wc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:r_});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),X.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:Ga(o)});let d={...e,sessionId:u,sessionStoreName:r_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await u_(d,new hc),f.error&&(m=`error`)}catch(t){let r=t instanceof Error?t.message:String(t);f={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:h(e.dataDir,u,{storeName:r_}),toolResultsDir:S(e.dataDir,u,{storeName:r_})}},m=`error`,X.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),X.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=vm({task:o,status:m,result:f.text,error:f.error}),v=new Date().toISOString();await p(e.dataDir,c,{role:`assistant`,content:_,timestamp:v,source:`cron`},{storeName:s});let y={task:o,status:m,content:_,childSessionId:u,createdAt:v};return await b(e.dataDir,c,y,{storeName:s}),await t(e.dataDir,c,e=>m_(e,8),{storeName:s}),await x(e.dataDir,c,{},{storeName:s}),{...f,sessionId:c,context:{snapshotPath:h(e.dataDir,c,{storeName:s}),toolResultsDir:S(e.dataDir,c,{storeName:s})}}}function m_(e,t){if(t<=0)return e.filter(e=>!h_(e));let n=e.reduce((e,t,n)=>(h_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!h_(e)||r.has(t))}function h_(e){return`source`in e&&e.source===`cron`}async function g_(e,t){if(Wa(e.dataDir),X.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...i_(e)}),e.channel===`CRON`&&!e.subagentContext)return p_(e);let n=t??new hc;try{return await u_(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:Yg(t)}),X.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}const __={"AGENTS.md":`---
138
145
  title: "AGENTS.md Template"
139
146
  summary: ".aimax template for AGENTS.md"
140
147
  read_when:
@@ -427,7 +434,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
427
434
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
428
435
 
429
436
  Add whatever helps you do your job. This is your cheat sheet.
430
- `},g_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function __(e,t){try{if(!(await W.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function v_(e,t,n){try{if(!(await W.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(G.dirname(e),{recursive:!0});try{await W.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function y_(e){let t=wt(e);return[e,t,G.join(t,`skills`),G.join(t,`sessions`),G.join(t,`memory`),G.join(e,`workspace`)]}function b_(e){let t=wt(e);return[...g_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>G.join(t,e)),G.join(t,`MEMORY.md`)]}function x_(e){return G.join(wt(e),`.bootstrapped`)}async function S_(e){try{return(await W.stat(x_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function C_(e){let t=x_(e);await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,``,{encoding:`utf-8`})}async function w_(e){let t=[],n=[];for(let n of y_(e))try{(await W.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of b_(e))try{(await W.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function T_(e){return(await w_(e)).ready}async function E_(e){if(await S_(e))return{ready:!0,performedBootstrap:!1};if((await w_(e)).ready)return await C_(e),{ready:!0,performedBootstrap:!1};let t=await D_(e);return await C_(e),{ready:!0,performedBootstrap:!0,result:t}}async function D_(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=wt(e),r=G.join(e,`workspace`),i=G.join(n,`skills`),a=G.join(n,`sessions`),o=G.join(n,`memory`);await __(e,t),await __(n,t),await __(i,t),await __(a,t),await __(o,t),await __(r,t);for(let e of g_){let r=h_[e]??``;await v_(G.join(n,e),r,t)}return await v_(G.join(n,`MEMORY.md`),``,t),t}async function O_(e){let t=G.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await W.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function k_(e,t){let n=G.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await W.mkdir(G.dirname(n),{recursive:!0}),await W.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function A_(e,t){let n=await O_(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 j_(e,t=7){let n=await O_(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 k_(e,n),i}var M_=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function N_(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function P_(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await z(t,n,s);if(!l)return{action:`created`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let u=(await V(t,n,l,s)).trim();if(u!==c){if(!a)throw new M_(`A different goal already exists for this session. Use --force to replace it.`,N_(u));return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})}}if(l.status===`complete`&&!a)throw new M_(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,N_(u));if(a)return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await I(t,n,d,{storeName:o,eventSource:`cli`})}}async function F_(e,t,n,r){let i=await be(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?He(i.request)?(await ge(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 I_(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ye(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 F_(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await ge(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 L_={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 R_(e){return e.action===`timeout`?L_.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?L_.approval.summary.approved:L_.approval.summary.denied}function z_(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:R_(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function B_(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 V_(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 H_(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
437
+ `},v_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function y_(e,t){try{if(!(await W.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function b_(e,t,n){try{if(!(await W.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(G.dirname(e),{recursive:!0});try{await W.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function x_(e){let t=wt(e);return[e,t,G.join(t,`skills`),G.join(t,`sessions`),G.join(t,`memory`),G.join(e,`workspace`)]}function S_(e){let t=wt(e);return[...v_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>G.join(t,e)),G.join(t,`MEMORY.md`)]}function C_(e){return G.join(wt(e),`.bootstrapped`)}async function w_(e){try{return(await W.stat(C_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function T_(e){let t=C_(e);await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,``,{encoding:`utf-8`})}async function E_(e){let t=[],n=[];for(let n of x_(e))try{(await W.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of S_(e))try{(await W.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function D_(e){return(await E_(e)).ready}async function O_(e){if(await w_(e))return{ready:!0,performedBootstrap:!1};if((await E_(e)).ready)return await T_(e),{ready:!0,performedBootstrap:!1};let t=await k_(e);return await T_(e),{ready:!0,performedBootstrap:!0,result:t}}async function k_(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=wt(e),r=G.join(e,`workspace`),i=G.join(n,`skills`),a=G.join(n,`sessions`),o=G.join(n,`memory`);await y_(e,t),await y_(n,t),await y_(i,t),await y_(a,t),await y_(o,t),await y_(r,t);for(let e of v_){let r=__[e]??``;await b_(G.join(n,e),r,t)}return await b_(G.join(n,`MEMORY.md`),``,t),t}async function A_(e){let t=G.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await W.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function j_(e,t){let n=G.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await W.mkdir(G.dirname(n),{recursive:!0}),await W.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function M_(e,t){let n=await A_(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 N_(e,t=7){let n=await A_(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 j_(e,n),i}var P_=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function F_(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function I_(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await z(t,n,s);if(!l)return{action:`created`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let u=(await V(t,n,l,s)).trim();if(u!==c){if(!a)throw new P_(`A different goal already exists for this session. Use --force to replace it.`,F_(u));return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})}}if(l.status===`complete`&&!a)throw new P_(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,F_(u));if(a)return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await I(t,n,d,{storeName:o,eventSource:`cli`})}}async function L_(e,t,n,r){let i=await be(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?He(i.request)?(await ge(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 R_(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ye(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 L_(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await ge(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 z_={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 B_(e){return e.action===`timeout`?z_.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?z_.approval.summary.approved:z_.approval.summary.denied}function V_(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:B_(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function H_(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 U_(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 W_(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
431
438
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
432
439
  `)):(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(`
433
- `))}export{fr as AutoSkillsLoader,Ct as BOOTSTRAP_FILE_NAMES,xt as BOOTSTRAP_MAX_CHARS,St as BOOTSTRAP_TOTAL_MAX_CHARS,en as ContinuationState,ee as DEFAULT_SESSION_STORE_NAME,$t as ENV_GOAL_CONTINUATION,Ac as GOAL_MULTILINE_TEMPLATE_EXAMPLE,Gt as GoalAccounting,M_ as GoalConflictError,L_ as HITL_MESSAGES,ki as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,mc as MAX_CHILDREN_PER_SESSION,pc as MAX_SUBAGENT_DEPTH,ce as MemoryIndexManager,Ag as PLUGIN_MANIFEST_FILENAME,jg as PLUGIN_MANIFEST_FILENAMES,_i as PluginHookRegistry,ih as PluginToolRegistry,qr as SYSTEM_AGENTS_DIR,hc as SubagentRegistry,ji as UiToolPauseSignal,Ie as addAgent,Me as addBinding,Yr as agentDirCandidates,ri as agentVisibility,wt as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,P as appendGoalEvent,gp as appendRecentToMemory,o as appendSessionFile,hp as appendToMemory,p as appendTranscriptEntry,P_ as applyCliGoalBeforeRun,R_ as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,qn as autoSkillsDir,D_ as bootstrapMountLayout,si as buildAgentDelegationPrompt,ci as buildAgentTaskPrompt,Mc as buildAimaxGoalCliHelpExtra,Ot as buildBootstrapContextFiles,Yt as buildBudgetLimitPrompt,Jt as buildContinuationPrompt,Zt as buildGoalContextItem,jc as buildGoalSlashHelpText,Xt as buildObjectiveUpdatedPrompt,H_ as buildResumeNarration,Wt as buildSkillsPrompt,vm as buildSubagentAnnounceMessage,nh as buildSystemPrompt,j_ as cleanupOldSubagentRecords,xe as clearPendingHitl,e_ as clearPendingUiTool,k as collapseLogPath,cn as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,rn as continuationTurnHadMeaningfulOutput,Zr as createAgentDefinitionsContext,jm as createAgentTools,Jf as createApplyPatchTool,Go as createAutoSkillCategoriesTool,Ko as createAutoSkillListTool,qo as createAutoSkillSearchTool,Jo as createAutoSkillViewTool,ur as createAutoSkillsLoader,kf as createBashTool,Sm as createBatchSubagentSpawnTool,se as createBuiltinMemoryProvider,tf as createContextManager,zf as createEditFileTool,pf as createExecTool,Om as createImageTool,Vf as createListDirTool,wp as createMemoryAppendTool,Rp as createMemoryForgetTool,Sp as createMemoryGetTool,Ip as createMemoryListTool,Pp as createMemoryLogTool,bp as createMemorySearchTool,Bp as createMemoryUpdateTool,Ep as createMemoryWriteTool,_e as createPendingHitl,Qg as createPendingUiTool,gi as createPluginProgressEmitter,Lg as createPluginRuntime,_f as createProcessTool,Ff as createReadFileTool,C as createSession,Od as createSessionContextStore,Hp as createSessionSearchTool,lm as createSkillListTool,um as createSkillLoadTool,xm as createSubagentSpawnTool,Em as createSubagentsTool,Am as createUiTool,Lf as createWriteFileTool,A as cronExecutionsPath,km as defaultUiToolInputSchema,H as deleteGoal,vp as deleteMemoryFile,Og as discoverAIMaxPlugins,ln as emitGoalUpdatedProgress,E_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,ai as filterSkillsForAgent,oi as filterToolsForAgent,ni as findAgentDefinition,Vt as findSkillByName,Kt as flushAccounting,z_ as formatApprovalResolution,B_ as formatClarifyResolution,V_ as formatReviewResolution,Sc as generateSessionTitle,ke as getAgentConfig,mp as getMemoryLines,N as goalEventsPath,R as goalObjectiveMdPath,B as goalPath,S_ as hasBootstrapSentinel,he as hitlHistoryPath,Ug as initializePluginSystem,w_ as inspectBootstrapMountLayout,D as inspectSession,T_ as isBootstrapMountLayoutReady,tn as isContinuationEnabled,Qt as isGoalContext,Ai as isHitlPauseSignal,Mi as isUiToolPauseSignal,Ce as listAgents,Uc as listAvailableSlashCommands,Ne as listBindings,up as listMemoryFiles,w as listSessionSummaries,y as listSessions,A_ as listSubagentRunsFromDisk,ei as loadAgentDefinitionsFromDir,Fe as loadAgentsConfig,v as loadArtifactOperations,Tt as loadBootstrapFiles,f as loadCronExecutionRecords,be as loadPendingHitl,be as readPendingHitl,Zg as loadPendingUiTool,Zg as readPendingUiTool,Ng as loadPluginManifest,Pg as loadPluginManifestRegistry,Bg as loadPlugins,j as loadSessionContextSnapshot,ne as loadSessionMetadata,Ut as loadSkillView,Rt as loadSkills,Bt as loadSkillsFromDirs,zt as loadSkillsWithPluginDirs,O_ as loadSubagentRegistryFromDisk,m as loadTranscript,an as maybeContinueGoalIfIdle,op as memoryDir,te as metadataPath,F as mirrorGoalStatusToSession,we as normalizeAgentId,ig as normalizePluginsConfig,u as normalizeSessionStoreName,ti as parseAgentDefinition,me as pendingHitlPath,Yg as pendingUiToolPath,sn as prependObjectiveUpdatedSteeringIfNeeded,sp as primaryMemoryPath,ii as publicAgentDefinitions,z as readGoal,ve as readHitlHistory,dp as readMemoryFile,fp as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,ae as registerEmbeddingProvider,fe as registerMemoryProvider,Ae as removeAgent,Le as removeBindings,_p as replaceMemoryFile,re as resetEmbeddingProviderRegistryForTests,pe as resetMemoryProviderRegistryForTests,$r as resolveAgentDefinitionsContext,Te as resolveAgentDir,Ee as resolveAgentIdByBinding,Pe as resolveAgentsConfigPath,je as resolveDefaultAgentId,U as resolveEmbeddingProvider,V as resolveGoalObjective,I_ as resolveHitlRequest,I_ as resolvePendingHitl,de as resolveMemoryProvider,Oe as resolveModelFallbacks,De as resolveModelString,$g as resolvePendingUiTool,Mg as resolvePluginManifestPath,t as rewriteTranscript,m_ as runAgent,Se as saveAgentsConfig,M as saveSessionMetadata,k_ as saveSubagentRegistryToDisk,Xr as scanAgentDefinitions,pp as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,nn as shouldContinueGoal,Mt as skillsDir,S as toolResultsDir,e as transcriptPath,ge as transitionHitlStatus,Re as updateAgent,ze as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,ag as validatePluginsConfig,F_ as validateResume,oh as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};
440
+ `))}export{fr as AutoSkillsLoader,Ct as BOOTSTRAP_FILE_NAMES,xt as BOOTSTRAP_MAX_CHARS,St as BOOTSTRAP_TOTAL_MAX_CHARS,en as ContinuationState,ee as DEFAULT_SESSION_STORE_NAME,$t as ENV_GOAL_CONTINUATION,Ac as GOAL_MULTILINE_TEMPLATE_EXAMPLE,Gt as GoalAccounting,P_ as GoalConflictError,z_ as HITL_MESSAGES,ki as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,mc as MAX_CHILDREN_PER_SESSION,pc as MAX_SUBAGENT_DEPTH,ce as MemoryIndexManager,Mg as PLUGIN_MANIFEST_FILENAME,Ng as PLUGIN_MANIFEST_FILENAMES,_i as PluginHookRegistry,ih as PluginToolRegistry,qr as SYSTEM_AGENTS_DIR,hc as SubagentRegistry,ji as UiToolPauseSignal,Ie as addAgent,Me as addBinding,Yr as agentDirCandidates,ri as agentVisibility,wt as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,P as appendGoalEvent,gp as appendRecentToMemory,o as appendSessionFile,hp as appendToMemory,p as appendTranscriptEntry,I_ as applyCliGoalBeforeRun,B_ as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,qn as autoSkillsDir,k_ as bootstrapMountLayout,si as buildAgentDelegationPrompt,ci as buildAgentTaskPrompt,Mc as buildAimaxGoalCliHelpExtra,Ot as buildBootstrapContextFiles,Yt as buildBudgetLimitPrompt,Jt as buildContinuationPrompt,Zt as buildGoalContextItem,jc as buildGoalSlashHelpText,Xt as buildObjectiveUpdatedPrompt,W_ as buildResumeNarration,Wt as buildSkillsPrompt,vm as buildSubagentAnnounceMessage,nh as buildSystemPrompt,N_ as cleanupOldSubagentRecords,xe as clearPendingHitl,n_ as clearPendingUiTool,k as collapseLogPath,cn as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,rn as continuationTurnHadMeaningfulOutput,Zr as createAgentDefinitionsContext,jm as createAgentTools,Jf as createApplyPatchTool,Go as createAutoSkillCategoriesTool,Ko as createAutoSkillListTool,qo as createAutoSkillSearchTool,Jo as createAutoSkillViewTool,ur as createAutoSkillsLoader,kf as createBashTool,Sm as createBatchSubagentSpawnTool,se as createBuiltinMemoryProvider,tf as createContextManager,zf as createEditFileTool,pf as createExecTool,Om as createImageTool,Vf as createListDirTool,wp as createMemoryAppendTool,Rp as createMemoryForgetTool,Sp as createMemoryGetTool,Ip as createMemoryListTool,Pp as createMemoryLogTool,bp as createMemorySearchTool,Bp as createMemoryUpdateTool,Ep as createMemoryWriteTool,_e as createPendingHitl,e_ as createPendingUiTool,gi as createPluginProgressEmitter,zg as createPluginRuntime,_f as createProcessTool,Ff as createReadFileTool,C as createSession,Od as createSessionContextStore,Hp as createSessionSearchTool,lm as createSkillListTool,um as createSkillLoadTool,xm as createSubagentSpawnTool,Em as createSubagentsTool,Am as createUiTool,Lf as createWriteFileTool,A as cronExecutionsPath,km as defaultUiToolInputSchema,H as deleteGoal,vp as deleteMemoryFile,Ag as discoverAIMaxPlugins,ln as emitGoalUpdatedProgress,O_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,ai as filterSkillsForAgent,oi as filterToolsForAgent,ni as findAgentDefinition,Vt as findSkillByName,Kt as flushAccounting,V_ as formatApprovalResolution,H_ as formatClarifyResolution,U_ as formatReviewResolution,Sc as generateSessionTitle,ke as getAgentConfig,mp as getMemoryLines,N as goalEventsPath,R as goalObjectiveMdPath,B as goalPath,w_ as hasBootstrapSentinel,he as hitlHistoryPath,Gg as initializePluginSystem,E_ as inspectBootstrapMountLayout,D as inspectSession,D_ as isBootstrapMountLayoutReady,tn as isContinuationEnabled,Qt as isGoalContext,Ai as isHitlPauseSignal,Mi as isUiToolPauseSignal,Ce as listAgents,Uc as listAvailableSlashCommands,Ne as listBindings,up as listMemoryFiles,w as listSessionSummaries,y as listSessions,M_ as listSubagentRunsFromDisk,ei as loadAgentDefinitionsFromDir,Fe as loadAgentsConfig,v as loadArtifactOperations,Tt as loadBootstrapFiles,f as loadCronExecutionRecords,be as loadPendingHitl,be as readPendingHitl,$g as loadPendingUiTool,$g as readPendingUiTool,Fg as loadPluginManifest,Ig as loadPluginManifestRegistry,Hg as loadPlugins,j as loadSessionContextSnapshot,ne as loadSessionMetadata,Ut as loadSkillView,Rt as loadSkills,Bt as loadSkillsFromDirs,zt as loadSkillsWithPluginDirs,A_ as loadSubagentRegistryFromDisk,m as loadTranscript,an as maybeContinueGoalIfIdle,op as memoryDir,te as metadataPath,F as mirrorGoalStatusToSession,we as normalizeAgentId,og as normalizePluginsConfig,u as normalizeSessionStoreName,ti as parseAgentDefinition,me as pendingHitlPath,Zg as pendingUiToolPath,sn as prependObjectiveUpdatedSteeringIfNeeded,sp as primaryMemoryPath,ii as publicAgentDefinitions,z as readGoal,ve as readHitlHistory,dp as readMemoryFile,fp as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,ae as registerEmbeddingProvider,fe as registerMemoryProvider,Ae as removeAgent,Le as removeBindings,_p as replaceMemoryFile,re as resetEmbeddingProviderRegistryForTests,pe as resetMemoryProviderRegistryForTests,$r as resolveAgentDefinitionsContext,Te as resolveAgentDir,Ee as resolveAgentIdByBinding,Pe as resolveAgentsConfigPath,je as resolveDefaultAgentId,U as resolveEmbeddingProvider,V as resolveGoalObjective,R_ as resolveHitlRequest,R_ as resolvePendingHitl,de as resolveMemoryProvider,Oe as resolveModelFallbacks,De as resolveModelString,t_ as resolvePendingUiTool,Pg as resolvePluginManifestPath,t as rewriteTranscript,g_ as runAgent,Se as saveAgentsConfig,M as saveSessionMetadata,j_ as saveSubagentRegistryToDisk,Xr as scanAgentDefinitions,pp as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,nn as shouldContinueGoal,Mt as skillsDir,S as toolResultsDir,e as transcriptPath,ge as transitionHitlStatus,Re as updateAgent,ze as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,sg as validatePluginsConfig,L_ as validateResume,oh as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",