@gencode/agents 0.0.33 → 0.0.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,81 +1,84 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as e,C as t,D as n,E as r,O as i,S as a,T as o,_ as s,a as c,b as l,c as u,d,f,g as p,h as m,i as h,k as g,l as _,m as v,n as y,o as b,p as x,r as S,s as C,u as w,v as T,w as E,x as D,y as O}from"./builtin-provider-CJJNj6nV.js";import{i as k,n as A,r as j}from"./provider-registry-CxtHsHdk.js";import{_ as M,a as N,c as P,d as ee,f as te,g as ne,h as re,i as ie,l as ae,m as oe,n as se,o as ce,p as le,s as ue,t as de,u as fe,v as pe}from"./config-DG3Q1aJ6.js";import F from"node:fs/promises";import I from"node:path";import me from"gray-matter";import{Type as L,calculateCost as he,getEnvApiKey as ge,parseStreamingJson as _e,registerApiProvider as ve,registerBuiltInApiProviders as ye,supportsXhigh as be}from"@mariozechner/pi-ai";import xe from"openai";import{AssistantMessageEventStream as Se}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as R}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as Ce,hasCopilotVisionInput as we}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as Te,clampReasoning as Ee}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as De}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import{createHash as Oe,randomUUID as z}from"node:crypto";import{Agent as ke}from"@mariozechner/pi-agent-core";import Ae from"node:os";import{spawn as je}from"node:child_process";import B from"node:fs";import{AsyncLocalStorage as Me}from"node:async_hooks";import Ne from"ajv";import{createJiti as Pe}from"jiti";import{isHitlExpired as Fe}from"@gencode/shared";const Ie=2e4,Le=15e4,Re=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`HEARTBEAT.md`,`MEMORY.md`,`BOOTSTRAP.md`];function V(e){return I.join(e,`.aimax`)}async function ze(e){let t=V(e),n=[];for(let e of Re){let r=I.join(t,e);try{let t=await F.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await F.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function Be(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
|
|
2
2
|
`),s].join(`
|
|
3
|
-
`),truncated:!0,originalLength:r.length}}function
|
|
4
|
-
`);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function
|
|
3
|
+
`),truncated:!0,originalLength:r.length}}function Ve(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function He(e,t){let n=t?.maxChars??Ie,r=Math.max(1,t?.totalMaxChars??Math.max(n,Le)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Ve(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=Be(a.content??``,a.name,e),l=Ve(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}function Ue(e){return I.join(e,`.aimax`,`skills`)}function We(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ge(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${We(n)}\n`)}function Ke(e){let t=me(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
|
|
4
|
+
`);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function qe(e){return Ye([Ue(e)])}async function Je(e,t){return Ye([Ue(e),...t])}async function Ye(e){let t=[],n=new Set;for(let r of e){let e;try{e=await F.readdir(r,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let i=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of i.sort()){if(t.length>=50)break;if(n.has(e))continue;let i=I.join(r,e,`SKILL.md`),a;try{a=await F.readFile(i,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let o;try{o=Ke(a)}catch(t){Ge(e,i,t);continue}t.push({name:e,description:o,location:i}),n.add(e)}}return t}function Xe(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
|
|
5
5
|
`)).join(`
|
|
6
|
-
`)}\n</available_skills>`}const
|
|
7
|
-
`)}function
|
|
6
|
+
`)}\n</available_skills>`}const Ze=3,Qe=5;var $e=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t})}complete(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`done`,n.record.result=t,n.record.endedAt=Date.now())}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now())}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}consumeCompleted(e){let t=this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId));for(let e of t)this.announced.add(e.runId);return t}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>3?{allowed:!1,reason:`Maximum subagent depth (3) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}};const et=new Map;function tt(e){let t=et.get(e);return t||(t={},et.set(e,t)),t}function nt(e){et.delete(e)}function rt(e,t){return I.isAbsolute(e)?I.normalize(e):I.normalize(I.join(t,e))}function it(e){let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`))return;let n=t.lastIndexOf(`/.pingclaw/skills/`);if(n===-1)return;let r=t.slice(n+18,t.length-9);if(!(!r||r.includes(`/`)))return r}var at=class{skillLocations;reportedSkills=new Set;pendingReadFilePaths=[];constructor(e){this.params=e,this.skillLocations=new Map(e.skills.map(e=>[I.normalize(e.location),e.name]))}onToolExecutionStart(e){if(e.toolName!==`read_file`||!e.args||typeof e.args!=`object`)return;let t=e.args.path;typeof t==`string`&&this.pendingReadFilePaths.push(rt(t,this.params.workspaceDir))}async onToolExecutionEnd(e){if(e.toolName!==`read_file`)return;let t=this.pendingReadFilePaths.pop(),n=t?this.skillLocations.get(t)??it(t):void 0;!n||e.isError||this.reportedSkills.has(n)||(this.reportedSkills.add(n),await this.params.reportDiagnostic?.({level:`info`,phase:`skill_activated`,message:`skill activated`,details:{skillName:n,resolvedPath:t}}),await this.params.report({type:`skill_used`,skillName:n,agent:`aimax:main`,taskId:`aimax[${this.params.sessionId}]`}))}},H=class extends Error{code;statusCode;statusText;providerMessage;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.retryable=e.retryable}};function ot(e){return{async chat(t){let n=st(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await ut(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:ct(n),historyMessages:n},e.hookCtx);let i={model:r,messages:n,stream:!1};typeof t.temperature==`number`&&(i.temperature=t.temperature),typeof t.maxTokens==`number`&&(i.max_tokens=t.maxTokens);let{signal:a,clear:o,didTimeout:s}=dt(t.signal,t.timeoutMs);try{let t;try{let n=e.baseUrl.replace(/\/$/,``);t=await fetch(`${n}/chat/completions`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:JSON.stringify(i),signal:a})}catch(e){throw pt(e,s())}if(!t.ok){let e=await ft(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new H({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:ht(t.status)})}let n;try{n=await t.json()}catch(e){throw new H({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}let o=n.choices?.[0]?.message?.content??n.choices?.[0]?.text??``,c=lt(n.usage);return await ut(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:o?[o]:[],usage:c},e.hookCtx),{text:o,usage:c,raw:n}}finally{o()}}}}function st(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function ct(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
|
|
7
|
+
`)}function lt(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}async function ut(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function dt(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function ft(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function pt(e,t){return e instanceof H?e:mt(e)?t?new H({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new H({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function mt(e){return e instanceof Error&&e.name===`AbortError`}function ht(e){return e===408||e===409||e===425||e===429||e>=500}function gt(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function _t(e){if(!gt(e))return null;let t=e,n=vt(t.message),r=U(n?.code)??U(t.code),i=U(n?.type)??U(t.type),a=U(n?.message)??yt(t.error)??U(t.message)??`Unknown upstream error`;return{message:bt(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:xt(r,i),raw:e}}function vt(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function yt(e){if(!(!e||typeof e!=`object`))return U(e.message)}function U(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function bt(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function xt(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}const St=(e,t,n)=>{let r=new Se;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0};try{let a=wt(e,t,n?.apiKey||ge(e.provider)||``,n?.headers),o=Tt(e,t,n);n?.onPayload?.(o);let s=await a.chat.completions.create(o,{signal:n?.signal});r.push({type:`start`,partial:i});let c=null,l=i.content,u=()=>l.length-1,d=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:u(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:u(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=_e(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=_t(t);if(n)throw new H({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},he(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=jt(a.finish_reason)),!a.delta))continue;a.delta.content!==null&&a.delta.content!==void 0&&a.delta.content.length>0&&((!c||c.type!==`text`)&&(d(c),c={type:`text`,text:``},i.content.push(c),r.push({type:`text_start`,contentIndex:u(),partial:i})),c.text+=a.delta.content,r.push({type:`text_delta`,contentIndex:u(),delta:a.delta.content,partial:i}));let o=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=a.delta[e];return t!=null&&t.length>0});if(o){(!c||c.type!==`thinking`)&&(d(c),c={type:`thinking`,thinking:``,thinkingSignature:o},i.content.push(c),r.push({type:`thinking_start`,contentIndex:u(),partial:i}));let e=a.delta[o];c.thinking+=e,r.push({type:`thinking_delta`,contentIndex:u(),delta:e,partial:i})}if(a.delta.tool_calls)for(let e of a.delta.tool_calls){(!c||c.type!==`toolCall`||e.id&&c.id!==e.id)&&(d(c),c={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(c),r.push({type:`toolcall_start`,contentIndex:u(),partial:i})),e.id&&(c.id=e.id),e.function?.name&&(c.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,c.partialArgs+=e.function.arguments,c.arguments=_e(c.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:u(),delta:t,partial:i})}let s=a.delta.reasoning_details;if(s&&Array.isArray(s)){for(let e of s)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(d(c),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(e){for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let t=e?.error?.metadata?.raw;t&&(i.errorMessage+=`\n${t}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Ct=(e,t,n)=>{let r=n?.apiKey||ge(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Te(e,n,r),a=be(e)?n?.reasoning:Ee(n?.reasoning);return St(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function wt(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};if(e.provider===`github-copilot`){let e=we(t.messages);Object.assign(i,Ce({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new xe({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Tt(e,t,n){let r=Nt(e),i=kt(e,t,r);Ot(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=At(t.tools,r):Et(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),(r.thinkingFormat===`zai`||r.thinkingFormat===`qwen`)&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort&&(a.reasoning_effort=n.reasoningEffort),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function Et(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function Dt(e){let t=e.replace(/[^a-zA-Z0-9]/g,``);return t.length<9?t+=`ABCDEFGHI`.slice(0,9-t.length):t.length>9&&(t=t.slice(0,9)),t}function Ot(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function kt(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Dt(t);if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=De(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:R(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:R(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:R(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>R(e.text)).join(``):a.map(e=>({type:`text`,text:R(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
8
8
|
|
|
9
9
|
`);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
|
|
10
10
|
`))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
11
|
-
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:R(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function
|
|
12
|
-
`);async function
|
|
13
|
-
`),r=n===-1?t:t.slice(0,n).trim(),i=r.match(/^\/([^\s:]+)\s*:(.*)$/);if(!i)return r;let[,a,o]=i,s=o.trimStart();return s?`/${a} ${s}`:`/${a}`}function
|
|
14
|
-
`)}}function
|
|
15
|
-
|
|
16
|
-
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function
|
|
17
|
-
`):e.content;return W(e.toolName)+W(t)}function G(e){return e.reduce((e,t)=>e+
|
|
18
|
-
`);async function
|
|
11
|
+
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:R(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function At(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function jt(e){if(e===null)return`stop`;switch(e){case`stop`:return`stop`;case`length`:return`length`;case`function_call`:case`tool_calls`:return`toolUse`;case`error`:case`content_filter`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function Mt(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||t===`opencode`||n.includes(`opencode.ai`),a=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),o=t===`xai`||n.includes(`api.x.ai`),s=t===`mistral`||n.includes(`mistral.ai`);return{supportsStore:!i,supportsDeveloperRole:!i,supportsReasoningEffort:!o&&!r,supportsUsageInStreaming:!0,maxTokensField:a?`max_tokens`:`max_completion_tokens`,requiresToolResultName:s,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:s,requiresMistralToolIds:s,thinkingFormat:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},supportsStrictMode:!0}}function Nt(e){let t=Mt(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresMistralToolIds:e.compat.requiresMistralToolIds??t.requiresMistralToolIds,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode}:t}let Pt=!1;function Ft(){Pt||=(ye(),ve({api:`openai-completions`,stream:St,streamSimple:Ct}),!0)}var It=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};await this.params.onProgress?.(n)}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const Lt=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`,`- The principle of title generation is to describe the behavioral characteristics of the conversation and not to answer based on the content of the conversation`].join(`
|
|
12
|
+
`);async function Rt(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o}=e,s=t.trim().replace(/\s+/g,` `);if(!s)return`New session`;if(!r.flashModel)return Bt(s);let c=r.flashModel,l=ot({baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:c,hooks:a,hookCtx:o});for(let e=1;e<=3;e++)try{let e=(await l.chat({system:Lt,user:JSON.stringify([s,n]),temperature:0,maxTokens:100,signal:i})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;e<3&&await zt(500*e)}return Bt(s)}function zt(e){return new Promise(t=>setTimeout(t,e))}function Bt(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);Array.isArray(t)&&(e=t?.[0]?.content?.[0].text??e)}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}async function Vt(e){let{sessionId:t,resetCommand:n,previousSessionId:r,resetMessage:i,startMessage:a,hookRegistry:o,hookContext:s,eventDispatcher:c}=e;n&&i&&await c.dispatchProgress(t,{type:`session_reset`,action:n.action,previousSessionId:r,message:i}),n&&i&&await o.dispatch(`session_reset`,{action:n.action,sessionId:t,previousSessionId:r,message:i},s,{eventDispatcher:c}),await c.dispatchProgress(t,{type:`start`,message:a}),await o.dispatch(`session_start`,{sessionId:t},s,{eventDispatcher:c})}async function Ht(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e;await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher});let o=await l(r.dataDir,t);await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher})}async function Ut(t){let{replyText:n,sessionId:r,isNewSession:a,transcriptMessage:o,initialUserEntryPersisted:s=!1,runParams:c,hookRegistry:l,hookContext:u,startTime:f,compactionEntry:p,eventDispatcher:m}=t;if(s||await _(c.dataDir,r,{role:`user`,content:o,timestamp:new Date().toISOString()}),p&&await _(c.dataDir,r,p),await _(c.dataDir,r,{role:`assistant`,content:n,timestamp:new Date().toISOString()}),a){let n=await Rt({message:o.trim()?o:`New session`,llm:c.llm,text:t.replyText,hooks:l,hookCtx:u});await e(c.dataDir,r,{title:n},{storeName:c.sessionStoreName}),await m.dispatchProgress(r,{type:`title_updated`,title:n})}let h={sessionId:r,text:n,usage:{input:0,output:0,total:0},durationMs:Date.now()-f,context:{snapshotPath:d(c.dataDir,r),toolResultsDir:i(c.dataDir,r)}};return await Ht({sessionId:r,result:h,runParams:c,hookRegistry:l,hookContext:u,eventDispatcher:m}),h}async function Wt(t){let{sessionId:n,isNewSession:r,transcriptMessage:a,runParams:o,hookRegistry:s,hookContext:c,startTime:l,text:u,usage:f,error:p,paused:m,eventDispatcher:h}=t;if(r){let r=await Rt({message:a,llm:o.llm,text:t.text,hooks:s,hookCtx:c});await e(o.dataDir,n,{title:r},{storeName:o.sessionStoreName}),await h.dispatchProgress(n,{type:`title_updated`,title:r})}let g={sessionId:n,text:u,usage:f,durationMs:Date.now()-l,error:p,paused:m,context:{snapshotPath:d(o.dataDir,n),toolResultsDir:i(o.dataDir,n)}};return await Ht({sessionId:n,result:g,runParams:o,hookRegistry:s,hookContext:c,eventDispatcher:h}),g}const Gt=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`}];function Kt(){return Gt.map(e=>({...e}))}function qt(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Jt(e){let t=new Set,n=[];for(let r of e){let e=qt(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Yt(e){let t=Kt(),n=Jt(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function Xt(e){let t=e.trim();if(!t)return``;let n=t.indexOf(`
|
|
13
|
+
`),r=n===-1?t:t.slice(0,n).trim(),i=r.match(/^\/([^\s:]+)\s*:(.*)$/);if(!i)return r;let[,a,o]=i,s=o.trimStart();return s?`/${a} ${s}`:`/${a}`}function Zt(e){let t=Xt(e);if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]+))?$/);if(!n)return null;let r=n[1]?.trim().toLowerCase()??``,i=(n[2]??``).trim();return r?{name:r,rest:i}:null}function Qt(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s),r=(n?(()=>{let[,e,t]=n,r=t.trimStart();return r?`/${e} ${r}`:`/${e}`})():t).match(/^\/([^\s@]+)(?:@[^\s]+)?(?:\s+([\s\S]+))?$/);if(!r)return null;let i=r[1]?.trim().toLowerCase()??``;if(i!==`new`&&i!==`reset`)return null;let a=(r[2]??``).trim();return{action:i===`new`?`new`:`reset`,remainder:a}}function $t(e,t){let n=Zt(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:qt(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Jt(t).map(e=>e.name.slice(1))).has(n.name)?{kind:`skill-direct`,name:n.name,args:n.rest}:{kind:`unknown`,name:n.name,args:n.rest}}const en=new Set([`/new`,`/reset`,`/compact`]),tn=new Set([`/help`]);function nn(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function rn(e){if(e.length===0)return[];let t=e.map(nn),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function an(e){let t=Yt(e.skills),n=t.builtin.filter(e=>en.has(e.name)),r=t.builtin.filter(e=>e.name===`/skill`),i=t.builtin.filter(e=>tn.has(e.name)),a=t.skillCommands.slice(0,4),o=[];return o.push(`帮助`),o.push(``),o.push(`会话命令`),o.push(...rn(n)),o.push(``),o.push(`技能命令`),o.push(...rn(r)),a.length>0?(o.push(...rn(a)),t.skillCommands.length>a.length&&o.push(` ... 还有 ${t.skillCommands.length-a.length} 个`)):o.push(` 未安装技能命令`),o.push(``),o.push(`其他命令`),o.push(...rn(i)),{kind:`reply`,text:o.join(`
|
|
14
|
+
`)}}function on(e,t){let n=t.trim().toLowerCase();return n&&Jt(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function sn(e){let t=on(e.ctx.skills,e.skillName);return t?{kind:`rewrite`,message:[`Use the "${t.name}" skill for this request.`,e.args?`User input:\n${e.args}`:null].filter(e=>!!e).join(`
|
|
15
|
+
|
|
16
|
+
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function cn(e){let t=$t(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?an(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?sn({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:{kind:`pass`,message:e.message}}function W(e){return Math.ceil(e.length/4*1.2)}function ln(e){if(e.role===`user`)return W(e.content);if(e.role===`assistant`){let t=W(e.content);for(let n of e.toolCalls??[])t+=W(n.name)+W(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
|
|
17
|
+
`):e.content;return W(e.toolName)+W(t)}function G(e){return e.reduce((e,t)=>e+ln(t),0)}const un=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
|
|
18
|
+
`);async function dn(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=pn(t,r,i),l,u=ot({baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:o,hookCtx:s});for(let e=1;e<=3;e++)try{let e=(await u.chat({system:un,user:c,temperature:0,maxTokens:2048,signal:a})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;l=t,e<3&&await fn(500*e)}throw l}function fn(e){return new Promise(t=>setTimeout(t,e))}function pn(e,t,n){let r=[];n?.trim()&&r.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(r.push(`[Prior summary]\n${t.trim()}\n`),r.push(`[Conversation to incorporate]`)):r.push(`[Conversation to summarise]`);for(let t of e)if(t.role===`user`)r.push(`User: ${t.content}`);else if(t.role===`assistant`){let e=t.toolCalls&&t.toolCalls.length>0?` [called tools: ${t.toolCalls.map(e=>e.name).join(`, `)}]`:``;r.push(`Assistant:${e} ${t.content}`.trimEnd())}else if(t.role===`tool_result`){let e=t.isError?`error`:`ok`,n=t.toolResultRef?[`[tool result persisted] ${t.toolResultRef.toolName} (${t.toolResultRef.originalChars} chars).`,`Full output: ${t.toolResultRef.storagePath}`,t.toolResultRef.preview.trim()?`Preview:\n${t.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
|
|
19
19
|
`):t.content,i=n.length>2e3?`${n.slice(0,2e3)}… [truncated]`:n;r.push(`Tool(${t.toolName})[${e}]: ${i}`)}return r.join(`
|
|
20
|
-
`)}function
|
|
21
|
-
`);function
|
|
22
|
-
`)}async function
|
|
20
|
+
`)}function mn(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=ln(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function hn(e){let t=new Set;for(let n of e)if(n.role===`assistant`)for(let e of n.toolCalls??[])t.add(e.id);let n=e.filter(e=>e.role!==`tool_result`||t.has(e.toolCallId));return n.length===e.length?e:n}async function gn(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=_n(t),l=c>=0?t[c].content:void 0,u=hn(c>=0?t.slice(c+1):t);if(u.length===0)return{status:`skipped`,reason:`No history to compact.`,estimatedTokens:0};let{toKeep:d,toSummarise:f}=mn(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:G(u)}:{status:`compacted`,entry:{role:`compaction`,content:await dn({entries:f,llm:r,previousSummary:l,instructions:i,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:G(d)}}function _n(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const vn=[`✨ 新会话已开启,我们可以重新开始啦~`,``,` 我是爱码Max,你的AI研发助手。你可以这样和我聊:`,` 💻 “用React写一个登录组件”`,` ✏️ “帮我写一个用户中心的PRD”`,` 🧪 “为这个接口设计测试用例”`,` 💬 “解释下什么是微服务”`,``,` 直接说出你的需求就行~`].join(`
|
|
21
|
+
`);function yn(){return{kind:`reply`,text:vn}}function bn(){return{kind:`reply`,text:`✅ Session reset.`}}function xn(e){let t=wn(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Tn(r):null,a=n??i?.text,o=a?Qt(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?En(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Dn(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Sn(e,t){if(e.resetShortCircuit)return{kind:`reset_reply`,action:e.resetCommand?.action??`new`,transcriptMessage:e.transcriptMessage,initialUserEntryPersisted:!0};if(!e.slashCommandSource)return{kind:`run`,effectivePrompt:e.promptInput,transcriptMessage:e.transcriptMessage};let n=cn({message:e.messageForRun??``,skills:t});if(n.kind===`reply`)return{kind:`reply`,replyText:n.text,transcriptMessage:e.transcriptMessage};if(n.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:n.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(n.kind===`rewrite`){let t=e.inputMode===`text`?n.message:En(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Dn(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Cn(e){let t=Sn(e.invocation,e.skills);if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await Ut({replyText:(t.action===`reset`?bn():yn()).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await Ut({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let n=await gn({entries:e.runParams.channel===`CRON`?[]:await l(e.runParams.dataDir,e.sessionId),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await Ut({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function wn(e){return typeof e.message==`string`}function Tn(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n.role!==`user`)continue;if(typeof n.content==`string`)return{index:t,text:n.content};if(!Array.isArray(n.content)||n.content.length===0)return null;let r=n.content[0];return r?.type===`text`&&typeof r.text==`string`?{index:t,text:r.text}:null}return null}function En(e,t){let n=Tn(e);return n?e.map((e,r)=>{if(r!==n.index)return e;let i=e;return typeof i.content==`string`?{...e,content:t}:Array.isArray(i.content)&&i.content.length>0?{...e,content:i.content.map((e,n)=>{if(n!==0)return e;let r=e;return r?.type===`text`&&typeof r.text==`string`?{...r,text:t}:e})}:e}):e}function Dn(e){return typeof e==`string`?e:JSON.stringify(e)}function On(e,t){if(!t||t<=0||e.length===0)return e;let n=0,r=e.length;for(let i=e.length-1;i>=0;i--)if(e[i].role===`user`){if(n++,n>t)return e.slice(r);r=i}return e}const kn={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function K(e,t){return e.map(e=>An(e,t))}function An(e,t){let n=new Date(e.timestamp).getTime();if(jn(e))return{role:`user`,content:e.content,timestamp:n};if(Mn(e)){let r=[];e.content&&r.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])r.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:r,api:t.api,provider:`openai`,model:t.model,usage:kn,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:Nn(r)}],isError:r.isError,timestamp:n}}function jn(e){return e.role===`user`}function Mn(e){return e.role===`assistant`}function Nn(e){if(!e.toolResultRef)return e.content;let t=e.toolResultRef.preview.trimEnd(),n=[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
|
|
22
|
+
`)}async function Pn(e){let t=d(e.dataDir,e.sessionId,e),n=new Map,r=new Map,a=[],o=[],s=[],c,l=0,u,f,p=await zn(t);for(let e of p.readStates)n.set(Fn(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);a.push(...p.compaction.budgets),o.push(...p.compaction.snips),s.push(...p.compaction.collapseSpans),c=p.compaction.sessionMemory,l=p.compaction.consecutiveAutocompactFailures,u=p.compaction.lastCompactionAt,f=p.compaction.lastCompactionLayer;let m=async()=>{let e={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,budgets:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:l,lastCompactionAt:u,lastCompactionLayer:f}};await F.mkdir(I.dirname(t),{recursive:!0}),await F.writeFile(t,JSON.stringify(e,null,2),`utf-8`)};return{async findReusableRead(e,t,r){let i=Fn(e,t,r),a=n.get(i);if(!a)return null;let o=await Ln(e);return o===null||o!==a.lastModifiedMs?(n.delete(i),await m(),null):a},async recordRead(e){let t=new Date().toISOString(),r={path:e.path,offset:e.offset,limit:e.limit,contentHash:Rn(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await Ln(e.path)??Date.now()};return n.set(Fn(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())In(i.path)===In(e)&&(n.delete(r),t=!0);t&&await m()},async persistToolResult(t){let n=t.thresholdChars??12e3;if(t.content.length<=n)return{content:t.content};let o=t.previewChars??2e3,s=i(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=I.join(s,c);await F.mkdir(s,{recursive:!0}),await F.writeFile(l,t.content,`utf-8`);let d=I.relative(e.dataDir,l).split(I.sep).join(`/`),p=Hn(t.content,o),h={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:d,preview:p,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(h.toolCallId,h),a.push({toolCallId:h.toolCallId,toolName:h.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:p.length,strategy:`persist`,createdAt:h.createdAt}),u=h.createdAt,f=`L2`,await m(),{content:Vn(h),reference:h}},async recordSnip(e){o.push(e),u=e.createdAt,f=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await m()},async recordCollapse(e){s.push(e),u=e.createdAt,f=e.layer,await m()},async setSessionMemory(t){c=t,await Un(e.dataDir,e.sessionId,t,e),await m()},async recordAutocompactResult(e){l=e.failed?l+1:0,u=e.timestamp,f=`L6`,await m()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,budgets:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:l,lastCompactionAt:u,lastCompactionLayer:f}}}}}function Fn(e,t,n){return`${In(e)}::${t??``}::${n??``}`}function In(e){return I.normalize(e)}async function Ln(e){try{return(await F.stat(e)).mtimeMs}catch{return null}}function Rn(e){return Oe(`sha1`).update(e).digest(`hex`)}async function zn(e){try{let t=await F.readFile(e,`utf-8`),n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Bn():{version:2,updatedAt:typeof n.updatedAt==`string`?n.updatedAt:new Date(0).toISOString(),readStates:Array.isArray(n.readStates)?n.readStates:[],toolResults:Array.isArray(n.toolResults)?n.toolResults:[],compaction:{sessionMemory:n.compaction?.sessionMemory,budgets:Array.isArray(n.compaction?.budgets)?n.compaction.budgets:[],snips:Array.isArray(n.compaction?.snips)?n.compaction.snips:[],collapseSpans:Array.isArray(n.compaction?.collapseSpans)?n.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof n.compaction?.consecutiveAutocompactFailures==`number`?n.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof n.compaction?.lastCompactionAt==`string`?n.compaction.lastCompactionAt:void 0,lastCompactionLayer:n.compaction?.lastCompactionLayer===`L1`||n.compaction?.lastCompactionLayer===`L2`||n.compaction?.lastCompactionLayer===`L3`||n.compaction?.lastCompactionLayer===`L4`||n.compaction?.lastCompactionLayer===`L5`||n.compaction?.lastCompactionLayer===`L6`?n.compaction.lastCompactionLayer:void 0}}}catch{return Bn()}}function Bn(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Vn(e){let t=e.preview.length<e.originalChars?`
|
|
23
23
|
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,``,`Preview:`,e.preview+t].join(`
|
|
24
|
-
`)}function
|
|
25
|
-
`),r=n>t*.5?n:t;return e.slice(0,r)}async function
|
|
26
|
-
`);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),
|
|
27
|
-
`);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),
|
|
24
|
+
`)}function Hn(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
|
|
25
|
+
`),r=n>t*.5?n:t;return e.slice(0,r)}async function Un(e,t,n,i){let a=r(e,t,i);await F.mkdir(I.dirname(a),{recursive:!0}),await F.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}const Wn=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Gn(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,signal:s,hooks:c,hookCtx:l,contextStore:u,dataDir:d,sessionId:f}=e,p,m=$n(t),h=m>=0?t.slice(m+1):t;m>=0&&(p=t[m].content);let g=t.length,_=hn(On(h,a)),v=[];u&&(p=await Kn({entries:_,existingSummary:p,llm:i,contextStore:u,signal:s,hooks:c,hookCtx:l}));let y=_;if(y=await qn({entries:y,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:u,compactionEvents:v}),y=await Jn({entries:y,contextStore:u,compactionEvents:v}),y=await Yn({entries:y,contextStore:u,compactionEvents:v,dataDir:d,sessionId:f}),!o)return{messages:K(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:G(y),compacted:!1},compactionEvents:v};let b=er(r),x=G(y)>=Math.max(1e3,b-13e3),S=u?.getSnapshot(),C=S?.compaction.consecutiveAutocompactFailures??0;if(!x||C>=3)return{messages:K(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:G(y),compacted:!1},compactionEvents:v};let{toKeep:w,toSummarise:T}=mn(y,b);if(T.length===0)return{messages:K(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:G(y),compacted:!1},compactionEvents:v};let E=new Date().toISOString();try{let e=S?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await dn({entries:T,llm:i,previousSummary:p,signal:s,hooks:c,hookCtx:l}),r={role:`compaction`,content:t,keptCount:w.length,droppedCount:T.length,timestamp:E};return await u?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:E}),v.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${T.length} entries with session memory`:`Autocompact summarised ${T.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,G(T)),affectedEntries:T.length,snapshotVersion:2}),{messages:K(hn(w),n),priorSummary:t,compactionEntry:r,stats:{originalCount:g,keptCount:w.length,estimatedTokens:G(w),compacted:!0},compactionEvents:v}}catch{return await u?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:E}),{messages:K(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:G(y),compacted:!1},compactionEvents:[...v,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function Kn(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=G(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&Qn(t)>=3;if(!u&&!d)return n??l?.summary;let f=await dn({entries:t,llm:r,previousSummary:n??l?.summary,instructions:`Produce a durable session memory for future compaction and resume.`,signal:a,hooks:o,hookCtx:s}),p={version:1,summary:f,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:c,trigger:u?`threshold`:`autocompact`};return await i.setSessionMemory(p),f}async function qn(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Zn).length<=n)return t;let c=n,l=[],u=0,d=0;for(let e=t.length-1;e>=0;--e){let n=t[e];if(!Zn(n)){l.push(n);continue}if(c>0&&n.content.length<=r){--c,l.push(n);continue}let i=n.toolResultRef?.preview?.trim()||n.content.slice(0,r).trim(),s=[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
|
|
26
|
+
`);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),hn(l.reverse())}async function Jn(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!Zn(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${e.toolName}`,`Preview:\n${e.toolResultRef?.preview?.trim()||e.content.slice(0,400).trim()}`].join(`
|
|
27
|
+
`);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),qn({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Yn(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a}=e,o=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(o.length<=2)return t;let s=o[o.length-2]??t.length,c=[],l=0,u=0,d=0;for(;l<t.length;){if(l>=s||t[l]?.role===`user`){c.push(t[l]),l+=1;continue}let e=l;for(;l<s&&t[l]?.role!==`user`;)l+=1;let r=t.slice(e,l),o=r.filter(Zn).filter(e=>Wn.has(e.toolName)),f=o.reduce((e,t)=>e+t.content.length,0);if(o.length<3||f<1500){c.push(...r);continue}let p=Xn(r,o),m=new Date().toISOString(),h={role:`assistant`,content:p,timestamp:m};c.push(h),u+=r.length,d+=Math.max(0,Math.floor(G(r)-G([h])));let g={id:z(),layer:`L5`,startEntryIndex:e,endEntryIndex:l-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:p,sourceCount:r.length,estimatedTokensFreed:d,createdAt:m};await n?.recordCollapse(g),i&&a&&await tr(i,a,g)}return u>0&&r.push({type:`compaction`,reason:`Collapsed ${u} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),c}function Xn(e,t){let n=[...new Set(t.map(e=>e.toolName))],r=t.slice(-3).map(e=>`- ${e.toolName}: ${(e.toolResultRef?.preview||e.content).slice(0,180).trim()}`).join(`
|
|
28
28
|
`),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
|
|
29
29
|
`);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
|
|
30
30
|
|
|
31
|
-
`)}function
|
|
32
|
-
`)}function
|
|
33
|
-
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const
|
|
34
|
-
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return
|
|
35
|
-
`);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function
|
|
36
|
-
`),c=Math.max(1,r.offset??1),l=Math.min(
|
|
31
|
+
`)}function Zn(e){return e.role===`tool_result`}function Qn(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function $n(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function er(e){return Math.max(256,e-Math.min(e/4,2e4))}async function tr(e,t,n){let r=w(e,t);await F.mkdir(I.dirname(r),{recursive:!0}),await F.appendFile(r,`${JSON.stringify(n)}\n`,`utf-8`)}async function nr(e){let t=await Pn(e);return{async getReusableRead(e,n,r){let i=await t.findReusableRead(e,n,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await t.recordRead(e)},async invalidateReadPath(e){await t.invalidatePath(e)},persistToolResult(e){return t.persistToolResult(e)},manageHistory(e){return Gn({...e,contextStore:t})},getSnapshot:t.getSnapshot}}async function rr(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId}):Gn({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId})}var ir=class extends Error{isHitlPause=!0;constructor(e,t,n){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.name=`HitlPauseSignal`}};function ar(e){return!!(e instanceof ir||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const or=L.Object({command:L.String({description:`Shell command to execute`}),workdir:L.Optional(L.String({description:`Working directory (relative to workspace root)`})),env:L.Optional(L.Record(L.String(),L.String())),timeout:L.Optional(L.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:L.Optional(L.Number({description:`Wait this many milliseconds before returning running state`})),background:L.Optional(L.Boolean({description:`Return immediately with running session`}))});function sr(e,t,n){return Math.max(t,Math.min(n,e))}function cr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function lr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:sr(Math.floor(e),0,12e4)}function ur(e,t){if(!t?.trim())return e;let n=I.isAbsolute(t)?I.normalize(t):I.normalize(I.join(e,t));if(!n.startsWith(e+I.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function dr(e){let t=e.outputTail.trim();return`${t.length>0?`${t}\n\n`:``}Process is running in the background. sessionId=${e.sessionId}\nUse process(action="poll"|"log", sessionId) to continue.`}function fr(e){return mr({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
|
|
32
|
+
`)}function pr(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function mr(e){let t=pr(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function hr(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:or,async execute(t,n,r){if(!n.command?.trim())return{content:[{type:`text`,text:`Error: command is required.`}],details:{status:`failed`}};let i;try{i=ur(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=cr(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,lr(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:dr(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?mr({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[fr(l)],p=pr(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
|
|
33
|
+
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const gr=L.Object({action:L.String({description:`Process action: list | poll | log | kill`}),sessionId:L.Optional(L.String({description:`Session id for non-list actions`})),offset:L.Optional(L.Number({description:`Log line offset (0-based)`})),limit:L.Optional(L.Number({description:`Maximum lines to return`})),timeout:L.Optional(L.Number({description:`Poll wait time in milliseconds`}))});function _r(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function vr(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function yr(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:gr,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
|
|
34
|
+
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return vr(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,_r(n.timeout));return t?{content:[{type:`text`,text:t.status===`running`?`Session ${i} is still running.`:`Session ${i} finished with status=${t.status}, exitCode=${t.exitCode??`null`}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal,aggregated:t.status!==`running`}}:vr(`No session found for ${i}`)}if(r===`log`){let t=e.registry.readLog({sessionId:i,scopeKey:e.scopeKey,offset:n.offset,limit:n.limit});return t?{content:[{type:`text`,text:t.text.trim().length>0?t.text:`(no output)`}],details:{status:t.status,sessionId:i,totalLines:t.totalLines,totalChars:t.totalChars,truncated:t.truncated,exitCode:t.exitCode,exitSignal:t.exitSignal}}:vr(`No session found for ${i}`)}if(r===`kill`){let t=await e.registry.terminate(i,e.scopeKey);return t?{content:[{type:`text`,text:t.status===`running`?`Termination signal sent to ${i}.`:`Session ${i} terminated with status=${t.status}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal}}:vr(`No session found for ${i}`)}return vr(`Unsupported action: ${n.action}`)}}}const br=2e5;function xr(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Sr(e,t){let n=e+t;return n.length<=br?{text:n,truncated:!1}:{text:n.slice(-br),truncated:!0}}function Cr(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Sr(e.output,r);e.output=i.text;let a=Sr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function q(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:xr(e.output),stdoutTail:xr(e.stdout),stderrTail:xr(e.stderr),outputTruncated:e.outputTruncated}}function J(e,t){return t?e.scopeKey===t:!0}function wr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Tr(e){return e?e.split(/\r?\n/):[]}function Er(e){let t=Tr(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=wr(e.limit,n?200:Math.max(1,t.length-r)),a=(n&&t.length>200?t.slice(t.length-200):t.slice(r,r+i)).join(`
|
|
35
|
+
`);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Dr(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Or(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Dr(e))};return{start(t){let n=je(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:z(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Cr(o,`stdout`,e)),n.stderr.on(`data`,e=>Cr(o,`stderr`,e));let s=wr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Cr(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),Cr(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),q(o)},get(e,t){let n=r(e);return!n||!J(n,t)?null:q(n)},list(n){return[...e.values(),...t.values()].filter(e=>J(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>q(e))},async wait(e,t,n){let i=r(e);if(!i||!J(i,t))return null;if(i.status!==`running`)return q(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!J(a,t)?null:q(a)},readLog(e){let t=r(e.sessionId);return!t||!J(t,e.scopeKey)?null:Er({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!J(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!J(n,t))return null;if(n.status!==`running`)return q(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?q(i):null}}}function kr(e){return hr({workspaceDir:e,registry:Or(),scopeKey:e})}const Ar=5*1024*1024,jr=2e3;function Mr(e,t){return I.isAbsolute(e)?I.normalize(e):I.normalize(I.join(t,e))}const Nr=L.Object({path:L.String({description:`File path (relative to workspace or absolute)`}),offset:L.Optional(L.Number({description:`Line offset (1-based, default: 1)`})),limit:L.Optional(L.Number({description:`Maximum lines to read (default: 2000)`}))});function Pr(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Nr,async execute(n,r){let i;try{i=Mr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await F.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}if(o.length>Ar){let e=o.slice(0,Ar).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Ar} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let s=o.toString(`utf-8`).split(`
|
|
36
|
+
`),c=Math.max(1,r.offset??1),l=Math.min(jr,r.limit??jr),u=s.slice(c-1,c-1+l),d=u.length<s.length-(c-1),f=u.map((e,t)=>`${(c+t).toString().padStart(4)} ${e}`).join(`
|
|
37
37
|
`),p=d?`\n[...${s.length-(c-1+u.length)} more lines]`:``;return await t?.rememberRead({path:i,content:u.join(`
|
|
38
38
|
`),lineCount:u.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:f+p}],details:{content:u.join(`
|
|
39
|
-
`),lines:u.length,truncated:d}}}}}const
|
|
40
|
-
`)||`(empty directory)`}],details:{entries:a}}}}}const
|
|
41
|
-
`)}function
|
|
42
|
-
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=
|
|
43
|
-
`)}function
|
|
44
|
-
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function
|
|
45
|
-
`)
|
|
46
|
-
`)
|
|
47
|
-
`)}
|
|
39
|
+
`),lines:u.length,truncated:d}}}}}const Fr=L.Object({path:L.String({description:`File path (relative to workspace or absolute)`}),content:L.String({description:`File content to write`})});function Ir(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Fr,async execute(n,r){let i;try{i=Mr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await F.mkdir(I.dirname(i),{recursive:!0}),await F.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const Lr=L.Object({path:L.String({description:`File path (relative to workspace or absolute)`}),old_string:L.String({description:`Exact text to replace`}),new_string:L.String({description:`Replacement text`})});function Rr(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Lr,async execute(n,r){let i;try{i=Mr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await F.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await F.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const zr=L.Object({path:L.Optional(L.String({description:`Directory path (default: workspace root)`}))});function Br(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:zr,async execute(t,n){let r=n.path??`.`,i;try{i=Mr(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await F.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
|
|
40
|
+
`)||`(empty directory)`}],details:{entries:a}}}}}const Vr=L.Object({input:L.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Hr(e,t){let n=I.isAbsolute(e)?I.normalize(e):I.normalize(I.join(t,e));if(!n.startsWith(t+I.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Ur(e,t){let n=I.relative(t,e);return!n||n===``?I.basename(e):n.startsWith(`..`)||I.isAbsolute(n)?e:n}async function Wr(e){await F.mkdir(I.dirname(e),{recursive:!0})}function Gr(e){let t=[`Success. Updated the following files:`];for(let n of e.added)t.push(`A ${n}`);for(let n of e.modified)t.push(`M ${n}`);for(let n of e.deleted)t.push(`D ${n}`);return t.join(`
|
|
41
|
+
`)}function Kr(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:Vr,async execute(t,n){try{let t=n.input?.trim();if(!t)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let r=Jr(t);if(r.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let i={added:[],modified:[],deleted:[]},a={added:new Set,modified:new Set,deleted:new Set};for(let t of r.hunks){if(t.kind===`add`){let n=Hr(t.path,e);await Wr(n),await F.writeFile(n,t.contents,`utf-8`),qr(i,a,`added`,Ur(n,e));continue}if(t.kind===`delete`){let n=Hr(t.path,e);await F.rm(n,{force:!0,recursive:!1}),qr(i,a,`deleted`,Ur(n,e));continue}let n=Hr(t.path,e),r=await Qr(n,t.chunks);if(t.movePath){let o=Hr(t.movePath,e);await Wr(o),await F.writeFile(o,r,`utf-8`),await F.rm(n,{force:!0,recursive:!1}),qr(i,a,`modified`,Ur(o,e))}else await F.writeFile(n,r,`utf-8`),qr(i,a,`modified`,Ur(n,e))}return{content:[{type:`text`,text:Gr(i)}],details:{summary:i}}}catch(e){if(ar(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function qr(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Jr(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Yr(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Xr(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Yr(e){let t=e[0]?.trim(),n=e[e.length-1]?.trim();if(t!==`*** Begin Patch`)throw Error(`The first line of the patch must be '*** Begin Patch'`);if(n!==`*** End Patch`)throw Error(`The last line of the patch must be '*** End Patch'`)}function Xr(e,t){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: empty hunk`);let n=e[0].trim();if(n.startsWith(`*** Add File: `)){let t=n.slice(14),r=``,i=1;for(let t of e.slice(1))if(t.startsWith(`+`))r+=`${t.slice(1)}\n`,i+=1;else break;return{hunk:{kind:`add`,path:t,contents:r},consumed:i}}if(n.startsWith(`*** Delete File: `))return{hunk:{kind:`delete`,path:n.slice(17)},consumed:1};if(n.startsWith(`*** Update File: `)){let r=n.slice(17),i=e.slice(1),a=1,o,s=i[0]?.trim();s?.startsWith(`*** Move to: `)&&(o=s.slice(13),i=i.slice(1),a+=1);let c=[];for(;i.length>0;){if(i[0].trim()===``){i=i.slice(1),a+=1;continue}if(i[0].startsWith(`***`))break;let{chunk:e,consumed:n}=Zr(i,t+a,c.length===0);c.push(e),i=i.slice(n),a+=n}if(c.length===0)throw Error(`Invalid patch hunk at line ${t}: Update file hunk for path '${r}' is empty`);return{hunk:{kind:`update`,path:r,movePath:o,chunks:c},consumed:a}}throw Error(`Invalid patch hunk at line ${t}: '${e[0]}' is not a valid hunk header.`)}function Zr(e,t,n){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: Update hunk does not contain any lines`);let r,i=0;if(e[0]===`@@`)i=1;else if(e[0].startsWith(`@@ `))r=e[0].slice(3),i=1;else if(!n)throw Error(`Invalid patch hunk at line ${t}: Expected update hunk to start with a @@ context marker.`);if(i>=e.length)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);let a={changeContext:r,oldLines:[],newLines:[],isEndOfFile:!1},o=0;for(let n of e.slice(i)){if(n===`*** End of File`){if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);a.isEndOfFile=!0,o+=1;break}let e=n[0];if(!e){a.oldLines.push(``),a.newLines.push(``),o+=1;continue}if(e===` `){let e=n.slice(1);a.oldLines.push(e),a.newLines.push(e),o+=1;continue}if(e===`+`){a.newLines.push(n.slice(1)),o+=1;continue}if(e===`-`){a.oldLines.push(n.slice(1)),o+=1;continue}if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Unexpected line found in update hunk.`);break}return{chunk:a,consumed:o+i}}async function Qr(e,t){let n=(await F.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
|
|
42
|
+
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=ei(n,$r(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
|
|
43
|
+
`)}function $r(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=ti(e,[a.changeContext],i,!1);if(n===null)throw Error(`Failed to find context '${a.changeContext}' in ${t}`);i=n+1}if(a.oldLines.length===0){let t=e.length>0&&e[e.length-1]===``?e.length-1:e.length;r.push([t,0,a.newLines]);continue}let n=a.oldLines,o=a.newLines,s=ti(e,n,i,a.isEndOfFile);if(s===null&&n[n.length-1]===``&&(n=n.slice(0,-1),o.length>0&&o[o.length-1]===``&&(o=o.slice(0,-1)),s=ti(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
|
|
44
|
+
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function ei(e,t){let n=[...e];for(let[e,r,i]of[...t].toReversed()){for(let t=0;t<r;t+=1)e<n.length&&n.splice(e,1);for(let t=0;t<i.length;t+=1)n.splice(e+t,0,i[t])}return n}function ti(e,t,n,r){if(t.length===0)return n;if(t.length>e.length)return null;let i=e.length-t.length,a=r&&e.length>=t.length?i:n;if(a>i)return null;for(let n=a;n<=i;n+=1)if(ni(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(ni(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(ni(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(ni(e,t,n,e=>ri(e.trim())))return n;return null}function ni(e,t,n,r){for(let i=0;i<t.length;i+=1)if(r(e[n+i])!==r(t[i]))return!1;return!0}function ri(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}const Y={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 ii(e){return e.action===`timeout`?Y.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Y.approval.summary.approved:Y.approval.summary.denied}function ai(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
|
|
45
|
+
`)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
|
|
46
|
+
`)):(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(`
|
|
47
|
+
`))}const oi=L.Object({question:L.String({description:`The question to ask the user.`}),options:L.Optional(L.Array(L.String(),{description:`Optional list of choices for the user to select from.`})),allow_free_text:L.Optional(L.Boolean({description:`Whether to allow the user to type a free-text response in addition to choices. Defaults to true.`}))});function si(e){return{name:`clarify`,label:Y.clarify.label,description:Y.clarify.description,parameters:oi,async execute(t,n){let r=z(),i=n.options&&n.options.length>0,a;throw a=i?{mode:`choice`,choices:n.options.map((e,t)=>({id:`option-${t}`,label:e})),allowFreeText:n.allow_free_text!==!1}:{mode:`text`,multiline:!0,placeholder:Y.clarify.placeholder},new ir({requestId:r,sessionId:e,kind:`clarify`,title:Y.clarify.title,prompt:n.question,input:a,policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`clarify`,toolArgs:n})}}}function ci(e){return I.join(e,`.aimax`)}function li(e){return I.join(ci(e),`MEMORY.md`)}async function ui(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function di(e,t){let n=ci(e),r=k({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:y({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function fi(e){return C(ci(e))}async function pi(e){try{return await F.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function mi(e){return pi(li(e))}async function hi(e,t,n){return await di(e,n).search(t)}async function gi(e,t,n,r,i){try{return await di(e,i).getLines(t,n,r)}catch{return null}}async function _i(e,t,n){let r=di(e,n);await r.append(t),await ui(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function vi(e,t,n,r){let i=di(e,r);await i.updateFile(t,n),await ui(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function yi(e,t,n){let r=di(e,n);await r.deleteFile(t),await ui(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const bi=L.Object({query:L.String({description:`Search query (case-insensitive substring match)`})});function xi(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memory files for relevant information`,parameters:bi,async execute(n,r){let i=(await hi(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
|
|
48
|
+
`)}],details:{matches:i}}}}}const Si=L.Object({file:L.String({description:`Memory file path`}),start_line:L.Number({description:`Start line number (1-based)`}),end_line:L.Number({description:`End line number (1-based)`})});function Ci(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read specific lines from a memory file`,parameters:Si,async execute(n,r){let i=await gi(e,r.file,r.start_line,r.end_line,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});return i===null?{content:[{type:`text`,text:`File not found: ${r.file}`}],details:{lines:null}}:{content:[{type:`text`,text:i.map((e,t)=>`${(r.start_line+t).toString().padStart(4)} ${e}`).join(`
|
|
49
|
+
`)||`(empty)`}],details:{lines:i}}}}}const wi=L.Object({content:L.String({description:`Content to append to MEMORY.md`})});function Ti(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append new information to the MEMORY.md file`,parameters:wi,async execute(n,r){try{return await _i(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{appended:!0}}}catch(e){return{content:[{type:`text`,text:`Error appending to memory: ${e instanceof Error?e.message:String(e)}`}],details:{appended:!1}}}}}}const Ei=L.Object({action:L.String({description:`A short description of the action that needs approval.`}),reason:L.String({description:`Why this action needs human approval.`}),details:L.Optional(L.String({description:`Additional details about the action (e.g. the command to execute).`}))});function Di(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:ii(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Oi(e,t){return{name:`request_approval`,label:Y.approval.label,description:Y.approval.description,parameters:Ei,async execute(n,r){if(t?.request.kind===`approval`&&t.toolContext?.toolName===`request_approval`&&t.toolContext.toolCallId===n&&t.resolution.action===`submit`)return{content:[{type:`text`,text:Di(t.resolution)}],details:{paused:!1,approved:t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1,resolution:t.resolution}};let i=z(),a;throw r.details&&(a={mimeType:`text/plain`,content:r.details}),new ir({requestId:i,sessionId:e,kind:`approval`,title:r.action,prompt:r.reason,preview:a,input:{mode:`choice`,choices:[{id:`approve`,label:Y.approval.choices.approve.label,description:Y.approval.choices.approve.description},{id:`deny`,label:Y.approval.choices.deny.label,description:Y.approval.choices.deny.description}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`request_approval`,toolArgs:r})}}}const ki=L.Object({title:L.String({description:`A short title for the review (e.g. 'Weekly Report Draft').`}),description:L.String({description:`What the user should review and what kind of feedback you need.`}),content:L.String({description:`The content to review (text, markdown, or JSON).`}),content_type:L.Optional(L.String({description:`MIME type: text/plain, application/json, or text/markdown. Defaults to text/markdown.`}))});function Ai(e){return{name:`request_review`,label:Y.review.label,description:Y.review.description,parameters:ki,async execute(t,n){let r=z(),i={mimeType:n.content_type??`text/markdown`,content:n.content};throw new ir({requestId:r,sessionId:e,kind:`review`,title:n.title,prompt:n.description,preview:i,input:{mode:`choice`,choices:[{id:`approve`,label:Y.review.choices.approve.label,description:Y.review.choices.approve.description},{id:`revise`,label:Y.review.choices.revise.label,description:Y.review.choices.revise.description},{id:`reject`,label:Y.review.choices.reject.label,description:Y.review.choices.reject.description}],allowFreeText:!0},policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`request_review`,toolArgs:n})}}}const ji=L.Object({task:L.String({description:`The task description for the subagent to execute`}),label:L.Optional(L.String({description:`Optional short label to identify this subagent`}))});function Mi(e){let t=e.label?`"${e.label}"`:`task: ${e.task}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${e.result??`(no output)`}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function Ni(e,t,n,r,i,a,o,s,c){return{name:`sessions_spawn`,label:`Spawn Subagent`,description:`Use this tool only when the user or system instructions explicitly require using a subagent, delegation, or parallel agent execution. Do not use it for routine decomposition or inferred parallelism. Returns immediately with status=accepted; the subagent result will be delivered back automatically as a follow-up message — do not poll or sleep.`,parameters:ji,async execute(l,u){let d=u.task.trim(),p=u.label?.trim();if(!d){let e={status:`error`,error:`task must not be empty`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=e.checkSpawnAllowed(t,n+1);if(!m.allowed){let e={status:`forbidden`,error:m.reason};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let h=z(),g=new AbortController,_;try{_=await f(r,i,{storeName:s.sessionStoreName})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}let v={runId:h,childSessionId:_,parentSessionId:t,task:d,label:p,depth:n+1,status:`running`,startedAt:Date.now(),abortController:g},y=c({dataDir:r,sessionId:_,message:d,channel:i,llm:a,...s,loopDetection:o,abortSignal:g.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(h,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(h,n)});e.register(v,y);let b={status:`accepted`,childSessionId:_,runId:h,note:`The subagent result will be sent back automatically. Do not poll or re-spawn.`};return{content:[{type:`text`,text:JSON.stringify(b)}],details:b}}}}const Pi=L.Object({action:L.Union([`list`,`kill`].map(e=>L.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:L.Optional(L.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Fi(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.floor(e%6e4/1e3)}s`}function Ii(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function Li(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:Pi,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let e=o.map((e,t)=>({index:t+1,runId:e.runId,label:e.label??e.task.slice(0,40),task:e.task,status:e.status,depth:e.depth,runtimeMs:e.endedAt?e.endedAt-e.startedAt:a-e.startedAt})),t={action:`list`,runs:e,text:(e.length===0?[`(no subagents)`]:e.map(e=>`${e.index}. [${e.status}] ${e.label} (${Fi(e.runtimeMs)})`)).join(`
|
|
50
|
+
`)};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Ii(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}const Ri=L.Object({image:L.String({description:`Image path or URL`}),prompt:L.Optional(L.String({description:`Prompt for image analysis`})),model:L.Optional(L.String({description:`Optional model override`})),maxBytesMb:L.Optional(L.Number({description:`Optional size cap in MB`}))});function zi(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Ri,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}function Bi(e,t){let n=I.join(e,`workspace`),r=t?.memoryOptions,i=Or(),a=[hr({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),yr({registry:i,scopeKey:n}),Pr(n,t?.contextManager),Ir(n,t?.contextManager),Rr(n,t?.contextManager),Br(n),Kr(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),xi(e,r),Ci(e,r),Ti(e,r),...t?.sessionId?[si(t.sessionId),Oi(t.sessionId,t.hitlResume),Ai(t.sessionId)]:[]];return t&&a.push(Ni(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Li(t.registry,t.parentSessionId)),a}const Vi={read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,memory_search:`Search memory files for relevant information`,memory_get:`Read specific lines from memory files`,memory_append:`Append new long-term memory`,sessions_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Hi=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function Ui(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...Hi.filter(e=>t.has(e)),...n.filter(e=>!Hi.includes(e)).sort()],displayName:t}}function Wi(e){let{ordered:t,displayName:n}=Ui(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??Vi[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
|
|
48
51
|
`),``].join(`
|
|
49
|
-
`)}function
|
|
50
|
-
`)}function
|
|
51
|
-
`)}function
|
|
52
|
+
`)}function Gi(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
|
|
53
|
+
`)}function Ki(e){return e?``:[`## Tool Call Style`,`Default: call routine low-risk tools directly without narrating every step.`,`Narrate briefly when actions are sensitive, long-running, or likely surprising.`,`When approvals are required, keep the command text exact and complete.`,``].join(`
|
|
54
|
+
`)}function qi(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: read its SKILL.md at <location> with `read_file`, then follow it.",`- If multiple could apply: choose the most specific one, then read/follow it.`,`- If none clearly apply: do not read any SKILL.md.`,`Constraints: never read more than one skill up front; only read after selecting.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
|
|
52
55
|
`)).join(`
|
|
53
56
|
`)}\n</available_skills>`,``].join(`
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
57
|
-
`)}function
|
|
58
|
-
`)}function
|
|
59
|
-
`)}function
|
|
60
|
-
`)}function
|
|
61
|
-
`)}function
|
|
62
|
-
`)}function
|
|
63
|
-
`)}function
|
|
64
|
-
`)}function
|
|
65
|
-
`)}function
|
|
66
|
-
`)}function
|
|
67
|
-
`):``}function
|
|
68
|
-
`,
|
|
69
|
-
`)}const
|
|
70
|
-
`).trim()}function Ca(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:ya(e)}function wa(e,t,n,r){if(r!==void 0)return`error:${Q(Ca(r))}`;if(!Z(n))return n===void 0?void 0:Q(n);let i=Z(n.details)?n.details:{},a=Sa(n);if(xa(e,t)&&e===`process`&&Z(t)){let e=t.action;if(e===`poll`)return Q({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Q({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 Q({details:i,text:a})}function Ta(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 Ea(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 Da(e,t){return[e,t].toSorted().join(`|`)}function Oa(e,t,n,r){let i=_a(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=va(t,n),s=Ta(a,t,o),c=s.count,l=xa(t,n),u=Ea(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:${Da(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 ka(e,t,n,r,i){let a=_a(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:va(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Aa(e,t){let n=_a(t.config),r=wa(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=va(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 ja(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 Ma(e){return e&&e.trim()||`tool`}function Na(e,t,n){if(!e.execute)return e;let r=Ma(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Oa(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);ja(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}ka(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Aa(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Aa(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Pa(e,t,n){return e.map(e=>Na(e,t,n))}async function Fa(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:l,skills:u,effectivePromptText:d,pluginTools:f},dependencies:{registry:p,spawnFn:m,createModel:h,abortSignal:g}}=e,_=t.channel===`CRON`,v=_?[]:await c(t.dataDir,n,{storeName:t.sessionStoreName}),y={model:t.llm.model,api:`openai-completions`},b=await tr({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName}),x=_?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await nr({entries:v,modelInfo:y,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:g,hooks:r,hookCtx:i,contextManager:b,dataDir:t.dataDir,sessionId:n});await Ia({sessionId:n,historyResult:x,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let S=t.subagentContext?.depth??0,C=[...Fi(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,registry:p,parentSessionId:n,depth:S,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,memory:t.memory,messaging:t.messaging,docs:t.docs,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},contextManager:b,hitlResume:t.hitlResume,spawnFn:m}),...f],w=C.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),T={};for(let e of C){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||T[t]||(T[t]=n)}let E=t.messaging?.enabled??t.channel!==`CRON`,D=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],O=ra({dataDir:t.dataDir,skills:u,contextFiles:s,toolNames:w,toolSummaries:T,promptMode:S>0?`minimal`:`full`,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:E,channels:D},docs:{localPath:t.docs?.localPath,webUrl:t.docs?.webUrl,sourceUrl:t.docs?.sourceUrl},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:ke.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:x.priorSummary}),k=await r.dispatch(`before_prompt_build`,{prompt:d},i,{eventDispatcher:o});for(let e of k)e&&(e.systemPrompt&&(O=e.systemPrompt),e.prependContext&&(O=`${e.prependContext}\n\n${O}`));await r.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:O},i,{eventDispatcher:o});let A=Pa(ma(C,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},et),j=t.llm.model,M=await r.dispatch(`before_model_resolve`,{prompt:d},i,{eventDispatcher:o});for(let e of M)e&&e.modelOverride&&(j=e.modelOverride);let N=h({...t.llm,model:j},n),P=new Oe({initialState:{systemPrompt:O,model:N,tools:A,messages:[]},getApiKey:e=>t.llm.apiKey});return x.messages.length>0&&P.replaceMessages(x.messages),{agent:P,resolvedModelId:j,historyMessages:x.messages,historyResult:x,workspaceDir:a.workspaceDir}}async function Ia(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;await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i}),await r.appendTranscriptEntry(n.compactionEntry),(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})}}async function La(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=new Map,S=da(),C=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Wa(`partial`in t?t.partial:void 0)??Wa(`message`in t?t.message:void 0)??Wa(`message`in e?e.message:void 0),i=Ga(t.delta,n,p);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),m+=i),n&&(p=n,m=n)}if(t.type===`done`){let e=t.message;f=Ua(e);let n=Ga(``,f,m||p);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),m+=n),p=f,m=f,e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ua(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Va(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}));b.push({message:t,toolResults:n}),d&&(await d(za(Ra(t),!!S.signal),n.map(Ba)),S.signal);return}if(e.type===`tool_execution_start`){m=``,x.set(e.toolCallId,e.args),s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=x.get(e.toolCallId);x.delete(e.toolCallId),await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);y=Date.now(),await fa(S,async()=>{await t.prompt(n)});let e=S.signal;if(e)throw e;if(!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Ka(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){if(rr(e))throw e;_=Ka(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{C()}let w=b.length>0?b[b.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:f?[f]:[],lastAssistant:w,usage:{input:h,output:g,total:h+g}},l);let T=b.length>0?Ua(b[b.length-1].message):``;if(S.signal)throw S.signal;return d&&b.length===0&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:T||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}function Ra(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function za(e,t){return!e||!t||e.content.trim()!==`HITL_PAUSED`?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Ba(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function Va(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:Ha(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ha(e){let t=e.indexOf(`
|
|
57
|
+
`)}function Ji(){return[`## Scenes`,'If the user message contains a `<scenes category="..." type="..." skills="...">...</scenes>` tag, treat it as an explicit scene activation request.',"In this tag, `category` means the scene category, `type` means the scene name, and `skills` means the skill list required by that scene.","The `category`, `type`, and `skills` attributes may each contain one or more comma-separated values. You must split them on commas, trim whitespace, and use every requested value.","Before executing the task, you must enumerate every requested `<category, scene, skill>` combination derived from those attributes.","For each requested skill, you must inspect `/scenes/<category>/<scene>/<skill>/` and read that skill's `SKILL.md` with `read_file`.","If one `<scenes ...>` tag requests multiple skills for the same scene, you must load them one by one. Do not stop after the first matching skill.","Do not start implementation, analysis, tool execution, or user-facing conclusions until all required scene `SKILL.md` files have been read.","After reading those scene `SKILL.md` files, you must follow their instructions as mandatory task-specific guidance unless a higher-priority instruction overrides them.","Scene skills are not loaded by default. Only load them when the user explicitly includes the `<scenes ...>` tag.",`Do not ignore, rewrite, or drop the scene tag semantics even if the natural-language request looks answerable without scene skills.`,``].join(`
|
|
58
|
+
`)}function Yi(){return[`## Memory Write`,`When the user asks to remember something or new long-term memory is needed, you must use memory_append. Do not use write_file or edit_file for memory writes.`,``].join(`
|
|
59
|
+
`)}function Xi(e){return[`## Memory Recall`,`Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search on MEMORY.md + memory/*.md; then use memory_get to pull only the needed lines. If low confidence after search, say you checked.`,e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
|
|
60
|
+
`)}function Zi(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`;return[`## Workspace`,`Your cloud working directory is: ${r}`,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, HEARTBEAT.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,``].join(`
|
|
61
|
+
`)}function Qi(e){if(!e?.enabled)return``;let t=[`## Sandbox`,`You are running in a containerized cloud CLI runtime.`];return e.containerWorkspaceDir?.trim()&&t.push(`Container workdir: ${e.containerWorkspaceDir.trim()}`),e.hostWorkspaceDir?.trim()&&t.push(`Host-mounted workspace: ${e.hostWorkspaceDir.trim()}`),t.push(``),t.join(`
|
|
62
|
+
`)}function $i(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=ea(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
|
|
63
|
+
`)}function ea(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(Date.UTC(n,r-1,i));return Number.isNaN(a.getTime())||a.getUTCFullYear()!==n||a.getUTCMonth()!==r-1||a.getUTCDate()!==i?null:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][a.getUTCDay()]}function ta(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools only when the user or system instructions explicitly require subagents, delegation, or parallel agent execution; otherwise stay in the current agent.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
|
|
64
|
+
`)}function na(e){if(e.isMinimal)return``;let t=e.docs,n=[`## Documentation`,t?.localPath?`Cloud docs mount: ${t.localPath}`:``,t?.webUrl?`Docs mirror: ${t.webUrl}`:``,t?.sourceUrl?`Source: ${t.sourceUrl}`:``,`For AiMax behavior, configuration, and architecture questions, consult documentation first.`,``].filter(Boolean);return n.length<=2?``:n.join(`
|
|
65
|
+
`)}function ra(e){if(!e)return``;let t=[e.hostname?`host=${e.hostname}`:``,e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
|
|
66
|
+
`)}function ia(e){return e.isMinimal?``:[`## Silent Replies`,`Do not send empty or filler replies.`,`If a tool already delivered the user-visible output, keep your final reply minimal and avoid duplication.`,``].join(`
|
|
67
|
+
`)}function aa(e){return e.isMinimal?``:[`## Heartbeats`,`Heartbeat prompt: ${e.heartbeatPrompt?.trim()||`Read HEARTBEAT.md if it exists (cloud workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`}`,`If a user message matches the heartbeat prompt and nothing needs attention, reply exactly: HEARTBEAT_OK`,`If something needs attention, do NOT include "HEARTBEAT_OK"; respond with the alert text instead.`,``].join(`
|
|
68
|
+
`)}function oa(e){let t=e.contextFiles,n=(e.bootstrapWarnings??[]).map(e=>e.trim()).filter(Boolean);if(t.length===0&&n.length===0)return``;let r=t.some(e=>(e.path.split(`/`).pop()?.toLowerCase()??``)===`soul.md`),i=[`# Project Context`,``];if(n.length>0){i.push(`⚠ Bootstrap truncation warning:`);for(let e of n)i.push(`- ${e}`);i.push(``)}t.length>0&&(i.push(`The following project context files have been loaded:`),i.push(`These are source-of-truth cloud files at their shown paths. If you update them, use the exact path shown in the heading, especially for files under .aimax.`)),r&&i.push(`If SOUL.md is present, embody its persona and tone. Avoid stiff, generic replies; follow its guidance unless higher-priority instructions override it.`),i.push(``);for(let e of t)i.push(`## ${e.path}`,``,e.content,``);return i.join(`
|
|
69
|
+
`)}function sa(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(`
|
|
70
|
+
`):``}function ca(e){let t=e.promptMode??`full`,n=t===`minimal`;if(t===`none`)return`You are a personal assistant running inside AiMax.`;let r=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Hi],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
|
|
71
|
+
`,Wi({toolNames:r,toolSummaries:e.toolSummaries}),Ki(n),Gi(),qi(i),Ji(),Yi(),Xi(e.memoryCitationsMode??`off`),Zi({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),Qi(e.sandboxInfo),$i({currentDate:e.currentDate,timezone:e.timezone}),ta({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),na({isMinimal:n,docs:e.docs}),ia({isMinimal:n}),aa({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),ra(e.runtimeInfo),oa({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),sa(e.priorConversationSummary)].filter(Boolean).join(`
|
|
72
|
+
`)}const la=new Me;async function ua(e,t){return await la.run(e,t)}function da(e){return{async emit(t){let n=la.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const fa=Symbol(`pluginToolOwner`);var pa=class{tools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,fa,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}list(){return[...this.tools]}namesForPlugin(e){return this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names)}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)}};function ma(e){return e[fa]}const ha=new Me;function ga(){return{}}async function _a(e,t){return await ha.run(e,t)}function va(e){let t=ha.getStore();!t||t.signal||(t.signal=e)}function ya(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=ma(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await ua({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r);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(ar(i)){va(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var ba=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await ua({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const X={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function xa(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Sa(e){let t=xa(e?.warningThreshold,X.warningThreshold),n=xa(e?.criticalThreshold,X.criticalThreshold),r=xa(e?.globalCircuitBreakerThreshold,X.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??X.enabled,historySize:xa(e?.historySize,X.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??X.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??X.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??X.detectors.pingPong}}}function Z(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ca(e,t){return`${e}:${Q(t)}`}function wa(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(wa).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${wa(t[e])}`).join(`,`)}}`}function Ta(e){try{return wa(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 Q(e){let t=Ta(e);return Oe(`sha256`).update(t).digest(`hex`)}function Ea(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Z(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Da(e){return!Z(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Z(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
73
|
+
`).trim()}function Oa(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:wa(e)}function ka(e,t,n,r){if(r!==void 0)return`error:${Q(Oa(r))}`;if(!Z(n))return n===void 0?void 0:Q(n);let i=Z(n.details)?n.details:{},a=Da(n);if(Ea(e,t)&&e===`process`&&Z(t)){let e=t.action;if(e===`poll`)return Q({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Q({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 Q({details:i,text:a})}function Aa(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 ja(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 Ma(e,t){return[e,t].toSorted().join(`|`)}function Na(e,t,n,r){let i=Sa(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Ca(t,n),s=Aa(a,t,o),c=s.count,l=Ea(t,n),u=ja(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:${Ma(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 Pa(e,t,n,r,i){let a=Sa(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Ca(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Fa(e,t){let n=Sa(t.config),r=ka(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Ca(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 Ia(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 La(e){return e&&e.trim()||`tool`}function Ra(e,t,n){if(!e.execute)return e;let r=La(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Na(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ia(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Pa(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Fa(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Fa(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function za(e,t,n){return e.map(e=>Ra(e,t,n))}async function Ba(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:u,effectivePromptText:d,pluginTools:f},dependencies:{registry:p,spawnFn:m,createModel:h,abortSignal:g}}=e,_=t.channel===`CRON`,v=_?[]:await l(t.dataDir,n,{storeName:t.sessionStoreName}),y={model:t.llm.model,api:`openai-completions`},b=await nr({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName}),x=_?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await rr({entries:v,modelInfo:y,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:g,hooks:r,hookCtx:i,contextManager:b,dataDir:t.dataDir,sessionId:n});await Va({sessionId:n,historyResult:x,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let S=t.subagentContext?.depth??0,C=[...Bi(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,registry:p,parentSessionId:n,depth:S,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,memory:t.memory,messaging:t.messaging,docs:t.docs,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},contextManager:b,hitlResume:t.hitlResume,spawnFn:m}),...f],w=C.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),T={};for(let e of C){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||T[t]||(T[t]=n)}let E=t.messaging?.enabled??t.channel!==`CRON`,D=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],O=ca({dataDir:t.dataDir,skills:u,contextFiles:s,toolNames:w,toolSummaries:T,promptMode:S>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:E,channels:D},docs:{localPath:t.docs?.localPath,webUrl:t.docs?.webUrl,sourceUrl:t.docs?.sourceUrl},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Ae.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:x.priorSummary}),k=await r.dispatch(`before_prompt_build`,{prompt:d},i,{eventDispatcher:o});for(let e of k)e&&(e.systemPrompt&&(O=e.systemPrompt),e.prependContext&&(O=`${e.prependContext}\n\n${O}`));await r.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:O},i,{eventDispatcher:o});let A=za(ya(C,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},tt),j=t.llm.model,M=await r.dispatch(`before_model_resolve`,{prompt:d},i,{eventDispatcher:o});for(let e of M)e&&e.modelOverride&&(j=e.modelOverride);let N=h({...t.llm,model:j},n),P=new ke({initialState:{systemPrompt:O,model:N,tools:A,messages:[]},getApiKey:e=>t.llm.apiKey});return x.messages.length>0&&P.replaceMessages(x.messages),{agent:P,resolvedModelId:j,historyMessages:x.messages,historyResult:x,workspaceDir:a.workspaceDir}}async function Va(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;await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i}),await r.appendTranscriptEntry(n.compactionEntry),(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})}}async function Ha(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=new Map,S=ga(),C=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Ya(`partial`in t?t.partial:void 0)??Ya(`message`in t?t.message:void 0)??Ya(`message`in e?e.message:void 0),i=Xa(t.delta,n,p);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),m+=i),n&&(p=n,m=n)}if(t.type===`done`){let e=t.message;f=Ja(e);let n=Xa(``,f,m||p);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),m+=n),p=f,m=f,e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ja(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Ka(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}));b.push({message:t,toolResults:n}),d&&(await d(Wa(Ua(t),!!S.signal),n.map(Ga)),S.signal);return}if(e.type===`tool_execution_start`){m=``,x.set(e.toolCallId,e.args),s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=x.get(e.toolCallId);x.delete(e.toolCallId),await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);y=Date.now(),await _a(S,async()=>{await t.prompt(n)});let e=S.signal;if(e)throw e;if(!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Za(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){if(ar(e))throw e;_=Za(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{C()}let w=b.length>0?b[b.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:f?[f]:[],lastAssistant:w,usage:{input:h,output:g,total:h+g}},l);let T=b.length>0?Ja(b[b.length-1].message):``;if(S.signal)throw S.signal;return d&&b.length===0&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:T||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}function Ua(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function Wa(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Ga(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function Ka(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:qa(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function qa(e){let t=e.indexOf(`
|
|
71
74
|
Preview:
|
|
72
|
-
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function
|
|
75
|
+
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Ja(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ya(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function Xa(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Za(e){let t=Qa(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function Qa(e){if(e instanceof H)return e;if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function $a(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,skillUsageTracker:o,hookRegistry:s,hookContext:c,abortSignal:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!l?.aborted&&n.needsAnnounce(r)&&d<10;){d++,await n.waitForAll(r);let e=n.consumeCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=eo(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Ha({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,skillUsageTracker:o,hooks:s,hookCtx:c,abortSignal: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)}return{text:f,inputTokens:p,outputTokens:m,error:h}}function eo(e){if(e.length===1){let t=e[0];return Mi({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Mi({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
|
|
73
76
|
|
|
74
77
|
---
|
|
75
78
|
|
|
76
|
-
`)}`}function Xa(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 Za(e){let t=Xa(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=I.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 Qa(e){let t=e.watchFactory??((e,t,n)=>B.watch(e,t,n)),n=I.join(e.dataDir,`.aimax`),r=[{target:I.join(n,`MEMORY.md`),kind:`memory-file`},{target:I.join(n,`memory.md`),kind:`memory-file-lower`},{target:I.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=Za({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 $a(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=I.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),o=no(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)l.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(c)??0)<1e3)return;u.set(c,t);let d={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:d.reason,files:d.files,source:d.source,providerId:d.providerId,timestamp:d.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,d,{...a,sessionId:d.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=I.join(t.dataDir,`.aimax`),m=O({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName})?.provider??v({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=Qa({dataDir:t.dataDir,sessionId:i,providerId:o??s??m.id,provider:m,onMemoryChanged:f});m.sync&&m.sync(`session-start`).catch(()=>{});let _=async e=>{await g(t.dataDir,i,e,to({sessionStoreName:t.sessionStoreName,providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:_,persistInitialUserEntry:async e=>d?!1:(await _({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{h()}}}function eo(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function to(e){return e.sessionStoreName||e.providerId||e.pluginId?{storeName:e.sessionStoreName,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function no(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 ro(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function io(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function ao(){let e=ke.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function oo(e){let t=e.trim(),n=ao();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?I.join(n,t.slice(2)):void 0:I.resolve(t)}const so=new Me({allErrors:!0,strict:!1}),co=new Map;function lo(e,t){let n=co.get(t);if(n)return n;let r=so.compile(e);return co.set(t,r),r}function uo(e){let t=e.cacheKey??JSON.stringify(e.schema),n=lo(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function fo(e){let t=io(e?.allow),n=io(e?.deny),r=io(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 po(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=uo({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 mo(e){try{return B.realpathSync(e)}catch{return null}}function ho(e){try{return B.statSync(e)}catch{return null}}function go(e,t){let n=I.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!I.isAbsolute(n)}function _o(e){return`0o${e.toString(8).padStart(3,`0`)}`}const vo=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),yo=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function bo(e){let t=I.join(e,`package.json`);if(B.existsSync(t))try{let e=JSON.parse(B.readFileSync(t,`utf-8`));return ro(e)?e:void 0}catch{return}}function xo(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 So(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Co(e){let t=mo(e.source),n=mo(e.rootDir);return!t||!n||go(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function wo(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=I.resolve(r);if(n.has(t))continue;n.add(t);let i=ho(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 To(e){return Co({source:e.source,rootDir:e.rootDir})||wo({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:So(e.ownershipUid)})}function Eo(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=${_o(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Do(e){let t=To({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Eo(t),source:e.source}),!0):!1}function Oo(e){return I.basename(e,I.extname(e))}function ko(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 Ao(e){for(let t of yo){let n=I.join(e,t);if(B.existsSync(n))return n}return null}function jo(e){let t;try{t=B.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=I.join(e.rootDir,n.name);if(n.isFile()){if(!vo.has(I.extname(n.name)))continue;let r=I.dirname(t);if(Do({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(ko({idHint:Oo(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=bo(t),i=xo(r);if(i.status===`ok`){for(let n of i.entries){let i=I.resolve(t,n);if(!go(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!B.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!vo.has(I.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Do({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Oo(i)}`:Oo(i);e.candidates.push(ko({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=Ao(t);a&&(Do({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(ko({idHint:I.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Mo(e){return e?e.map(oo).filter(e=>typeof e==`string`&&e.length>0):[]}function No(){let e=ao();if(e)return I.join(e,`.aimax`,`extensions`)}function Po(e){return I.join(e,`.aimax`,`extensions`)}function Fo(e){return I.join(e,`.aimax`,`extensions`)}function Io(e={}){let t=[],n=[],r=Mo(e.extraPaths);for(let i of r){if(!B.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=ho(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!vo.has(I.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=I.dirname(i);if(Do({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(ko({idHint:Oo(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&jo({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?jo({rootDir:Po(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&jo({rootDir:Fo(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=No();return i?jo({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&&jo({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Lo(e){let t=e.rejectHardlinks??!0,n=mo(e.rootPath),r=mo(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!go(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=B.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:B.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ro=`aimax.plugin.json`,zo=[Ro];function Bo(e){for(let t of zo){let n=I.join(e,t);if(B.existsSync(n))return n}return I.join(e,Ro)}function Vo(e,t=!0){let n=Bo(e),r=Lo({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(B.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{B.closeSync(r.fd)}if(!ro(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=ro(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=io(i.skills),f;return ro(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 Ho(e){let t=new Map,n=[];for(let r of e){let e=Vo(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 Uo=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Wo(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Go(e,t,n,r){process.stderr.write(`[${Wo()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Ko(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Go(Uo.INFO,e.pluginId,t,n),warn:n=>Go(Uo.WARN,e.pluginId,t,n),error:n=>Go(Uo.ERROR,e.pluginId,t,n)})}}}function qo(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 Jo(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 Yo(e){let t=[...e.registry.diagnostics],n=new ca,r=new ha,i=[],a=[],o=e.runtime?.llm?at({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Xo(e.runtime?.llmAllowlist),c=Ne(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=qo({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Jo({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,h=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!h){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 g=Ko({pluginId:l.id}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Zo(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},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);m({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);k({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=I.isAbsolute(e)?e:I.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>oa(l.id)};try{h(v)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=I.isAbsolute(e)?e:I.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Xo(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Zo(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Qo(e={}){let t=fo(e.config),n=Io({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Ho(n.candidates),i=po({config:t,registry:r}),a=Yo({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 $o(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Qo({...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 ha,pluginSkillDirs:o?.registry.skills??[],pluginTools:o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function es(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=I.join(t.dataDir,`workspace`),a=n,o=!a;a?await b(t.dataDir,a,{storeName:t.sessionStoreName}):a=await d(t.dataDir,t.channel,{storeName:t.sessionStoreName});let s={sessionId:a,workspaceDir:i,channel:t.channel},c=$o({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),l=c.hookRegistry,u=await $a({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:l});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:l,pluginContext:c,runContext:u,start:e=>Bt({sessionId:a,runParams:t,hookRegistry:l,hookContext:s,eventDispatcher:r,...e})}}function ts(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ns(e){if(!(e instanceof Error))return{errorValue:ts(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]=ts(n[e]));return t}async function rs(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ns(e.error)}})}function is(e,t,n){return I.join(T(e,t,n),`pending-hitl.json`)}function as(e,t,n){return I.join(T(e,t,n),`hitl-history.jsonl`)}async function os(e,t,n,r){let i=T(e,t,r);await F.mkdir(i,{recursive:!0});let a=is(e,t,r);await F.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function ss(e,t,n,r){let i=T(e,t,r);await F.mkdir(i,{recursive:!0});let a=as(e,t,r),o=JSON.stringify(n)+`
|
|
77
|
-
`;await F.appendFile(a,
|
|
78
|
-
`)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function
|
|
79
|
+
`)}`}function to(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 no(e){let t=to(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=I.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 ro(e){let t=e.watchFactory??((e,t,n)=>B.watch(e,t,n)),n=I.join(e.dataDir,`.aimax`),r=[{target:I.join(n,`MEMORY.md`),kind:`memory-file`},{target:I.join(n,`memory.md`),kind:`memory-file-lower`},{target:I.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=no({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 io(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=I.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),o=so(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)l.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(c)??0)<1e3)return;u.set(c,t);let d={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:d.reason,files:d.files,source:d.source,providerId:d.providerId,timestamp:d.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,d,{...a,sessionId:d.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=I.join(t.dataDir,`.aimax`),m=k({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName})?.provider??y({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=ro({dataDir:t.dataDir,sessionId:i,providerId:o??s??m.id,provider:m,onMemoryChanged:f});m.sync&&m.sync(`session-start`).catch(()=>{});let g=async e=>{await _(t.dataDir,i,e,oo({sessionStoreName:t.sessionStoreName,providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:g,persistInitialUserEntry:async e=>d?!1:(await g({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{h()}}}function ao(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function oo(e){return e.sessionStoreName||e.providerId||e.pluginId?{storeName:e.sessionStoreName,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function so(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 co(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lo(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function uo(){let e=Ae.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function fo(e){let t=e.trim(),n=uo();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?I.join(n,t.slice(2)):void 0:I.resolve(t)}const po=new Ne({allErrors:!0,strict:!1}),mo=new Map;function ho(e,t){let n=mo.get(t);if(n)return n;let r=po.compile(e);return mo.set(t,r),r}function go(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ho(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function _o(e){let t=lo(e?.allow),n=lo(e?.deny),r=lo(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 vo(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=go({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 yo(e){try{return B.realpathSync(e)}catch{return null}}function bo(e){try{return B.statSync(e)}catch{return null}}function xo(e,t){let n=I.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!I.isAbsolute(n)}function So(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Co=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),wo=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function To(e){let t=I.join(e,`package.json`);if(B.existsSync(t))try{let e=JSON.parse(B.readFileSync(t,`utf-8`));return co(e)?e:void 0}catch{return}}function Eo(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 Do(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Oo(e){let t=yo(e.source),n=yo(e.rootDir);return!t||!n||xo(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function ko(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=I.resolve(r);if(n.has(t))continue;n.add(t);let i=bo(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 Ao(e){return Oo({source:e.source,rootDir:e.rootDir})||ko({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Do(e.ownershipUid)})}function jo(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=${So(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Mo(e){let t=Ao({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:jo(t),source:e.source}),!0):!1}function No(e){return I.basename(e,I.extname(e))}function Po(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 Fo(e){for(let t of wo){let n=I.join(e,t);if(B.existsSync(n))return n}return null}function Io(e){let t;try{t=B.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=I.join(e.rootDir,n.name);if(n.isFile()){if(!Co.has(I.extname(n.name)))continue;let r=I.dirname(t);if(Mo({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Po({idHint:No(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=To(t),i=Eo(r);if(i.status===`ok`){for(let n of i.entries){let i=I.resolve(t,n);if(!xo(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!B.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Co.has(I.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Mo({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${No(i)}`:No(i);e.candidates.push(Po({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=Fo(t);a&&(Mo({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Po({idHint:I.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Lo(e){return e?e.map(fo).filter(e=>typeof e==`string`&&e.length>0):[]}function Ro(){let e=uo();if(e)return I.join(e,`.aimax`,`extensions`)}function zo(e){return I.join(e,`.aimax`,`extensions`)}function Bo(e){return I.join(e,`.aimax`,`extensions`)}function Vo(e={}){let t=[],n=[],r=Lo(e.extraPaths);for(let i of r){if(!B.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=bo(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Co.has(I.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=I.dirname(i);if(Mo({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Po({idHint:No(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Io({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Io({rootDir:zo(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Io({rootDir:Bo(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Ro();return i?Io({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&&Io({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Ho(e){let t=e.rejectHardlinks??!0,n=yo(e.rootPath),r=yo(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!xo(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=B.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:B.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Uo=`aimax.plugin.json`,Wo=[Uo];function Go(e){for(let t of Wo){let n=I.join(e,t);if(B.existsSync(n))return n}return I.join(e,Uo)}function Ko(e,t=!0){let n=Go(e),r=Ho({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(B.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{B.closeSync(r.fd)}if(!co(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=co(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=lo(i.skills),f;return co(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 qo(e){let t=new Map,n=[];for(let r of e){let e=Ko(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 Jo=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Yo(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Xo(e,t,n,r){process.stderr.write(`[${Yo()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Zo(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Xo(Jo.INFO,e.pluginId,t,n),warn:n=>Xo(Jo.WARN,e.pluginId,t,n),error:n=>Xo(Jo.ERROR,e.pluginId,t,n)})}}}function Qo(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 $o(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 es(e){let t=[...e.registry.diagnostics],n=new pa,r=new ba,i=[],a=[],o=e.runtime?.llm?ot({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=ts(e.runtime?.llmAllowlist),c=Pe(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Qo({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=$o({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 g=Zo({pluginId:l.id}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!ns(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},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);h({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);A({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=I.isAbsolute(e)?e:I.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>da(l.id)};try{m(v)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=I.isAbsolute(e)?e:I.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function ts(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function ns(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function rs(e={}){let t=_o(e.config),n=Vo({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=qo(n.candidates),i=vo({config:t,registry:r}),a=es({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 is(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?rs({...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 ba,pluginSkillDirs:o?.registry.skills??[],pluginTools:o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function as(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=I.join(t.dataDir,`workspace`),a=n,o=!a;a?await x(t.dataDir,a,{storeName:t.sessionStoreName}):a=await f(t.dataDir,t.channel,{storeName:t.sessionStoreName});let s={sessionId:a,workspaceDir:i,channel:t.channel},c=is({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),l=c.hookRegistry,u=await io({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:l});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:l,pluginContext:c,runContext:u,start:e=>Vt({sessionId:a,runParams:t,hookRegistry:l,hookContext:s,eventDispatcher:r,...e})}}function os(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ss(e){if(!(e instanceof Error))return{errorValue:os(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]=os(n[e]));return t}async function cs(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ss(e.error)}})}function ls(e,t,n){return I.join(o(e,t,n),`pending-hitl.json`)}function us(e,t,n){return I.join(o(e,t,n),`hitl-history.jsonl`)}async function ds(e,t,n,r){let i=o(e,t,r);await F.mkdir(i,{recursive:!0});let a=ls(e,t,r);await F.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function fs(e,t,n,r){let i=o(e,t,r);await F.mkdir(i,{recursive:!0});let a=us(e,t,r),s=JSON.stringify(n)+`
|
|
80
|
+
`;await F.appendFile(a,s,`utf-8`)}async function ps(e,t,n){let r=ls(e,t,n);try{let e=await F.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ms(e,t,n){let r=us(e,t,n);try{let e=await F.readFile(r,`utf-8`),t=[];for(let n of e.split(`
|
|
81
|
+
`)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function hs(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await ds(e,t,c,o),await fs(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function gs(e,t,n,r,i,a){let o=await ps(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await ds(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await fs(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function _s(e,t,n,r){let i=await ps(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function vs(e,t,n){let r=ls(e,t,n);try{await F.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function ys(e,t){return{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:{"Client-Code":`AIMax`,"X-Session-Id":t},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}async function bs(e,t){Ft();let n=Date.now(),r=new It(e),i=xn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await as({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,m=c.pluginContext,h=c.runContext;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}}),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 E(e.dataDir,ao({sessionId:l,title:Bt(a),channel:e.channel}),{storeName:e.sessionStoreName}),i.resetCommand&&!e.hitlResume&&(o=await h.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let g=new AbortController;e.abortSignal?.aborted?g.abort():e.abortSignal?.addEventListener(`abort`,()=>g.abort());let _=await ze(e.dataDir),v=[],y=He(_,{warn:e=>v.push(e)});await r.dispatchDiagnostic(l,{level:v.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length}});let b=await Je(e.dataDir,m.pluginSkillDirs),x=new at({workspaceDir:d,sessionId:l,skills:b,report:e=>r.dispatchProgress(l,e),reportDiagnostic:e=>r.dispatchDiagnostic(l,{level:e.level,scope:`skill`,phase:e.phase,message:e.message,details:e.details})});await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:b.length,pluginSkillDirCount:m.pluginSkillDirs.length}});let S=e=>h.appendTranscriptEntry(e),C=await Cn({invocation:i,skills:b,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(C.kind===`completed`)return C.result;let w=C.effectivePrompt;a=C.transcriptMessage;let T=typeof w==`string`?w:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof w==`string`?`string`:`messages`,transcriptLength:a.length}});let D=await Ba({session:{runParams:e,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:b,effectivePromptText:T,pluginTools:m.pluginTools},dependencies:{registry:t,spawnFn:e=>bs(e,new $e),createModel:ys,abortSignal:g.signal}}),O=D.agent,k=D.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:k,historyMessageCount:D.historyMessages.length,pluginToolCount:m.pluginTools.length}}),g.signal.addEventListener(`abort`,()=>O.abort());let A=0,j=0,M=``,N;try{e.hitlResume||(o=await h.persistInitialUserEntry(a)||o),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let n=await Ha({agent:O,message:w,sessionId:l,modelId:k,historyMessages:D.historyMessages,eventDispatcher:r,skillUsageTracker:x,hooks:p,hookCtx:f,abortSignal:g.signal,onTurnRecordProduced:async(e,t)=>{e&&await S(e);for(let e of t)await S(e)}});M=n.text,A+=n.inputTokens,j+=n.outputTokens,n.error&&(N=n.error),await r.dispatchDiagnostic(l,{level:n.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let i=await $a({agent:O,registry:t,sessionId:l,resolvedModelId:k,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});i.text&&(M=i.text),A+=i.inputTokens,j+=i.outputTokens,i.error&&!N&&(N=i.error),await r.dispatchDiagnostic(l,{level:i.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!i.error,error:i.error,inputTokens:i.inputTokens,outputTokens:i.outputTokens}})}catch(t){if(ar(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await hs(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}});let c={input:A,output:j,total:A+j};return Wt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}throw await cs({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),t}finally{nt(l),h.stop()}let P={input:A,output:j,total:A+j};return await r.dispatchDiagnostic(l,{level:N?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:P.input,outputTokens:P.output,totalTokens:P.total,hasError:!!N,error:N}}),Wt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M,usage:P,error:N})}async function xs(e,t){let n=t??new $e;try{return await bs(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:ss(t)}),t}}const Ss={"AGENTS.md":`---
|
|
79
82
|
title: "AGENTS.md Template"
|
|
80
83
|
summary: ".aimax template for AGENTS.md"
|
|
81
84
|
read_when:
|
|
@@ -382,4 +385,4 @@ read_when:
|
|
|
382
385
|
# Add tasks below when you want the agent to check something periodically.
|
|
383
386
|
|
|
384
387
|
# This file lives at .aimax/HEARTBEAT.md, not in workspace/.
|
|
385
|
-
`},
|
|
388
|
+
`},Cs=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await F.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 F.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function ws(e,t,n){try{if(!(await F.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 F.mkdir(I.dirname(e),{recursive:!0});try{await F.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 Ts(e){let t=V(e);return[e,t,I.join(t,`skills`),I.join(t,`sessions`),I.join(t,`memory`),I.join(e,`workspace`)]}function Es(e){let t=V(e);return[...Cs.filter(e=>e!==`BOOTSTRAP.md`).map(e=>I.join(t,e)),I.join(t,`MEMORY.md`)]}function Ds(e){return I.join(V(e),`.bootstrapped`)}async function Os(e){try{return(await F.stat(Ds(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function ks(e){let t=Ds(e);await F.mkdir(I.dirname(t),{recursive:!0}),await F.writeFile(t,``,{encoding:`utf-8`})}async function As(e){let t=[],n=[];for(let n of Ts(e))try{(await F.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Es(e))try{(await F.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 js(e){return(await As(e)).ready}async function Ms(e){if(await Os(e))return{ready:!0,performedBootstrap:!1};if((await As(e)).ready)return await ks(e),{ready:!0,performedBootstrap:!1};let t=await Ns(e);return await ks(e),{ready:!0,performedBootstrap:!0,result:t}}async function Ns(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=V(e),r=I.join(e,`workspace`),i=I.join(n,`skills`),a=I.join(n,`sessions`),o=I.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 Cs){let r=Ss[e]??``;await ws(I.join(n,e),r,t)}return await ws(I.join(n,`MEMORY.md`),``,t),t}async function Ps(e){let t=I.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await F.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 Fs(e,t){let n=I.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 F.mkdir(I.dirname(n),{recursive:!0}),await F.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Is(e,t){let n=await Ps(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 Ls(e,t=7){let n=await Ps(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 Fs(e,n),i}async function Rs(e,t,n,r){let i=await ps(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Fe(i.request)?(await gs(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 zs(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await _s(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 Rs(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await gs(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}}export{Re as BOOTSTRAP_FILE_NAMES,Ie as BOOTSTRAP_MAX_CHARS,Le as BOOTSTRAP_TOTAL_MAX_CHARS,u as DEFAULT_SESSION_STORE_NAME,Y as HITL_MESSAGES,ir as HitlPauseSignal,Qe as MAX_CHILDREN_PER_SESSION,Ze as MAX_SUBAGENT_DEPTH,S as MemoryIndexManager,Uo as PLUGIN_MANIFEST_FILENAME,Wo as PLUGIN_MANIFEST_FILENAMES,ba as PluginHookRegistry,pa as PluginToolRegistry,$e as SubagentRegistry,de as addAgent,se as addBinding,V as aimaxDir,_i as appendToMemory,_ as appendTranscriptEntry,ii as approvalSummaryFromResolution,Ns as bootstrapMountLayout,He as buildBootstrapContextFiles,ai as buildResumeNarration,Xe as buildSkillsPrompt,Mi as buildSubagentAnnounceMessage,ca as buildSystemPrompt,Ls as cleanupOldSubagentRecords,vs as clearPendingHitl,w as collapseLogPath,d as contextSnapshotPath,Bi as createAgentTools,Kr as createApplyPatchTool,kr as createBashTool,y as createBuiltinMemoryProvider,si as createClarifyTool,nr as createContextManager,Rr as createEditFileTool,hr as createExecTool,zi as createImageTool,Br as createListDirTool,Ti as createMemoryAppendTool,Ci as createMemoryGetTool,xi as createMemorySearchTool,hs as createPendingHitl,da as createPluginProgressEmitter,Zo as createPluginRuntime,yr as createProcessTool,Pr as createReadFileTool,Oi as createRequestApprovalTool,Ai as createRequestReviewTool,f as createSession,Pn as createSessionContextStore,Ni as createSessionsSpawnTool,Li as createSubagentsTool,Ir as createWriteFileTool,yi as deleteMemoryFile,Vo as discoverAIMaxPlugins,Ms as ensureBootstrapMountLayout,x as ensureSession,v as exportSession,Di as formatApprovalResolution,Rt as generateSessionTitle,ie as getAgentConfig,gi as getMemoryLines,Os as hasBootstrapSentinel,us as hitlHistoryPath,rs as initializePluginSystem,As as inspectBootstrapMountLayout,m as inspectSession,js as isBootstrapMountLayoutReady,ar as isHitlPauseSignal,N as listAgents,Yt as listAvailableSlashCommands,ce as listBindings,fi as listMemoryFiles,p as listSessionSummaries,s as listSessions,Is as listSubagentRunsFromDisk,ue as loadAgentsConfig,ze as loadBootstrapFiles,ps as loadPendingHitl,ps as readPendingHitl,Ko as loadPluginManifest,qo as loadPluginManifestRegistry,es as loadPlugins,T as loadSessionContextSnapshot,O as loadSessionMetadata,qe as loadSkills,Ye as loadSkillsFromDirs,Je as loadSkillsWithPluginDirs,Ps as loadSubagentRegistryFromDisk,l as loadTranscript,ci as memoryDir,D as metadataPath,P as normalizeAgentId,_o as normalizePluginsConfig,a as normalizeSessionStoreName,ls as pendingHitlPath,li as primaryMemoryPath,ms as readHitlHistory,pi as readMemoryFile,mi as readPrimaryMemory,h as registerEmbeddingProvider,A as registerMemoryProvider,ae as removeAgent,fe as removeBindings,vi as replaceMemoryFile,c as resetEmbeddingProviderRegistryForTests,j as resetMemoryProviderRegistryForTests,ee as resolveAgentDir,te as resolveAgentIdByBinding,le as resolveAgentsConfigPath,oe as resolveDefaultAgentId,b as resolveEmbeddingProvider,zs as resolveHitlRequest,zs as resolvePendingHitl,k as resolveMemoryProvider,re as resolveModelFallbacks,ne as resolveModelString,Go as resolvePluginManifestPath,t as rewriteTranscript,xs as runAgent,M as saveAgentsConfig,E as saveSessionMetadata,Fs as saveSubagentRegistryToDisk,hi as searchMemory,o as sessionDir,r as sessionMemoryPath,n as sessionsDir,Ue as skillsDir,i as toolResultsDir,g as transcriptPath,gs as transitionHitlStatus,pe as updateAgentIdentity,e as updateSessionMetadata,vo as validatePluginsConfig,Rs as validateResume,ya as wrapToolsWithHooks};
|