aws-runtime-bridge 1.9.141 → 1.9.142

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.
@@ -1,21 +1,21 @@
1
- import{EventEmitter as Ve}from"node:events";import{randomUUID as Xe}from"node:crypto";import F from"node:fs";import Ze from"node:os";import H from"node:path";import{Client as et}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as tt}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as ot}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as st}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as nt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as it,DEFAULT_TOOL_PERMISSION_POLICY as Ae}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as rt,createAskUserQuestionTool as at}from"./ask-user-question-tool.js";import{createSkillTool as lt}from"./skill-tool.js";import{createTodoWriteTool as ct,createTodoReadTool as ut}from"./todo-tool.js";import{createSubAgentTools as mt}from"./sub-agent-tools.js";import{createAwaitCompleteTool as dt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as ht}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as X}from"./background-command-manager.js";import{createTerminalTool as pt}from"./terminal-tool.js";import{buildPluginPrompt as ft,createPluginTools as gt}from"./plugin-tools.js";import{loadAcodeCommands as Tt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as Ce}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as yt,COMPACTION_LLM_PROMPT_TEMPLATE as At,conversationSizeKB as Z,estimateConversationTokens as se,performCompaction as _e,pruneToolOutputs as Ct,summarizeConversation as be}from"./compaction.js";import{loadAcodeConfig as _t,loadAcodeSkillGroup as bt}from"./config.js";import{ACodeHookBus as wt,findDeniedHookResult as ue}from"./hooks/hookBus.js";import{isMcpPollingToolName as $t,isMcpBlockingToolName as kt,getSemanticToolName as we}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as D}from"./meeting-debug-log.js";import{buildToolCatalog as $e,matchesToolAllocation as ke,mergeAllocatableTools as ne,PRESET_EXPLORE as St,rebindDefaultAgentId as Se,resolveToolAllocation as Mt,SUB_AGENT_ALLOWED_MCP_TOOLS as vt}from"./tool-allocation.js";function Rt(s){if(typeof s!="object"||s===null)return!1;const e=s;return e.kind==="builtin"&&typeof e.toolName=="string"&&typeof e.exposedName=="string"&&typeof e.description=="string"&&typeof e.execute=="function"&&typeof e.inputSchema=="object"&&e.inputSchema!==null}function xt(s){return s.type==="text"?{type:"text",text:s.text}:{type:"image_url",image_url:{url:s.image_url.url}}}function Et(s){return{id:s.id,type:"function",function:{name:s.function.name,arguments:s.function.arguments}}}function Nt(s){const e={role:s.role,content:Array.isArray(s.content)?s.content.map(xt):s.content};return s.tool_call_id&&(e.tool_call_id=s.tool_call_id),s.tool_calls&&(e.tool_calls=s.tool_calls.map(Et)),e}function me(s){return s.map(Nt)}function It(s,e){const t=q(s.prompt_cache_hit_tokens),o=q(s.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const n=q(s.cache_read_input_tokens),a=q(s.cache_creation_input_tokens);if(n!==void 0||a!==void 0){const c=q(s.input_tokens)??0;return{cacheHitTokens:n??0,cacheMissTokens:(a??0)+c}}const i=q(s.cache_hit_tokens),l=q(s.cache_miss_tokens);if(i!==void 0||l!==void 0)return{cacheHitTokens:i??0,cacheMissTokens:l??0};const r=q(s.prompt_tokens_details?.cached_tokens);if(r!==void 0){const c=e!==void 0?Math.max(0,e-r):0;return{cacheHitTokens:r,cacheMissTokens:c}}}function q(s){const e=typeof s=="number"?s:typeof s=="string"&&s.trim()?Number(s):NaN;if(!(!Number.isFinite(e)||e<0))return e}function Pt(s,e){if(!s)return e;const t=o=>{const n=e[o],a=s[o];return o==="prompt_tokens_details"?{...a,...n}:n??a};return{prompt_tokens:t("prompt_tokens"),completion_tokens:t("completion_tokens"),input_tokens:t("input_tokens"),output_tokens:t("output_tokens"),prompt_cache_hit_tokens:t("prompt_cache_hit_tokens"),prompt_cache_miss_tokens:t("prompt_cache_miss_tokens"),cache_read_input_tokens:t("cache_read_input_tokens"),cache_creation_input_tokens:t("cache_creation_input_tokens"),cache_hit_tokens:t("cache_hit_tokens"),cache_miss_tokens:t("cache_miss_tokens"),prompt_tokens_details:t("prompt_tokens_details")}}function Dt(){return new Date().toISOString()}function v(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function Me(s){return v(s)}function ve(s,e){return e.map(t=>({serverName:s,toolName:t.name,kind:"mcp",exposedName:wo(s,t.name),description:t.description,inputSchema:Me(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function N(s){return String(s??"").trim()||void 0}const Re=6e4,xe=30*6e4,Ee=6e4,Ne=6e4,ie=-1,Ie=ie,Lt=1e3,Ot=3e4,re=6e4,Pe=0,Ut=2147483647,Bt=10*6e4+2e3,qt=1e4,ae=5e3,De=10*60*1e3,K=10*1024*1024,Le=800*1024,le=process.env.ACODE_COMPACTION_DEBUG==="1",Oe=le?H.join(Ze.tmpdir(),"acode-compaction-debug.log"):"";function u(...s){le&&console.log(...s)}const Ft=process.env.ACODE_TOKEN_DEBUG==="1";function G(...s){Ft&&console.log("[TokenDebug][Runtime]",...s)}const zt=64e3;function de(s){const e=s.contextLimit&&s.contextLimit>0?s.contextLimit:zt,t=s.maxOutput&&s.maxOutput>0?s.maxOutput:8192,o=s.inputLimit&&s.inputLimit>0?s.inputLimit:void 0,n=yt(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:n}}async function x(s,e,t,o){if(e<=0)return await s;let n;try{return await new Promise((a,i)=>{n=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),s.then(a,i)})}finally{n&&clearTimeout(n)}}async function ee(s,e,t,o=qt){try{await x(e,o,s)}catch(n){t(n instanceof Error?n.message:String(n))}}function Q(s,e){if(s===0||s==="0")return 0;const t=typeof s=="number"?s:Number(s);return t===ie?ie:Number.isFinite(t)&&t>0?Math.floor(t):e}function te(s,e){const t=Q(s,e);return t>0?t:e}const Ue=3;function he(s){return s?Math.ceil(s.length/Ue):0}function jt(s,e){let t=s.length;for(const o of e){const n=(o.kind==="mcp",o.toolName);if(t+=n.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const a=o;a.inputSchema&&(t+=JSON.stringify(a.inputSchema).length)}}return Math.ceil(t/Ue)}function Be(s){if(s.length===0)return 0;const e=JSON.stringify(Ke(s));return he(e)}async function Wt(s){await new Promise(e=>setTimeout(e,s))}function Jt(s){return typeof s=="boolean"}function Ht(s,e,t){if(Jt(t?.supportsImageInput))return t.supportsImageInput;const o=v(e)?e.models:void 0,n=v(o)?o[s]:void 0;if(!v(n))return!1;const a=n.modalities;return!v(a)||!Array.isArray(a.input)?!1:a.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function pe(s,e,t,o){if(s!==void 0)return s;if(!e)return;const n=e.models;if(v(n)){const a=n[t];if(v(a)){const i=a[o];if(i!==void 0)return i}}return e[o]}function Kt(s,e){const t=e.provider?.default,o=t?.options,n=s.model||t?.model||e.model||"acode-default",a=N(s.effort)||N(o?.effort)||N(t?.effort)||void 0;return{model:n,baseURL:N(o?.baseURL||o?.baseUrl),apiKey:N(o?.apiKey),effort:a,systemPrompt:s.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:te(o?.requestTimeoutMs??o?.timeoutMs,Re),requestTotalTimeoutMs:te(o?.requestTotalTimeoutMs,xe),requestRetryCount:Q(o?.requestRetryCount,Ie),requestFirstByteTimeoutMs:te(o?.requestFirstByteTimeoutMs,Ee),requestStreamIdleTimeoutMs:te(o?.requestStreamIdleTimeoutMs,Ne),mcpToolTimeoutMs:te(o?.mcpToolTimeoutMs,re),mcpPollingToolTimeoutMs:Q(o?.mcpPollingToolTimeoutMs,Pe),supportsImageInput:Ht(n,t,o),contextLimit:Q(pe(o?.contextLimit,t,n,"contextLimit"),0)||void 0,inputLimit:Q(pe(o?.inputLimit,t,n,"inputLimit"),0)||void 0,maxOutput:Q(pe(o?.maxOutput,t,n,"maxOutput"),0)||void 0}}function z(s,e){const t=e.replace(/\s+/g," ").trim();t&&s.push({type:"text",text:t})}function Gt(s,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${s||"image/png"};base64,${t}`}function Qt(s){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(s.trim())}function Yt(s){let e;try{e=new URL(s)}catch{throw new Error(`ACode image URL is invalid: ${s}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`ACode image URL protocol is not supported: ${e.protocol}`)}async function Vt(s){const e=await s.arrayBuffer();if(e.byteLength>K)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${K} bytes`);return Buffer.from(e).toString("base64")}async function Xt(s){const e=s.trim();if(Qt(e)){if(e.slice(e.indexOf(",")+1).length*.75>K)throw new Error(`ACode inline image exceeds the ${K} byte size limit`);return e}Yt(e);const t=await fetch(e);if(!t.ok)throw new Error(`ACode image fetch failed: ${t.status} ${await t.text()}`);const o=t.headers.get("content-type")||"",n=o.split(";")[0]?.trim().toLowerCase()||"";if(!n.startsWith("image/"))throw new Error(`ACode image URL did not return an image content type: ${o||"unknown"}`);return`data:${n};base64,${await Vt(t)}`}function Zt(s){const e=N(s.base64Data??s.base64??s.data);return e?e.length*.75>K?void 0:Gt(N(s.mediaType??s.mimeType)||"image/png",e):N(s.url??s.serverUrl)}function qe(s,e,t,o){return`[Attached file: ${[s?`name=${s}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(a=>!!a).join(", ")}]`}function eo(s){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,n=0,a=e.exec(s);for(;a!==null;){z(t,s.slice(n,a.index));const i=a[1],l=(a[2]||"").trim();if(i==="\u56FE\u7247"&&l)t.push({type:"image_url",image_url:{url:l}}),o=!0;else if(i==="\u6587\u4EF6"&&l){const[r="",c="",m="",f=""]=l.split("|").map(g=>g.trim());z(t,qe(r,c,m,f))}else z(t,a[0]);n=a.index+a[0].length,a=e.exec(s)}return t.length===0?{content:s,hasImages:!1}:(z(t,s.slice(n)),{content:t,hasImages:o})}function to(s,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const n of o)if(Array.isArray(n))for(const a of n){if(!v(a))continue;const i=N(a.content);if(!i)continue;const l=N(a.senderName);z(s,l?`Message from ${l}:`:"Message:");const r=fe(i);Array.isArray(r.content)?s.push(...r.content):z(s,r.content),t=t||r.hasImages}return t}function oo(s){let e;try{e=JSON.parse(s)}catch{return}if(!v(e))return;const t=[];let o=to(t,e);const n=N(e.text)||"",a=Array.isArray(e.attachments)?e.attachments:[];z(t,n);for(const i of a){if(!v(i))continue;const l=i;if(String(l.type??l.kind??"").toLowerCase()==="image"){const m=Zt(l);m?(t.push({type:"image_url",image_url:{url:m}}),o=!0):N(l.base64Data??l.base64??l.data)&&z(t,`[Image attachment omitted: ${N(l.name)||"unnamed"} exceeds the ${K} byte inline limit]`);continue}const c=N(l.url??l.serverUrl)||"";z(t,qe(N(l.name)||"",c,N(l.mediaType??l.mimeType)||"",N(l.size)||""))}return t.length===0?{content:s,hasImages:!1}:{content:t,hasImages:o}}function fe(s){return oo(s)??eo(s)}async function Fe(s){if(!Array.isArray(s))return s;const e=[];for(const t of s){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await Xt(t.image_url.url)}})}return e}function so(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function no(s,e){const t=s.permissions??e.permissions??{},o=s.permissions?[]:e.allowedTools??[],n=s.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(a=>a.trim()).filter(Boolean),deny:[...t.deny??[],...n].map(a=>a.trim()).filter(Boolean)}}function io(s,e){return s==="*"?!0:s.endsWith("*")?e.startsWith(s.slice(0,-1)):s===e}function ro(s){return s.kind==="builtin"?[s.exposedName,s.toolName,`builtin.${s.toolName}`]:[s.exposedName,s.toolName,`${s.serverName}.${s.toolName}`,`mcp.${s.serverName}.${s.toolName}`]}function ze(s,e){return ro(e).some(t=>io(s,t))}function je(s,e,t){if(e.length>0&&!e.some(o=>ze(o,s)))throw new Error(t)}function ge(s,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>ze(o,s)))throw new Error(`ACode tool denied by permission rule: ${s.exposedName}`);je(s,e.allow,`ACode tool is not in allowed permission rules: ${s.exposedName}`),je(s,t??[],`ACode slash command does not allow tool: ${s.exposedName}`)}}function ao(s,e,t){try{return ge(s,e,t),!0}catch{return!1}}function ce(s){const e=s.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function lo(s){try{const e=new URL(s);e.search="",e.hash="";const t=new URL(ce(e.toString()));return`${t.origin}${t.pathname}`}catch{return ce(s).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function co(s){const e=[...s].reverse().find(o=>o.role==="user"),t=so(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function We(s){try{const e=JSON.parse(s);return Me(e)?e:{}}catch{return{}}}function uo(s,e,t){if(new Set([rt,"await_complete"]).has(s.toolName))return 0;if(s.toolName!=="Bash")return t;const n=e.timeout_ms??e.timeoutMs,a=typeof n=="number"?n:typeof n=="string"?Number(n):NaN;return!Number.isFinite(a)||a<=0?Math.max(t,Bt):Math.min(Math.floor(a),10*6e4)+2e3}function mo(s,e){const t=s.trim();return`ACode \u5DF2\u63A5\u6536\u4EFB\u52A1\u3002\u5F53\u524D\u5DF2\u52A0\u8F7D ${e.configMcpCount} \u4E2A MCP \u914D\u7F6E\u3001${e.exposedTools.length} \u4E2A MCP Tool \u4E0E ${e.skills.length} \u4E2A Skill\u3002${t?`\u8F93\u5165\u6458\u8981\uFF1A${t.slice(0,200)}`:""}`}function O(s){if(!v(s))return String(s??"");const e=s.content;if(Array.isArray(e)){const t=e.map(o=>v(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
- `)}return JSON.stringify(s)}function oe(s){return s instanceof Error?s.message:String(s)}function ho(s){let e=16;if(typeof s.content=="string")e+=s.content.length*2;else if(Array.isArray(s.content))for(const t of s.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return s.tool_calls&&(e+=JSON.stringify(s.tool_calls).length),s.tool_call_id&&(e+=s.tool_call_id.length),e}async function po(s,e,t,o,n){let a=0;for(const l of s)a+=ho(l);if(a<=e)return 0;const i=await _e(s,t,o,{llmSummarizer:n});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:be(s,{llmSummarizer:n,contextLimit:t})}function Je(s){const e=oe(s).toLowerCase();return e.includes("context_length_exceeded")||e.includes("context length")||e.includes("maximum context")||e.includes("max context")||e.includes("token limit")||e.includes("tokens exceed")||e.includes("too many tokens")||e.includes("input is too long")||e.includes("prompt is too long")||e.includes("request too large")||e.includes("413")}function fo(s){const e=oe(s).toLowerCase();return Je(s)?!1:e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||/\b(408|429|500|502|503|504|520|521|522|523|524)\b/.test(e)}function go(s){if(typeof s!="object"||s===null)return!1;const e=Reflect.get(s,"code"),t=oe(s).toLowerCase();return e===-32001||t.includes("request timed out")}function To(s){if(typeof s=="object"&&s!==null){const e=Reflect.get(s,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(s,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function yo(s,e){return JSON.stringify({ok:!1,tool:s.exposedName,error:{type:To(e),message:oe(e)}})}function He(s){const e=JSON.stringify(s);return e.length>500?`${e.slice(0,500)}\u2026`:e}function Ao(s){const e=[s?.reasoning_content,s?.reasoning_text,s?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(v(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function Co(s){return s.length===0?"":["Skills are available for this session.","Use the `skill` tool to load specialized skill instructions when a user task matches one of the available skills listed in the tool description.","Do not attempt to follow skill instructions from memory \u2014 always invoke the `skill` tool first to load the full content."].join(" ")}function _o(s){return s.length===0?"":["Available slash commands:",...s.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
1
+ import{EventEmitter as Ve}from"node:events";import{randomUUID as Xe}from"node:crypto";import F from"node:fs";import Ze from"node:os";import H from"node:path";import{Client as et}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as tt}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as ot}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as st}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as nt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as it,DEFAULT_TOOL_PERMISSION_POLICY as Ae}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as rt,createAskUserQuestionTool as at}from"./ask-user-question-tool.js";import{createSkillTool as lt}from"./skill-tool.js";import{createTodoWriteTool as ct,createTodoReadTool as ut}from"./todo-tool.js";import{createSubAgentTools as mt}from"./sub-agent-tools.js";import{createAwaitCompleteTool as dt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as ht}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as X}from"./background-command-manager.js";import{createTerminalTool as pt}from"./terminal-tool.js";import{buildPluginPrompt as ft,createPluginTools as gt}from"./plugin-tools.js";import{loadAcodeCommands as Tt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as Ce}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as yt,COMPACTION_LLM_PROMPT_TEMPLATE as At,conversationSizeKB as Z,estimateConversationTokens as se,performCompaction as _e,pruneToolOutputs as Ct,summarizeConversation as be}from"./compaction.js";import{loadAcodeConfig as _t,loadAcodeSkillGroup as bt}from"./config.js";import{ACodeHookBus as wt,findDeniedHookResult as ue}from"./hooks/hookBus.js";import{isMcpPollingToolName as $t,isMcpBlockingToolName as kt,getSemanticToolName as we}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as D}from"./meeting-debug-log.js";import{buildToolCatalog as $e,matchesToolAllocation as ke,mergeAllocatableTools as ne,PRESET_EXPLORE as St,rebindDefaultAgentId as Se,resolveToolAllocation as Mt,SUB_AGENT_ALLOWED_MCP_TOOLS as Rt}from"./tool-allocation.js";function vt(s){if(typeof s!="object"||s===null)return!1;const e=s;return e.kind==="builtin"&&typeof e.toolName=="string"&&typeof e.exposedName=="string"&&typeof e.description=="string"&&typeof e.execute=="function"&&typeof e.inputSchema=="object"&&e.inputSchema!==null}function xt(s){return s.type==="text"?{type:"text",text:s.text}:{type:"image_url",image_url:{url:s.image_url.url}}}function Et(s){return{id:s.id,type:"function",function:{name:s.function.name,arguments:s.function.arguments}}}function Nt(s){const e={role:s.role,content:Array.isArray(s.content)?s.content.map(xt):s.content};return s.tool_call_id&&(e.tool_call_id=s.tool_call_id),s.tool_calls&&(e.tool_calls=s.tool_calls.map(Et)),e}function me(s){return s.map(Nt)}function Pt(s,e){const t=q(s.prompt_cache_hit_tokens),o=q(s.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const n=q(s.cache_read_input_tokens),a=q(s.cache_creation_input_tokens);if(n!==void 0||a!==void 0){const c=q(s.input_tokens)??0;return{cacheHitTokens:n??0,cacheMissTokens:(a??0)+c}}const i=q(s.cache_hit_tokens),l=q(s.cache_miss_tokens);if(i!==void 0||l!==void 0)return{cacheHitTokens:i??0,cacheMissTokens:l??0};const r=q(s.prompt_tokens_details?.cached_tokens);if(r!==void 0){const c=e!==void 0?Math.max(0,e-r):0;return{cacheHitTokens:r,cacheMissTokens:c}}}function q(s){const e=typeof s=="number"?s:typeof s=="string"&&s.trim()?Number(s):NaN;if(!(!Number.isFinite(e)||e<0))return e}function It(s,e){if(!s)return e;const t=o=>{const n=e[o],a=s[o];return o==="prompt_tokens_details"?{...a,...n}:n??a};return{prompt_tokens:t("prompt_tokens"),completion_tokens:t("completion_tokens"),input_tokens:t("input_tokens"),output_tokens:t("output_tokens"),prompt_cache_hit_tokens:t("prompt_cache_hit_tokens"),prompt_cache_miss_tokens:t("prompt_cache_miss_tokens"),cache_read_input_tokens:t("cache_read_input_tokens"),cache_creation_input_tokens:t("cache_creation_input_tokens"),cache_hit_tokens:t("cache_hit_tokens"),cache_miss_tokens:t("cache_miss_tokens"),prompt_tokens_details:t("prompt_tokens_details")}}function Dt(){return new Date().toISOString()}function R(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function Me(s){return R(s)}function Re(s,e){return e.map(t=>({serverName:s,toolName:t.name,kind:"mcp",exposedName:wo(s,t.name),description:t.description,inputSchema:Me(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function N(s){return String(s??"").trim()||void 0}const ve=6e4,xe=30*6e4,Ee=6e4,Ne=6e4,ie=-1,Pe=ie,Lt=1e3,Ot=3e4,re=6e4,Ie=0,Ut=2147483647,Bt=10*6e4+2e3,qt=1e4,ae=5e3,De=10*60*1e3,K=10*1024*1024,Le=800*1024,le=process.env.ACODE_COMPACTION_DEBUG==="1",Oe=le?H.join(Ze.tmpdir(),"acode-compaction-debug.log"):"";function u(...s){le&&console.log(...s)}const Ft=process.env.ACODE_TOKEN_DEBUG==="1";function G(...s){Ft&&console.log("[TokenDebug][Runtime]",...s)}const zt=64e3;function de(s){const e=s.contextLimit&&s.contextLimit>0?s.contextLimit:zt,t=s.maxOutput&&s.maxOutput>0?s.maxOutput:8192,o=s.inputLimit&&s.inputLimit>0?s.inputLimit:void 0,n=yt(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:n}}async function x(s,e,t,o){if(e<=0)return await s;let n;try{return await new Promise((a,i)=>{n=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),s.then(a,i)})}finally{n&&clearTimeout(n)}}async function ee(s,e,t,o=qt){try{await x(e,o,s)}catch(n){t(n instanceof Error?n.message:String(n))}}function Q(s,e){if(s===0||s==="0")return 0;const t=typeof s=="number"?s:Number(s);return t===ie?ie:Number.isFinite(t)&&t>0?Math.floor(t):e}function te(s,e){const t=Q(s,e);return t>0?t:e}const Ue=3;function he(s){return s?Math.ceil(s.length/Ue):0}function jt(s,e){let t=s.length;for(const o of e){const n=(o.kind==="mcp",o.toolName);if(t+=n.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const a=o;a.inputSchema&&(t+=JSON.stringify(a.inputSchema).length)}}return Math.ceil(t/Ue)}function Be(s){if(s.length===0)return 0;const e=JSON.stringify(Ke(s));return he(e)}async function Wt(s){await new Promise(e=>setTimeout(e,s))}function Jt(s){return typeof s=="boolean"}function Ht(s,e,t){if(Jt(t?.supportsImageInput))return t.supportsImageInput;const o=R(e)?e.models:void 0,n=R(o)?o[s]:void 0;if(!R(n))return!1;const a=n.modalities;return!R(a)||!Array.isArray(a.input)?!1:a.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function pe(s,e,t,o){if(s!==void 0)return s;if(!e)return;const n=e.models;if(R(n)){const a=n[t];if(R(a)){const i=a[o];if(i!==void 0)return i}}return e[o]}function Kt(s,e){const t=e.provider?.default,o=t?.options,n=s.model||t?.model||e.model||"acode-default",a=N(s.effort)||N(o?.effort)||N(t?.effort)||void 0;return{model:n,baseURL:N(o?.baseURL||o?.baseUrl),apiKey:N(o?.apiKey),effort:a,systemPrompt:s.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:te(o?.requestTimeoutMs??o?.timeoutMs,ve),requestTotalTimeoutMs:te(o?.requestTotalTimeoutMs,xe),requestRetryCount:Q(o?.requestRetryCount,Pe),requestFirstByteTimeoutMs:te(o?.requestFirstByteTimeoutMs,Ee),requestStreamIdleTimeoutMs:te(o?.requestStreamIdleTimeoutMs,Ne),mcpToolTimeoutMs:te(o?.mcpToolTimeoutMs,re),mcpPollingToolTimeoutMs:Q(o?.mcpPollingToolTimeoutMs,Ie),supportsImageInput:Ht(n,t,o),contextLimit:Q(pe(o?.contextLimit,t,n,"contextLimit"),0)||void 0,inputLimit:Q(pe(o?.inputLimit,t,n,"inputLimit"),0)||void 0,maxOutput:Q(pe(o?.maxOutput,t,n,"maxOutput"),0)||void 0}}function z(s,e){const t=e.replace(/\s+/g," ").trim();t&&s.push({type:"text",text:t})}function Gt(s,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${s||"image/png"};base64,${t}`}function Qt(s){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(s.trim())}function Yt(s){let e;try{e=new URL(s)}catch{throw new Error(`ACode image URL is invalid: ${s}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`ACode image URL protocol is not supported: ${e.protocol}`)}async function Vt(s){const e=await s.arrayBuffer();if(e.byteLength>K)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${K} bytes`);return Buffer.from(e).toString("base64")}async function Xt(s){const e=s.trim();if(Qt(e)){if(e.slice(e.indexOf(",")+1).length*.75>K)throw new Error(`ACode inline image exceeds the ${K} byte size limit`);return e}Yt(e);const t=await fetch(e);if(!t.ok)throw new Error(`ACode image fetch failed: ${t.status} ${await t.text()}`);const o=t.headers.get("content-type")||"",n=o.split(";")[0]?.trim().toLowerCase()||"";if(!n.startsWith("image/"))throw new Error(`ACode image URL did not return an image content type: ${o||"unknown"}`);return`data:${n};base64,${await Vt(t)}`}function Zt(s){const e=N(s.base64Data??s.base64??s.data);return e?e.length*.75>K?void 0:Gt(N(s.mediaType??s.mimeType)||"image/png",e):N(s.url??s.serverUrl)}function qe(s,e,t,o){return`[Attached file: ${[s?`name=${s}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(a=>!!a).join(", ")}]`}function eo(s){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,n=0,a=e.exec(s);for(;a!==null;){z(t,s.slice(n,a.index));const i=a[1],l=(a[2]||"").trim();if(i==="\u56FE\u7247"&&l)t.push({type:"image_url",image_url:{url:l}}),o=!0;else if(i==="\u6587\u4EF6"&&l){const[r="",c="",m="",f=""]=l.split("|").map(g=>g.trim());z(t,qe(r,c,m,f))}else z(t,a[0]);n=a.index+a[0].length,a=e.exec(s)}return t.length===0?{content:s,hasImages:!1}:(z(t,s.slice(n)),{content:t,hasImages:o})}function to(s,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const n of o)if(Array.isArray(n))for(const a of n){if(!R(a))continue;const i=N(a.content);if(!i)continue;const l=N(a.senderName);z(s,l?`Message from ${l}:`:"Message:");const r=fe(i);Array.isArray(r.content)?s.push(...r.content):z(s,r.content),t=t||r.hasImages}return t}function oo(s){let e;try{e=JSON.parse(s)}catch{return}if(!R(e))return;const t=[];let o=to(t,e);const n=N(e.text)||"",a=Array.isArray(e.attachments)?e.attachments:[];z(t,n);for(const i of a){if(!R(i))continue;const l=i;if(String(l.type??l.kind??"").toLowerCase()==="image"){const m=Zt(l);m?(t.push({type:"image_url",image_url:{url:m}}),o=!0):N(l.base64Data??l.base64??l.data)&&z(t,`[Image attachment omitted: ${N(l.name)||"unnamed"} exceeds the ${K} byte inline limit]`);continue}const c=N(l.url??l.serverUrl)||"";z(t,qe(N(l.name)||"",c,N(l.mediaType??l.mimeType)||"",N(l.size)||""))}return t.length===0?{content:s,hasImages:!1}:{content:t,hasImages:o}}function fe(s){return oo(s)??eo(s)}async function Fe(s){if(!Array.isArray(s))return s;const e=[];for(const t of s){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await Xt(t.image_url.url)}})}return e}function so(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function no(s,e){const t=s.permissions??e.permissions??{},o=s.permissions?[]:e.allowedTools??[],n=s.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(a=>a.trim()).filter(Boolean),deny:[...t.deny??[],...n].map(a=>a.trim()).filter(Boolean)}}function io(s,e){return s==="*"?!0:s.endsWith("*")?e.startsWith(s.slice(0,-1)):s===e}function ro(s){return s.kind==="builtin"?[s.exposedName,s.toolName,`builtin.${s.toolName}`]:[s.exposedName,s.toolName,`${s.serverName}.${s.toolName}`,`mcp.${s.serverName}.${s.toolName}`]}function ze(s,e){return ro(e).some(t=>io(s,t))}function je(s,e,t){if(e.length>0&&!e.some(o=>ze(o,s)))throw new Error(t)}function ge(s,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>ze(o,s)))throw new Error(`ACode tool denied by permission rule: ${s.exposedName}`);je(s,e.allow,`ACode tool is not in allowed permission rules: ${s.exposedName}`),je(s,t??[],`ACode slash command does not allow tool: ${s.exposedName}`)}}function ao(s,e,t){try{return ge(s,e,t),!0}catch{return!1}}function ce(s){const e=s.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function lo(s){try{const e=new URL(s);e.search="",e.hash="";const t=new URL(ce(e.toString()));return`${t.origin}${t.pathname}`}catch{return ce(s).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function co(s){const e=[...s].reverse().find(o=>o.role==="user"),t=so(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function We(s){try{const e=JSON.parse(s);return Me(e)?e:{}}catch{return{}}}function uo(s,e,t){if(new Set([rt,"await_complete"]).has(s.toolName))return 0;if(s.toolName!=="Bash")return t;const n=e.timeout_ms??e.timeoutMs,a=typeof n=="number"?n:typeof n=="string"?Number(n):NaN;return!Number.isFinite(a)||a<=0?Math.max(t,Bt):Math.min(Math.floor(a),10*6e4)+2e3}function mo(s,e){const t=s.trim();return`ACode \u5DF2\u63A5\u6536\u4EFB\u52A1\u3002\u5F53\u524D\u5DF2\u52A0\u8F7D ${e.configMcpCount} \u4E2A MCP \u914D\u7F6E\u3001${e.exposedTools.length} \u4E2A MCP Tool \u4E0E ${e.skills.length} \u4E2A Skill\u3002${t?`\u8F93\u5165\u6458\u8981\uFF1A${t.slice(0,200)}`:""}`}function O(s){if(!R(s))return String(s??"");const e=s.content;if(Array.isArray(e)){const t=e.map(o=>R(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
+ `)}return JSON.stringify(s)}function oe(s){return s instanceof Error?s.message:String(s)}function ho(s){let e=16;if(typeof s.content=="string")e+=s.content.length*2;else if(Array.isArray(s.content))for(const t of s.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return s.tool_calls&&(e+=JSON.stringify(s.tool_calls).length),s.tool_call_id&&(e+=s.tool_call_id.length),e}async function po(s,e,t,o,n){let a=0;for(const l of s)a+=ho(l);if(a<=e)return 0;const i=await _e(s,t,o,{llmSummarizer:n});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:be(s,{llmSummarizer:n,contextLimit:t})}function Je(s){const e=oe(s).toLowerCase();return e.includes("context_length_exceeded")||e.includes("context length")||e.includes("maximum context")||e.includes("max context")||e.includes("token limit")||e.includes("tokens exceed")||e.includes("too many tokens")||e.includes("input is too long")||e.includes("prompt is too long")||e.includes("request too large")||e.includes("413")}function fo(s){const e=oe(s).toLowerCase();return Je(s)?!1:e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||/\b(408|429|500|502|503|504|520|521|522|523|524)\b/.test(e)}function go(s){if(typeof s!="object"||s===null)return!1;const e=Reflect.get(s,"code"),t=oe(s).toLowerCase();return e===-32001||t.includes("request timed out")}function To(s){if(typeof s=="object"&&s!==null){const e=Reflect.get(s,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(s,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function yo(s,e){return JSON.stringify({ok:!1,tool:s.exposedName,error:{type:To(e),message:oe(e)}})}function He(s){const e=JSON.stringify(s);return e.length>500?`${e.slice(0,500)}\u2026`:e}function Ao(s){const e=[s?.reasoning_content,s?.reasoning_text,s?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(R(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function Co(s){return s.length===0?"":["Skills are available for this session.","Use the `skill` tool to load specialized skill instructions when a user task matches one of the available skills listed in the tool description.","Do not attempt to follow skill instructions from memory \u2014 always invoke the `skill` tool first to load the full content."].join(" ")}function _o(s){return s.length===0?"":["Available slash commands:",...s.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
3
3
  `)}function bo(s){if(!s||typeof s!="object")return"";const e=s,t=[],o=e.displayName,n=e.roleName,a=e.instanceName,i=e.projectId,l=e.workspacePath,r=e.runtimeMode,c=e.describe;return typeof o=="string"&&o.trim()&&t.push(`Display Name: ${o.trim()}`),typeof n=="string"&&n.trim()&&t.push(`Role: ${n.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Instance: ${a.trim()}`),typeof i=="string"&&i.trim()&&t.push(`Project: ${i.trim()}`),typeof l=="string"&&l.trim()&&t.push(`Workspace: ${l.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Runtime Mode: ${r.trim()}`),typeof c=="string"&&c.trim()&&t.push(`Description: ${c.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
4
- `)}function Ke(s){return s.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function wo(s,e){return`${s}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function $o(s){const e={"Content-Type":"application/json"};return s.apiKey&&(e.Authorization=`Bearer ${s.apiKey}`),e}function ko(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,So(e)?Mo(t):t]))}function So(s){const e=s.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function Mo(s){return s.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function vo(s){return s.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function Ro(s,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=s.get(t)??{id:e.id||`call-${t}`,type:"function",function:{name:"",arguments:""}};e.id&&(o.id=e.id),e.function?.name&&(o.function.name+=e.function.name),e.function?.arguments&&(o.function.arguments+=e.function.arguments),s.set(t,o)}function xo(s){return[...s.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}function Eo(){const s=process.env.ACODE_ABORT_FORCE_SETTLE_GRACE_MS;if(s===void 0||s.trim()==="")return 6e4;const e=Number(s.trim());return Number.isFinite(e)&&e>=0?Math.floor(e):6e4}class Y extends Ve{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:Re,requestTotalTimeoutMs:xe,requestRetryCount:Ie,requestFirstByteTimeoutMs:Ee,requestStreamIdleTimeoutMs:Ne,mcpToolTimeoutMs:re,mcpPollingToolTimeoutMs:Pe,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new Ce([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:{...Ae}},this.abortController=null,this.exposedToolsInitialized=!1,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.submitQueue=Promise.resolve(),this.activeTurnToken=null,this.forceSettleWaiters=new Map,this.abortForceSettleTimer=null,this.activeTurn=!1,this.forceMessagePending=!1,this.abortRequested=!1,this.toolSettleSlot=null,this.toolSettleSeq=0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.permissionWaiters=new Map,this.hookBus=new wt({sessionId:e.sessionId,onError:(t,o)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${t.name}: ${o instanceof Error?o.message:String(o)}`})}});for(const t of e.hooks??[])this.hookBus.register(t);e.toolPermissionPolicy&&(this.state.toolPermissionPolicy={...Ae,...e.toolPermissionPolicy})}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:Dt(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,n){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:n})}handleCompactionPhase(e,t){switch(t.phase){case"prune_start":this.emitCompactionPhase(e,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u6B63\u5728\u88C1\u526A ${t.messageCount??0} \u6761\u6D88\u606F\u4E2D\u7684\u5DE5\u5177\u8F93\u51FA...`);break;case"prune_end":this.emitCompactionPhase(e,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${t.prunedCount??0} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${t.freedTokens??0} tokens`);break;case"summarize_start":this.emitCompactionPhase(e,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6B63\u5728\u6458\u8981 ${t.messageCount??0} \u6761\u65E9\u671F\u5BF9\u8BDD...`);break;case"summarize_end":this.emitCompactionPhase(e,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${t.summarizedCount??0} \u6761\u6D88\u606F${t.usedLLM?" (LLM \u6458\u8981)":" (\u89C4\u5219\u6458\u8981)"}`);break}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await _t(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:n}=await this.loadAllSkills(),a=Kt(this.config,e);u(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${a.model}, baseURL=${a.baseURL??"(none)"}, apiKey=${a.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const i=no(this.config,e),l=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},a.mcpToolTimeoutMs),r=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const c=await this.fetchProfilePrompt(l),m=this.config.agentId||"unknown";ht(m),X.reconcileOrphans(m);const f=it(this.config.workingDirectory,m,this.config.onFileChange,{manager:X,emitCompleted:h=>{this.emitAcodeEvent("background_command_completed",h)}},this.createToolPermissionController()),g=at(this.buildAskUserQuestionDeps(),()=>this.contextVersion),k=lt(t);this.skillTool=k;const T=ct(m),b=ut(m),C=this.config.subAgentManager?mt(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],d=dt(this.buildAwaitCompleteDeps()),A=this.config.terminalManager?pt(m,{terminalManager:this.config.terminalManager}):null,M=gt({pluginBridge:this.config.pluginBridge}),_=[...f,g,k,T,b,...C,d,...A?[A]:[],...M,...l.flatMap(h=>h.tools),...Se(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const h=Se(this.config.subAgentSuiteTools??[],this.config.agentId??""),B=ne(_,h);_.length=0,_.push(...B)}let S=_;const w=this.config.subAgentAllowedTools;w&&w.length>0&&(S=S.filter(h=>ke(h,w)));const E=this.resolveCommandDirs(e);let p=[...E,...this.discoverPluginCommandDirs()];if(this.config.pluginBridge?.getCommandDirs)try{const h=await this.config.pluginBridge.getCommandDirs();h.length>0&&(p=[...p,...h])}catch(h){u(`[ACodeRuntime] \u63D2\u4EF6\u547D\u4EE4\u76EE\u5F55\u83B7\u53D6\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${h instanceof Error?h.message:String(h)}`)}p=[...new Set(p)],this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const y=await Tt(p),R=new Ce(y),I=Co(t),$=_o(y),L=this.config.pluginBridge?ft():void 0,j=[a.systemPrompt,I,$,L].map(h=>h?.trim()).filter(h=>!!h).join(`
4
+ `)}function Ke(s){return s.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function wo(s,e){return`${s}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function $o(s){const e={"Content-Type":"application/json"};return s.apiKey&&(e.Authorization=`Bearer ${s.apiKey}`),e}function ko(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,So(e)?Mo(t):t]))}function So(s){const e=s.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function Mo(s){return s.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function Ro(s){return s.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function vo(s,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=s.get(t)??{id:e.id||`call-${t}`,type:"function",function:{name:"",arguments:""}};e.id&&(o.id=e.id),e.function?.name&&(o.function.name+=e.function.name),e.function?.arguments&&(o.function.arguments+=e.function.arguments),s.set(t,o)}function xo(s){return[...s.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}function Eo(){const s=process.env.ACODE_ABORT_FORCE_SETTLE_GRACE_MS;if(s===void 0||s.trim()==="")return 6e4;const e=Number(s.trim());return Number.isFinite(e)&&e>=0?Math.floor(e):6e4}class Y extends Ve{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:ve,requestTotalTimeoutMs:xe,requestRetryCount:Pe,requestFirstByteTimeoutMs:Ee,requestStreamIdleTimeoutMs:Ne,mcpToolTimeoutMs:re,mcpPollingToolTimeoutMs:Ie,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new Ce([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:{...Ae}},this.abortController=null,this.exposedToolsInitialized=!1,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.submitQueue=Promise.resolve(),this.activeTurnToken=null,this.forceSettleWaiters=new Map,this.abortForceSettleTimer=null,this.activeTurn=!1,this.forceMessagePending=!1,this.abortRequested=!1,this.toolSettleSlot=null,this.toolSettleSeq=0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.permissionWaiters=new Map,this.hookBus=new wt({sessionId:e.sessionId,onError:(t,o)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${t.name}: ${o instanceof Error?o.message:String(o)}`})}});for(const t of e.hooks??[])this.hookBus.register(t);e.toolPermissionPolicy&&(this.state.toolPermissionPolicy={...Ae,...e.toolPermissionPolicy})}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:Dt(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,n){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:n})}handleCompactionPhase(e,t){switch(t.phase){case"prune_start":this.emitCompactionPhase(e,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u6B63\u5728\u88C1\u526A ${t.messageCount??0} \u6761\u6D88\u606F\u4E2D\u7684\u5DE5\u5177\u8F93\u51FA...`);break;case"prune_end":this.emitCompactionPhase(e,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${t.prunedCount??0} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${t.freedTokens??0} tokens`);break;case"summarize_start":this.emitCompactionPhase(e,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6B63\u5728\u6458\u8981 ${t.messageCount??0} \u6761\u65E9\u671F\u5BF9\u8BDD...`);break;case"summarize_end":this.emitCompactionPhase(e,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${t.summarizedCount??0} \u6761\u6D88\u606F${t.usedLLM?" (LLM \u6458\u8981)":" (\u89C4\u5219\u6458\u8981)"}`);break}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await _t(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:n}=await this.loadAllSkills(),a=Kt(this.config,e);u(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${a.model}, baseURL=${a.baseURL??"(none)"}, apiKey=${a.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const i=no(this.config,e),l=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},a.mcpToolTimeoutMs),r=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const c=await this.fetchProfilePrompt(l),m=this.config.agentId||"unknown";ht(m),X.reconcileOrphans(m);const f=it(this.config.workingDirectory,m,this.config.onFileChange,{manager:X,emitCompleted:h=>{this.emitAcodeEvent("background_command_completed",h)}},this.createToolPermissionController()),g=at(this.buildAskUserQuestionDeps(),()=>this.contextVersion),k=lt(t);this.skillTool=k;const T=ct(m),b=ut(m),_=this.config.subAgentManager?mt(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],d=dt(this.buildAwaitCompleteDeps()),A=this.config.terminalManager?pt(m,{terminalManager:this.config.terminalManager}):null,M=gt({pluginBridge:this.config.pluginBridge}),C=[...f,g,k,T,b,..._,d,...A?[A]:[],...M,...l.flatMap(h=>h.tools),...Se(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const h=Se(this.config.subAgentSuiteTools??[],this.config.agentId??""),B=ne(C,h);C.length=0,C.push(...B)}let S=C;const w=this.config.subAgentAllowedTools;w&&w.length>0&&(S=S.filter(h=>ke(h,w)));const E=this.resolveCommandDirs(e);let p=[...E,...this.discoverPluginCommandDirs()];if(this.config.pluginBridge?.getCommandDirs)try{const h=await this.config.pluginBridge.getCommandDirs();h.length>0&&(p=[...p,...h])}catch(h){u(`[ACodeRuntime] \u63D2\u4EF6\u547D\u4EE4\u76EE\u5F55\u83B7\u53D6\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${h instanceof Error?h.message:String(h)}`)}p=[...new Set(p)],this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const y=await Tt(p),v=new Ce(y),P=Co(t),$=_o(y),L=this.config.pluginBridge?ft():void 0,j=[a.systemPrompt,P,$,L].map(h=>h?.trim()).filter(h=>!!h).join(`
5
5
 
6
6
  `),U=h=>h?.trim()?[{role:"system",content:h.trim()}]:[],W=[this.config.rolePrompt,c].map(h=>h?.trim()).filter(h=>!!h).join(`
7
7
 
8
8
  `),J=[...U(this.config.globalPrompt),...U(W),...U(this.config.memory),...j?[{role:"system",content:j}]:[]],V=J.map(h=>h.content).filter(Boolean).join(`
9
9
 
10
- `);this.initialConversation=me(J),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:a,permissions:i,mcpConnections:l,ownsMcpConnections:r,exposedTools:S,commands:y,commandRegistry:R,conversation:me(J),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:this.state.toolPermissionPolicy},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:y.length});const P=de(a);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:y.length,estimatedContextTokens:jt(V,S),contextLimit:P.contextLimit,maxOutput:P.maxOutput,...P.inputLimit!==void 0?{inputLimit:P.inputLimit}:{},compactionThreshold:P.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:l.length,builtInToolCount:f.length,toolCount:S.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:S.map(h=>({name:h.exposedName,source:h.kind==="mcp"?`${h.serverName}.${h.toolName}`:`builtin.${h.toolName}`,description:h.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(h=>({name:h.name,description:h.description,directory:h.directory})),skillGroups:o.map(h=>({dir:h.dir,exists:h.exists,skills:h.skills.map(B=>({name:B.name,description:B.description,directory:B.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:y.length,commandDirs:E,commands:y.map(h=>({name:h.name,description:h.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(n)}async loadAllSkills(){const e=this.config.skillsDir??"",t=H.join(this.config.workingDirectory,".acode","skills"),o=H.join(this.config.workingDirectory,".agentswork","skills"),n=new Set,a=[],i=[];for(const c of[e,t,o]){if(!c)continue;const m=H.resolve(c);if(!n.has(m)){n.add(m),a.push(await bt(c));try{await F.promises.access(m),i.push(m)}catch{}}}const l=new Map;for(const c of a)for(const m of c.skills)l.set(m.name,m);return{skills:[...l.values()],skillGroups:a,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=F.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=F.watch(t,()=>{this.scheduleSkillRefresh()})}catch{continue}}o&&(o.on("error",()=>{}),this.skillWatchers.push(o))}}scheduleSkillRefresh(){this.skillRefreshTimer&&clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=setTimeout(()=>{this.skillRefreshTimer=null,this.refreshSkills()},Y.SKILL_REFRESH_DEBOUNCE_MS)}async refreshSkills(){if(!(!this.state.started||this.state.terminated))try{const{skills:e,skillGroups:t}=await this.loadAllSkills();this.skillTool&&this.skillTool.refresh(e),this.state.skills=e,this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:e.length,skills:e.map(o=>({name:o.name,description:o.description,directory:o.directory})),skillGroups:t.map(o=>({dir:o.dir,exists:o.exists,skills:o.skills.map(n=>({name:n.name,description:n.description,directory:n.directory}))}))}),u(`[skill-watch] Skills refreshed: ${e.length} skills (${e.map(o=>o.name).join(", ")||"none"})`,{sessionId:this.config.sessionId})}catch(e){console.error("[skill-watch] Failed to refresh skills:",e instanceof Error?e.message:e)}}stopSkillWatchers(){this.skillRefreshTimer&&(clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=null);for(const e of this.skillWatchers)try{e.close()}catch{}this.skillWatchers=[]}startCompactionDebugLog(){if(!le||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:n,threshold:a}=de(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,l=se(this.state.conversation)+Be(this.state.exposedTools),r=Math.max(i,l),c=Z(this.state.conversation),m=this.state.started&&!this.state.terminated,f=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${c}KB`,`estimation=${l} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${n??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${a}`,`remainingToTrigger=${Math.max(0,a-i)}`,`isRunning=${m}`,`shouldCompact=${m?r>=a:!1}`,"---"].join(" | ");F.promises.appendFile(Oe,f+`
11
- `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;u(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${t}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const o=this.submitQueue.then(()=>(u(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmitGuarded(e,t)));return this.submitQueue=o.catch(()=>{u("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),u("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}executeSubmitGuarded(e,t){const o={};this.activeTurnToken=o;const n=this.executeSubmit(e,t),a=new Promise(i=>{this.forceSettleWaiters.set(o,i)});return n.finally(()=>{this.forceSettleWaiters.delete(o),this.activeTurnToken===o&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([n,a])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=Eo();this.abortForceSettleTimer=setTimeout(()=>{this.abortForceSettleTimer=null,this.activeTurn&&this.activeTurnToken===e&&this.forceSettleActiveTurn(`turn still unsettled ${t}ms after abort()`)},t),typeof this.abortForceSettleTimer.unref=="function"&&this.abortForceSettleTimer.unref()}forceSettleActiveTurn(e){const t=this.activeTurnToken;console.error(`[ACodeRuntime] \u{1F6A8} FORCE SETTLE: active turn ignored abort() (${e}). Force-settling to unblock submitQueue; late executeSubmit continuation will be superseded.`),this.contextVersion+=1,this.activeTurn=!1,this.abortRequested=!1,this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.emitAcodeEvent("error",{message:`ACode turn force-settled: ${e}`}),this.emitAcodeEvent("turn_complete",{failed:!0});const o=t?this.forceSettleWaiters.get(t):void 0;t&&this.forceSettleWaiters.delete(t),this.activeTurnToken=null,o?.()}notifyForceMessage(){this.forceMessagePending=!0,u("[ACodeRuntime] \u{1F514} Force message pending flag set")}addBuiltInTools(e){if(!this.state||!this.exposedToolsInitialized||!Array.isArray(e))return 0;const t=new Set(this.state.exposedTools.map(n=>n.exposedName)),o=[];for(const n of e)Rt(n)&&(t.has(n.exposedName)||(t.add(n.exposedName),o.push(n)));return o.length===0?0:(this.state.exposedTools=[...this.state.exposedTools,...o],this.emitExposedToolsStatus(),o.length)}removeBuiltInToolsByPrefix(e){if(!this.state||!this.exposedToolsInitialized||!e)return 0;const t=this.state.exposedTools.length;this.state.exposedTools=this.state.exposedTools.filter(n=>!n.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}addPluginCommands(e){if(!this.state||e.length===0)return;this.state.commandRegistry.addCommands(e);const t=new Set(this.state.commands.map(o=>o.name));this.state.commands=[...this.state.commands,...e.filter(o=>!t.has(o.name))]}emitExposedToolsStatus(){this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(e=>e.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(e=>({name:e.exposedName,source:e.kind==="mcp"?`${e.serverName}.${e.toolName}`:`builtin.${e.toolName}`,description:e.description||""}))})}async injectForceMessage(){if(!this.forceMessagePending)return!1;this.forceMessagePending=!1;const e=this.state.mcpConnections.find(t=>t.tools.some(o=>o.toolName==="get_message"));if(!e)return u("[ACodeRuntime] injectForceMessage: no connection with get_message found"),!1;try{const t=await x(e.client.callTool({name:"get_message",arguments:{_aws_force_inject:!0}},void 0,{timeout:1e4}),1e4,"injectForceMessage get_message"),o=O(t);let n=[];try{const r=JSON.parse(o);Array.isArray(r?.directMessages)&&(n=r.directMessages.filter(c=>c?.force===!0))}catch{return!1}if(n.length===0)return!1;const a=JSON.stringify({directMessages:n,groupMessages:[]}),i=`forced_get_msg_${Date.now()}`,l=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:i,type:"function",function:{name:l,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:i,content:a}),u(`[ACodeRuntime] injectForceMessage: injected ${n.length} force message(s) into conversation`),!0}catch(t){return u(`[ACodeRuntime] injectForceMessage failed: ${t}`),!1}}async resetContext(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");this.contextVersion+=1,this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.state.conversation=me(this.initialConversation),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t){const o=Date.now();if(u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),u("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),u(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),u(`[ACodeRuntime] \u{1F522} Context version: ${t}`),u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const n=this.activeTurnToken,a=e.trim();let i=!1;try{u("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const l=Date.now(),r=await this.hookBus.dispatch("UserPromptSubmit",{prompt:a}),c=Date.now()-l;if(u(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${c}ms, results: ${r.length}`),this.isTurnSuperseded(t)){u("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const m=ue(r);if(m){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${m.message}`),this.emitAcodeEvent("error",{message:m.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}u("[ACodeRuntime] \u{1F50D} Expanding command if any...");const f=this.state.commandRegistry.expand(a),g=f?.prompt.trim()||a,k=f?.command.allowedTools;if(f&&(u(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${f.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:f.command.name,arguments:f.argumentsText,sourcePath:f.command.sourcePath})),!this.state.provider.baseURL){u("[ACodeRuntime] \u26A0\uFE0F No provider baseURL configured, using fallback response");const _=mo(g,this.state);this.emitAcodeEvent("assistant_delta",{text:_}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:_.length}}),i=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}u("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const T=fe(g);if(T.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");u("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const b=await Fe(T.content);if(this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}u("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:b}),u(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),u("[ACodeRuntime] Starting runModelTurn...");const C=Date.now(),d=await this.runModelTurn(k,t),A=Date.now()-C;if(u(`[ACodeRuntime] \u2705 runModelTurn completed in ${A}ms`),u(`[ACodeRuntime] \u{1F4DD} Result: text=${d.text?d.text.slice(0,80)+(d.text.length>80?"...":""):"(empty)"}, finishReason=${d.finishReason||"(none)"}`),this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}d.text&&!this.state.provider.stream&&(u("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:d.text})),u("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length},...d.responseBody?{responseBody:d.responseBody}:{},...d.finishReason?{finishReason:d.finishReason}:{}}),G(`turn_complete emitted: usage=${JSON.stringify(d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length})} (providerUsage=${d.usage?"real":"FALLBACK-text-length"}) textLength=${d.text.length} totalOutputTextLength=${d.totalOutputTextLength}`),u(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(d.usage?"":" (estimated, no provider usage)")),i=!0;const M=Date.now()-o;u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),u(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${M}ms`),u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(l){const r=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${r}ms:`,l instanceof Error?l.message:String(l)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",l instanceof Error?l.stack:"(no stack)"),this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){u("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),i=!0;return}u("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:l instanceof Error?l.message:String(l)}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0}finally{const l=Date.now()-o;u(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${l}ms`),u(`[ACodeRuntime] \u{1F50D} turnCompleted=${i}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===n&&(this.activeTurn=!1,this.abortRequested=!1),!i&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${l}ms. This indicates a code path that should have emitted turn_complete but didn't. Forcing failed turn_complete to prevent state stuck.`),this.emitAcodeEvent("error",{message:"ACode turn completed without proper completion event (internal error)"}),this.emitAcodeEvent("turn_complete",{failed:!0}),u("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(u(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.armAbortForceSettle()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,n)=>{this.questionWaiters.set(e,{resolve:o,reject:n,contextVersion:t})})}}async buildAllocatableToolList(){const e=this.state?.exposedTools??[],t=this.config.subAgentSuiteTools??[];let o=[];if(this.config.subAgentSuiteToolProvider)try{o=await this.config.subAgentSuiteToolProvider([])}catch{o=[]}return ne(e,ne(t,o))}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,n=this.config.workingDirectory,a=this.config;return{spawnSubAgent:async i=>{let l=this.config.subAgentSuiteTools;if(i.allowedTools&&i.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const c=await this.config.subAgentSuiteToolProvider(i.allowedTools);c.length>0&&(l=l?ne(l,c):c)}catch{}const r=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,...i.allowedTools&&i.allowedTools.length>0?{allowedTools:i.allowedTools}:{},workingDirectory:n,parentConfig:{...a,sharedMcpConnections:this.state?.mcpConnections,...l&&l.length>0?{subAgentSuiteTools:l}:{}}});return await e.start(r),{subId:r}},listSubAgentToolCatalog:async()=>$e(await this.buildAllocatableToolList()),listSubAgents:async()=>{const i=e.listByParent(t),l=[],r=[];for(const c of i){const m={subId:c.subId,subagentType:c.subagentType,description:c.description,status:c.status,startedAt:c.startedAt,endedAt:c.endedAt,durationMs:c.durationMs};c.status==="pending"||c.status==="running"?l.push(m):r.push(m)}return r.sort((c,m)=>(m.endedAt??0)-(c.endedAt??0)),{running:l,history:r}},getSubAgentStatus:async i=>{const l=e.getSubAgent(i);return l?{subId:l.subId,subagentType:l.subagentType,description:l.description,status:l.status,startedAt:l.startedAt,endedAt:l.endedAt,durationMs:l.durationMs,prompt:l.prompt,result:l.result,errorMessage:l.errorMessage,contextSnapshot:l.contextSnapshot}:null},awaitSubAgents:async(i,l)=>{const r=new Set;for(const c of i)this.pendingAwaitedSubIds.add(c),r.add(c);try{return await e.awaitCompletion(i,l)}finally{for(const c of r)this.pendingAwaitedSubIds.delete(c)}},abortSubAgent:i=>e.abort(i)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,n)=>{for(const a of o)this.pendingAwaitedSubIds.add(a);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,n)}finally{for(const a of o)this.pendingAwaitedSubIds.delete(a)}}:null,awaitBgCommands:(o,n)=>{for(const a of o)this.pendingAwaitedBgTaskIds.add(a);try{return X.awaitCompletion(e,o,n)}finally{for(const a of o)this.pendingAwaitedBgTaskIds.delete(a)}}}}submitQuestionAnswer(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}createToolPermissionController(){return{getLevel:e=>this.state.toolPermissionPolicy[e]??"allow",requestPermission:(e,t)=>this.requestToolPermission(e,t)}}requestToolPermission(e,t){const o=Xe();return new Promise(n=>{this.permissionWaiters.set(o,{capability:e,detail:t,resolve:n}),this.emitAcodeEvent("tool_permission_request",{requestId:o,capability:e,agentId:this.config.agentId,...t})})}submitToolPermissionDecision(e,t){const o=this.permissionWaiters.get(e);return o?(this.permissionWaiters.delete(e),o.resolve(t),!0):!1}rejectAllPermissionWaiters(e){if(this.permissionWaiters.size!==0){for(const[,t]of this.permissionWaiters)t.resolve(!1);this.permissionWaiters.clear(),D("tool-permission",`waiters rejected: ${e}`)}}setToolPermissionPolicy(e){this.state.toolPermissionPolicy={...this.state.toolPermissionPolicy,...e}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);u(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(n=>{u(`[ACodeRuntime] \u26A0\uFE0F manager.abort(${o}) threw: ${n instanceof Error?n.message:String(n)}`)})}cancelPendingAwaitedBgTasks(){if(this.pendingAwaitedBgTaskIds.size===0)return;const e=this.config.agentId??"unknown",t=Array.from(this.pendingAwaitedBgTaskIds);u(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),X.interruptAwaits(e,t)}detachCurrentToolExecution(){const e=this.toolSettleSlot;return!e||!e.settlable||e.settled?!1:(e.settled=!0,e.resolveSettle?.(),u(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${e.toolName} (toolCallId=${e.toolCallId}) to background`),!0)}beginToolSettle(e,t,o){const n=e.toolName==="Bash",a=++this.toolSettleSeq;let i;const l=n?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:a,toolName:e.toolName,toolCallId:o,settlable:n,settled:!1,resolveSettle:i??null},{seq:a,signal:l}}clearToolSettle(e){this.toolSettleSlot?.seq===e&&(this.toolSettleSlot=null)}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.armAbortForceSettle(),this.rejectAllQuestionWaiters("session terminated"),this.rejectAllPermissionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await ee("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await ee("ACode background commands shutdown",X.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),ee("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await ee("ACode Stop hooks",this.hookBus.dispatch("Stop",{reason:"session_stop"}),t=>{this.emitAcodeEvent("error",{message:t})}),this.state.terminated=!0,this.sessionCompleteEmitted||(this.sessionCompleteEmitted=!0,this.emitAcodeEvent("session_complete",{exitCode:0})),this.stopCompactionDebugLog(),this.stopSkillWatchers(),le)try{F.promises.appendFile(Oe,`[${new Date().toISOString()}] runtime stopped | ---
12
- `,"utf-8").catch(()=>{})}catch{}}discoverPluginCommandDirs(){const e=this.config.pluginsDir;if(!e)return[];let t;try{t=F.readdirSync(e)}catch{return[]}const o=[];for(const n of t){if(n.startsWith("."))continue;const a=H.join(e,n);let i;try{i=F.statSync(a)}catch{continue}if(!i.isDirectory())continue;const l=H.join(a,"commands");let r;try{F.existsSync(l)&&(r=F.statSync(l))}catch{r=void 0}r?.isDirectory()&&o.push(l)}return o}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",n,a,i,l="",r=0;this.lastIterationUsage=void 0,u(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const c=50;for(let m=0;m<c;m+=1){if(u(`[ACodeRuntime] \u{1F504} Iteration ${m+1} starting...`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${m+1}, aborting`),{text:"",totalOutputTextLength:l.length};await this.injectForceMessage();const f=Date.now(),g=await this.requestChatCompletion(e),k=Date.now()-f;if(u(`[ACodeRuntime] \u{1F916} AI request completed in ${k}ms, choices: ${g.choices?.length||0}`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${m+1}`),{text:"",totalOutputTextLength:l.length};if(this.state.terminated)throw u(`[ACodeRuntime] Runtime terminated at iteration ${m+1}`),new Error("ACode runtime was stopped during the active turn");const T=g.choices?.[0];a=JSON.stringify(g,null,2),i=typeof T?.finish_reason=="string"?T.finish_reason:void 0;const b=T?.message,C=typeof b?.content=="string"?b.content:"",d=Array.isArray(b?.tool_calls)?b.tool_calls:[];if(u(`[ACodeRuntime] AI response: content=${C?C.slice(0,100)+(C.length>100?"...":""):"(empty)"}, toolCalls=${d.length}, finishReason=${i||"(none)"}`),g.usage){const S=q(g.usage.prompt_tokens??g.usage.input_tokens),w=q(g.usage.completion_tokens??g.usage.output_tokens),E=S!==void 0,p=w!==void 0;if(G(`provider usage parsed: raw=${JSON.stringify(g.usage)} input=${S} output=${w} hasInput=${E} hasOutput=${p} iteration=${m+1}`),E||p){const y=It(g.usage,S),R=n?.outputTokens??l.length+C.length;this.state.accumulatedCacheHitTokens+=y?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=y?.cacheMissTokens??0,n={inputTokens:E?S:n?.inputTokens??0,outputTokens:p?w:R,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=n,r+=E?S:0,this.state.accumulatedInputTokens=E?S:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=p?w:this.state.accumulatedOutputTokens,G(`finalUsage updated: ${JSON.stringify(n)} (cacheUsage=${JSON.stringify(y??null)})`),u(`[ACodeRuntime] \u{1F4B0} Token usage: input=${n.inputTokens}, output=${n.outputTokens} (turn accumulated cost: input=${r})`),u(y?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${y.cacheHitTokens}, miss=${y.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else G(`provider response has NO usage field (fallback to text-length estimate), iteration=${m+1}`);if(this.state.conversation.push({role:"assistant",content:C||null,tool_calls:d.length>0?d:void 0}),C&&(o=C,l+=C,u(`[ACodeRuntime] \u2728 Captured assistant text: ${C.slice(0,80)}...`)),d.length===0)return u(`[ACodeRuntime] \u2705 No tool calls at iteration ${m+1}, completing turn`),{text:o,usage:n,responseBody:a,finishReason:i,totalOutputTextLength:l.length};const A=d.map(S=>S.function.name).join(", ");u(`[ACodeRuntime] \u{1F527} Executing ${d.length} tool(s) at iteration ${m+1}: ${A}`);const M=Date.now();await this.handleToolCalls(d,e,t);const _=Date.now()-M;if(u(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${_}ms at iteration ${m+1}`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${m+1}`),{text:"",totalOutputTextLength:l.length};u(`[ACodeRuntime] \u{1F504} Preparing iteration ${m+2}...`)}return console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: Reached safety limit of ${c} iterations! This indicates a potential infinite loop. Forcing turn completion.`),{text:o||`ACode \u5DF2\u8FBE\u5230\u5B89\u5168\u8FED\u4EE3\u4E0A\u9650\uFF08${c}\u6B21\uFF09\uFF0C\u5F3A\u5236\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD\u3002`,usage:n,responseBody:a,finishReason:i||"safety_iteration_limit_reached",totalOutputTextLength:l.length}}async summarizeConversationWithLLM(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured for LLM summarization");const n={"Content-Type":"application/json"};t.apiKey&&(n.Authorization=`Bearer ${t.apiKey}`);const a={model:t.model,stream:!1,messages:[{role:"system",content:"You are a helpful AI assistant tasked with summarizing conversations. When asked to summarize, provide a detailed but concise summary of the conversation. Focus on information that would be helpful for continuing the conversation, especially what was in progress and what needs to happen next. Do not respond to any questions in the conversation, only output the summary."},{role:"user",content:`Below is an earlier conversation (${e.messageCount} messages) that needs to be summarized to free context space (current context limit: ${e.contextLimit} tokens).
10
+ `);this.initialConversation=me(J),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:a,permissions:i,mcpConnections:l,ownsMcpConnections:r,exposedTools:S,commands:y,commandRegistry:v,conversation:me(J),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:this.state.toolPermissionPolicy},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:y.length});const I=de(a);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:y.length,estimatedContextTokens:jt(V,S),contextLimit:I.contextLimit,maxOutput:I.maxOutput,...I.inputLimit!==void 0?{inputLimit:I.inputLimit}:{},compactionThreshold:I.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:l.length,builtInToolCount:f.length,toolCount:S.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:S.map(h=>({name:h.exposedName,source:h.kind==="mcp"?`${h.serverName}.${h.toolName}`:`builtin.${h.toolName}`,description:h.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(h=>({name:h.name,description:h.description,directory:h.directory})),skillGroups:o.map(h=>({dir:h.dir,exists:h.exists,skills:h.skills.map(B=>({name:B.name,description:B.description,directory:B.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:y.length,commandDirs:E,commands:y.map(h=>({name:h.name,description:h.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(n)}async loadAllSkills(){const e=this.config.skillsDir??"",t=H.join(this.config.workingDirectory,".acode","skills"),o=H.join(this.config.workingDirectory,".agentswork","skills"),n=new Set,a=[],i=[];for(const c of[e,t,o]){if(!c)continue;const m=H.resolve(c);if(!n.has(m)){n.add(m),a.push(await bt(c));try{await F.promises.access(m),i.push(m)}catch{}}}const l=new Map;for(const c of a)for(const m of c.skills)l.set(m.name,m);return{skills:[...l.values()],skillGroups:a,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=F.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=F.watch(t,()=>{this.scheduleSkillRefresh()})}catch{continue}}o&&(o.on("error",()=>{}),this.skillWatchers.push(o))}}scheduleSkillRefresh(){this.skillRefreshTimer&&clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=setTimeout(()=>{this.skillRefreshTimer=null,this.refreshSkills()},Y.SKILL_REFRESH_DEBOUNCE_MS)}async refreshSkills(){if(!(!this.state.started||this.state.terminated))try{const{skills:e,skillGroups:t}=await this.loadAllSkills();this.skillTool&&this.skillTool.refresh(e),this.state.skills=e,this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:e.length,skills:e.map(o=>({name:o.name,description:o.description,directory:o.directory})),skillGroups:t.map(o=>({dir:o.dir,exists:o.exists,skills:o.skills.map(n=>({name:n.name,description:n.description,directory:n.directory}))}))}),u(`[skill-watch] Skills refreshed: ${e.length} skills (${e.map(o=>o.name).join(", ")||"none"})`,{sessionId:this.config.sessionId})}catch(e){console.error("[skill-watch] Failed to refresh skills:",e instanceof Error?e.message:e)}}stopSkillWatchers(){this.skillRefreshTimer&&(clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=null);for(const e of this.skillWatchers)try{e.close()}catch{}this.skillWatchers=[]}startCompactionDebugLog(){if(!le||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:n,threshold:a}=de(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,l=se(this.state.conversation)+Be(this.state.exposedTools),r=Math.max(i,l),c=Z(this.state.conversation),m=this.state.started&&!this.state.terminated,f=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${c}KB`,`estimation=${l} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${n??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${a}`,`remainingToTrigger=${Math.max(0,a-i)}`,`isRunning=${m}`,`shouldCompact=${m?r>=a:!1}`,"---"].join(" | ");F.promises.appendFile(Oe,f+`
11
+ `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;u(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${t}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const o=this.submitQueue.then(()=>(u(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmitGuarded(e,t)));return this.submitQueue=o.catch(()=>{u("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),u("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}executeSubmitGuarded(e,t){const o={};this.activeTurnToken=o;const n=this.executeSubmit(e,t),a=new Promise(i=>{this.forceSettleWaiters.set(o,i)});return n.finally(()=>{this.forceSettleWaiters.delete(o),this.activeTurnToken===o&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([n,a])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=Eo();this.abortForceSettleTimer=setTimeout(()=>{this.abortForceSettleTimer=null,this.activeTurn&&this.activeTurnToken===e&&this.forceSettleActiveTurn(`turn still unsettled ${t}ms after abort()`)},t),typeof this.abortForceSettleTimer.unref=="function"&&this.abortForceSettleTimer.unref()}forceSettleActiveTurn(e){const t=this.activeTurnToken;console.error(`[ACodeRuntime] \u{1F6A8} FORCE SETTLE: active turn ignored abort() (${e}). Force-settling to unblock submitQueue; late executeSubmit continuation will be superseded.`),this.contextVersion+=1,this.activeTurn=!1,this.abortRequested=!1,this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.emitAcodeEvent("error",{message:`ACode turn force-settled: ${e}`}),this.emitAcodeEvent("turn_complete",{failed:!0});const o=t?this.forceSettleWaiters.get(t):void 0;t&&this.forceSettleWaiters.delete(t),this.activeTurnToken=null,o?.()}notifyForceMessage(){this.forceMessagePending=!0,u("[ACodeRuntime] \u{1F514} Force message pending flag set")}addBuiltInTools(e){if(!this.state||!this.exposedToolsInitialized||!Array.isArray(e))return 0;const t=new Set(this.state.exposedTools.map(n=>n.exposedName)),o=[];for(const n of e)vt(n)&&(t.has(n.exposedName)||(t.add(n.exposedName),o.push(n)));return o.length===0?0:(this.state.exposedTools=[...this.state.exposedTools,...o],this.emitExposedToolsStatus(),o.length)}removeBuiltInToolsByPrefix(e){if(!this.state||!this.exposedToolsInitialized||!e)return 0;const t=this.state.exposedTools.length;this.state.exposedTools=this.state.exposedTools.filter(n=>!n.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}addPluginCommands(e){if(!this.state||e.length===0)return;this.state.commandRegistry.addCommands(e);const t=new Set(this.state.commands.map(o=>o.name));this.state.commands=[...this.state.commands,...e.filter(o=>!t.has(o.name))]}emitExposedToolsStatus(){this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(e=>e.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(e=>({name:e.exposedName,source:e.kind==="mcp"?`${e.serverName}.${e.toolName}`:`builtin.${e.toolName}`,description:e.description||""}))})}async injectForceMessage(){if(!this.forceMessagePending)return!1;this.forceMessagePending=!1;const e=this.state.mcpConnections.find(t=>t.tools.some(o=>o.toolName==="get_message"));if(!e)return u("[ACodeRuntime] injectForceMessage: no connection with get_message found"),!1;try{const t=await x(e.client.callTool({name:"get_message",arguments:{_aws_force_inject:!0}},void 0,{timeout:1e4}),1e4,"injectForceMessage get_message"),o=O(t);let n=[];try{const r=JSON.parse(o);Array.isArray(r?.directMessages)&&(n=r.directMessages.filter(c=>c?.force===!0))}catch{return!1}if(n.length===0)return!1;const a=JSON.stringify({directMessages:n,groupMessages:[]}),i=`forced_get_msg_${Date.now()}`,l=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:i,type:"function",function:{name:l,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:i,content:a}),u(`[ACodeRuntime] injectForceMessage: injected ${n.length} force message(s) into conversation`),!0}catch(t){return u(`[ACodeRuntime] injectForceMessage failed: ${t}`),!1}}async resetContext(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");this.contextVersion+=1,this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.state.conversation=me(this.initialConversation),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t){const o=Date.now();if(u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),u("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),u(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),u(`[ACodeRuntime] \u{1F522} Context version: ${t}`),u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const n=this.activeTurnToken,a=e.trim();let i=!1;try{u("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const l=Date.now(),r=await this.hookBus.dispatch("UserPromptSubmit",{prompt:a}),c=Date.now()-l;if(u(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${c}ms, results: ${r.length}`),this.isTurnSuperseded(t)){u("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const m=ue(r);if(m){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${m.message}`),this.emitAcodeEvent("error",{message:m.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}u("[ACodeRuntime] \u{1F50D} Expanding command if any...");const f=this.state.commandRegistry.expand(a),g=f?.prompt.trim()||a,k=f?.command.allowedTools;if(f){u(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${f.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:f.command.name,arguments:f.argumentsText,sourcePath:f.command.sourcePath});const C=f.command.plugin;C&&(u(`[ACodeRuntime] \u{1F4CB} Slash command belongs to plugin: ${C}`),this.config.pluginBridge?.exposePlugin?.(C))}if(!this.state.provider.baseURL){u("[ACodeRuntime] \u26A0\uFE0F No provider baseURL configured, using fallback response");const C=mo(g,this.state);this.emitAcodeEvent("assistant_delta",{text:C}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:C.length}}),i=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}u("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const T=fe(g);if(T.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");u("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const b=await Fe(T.content);if(this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}u("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:b}),u(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),u("[ACodeRuntime] Starting runModelTurn...");const _=Date.now(),d=await this.runModelTurn(k,t),A=Date.now()-_;if(u(`[ACodeRuntime] \u2705 runModelTurn completed in ${A}ms`),u(`[ACodeRuntime] \u{1F4DD} Result: text=${d.text?d.text.slice(0,80)+(d.text.length>80?"...":""):"(empty)"}, finishReason=${d.finishReason||"(none)"}`),this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}d.text&&!this.state.provider.stream&&(u("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:d.text})),u("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length},...d.responseBody?{responseBody:d.responseBody}:{},...d.finishReason?{finishReason:d.finishReason}:{}}),G(`turn_complete emitted: usage=${JSON.stringify(d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length})} (providerUsage=${d.usage?"real":"FALLBACK-text-length"}) textLength=${d.text.length} totalOutputTextLength=${d.totalOutputTextLength}`),u(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(d.usage?"":" (estimated, no provider usage)")),i=!0;const M=Date.now()-o;u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),u(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${M}ms`),u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(l){const r=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${r}ms:`,l instanceof Error?l.message:String(l)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",l instanceof Error?l.stack:"(no stack)"),this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){u("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),i=!0;return}u("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:l instanceof Error?l.message:String(l)}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0}finally{const l=Date.now()-o;u(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${l}ms`),u(`[ACodeRuntime] \u{1F50D} turnCompleted=${i}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===n&&(this.activeTurn=!1,this.abortRequested=!1),!i&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${l}ms. This indicates a code path that should have emitted turn_complete but didn't. Forcing failed turn_complete to prevent state stuck.`),this.emitAcodeEvent("error",{message:"ACode turn completed without proper completion event (internal error)"}),this.emitAcodeEvent("turn_complete",{failed:!0}),u("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(u(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.armAbortForceSettle()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,n)=>{this.questionWaiters.set(e,{resolve:o,reject:n,contextVersion:t})})}}async buildAllocatableToolList(){const e=this.state?.exposedTools??[],t=this.config.subAgentSuiteTools??[];let o=[];if(this.config.subAgentSuiteToolProvider)try{o=await this.config.subAgentSuiteToolProvider([])}catch{o=[]}return ne(e,ne(t,o))}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,n=this.config.workingDirectory,a=this.config;return{spawnSubAgent:async i=>{let l=this.config.subAgentSuiteTools;if(i.allowedTools&&i.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const c=await this.config.subAgentSuiteToolProvider(i.allowedTools);c.length>0&&(l=l?ne(l,c):c)}catch{}const r=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,...i.allowedTools&&i.allowedTools.length>0?{allowedTools:i.allowedTools}:{},workingDirectory:n,parentConfig:{...a,sharedMcpConnections:this.state?.mcpConnections,...l&&l.length>0?{subAgentSuiteTools:l}:{}}});return await e.start(r),{subId:r}},listSubAgentToolCatalog:async()=>$e(await this.buildAllocatableToolList()),listSubAgents:async()=>{const i=e.listByParent(t),l=[],r=[];for(const c of i){const m={subId:c.subId,subagentType:c.subagentType,description:c.description,status:c.status,startedAt:c.startedAt,endedAt:c.endedAt,durationMs:c.durationMs};c.status==="pending"||c.status==="running"?l.push(m):r.push(m)}return r.sort((c,m)=>(m.endedAt??0)-(c.endedAt??0)),{running:l,history:r}},getSubAgentStatus:async i=>{const l=e.getSubAgent(i);return l?{subId:l.subId,subagentType:l.subagentType,description:l.description,status:l.status,startedAt:l.startedAt,endedAt:l.endedAt,durationMs:l.durationMs,prompt:l.prompt,result:l.result,errorMessage:l.errorMessage,contextSnapshot:l.contextSnapshot}:null},awaitSubAgents:async(i,l)=>{const r=new Set;for(const c of i)this.pendingAwaitedSubIds.add(c),r.add(c);try{return await e.awaitCompletion(i,l)}finally{for(const c of r)this.pendingAwaitedSubIds.delete(c)}},abortSubAgent:i=>e.abort(i)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,n)=>{for(const a of o)this.pendingAwaitedSubIds.add(a);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,n)}finally{for(const a of o)this.pendingAwaitedSubIds.delete(a)}}:null,awaitBgCommands:(o,n)=>{for(const a of o)this.pendingAwaitedBgTaskIds.add(a);try{return X.awaitCompletion(e,o,n)}finally{for(const a of o)this.pendingAwaitedBgTaskIds.delete(a)}}}}submitQuestionAnswer(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}createToolPermissionController(){return{getLevel:e=>this.state.toolPermissionPolicy[e]??"allow",requestPermission:(e,t)=>this.requestToolPermission(e,t)}}requestToolPermission(e,t){const o=Xe();return new Promise(n=>{this.permissionWaiters.set(o,{capability:e,detail:t,resolve:n}),this.emitAcodeEvent("tool_permission_request",{requestId:o,capability:e,agentId:this.config.agentId,...t})})}submitToolPermissionDecision(e,t){const o=this.permissionWaiters.get(e);return o?(this.permissionWaiters.delete(e),o.resolve(t),!0):!1}rejectAllPermissionWaiters(e){if(this.permissionWaiters.size!==0){for(const[,t]of this.permissionWaiters)t.resolve(!1);this.permissionWaiters.clear(),D("tool-permission",`waiters rejected: ${e}`)}}setToolPermissionPolicy(e){this.state.toolPermissionPolicy={...this.state.toolPermissionPolicy,...e}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);u(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(n=>{u(`[ACodeRuntime] \u26A0\uFE0F manager.abort(${o}) threw: ${n instanceof Error?n.message:String(n)}`)})}cancelPendingAwaitedBgTasks(){if(this.pendingAwaitedBgTaskIds.size===0)return;const e=this.config.agentId??"unknown",t=Array.from(this.pendingAwaitedBgTaskIds);u(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),X.interruptAwaits(e,t)}detachCurrentToolExecution(){const e=this.toolSettleSlot;return!e||!e.settlable||e.settled?!1:(e.settled=!0,e.resolveSettle?.(),u(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${e.toolName} (toolCallId=${e.toolCallId}) to background`),!0)}beginToolSettle(e,t,o){const n=e.toolName==="Bash",a=++this.toolSettleSeq;let i;const l=n?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:a,toolName:e.toolName,toolCallId:o,settlable:n,settled:!1,resolveSettle:i??null},{seq:a,signal:l}}clearToolSettle(e){this.toolSettleSlot?.seq===e&&(this.toolSettleSlot=null)}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.armAbortForceSettle(),this.rejectAllQuestionWaiters("session terminated"),this.rejectAllPermissionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await ee("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await ee("ACode background commands shutdown",X.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),ee("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await ee("ACode Stop hooks",this.hookBus.dispatch("Stop",{reason:"session_stop"}),t=>{this.emitAcodeEvent("error",{message:t})}),this.state.terminated=!0,this.sessionCompleteEmitted||(this.sessionCompleteEmitted=!0,this.emitAcodeEvent("session_complete",{exitCode:0})),this.stopCompactionDebugLog(),this.stopSkillWatchers(),le)try{F.promises.appendFile(Oe,`[${new Date().toISOString()}] runtime stopped | ---
12
+ `,"utf-8").catch(()=>{})}catch{}}discoverPluginCommandDirs(){const e=this.config.pluginsDir;if(!e)return[];let t;try{t=F.readdirSync(e)}catch{return[]}const o=[];for(const n of t){if(n.startsWith("."))continue;const a=H.join(e,n);let i;try{i=F.statSync(a)}catch{continue}if(!i.isDirectory())continue;const l=H.join(a,"commands");let r;try{F.existsSync(l)&&(r=F.statSync(l))}catch{r=void 0}r?.isDirectory()&&o.push(l)}return o}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",n,a,i,l="",r=0;this.lastIterationUsage=void 0,u(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const c=50;for(let m=0;m<c;m+=1){if(u(`[ACodeRuntime] \u{1F504} Iteration ${m+1} starting...`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${m+1}, aborting`),{text:"",totalOutputTextLength:l.length};await this.injectForceMessage();const f=Date.now(),g=await this.requestChatCompletion(e),k=Date.now()-f;if(u(`[ACodeRuntime] \u{1F916} AI request completed in ${k}ms, choices: ${g.choices?.length||0}`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${m+1}`),{text:"",totalOutputTextLength:l.length};if(this.state.terminated)throw u(`[ACodeRuntime] Runtime terminated at iteration ${m+1}`),new Error("ACode runtime was stopped during the active turn");const T=g.choices?.[0];a=JSON.stringify(g,null,2),i=typeof T?.finish_reason=="string"?T.finish_reason:void 0;const b=T?.message,_=typeof b?.content=="string"?b.content:"",d=Array.isArray(b?.tool_calls)?b.tool_calls:[];if(u(`[ACodeRuntime] AI response: content=${_?_.slice(0,100)+(_.length>100?"...":""):"(empty)"}, toolCalls=${d.length}, finishReason=${i||"(none)"}`),g.usage){const S=q(g.usage.prompt_tokens??g.usage.input_tokens),w=q(g.usage.completion_tokens??g.usage.output_tokens),E=S!==void 0,p=w!==void 0;if(G(`provider usage parsed: raw=${JSON.stringify(g.usage)} input=${S} output=${w} hasInput=${E} hasOutput=${p} iteration=${m+1}`),E||p){const y=Pt(g.usage,S),v=n?.outputTokens??l.length+_.length;this.state.accumulatedCacheHitTokens+=y?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=y?.cacheMissTokens??0,n={inputTokens:E?S:n?.inputTokens??0,outputTokens:p?w:v,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=n,r+=E?S:0,this.state.accumulatedInputTokens=E?S:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=p?w:this.state.accumulatedOutputTokens,G(`finalUsage updated: ${JSON.stringify(n)} (cacheUsage=${JSON.stringify(y??null)})`),u(`[ACodeRuntime] \u{1F4B0} Token usage: input=${n.inputTokens}, output=${n.outputTokens} (turn accumulated cost: input=${r})`),u(y?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${y.cacheHitTokens}, miss=${y.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else G(`provider response has NO usage field (fallback to text-length estimate), iteration=${m+1}`);if(this.state.conversation.push({role:"assistant",content:_||null,tool_calls:d.length>0?d:void 0}),_&&(o=_,l+=_,u(`[ACodeRuntime] \u2728 Captured assistant text: ${_.slice(0,80)}...`)),d.length===0)return u(`[ACodeRuntime] \u2705 No tool calls at iteration ${m+1}, completing turn`),{text:o,usage:n,responseBody:a,finishReason:i,totalOutputTextLength:l.length};const A=d.map(S=>S.function.name).join(", ");u(`[ACodeRuntime] \u{1F527} Executing ${d.length} tool(s) at iteration ${m+1}: ${A}`);const M=Date.now();await this.handleToolCalls(d,e,t);const C=Date.now()-M;if(u(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${C}ms at iteration ${m+1}`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${m+1}`),{text:"",totalOutputTextLength:l.length};u(`[ACodeRuntime] \u{1F504} Preparing iteration ${m+2}...`)}return console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: Reached safety limit of ${c} iterations! This indicates a potential infinite loop. Forcing turn completion.`),{text:o||`ACode \u5DF2\u8FBE\u5230\u5B89\u5168\u8FED\u4EE3\u4E0A\u9650\uFF08${c}\u6B21\uFF09\uFF0C\u5F3A\u5236\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD\u3002`,usage:n,responseBody:a,finishReason:i||"safety_iteration_limit_reached",totalOutputTextLength:l.length}}async summarizeConversationWithLLM(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured for LLM summarization");const n={"Content-Type":"application/json"};t.apiKey&&(n.Authorization=`Bearer ${t.apiKey}`);const a={model:t.model,stream:!1,messages:[{role:"system",content:"You are a helpful AI assistant tasked with summarizing conversations. When asked to summarize, provide a detailed but concise summary of the conversation. Focus on information that would be helpful for continuing the conversation, especially what was in progress and what needs to happen next. Do not respond to any questions in the conversation, only output the summary."},{role:"user",content:`Below is an earlier conversation (${e.messageCount} messages) that needs to be summarized to free context space (current context limit: ${e.contextLimit} tokens).
13
13
 
14
14
  --- Conversation Start ---
15
15
  ${e.conversationText}
16
16
  --- Conversation End ---
17
17
 
18
- `+At}]},i=new AbortController;this.abortController=i;let l=!1;try{return await x((async()=>{const r=await x(fetch(ce(o),{method:"POST",headers:n,body:JSON.stringify(a),signal:i.signal}),t.requestTotalTimeoutMs,"ACode LLM summarization",()=>{l=!0,i.abort()});if(!r.ok){const f=await x(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{l=!0,i.abort()}),g=f.length>500?`${f.slice(0,500)}...(truncated, total ${f.length} chars)`:f;throw new Error(`ACode LLM summarization request failed: ${r.status} ${g}`)}const m=(await x(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{l=!0,i.abort()})).choices?.[0]?.message?.content;if(!m||m.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return m})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{i.abort()})}catch(r){throw r instanceof Error&&r.name==="AbortError"?l?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):r}finally{this.abortController===i&&(this.abortController=null)}}async requestChatCompletion(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured");const{contextLimit:n,maxOutput:a,inputLimit:i,threshold:l}=de(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,c=se(this.state.conversation)+Be(this.state.exposedTools),m=Math.max(r,c),f=m>=l;if(u(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${c}, effectiveUsed=${m}, contextLimit=${n}, inputLimit=${i??"n/a"}, maxOutput=${a}, triggerThreshold=${l}, shouldCompact=${f}`),f){const p=Z(this.state.conversation),y=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:y,sizeKB:p,estimatedTokens:c,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:r>=l?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(y,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${m} tokens, \u9608\u503C: ${l}, \u89E6\u53D1: ${r>=l?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const R=await _e(this.state.conversation,n,a,{llmSummarizer:$=>this.summarizeConversationWithLLM($),onPhase:$=>this.handleCompactionPhase(y,$),actualUsedTokens:m}),I=Z(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:y,sizeBeforeKB:p,sizeAfterKB:I,freedKB:Math.round((p-I)*10)/10,strategy:R.strategy,freedTokens:R.freedTokens,tokensBefore:R.tokensBefore,tokensAfter:R.tokensAfter,prunedToolMessages:R.prunedToolMessages,summarizedMessages:R.summarizedMessages,messageCountBefore:R.messageCountBefore,messageCountAfter:R.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const g=await po(this.state.conversation,Le,n,a,p=>this.summarizeConversationWithLLM(p));g>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${g} older messages to fit within ${Le} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const k=this.state.exposedTools.filter(p=>ao(p,this.state.permissions,e)),T=()=>{const p={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(p.reasoning_effort=t.effort),t.stream&&(p.stream_options={include_usage:!0}),k.length>0&&(p.tools=Ke(k),p.tool_choice="auto"),p},b="POST",C=lo(o),d=$o(t),A=ko(d),M=p=>{const y=JSON.stringify(p,null,2);u(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${C}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:C,requestMethod:b,requestUrl:C,requestHeaders:A,stream:t.stream,messageCount:this.state.conversation.length,toolCount:k.length,lastUserMessagePreview:co(this.state.conversation),estimatedContextTokens:he(y),requestBody:y,...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),G(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${k.length} estimatedContextTokens=${he(y)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let _=T();M(_);const S=t.requestRetryCount===ie,w=S?1/0:t.requestRetryCount+1;let E=!1;for(let p=1;S||p<=w;p+=1){this.state.terminated||(this.abortRequested=!1),p>1&&M(_);const y=new AbortController;this.abortController=y;let R=!1;try{return await x((async()=>{const I=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,$=await x(fetch(ce(o),{method:b,headers:d,body:JSON.stringify(_),signal:y.signal}),I,"ACode provider request",()=>{R=!0,y.abort()});if(!$.ok){const U=await x($.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{R=!0,y.abort()}),W=U.length>500?`${U.slice(0,500)}...(truncated, total ${U.length} chars)`:U;throw new Error(`ACode provider request failed: ${$.status} ${W}`)}const L=$.headers?.get?.("content-type")||"";if(t.stream&&L.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream($,t.requestStreamIdleTimeoutMs,y,t.requestFirstByteTimeoutMs);const j=await x($.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{R=!0,y.abort()});return v(j)?j:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof j}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{y.abort()})}catch(I){let $;if(I instanceof Error&&I.name==="AbortError"?R?$=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?$=new Error("ACode provider request aborted by user"):$=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):$=I instanceof Error?I:new Error(String(I)),!E&&!this.abortRequested&&!this.state.terminated&&Je($)){const W=Z(this.state.conversation),J=se(this.state.conversation),V=this.state.conversation.length,P=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:P,sizeKB:W,estimatedTokens:J,messageCount:V,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(P,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${V}\u6761, \u5927\u5C0F: ${W}KB`),this.emitCompactionPhase(P,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const h=Ct(this.state.conversation,n);this.emitCompactionPhase(P,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${h.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${h.freedTokens} tokens`),this.emitCompactionPhase(P,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const B=await be(this.state.conversation,{llmSummarizer:Ye=>this.summarizeConversationWithLLM(Ye),contextLimit:n});this.emitCompactionPhase(P,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${B} \u6761\u6D88\u606F`);const Te=Z(this.state.conversation),Ge=se(this.state.conversation),Qe=this.state.conversation.length;E=!0;const ye=h.prunedCount+B;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:P,sizeBeforeKB:W,sizeAfterKB:Te,freedKB:Math.round((W-Te)*10)/10,tokensBefore:J,tokensAfter:Ge,messageCountBefore:V,messageCountAfter:Qe,strategy:B>0?"summarize":"prune",freedTokens:h.freedTokens,prunedToolMessages:h.prunedCount,summarizedMessages:B,trigger:"provider_overflow_error"}),ye===0)throw $;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${ye} older messages and rebuilt the request instead of retrying the same oversized payload`}),_=T(),M(_),p-=1;continue}if(!((S||p<w)&&!this.abortRequested&&!this.state.terminated&&fo($)))throw $;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${p}${S?"":`/${w}`} failed; retrying: ${$.message}`,nonFatal:!0});const j=Math.min(Ot,Lt*Math.pow(2,p-1)),U=Math.random()*1e3;await Wt(j+U)}finally{this.abortController===y&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,n){if(!e.body)throw new Error("ACode provider stream response has no body");const a=e.body.getReader(),i=new TextDecoder,l=new Map;let r="",c="",m;const f=k=>{for(const T of vo(k)){if(T==="[DONE]")continue;const b=JSON.parse(T);if(!v(b))continue;const C=b.usage;C&&(m=Pt(m,C),G(`stream usage chunk received: ${JSON.stringify(C)} -> merged: ${JSON.stringify(m)}`));const A=b.choices?.[0]?.delta,M=Ao(A);M&&this.emitAcodeEvent("thinking_delta",{text:M});const _=typeof A?.content=="string"?A.content:"";_&&(r+=_,this.emitAcodeEvent("assistant_delta",{text:_}));const S=Array.isArray(A?.tool_calls)?A.tool_calls:[];for(const w of S)Ro(l,w)}};let g=!0;for(;;){const k=g&&n?n:t,{done:T,value:b}=await x(a.read(),k,g?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(g=!1,T)break;c+=i.decode(b,{stream:!0});const C=c.split(/\r?\n\r?\n/);c=C.pop()??"";for(const d of C)f(d)}return c+=i.decode(),c.trim()&&f(c),{choices:[{message:{content:r||null,tool_calls:xo(l)}}],...m?{usage:m}:{}}}async handleToolCalls(e,t,o=this.contextVersion){u(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const n=i=>we(i.function.name)==="poll_message",a=[...e.filter(i=>!n(i)),...e.filter(i=>n(i))];e.length>1&&a.some((i,l)=>i!==e[l])&&u(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${a.map(i=>i.function.name).join(", ")}`);for(const i of a){if(this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const l=i.function.name;u(`[ACodeRuntime] \u{1F50D} Looking up tool: ${l}`);let r=this.state.exposedTools.find(c=>c.exposedName===l);if(r||(r=this.state.exposedTools.find(c=>c.toolName===l),r&&u(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${l} -> ${r.exposedName}`)),!r){console.error(`[ACodeRuntime] \u274C Tool not found: ${l}, available tools: ${this.state.exposedTools.map(c=>c.exposedName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP tool not found: ${l}`});continue}u(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const _=We(i.function.arguments);u(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(_).slice(0,200)}`),ge(r,this.state.permissions,t);const S=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:_});if(this.isTurnSuperseded(o))return;const w=ue(S);if(w)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${w.message}`),new Error(w.message||`ACode tool denied by hook: ${r.exposedName}`);u(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:_,argumentsPreview:He(_)});const E=Date.now(),p=uo(r,_,this.state.provider.mcpToolTimeoutMs);u(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${p}ms, abortRequested: ${this.abortRequested})`),p<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${p})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const y=this.beginToolSettle(r,_,i.id);try{const R=await x(r.execute(_,{onOutput:L=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:L.stream,text:L.text,sequence:L.sequence,cwd:L.cwd,commandLineCount:L.commandLineCount,...L.commandFilePath?{commandFilePath:L.commandFilePath}:{}})},toolCallId:i.id,...y.signal?{settleSignal:y.signal}:{}}),p,`ACode built-in tool ${r.toolName}`),I=Date.now()-E;if(u(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${I}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,result:O(R)}),this.isTurnSuperseded(o)))return;const $=O(R);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${$.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,toolUseId:i.id,result:$}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:$}),await this.appendSyntheticMultimodalUserMessage($,i.id,o)}finally{this.clearToolSettle(y.seq)}continue}const c=this.state.mcpConnections.find(_=>_.serverName===r.serverName);if(!c){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(_=>_.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const m=We(i.function.arguments);u(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(m).slice(0,200)}`),ge(r,this.state.permissions,t);const f=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:m});if(this.isTurnSuperseded(o))return;const g=ue(f);if(g)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${g.message}`),new Error(g.message||`ACode tool denied by hook: ${r.exposedName}`);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.serverName,tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:m,argumentsPreview:He(m)});const k=$t(r.toolName),T=kt(r.toolName),b=k?this.state.provider.mcpPollingToolTimeoutMs:T?0:this.state.provider.mcpToolTimeoutMs,C=Date.now();u(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${b}ms, polling: ${k})`);const d=k&&we(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(c,r,m,b):await this.callMcpToolWithTimeout(c,r,m,b,k),A=Date.now()-C;if(u(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${A}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:O(d)}),this.isTurnSuperseded(o)))return;let M=O(d);k&&(M=this.expandCommandsInPolledResult(M)),u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${M.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,toolUseId:i.id,result:M}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:M}),await this.appendSyntheticMultimodalUserMessage(M,i.id,o)}catch(c){const m=c instanceof Error&&c.message.includes("timed out after"),f=c instanceof Error&&c.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${m}, isAbortError=${f}`,c instanceof Error?c.message:String(c)),this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw u(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,toolUseId:i.id,result:`[aborted] ${c instanceof Error?c.message:String(c)}`,failed:!0,aborted:!0}),c instanceof Error?c:new Error(String(c));u(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${m})`),this.appendToolFailureResult(i,r,c)}}u(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,n,a,i){const l=n>0?n:Ut,c=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const m=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await x(Promise.race([e.client.callTool({name:t.toolName,arguments:c},void 0,{timeout:l,...i?{signal:i}:{}}),m.promise]),n,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(f){if(i?.aborted||!a||n>0||!go(f))throw f;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{m.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const n=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
18
+ `+At}]},i=new AbortController;this.abortController=i;let l=!1;try{return await x((async()=>{const r=await x(fetch(ce(o),{method:"POST",headers:n,body:JSON.stringify(a),signal:i.signal}),t.requestTotalTimeoutMs,"ACode LLM summarization",()=>{l=!0,i.abort()});if(!r.ok){const f=await x(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{l=!0,i.abort()}),g=f.length>500?`${f.slice(0,500)}...(truncated, total ${f.length} chars)`:f;throw new Error(`ACode LLM summarization request failed: ${r.status} ${g}`)}const m=(await x(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{l=!0,i.abort()})).choices?.[0]?.message?.content;if(!m||m.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return m})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{i.abort()})}catch(r){throw r instanceof Error&&r.name==="AbortError"?l?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):r}finally{this.abortController===i&&(this.abortController=null)}}async requestChatCompletion(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured");const{contextLimit:n,maxOutput:a,inputLimit:i,threshold:l}=de(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,c=se(this.state.conversation)+Be(this.state.exposedTools),m=Math.max(r,c),f=m>=l;if(u(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${c}, effectiveUsed=${m}, contextLimit=${n}, inputLimit=${i??"n/a"}, maxOutput=${a}, triggerThreshold=${l}, shouldCompact=${f}`),f){const p=Z(this.state.conversation),y=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:y,sizeKB:p,estimatedTokens:c,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:r>=l?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(y,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${m} tokens, \u9608\u503C: ${l}, \u89E6\u53D1: ${r>=l?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const v=await _e(this.state.conversation,n,a,{llmSummarizer:$=>this.summarizeConversationWithLLM($),onPhase:$=>this.handleCompactionPhase(y,$),actualUsedTokens:m}),P=Z(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:y,sizeBeforeKB:p,sizeAfterKB:P,freedKB:Math.round((p-P)*10)/10,strategy:v.strategy,freedTokens:v.freedTokens,tokensBefore:v.tokensBefore,tokensAfter:v.tokensAfter,prunedToolMessages:v.prunedToolMessages,summarizedMessages:v.summarizedMessages,messageCountBefore:v.messageCountBefore,messageCountAfter:v.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const g=await po(this.state.conversation,Le,n,a,p=>this.summarizeConversationWithLLM(p));g>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${g} older messages to fit within ${Le} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const k=this.state.exposedTools.filter(p=>ao(p,this.state.permissions,e)),T=()=>{const p={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(p.reasoning_effort=t.effort),t.stream&&(p.stream_options={include_usage:!0}),k.length>0&&(p.tools=Ke(k),p.tool_choice="auto"),p},b="POST",_=lo(o),d=$o(t),A=ko(d),M=p=>{const y=JSON.stringify(p,null,2);u(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${_}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:_,requestMethod:b,requestUrl:_,requestHeaders:A,stream:t.stream,messageCount:this.state.conversation.length,toolCount:k.length,lastUserMessagePreview:co(this.state.conversation),estimatedContextTokens:he(y),requestBody:y,...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),G(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${k.length} estimatedContextTokens=${he(y)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let C=T();M(C);const S=t.requestRetryCount===ie,w=S?1/0:t.requestRetryCount+1;let E=!1;for(let p=1;S||p<=w;p+=1){this.state.terminated||(this.abortRequested=!1),p>1&&M(C);const y=new AbortController;this.abortController=y;let v=!1;try{return await x((async()=>{const P=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,$=await x(fetch(ce(o),{method:b,headers:d,body:JSON.stringify(C),signal:y.signal}),P,"ACode provider request",()=>{v=!0,y.abort()});if(!$.ok){const U=await x($.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{v=!0,y.abort()}),W=U.length>500?`${U.slice(0,500)}...(truncated, total ${U.length} chars)`:U;throw new Error(`ACode provider request failed: ${$.status} ${W}`)}const L=$.headers?.get?.("content-type")||"";if(t.stream&&L.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream($,t.requestStreamIdleTimeoutMs,y,t.requestFirstByteTimeoutMs);const j=await x($.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{v=!0,y.abort()});return R(j)?j:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof j}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{y.abort()})}catch(P){let $;if(P instanceof Error&&P.name==="AbortError"?v?$=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?$=new Error("ACode provider request aborted by user"):$=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):$=P instanceof Error?P:new Error(String(P)),!E&&!this.abortRequested&&!this.state.terminated&&Je($)){const W=Z(this.state.conversation),J=se(this.state.conversation),V=this.state.conversation.length,I=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:I,sizeKB:W,estimatedTokens:J,messageCount:V,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(I,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${V}\u6761, \u5927\u5C0F: ${W}KB`),this.emitCompactionPhase(I,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const h=Ct(this.state.conversation,n);this.emitCompactionPhase(I,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${h.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${h.freedTokens} tokens`),this.emitCompactionPhase(I,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const B=await be(this.state.conversation,{llmSummarizer:Ye=>this.summarizeConversationWithLLM(Ye),contextLimit:n});this.emitCompactionPhase(I,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${B} \u6761\u6D88\u606F`);const Te=Z(this.state.conversation),Ge=se(this.state.conversation),Qe=this.state.conversation.length;E=!0;const ye=h.prunedCount+B;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:I,sizeBeforeKB:W,sizeAfterKB:Te,freedKB:Math.round((W-Te)*10)/10,tokensBefore:J,tokensAfter:Ge,messageCountBefore:V,messageCountAfter:Qe,strategy:B>0?"summarize":"prune",freedTokens:h.freedTokens,prunedToolMessages:h.prunedCount,summarizedMessages:B,trigger:"provider_overflow_error"}),ye===0)throw $;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${ye} older messages and rebuilt the request instead of retrying the same oversized payload`}),C=T(),M(C),p-=1;continue}if(!((S||p<w)&&!this.abortRequested&&!this.state.terminated&&fo($)))throw $;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${p}${S?"":`/${w}`} failed; retrying: ${$.message}`,nonFatal:!0});const j=Math.min(Ot,Lt*Math.pow(2,p-1)),U=Math.random()*1e3;await Wt(j+U)}finally{this.abortController===y&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,n){if(!e.body)throw new Error("ACode provider stream response has no body");const a=e.body.getReader(),i=new TextDecoder,l=new Map;let r="",c="",m;const f=k=>{for(const T of Ro(k)){if(T==="[DONE]")continue;const b=JSON.parse(T);if(!R(b))continue;const _=b.usage;_&&(m=It(m,_),G(`stream usage chunk received: ${JSON.stringify(_)} -> merged: ${JSON.stringify(m)}`));const A=b.choices?.[0]?.delta,M=Ao(A);M&&this.emitAcodeEvent("thinking_delta",{text:M});const C=typeof A?.content=="string"?A.content:"";C&&(r+=C,this.emitAcodeEvent("assistant_delta",{text:C}));const S=Array.isArray(A?.tool_calls)?A.tool_calls:[];for(const w of S)vo(l,w)}};let g=!0;for(;;){const k=g&&n?n:t,{done:T,value:b}=await x(a.read(),k,g?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(g=!1,T)break;c+=i.decode(b,{stream:!0});const _=c.split(/\r?\n\r?\n/);c=_.pop()??"";for(const d of _)f(d)}return c+=i.decode(),c.trim()&&f(c),{choices:[{message:{content:r||null,tool_calls:xo(l)}}],...m?{usage:m}:{}}}async handleToolCalls(e,t,o=this.contextVersion){u(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const n=i=>we(i.function.name)==="poll_message",a=[...e.filter(i=>!n(i)),...e.filter(i=>n(i))];e.length>1&&a.some((i,l)=>i!==e[l])&&u(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${a.map(i=>i.function.name).join(", ")}`);for(const i of a){if(this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const l=i.function.name;u(`[ACodeRuntime] \u{1F50D} Looking up tool: ${l}`);let r=this.state.exposedTools.find(c=>c.exposedName===l);if(r||(r=this.state.exposedTools.find(c=>c.toolName===l),r&&u(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${l} -> ${r.exposedName}`)),!r){console.error(`[ACodeRuntime] \u274C Tool not found: ${l}, available tools: ${this.state.exposedTools.map(c=>c.exposedName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP tool not found: ${l}`});continue}u(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const C=We(i.function.arguments);u(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(C).slice(0,200)}`),ge(r,this.state.permissions,t);const S=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:C});if(this.isTurnSuperseded(o))return;const w=ue(S);if(w)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${w.message}`),new Error(w.message||`ACode tool denied by hook: ${r.exposedName}`);u(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:C,argumentsPreview:He(C)});const E=Date.now(),p=uo(r,C,this.state.provider.mcpToolTimeoutMs);u(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${p}ms, abortRequested: ${this.abortRequested})`),p<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${p})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const y=this.beginToolSettle(r,C,i.id);try{const v=await x(r.execute(C,{onOutput:L=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:L.stream,text:L.text,sequence:L.sequence,cwd:L.cwd,commandLineCount:L.commandLineCount,...L.commandFilePath?{commandFilePath:L.commandFilePath}:{}})},toolCallId:i.id,...y.signal?{settleSignal:y.signal}:{}}),p,`ACode built-in tool ${r.toolName}`),P=Date.now()-E;if(u(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${P}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,result:O(v)}),this.isTurnSuperseded(o)))return;const $=O(v);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${$.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,toolUseId:i.id,result:$}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:$}),await this.appendSyntheticMultimodalUserMessage($,i.id,o)}finally{this.clearToolSettle(y.seq)}continue}const c=this.state.mcpConnections.find(C=>C.serverName===r.serverName);if(!c){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(C=>C.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const m=We(i.function.arguments);u(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(m).slice(0,200)}`),ge(r,this.state.permissions,t);const f=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:m});if(this.isTurnSuperseded(o))return;const g=ue(f);if(g)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${g.message}`),new Error(g.message||`ACode tool denied by hook: ${r.exposedName}`);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.serverName,tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:m,argumentsPreview:He(m)});const k=$t(r.toolName),T=kt(r.toolName),b=k?this.state.provider.mcpPollingToolTimeoutMs:T?0:this.state.provider.mcpToolTimeoutMs,_=Date.now();u(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${b}ms, polling: ${k})`);const d=k&&we(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(c,r,m,b):await this.callMcpToolWithTimeout(c,r,m,b,k),A=Date.now()-_;if(u(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${A}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:O(d)}),this.isTurnSuperseded(o)))return;let M=O(d);k&&(M=this.expandCommandsInPolledResult(M)),u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${M.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,toolUseId:i.id,result:M}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:M}),await this.appendSyntheticMultimodalUserMessage(M,i.id,o)}catch(c){const m=c instanceof Error&&c.message.includes("timed out after"),f=c instanceof Error&&c.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${m}, isAbortError=${f}`,c instanceof Error?c.message:String(c)),this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw u(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,toolUseId:i.id,result:`[aborted] ${c instanceof Error?c.message:String(c)}`,failed:!0,aborted:!0}),c instanceof Error?c:new Error(String(c));u(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${m})`),this.appendToolFailureResult(i,r,c)}}u(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,n,a,i){const l=n>0?n:Ut,c=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const m=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await x(Promise.race([e.client.callTool({name:t.toolName,arguments:c},void 0,{timeout:l,...i?{signal:i}:{}}),m.promise]),n,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(f){if(i?.aborted||!a||n>0||!go(f))throw f;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{m.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const n=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
19
19
  Error: ${o.error}`:`Sub-agent ${o.subId} [${o.status}]: ${o.description}
20
20
  Output: ${o.output.length>500?o.output.slice(0,500)+"... (truncated)":o.output}`;return{msgId:`subagent-completion-${o.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:n,requireReply:!1,prompt:`Sub-agent ${o.subId} (${o.description}) has reached terminal state: ${o.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}});return{content:[{type:"text",text:JSON.stringify({directMessages:t,groupMessages:[],fromBuffer:!1,systemMessages:[]},null,2)}]}}static mergeSubAgentCompletionsIntoMcpResult(e,t){if(t.length===0)return e;const o=O(e);let n;try{n=JSON.parse(o)}catch{return e}const i=[...t.map(l=>{const r=l.error?`Sub-agent ${l.subId} [${l.status}]: ${l.description}
21
21
  Error: ${l.error}`:`Sub-agent ${l.subId} [${l.status}]: ${l.description}
@@ -105,5 +105,5 @@ ${l}`}).join(`
105
105
  - \u2705 \u82E5\u5168\u90E8 memory_status \u4E3A "normal"\uFF1A\u9759\u9ED8\u7ED3\u675F
106
106
 
107
107
  \u6CE8\u610F\uFF1A\u4F60\u8FD0\u884C\u5728\u72EC\u7ACB\u7684\u4E0A\u4E0B\u6587\u7A97\u53E3\u4E2D\uFF0C\u4E0D\u5F71\u54CD\u4E3B agent \u7684\u4E3B\u7EBF\u4EFB\u52A1\u3002\u8BF7\u9AD8\u6548\u5B8C\u6210\uFF0C\u4E0D\u8981\u8BE2\u95EE\u7528\u6237\u3002
108
- \u5B8C\u6210\u540E\u7CFB\u7EDF\u4F1A\u901A\u8FC7\u67E5\u8BE2\u670D\u52A1\u7AEF\u771F\u5B9E\u72B6\u6001\u8FDB\u884C\u4E8C\u6B21\u9A8C\u8BC1\uFF08\u4E0D\u4F9D\u8D56\u4F60\u7684\u81EA\u62A5\u7ED3\u679C\uFF09\u3002\u82E5\u9A8C\u8BC1\u53D1\u73B0\u4ECD\u6709 memory \u7684 memory_status \u4E3A "updating"\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`}async processMemoryAutoDelegates(e){const t=this.config.subAgentManager;if(!t)return e;let o;try{o=O(e)}catch{return e}let n;try{n=JSON.parse(o)}catch{return e}const a=n.directMessages;if(!Array.isArray(a)||a.length===0)return e;const i=[];let l=0;for(const c of a){const m=c._acodeAutoDelegate;if(m&&(m.type==="memory_expiration"||m.type==="memory_file_change"||m.type==="memory_cleanup")){l++;const f=Date.now(),g=m.uris.filter(d=>this.pendingMemorySubAgents.has(d)).length,k=m.uris.filter(d=>{const A=this.memoryDelegateCooldownUntil.get(d);return A!==void 0&&f<A}).length,T=m.uris.filter(d=>{if(this.pendingMemorySubAgents.has(d))return!1;const A=this.memoryDelegateCooldownUntil.get(d);return!(A!==void 0&&f<A)});if(T.length===0){u(`[ACodeRuntime] Memory ${m.type} skipped: ${g} in-progress, ${k} in cooldown (total ${m.uris.length} URIs)`);continue}const b=Array.isArray(m.fileChanges)?m.fileChanges.filter(d=>T.includes(d.uri)):void 0,C=this.buildMemoryDelegatePrompt({type:m.type,uris:T,fileChanges:b});try{const d=Mt("explore",[],$e(await this.buildAllocatableToolList())).patterns,A=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:St,description:`Memory ${m.type} auto-delegate (${T.length} items)`,prompt:C,...d.length>0?{allowedTools:d}:{},workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const w of T)this.pendingMemorySubAgents.set(w,A);const M=new Set(T);t.subscribe(A,()=>{const w=t.getSubAgent(A);if(w&&(w.status==="completed"||w.status==="failed"||w.status==="cancelled")){const E=Date.now();for(const p of M)this.pendingMemorySubAgents.get(p)===A&&this.pendingMemorySubAgents.delete(p),this.memoryDelegateCooldownUntil.set(p,E+De);for(const[p,y]of this.memoryDelegateCooldownUntil)y<=E&&this.memoryDelegateCooldownUntil.delete(p);u(`[ACodeRuntime] Memory delegate sub-agent ${A} finished (${w.status}), ${M.size} URI(s) entered ${De}ms cooldown`)}});const _=m.type,S=async(w,E)=>this.recheckMemoryDelegate(_,T,w,E);await t.startWithRecheck(A,S,3),u(`[ACodeRuntime] Auto-delegated memory ${m.type} to sub-agent ${A} (${T.length} URIs, ${m.uris.length-T.length} already in progress)`)}catch(d){for(const A of T)this.pendingMemorySubAgents.delete(A);u(`[ACodeRuntime] Failed to auto-delegate memory ${m.type} (suppressed, will retry next poll): ${d instanceof Error?d.message:String(d)}`)}}else i.push(c)}if(l===0)return e;if(i.length===0)return null;const r={...n,directMessages:i};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,n){const a=this.config.subAgentManager;if(!a)return D("runtime.poll.no-subagent-manager","\u65E0 SubAgentManager\uFF0C\u76F4\u63A5\u8D70\u666E\u901A MCP \u8C03\u7528"),await this.callMcpToolWithTimeout(e,t,o,n,!0);const i=a.takeCompletedSubAgents();if(i.length>0)return u(`[ACodeRuntime] poll_message: ${i.length} sub-agent(s) already completed, returning synthetic result`),D("runtime.poll.subagent-synthetic",`${i.length} \u4E2A\u5B50 agent \u5DF2\u5B8C\u6210\uFF0C\u76F4\u63A5\u8FD4\u56DE\u5408\u6210\u7ED3\u679C\uFF08\u4E0D\u8C03 MCP\uFF09`),Y.formatSubAgentCompletionAsPollResult(i);let l=!1,r=0;for(;;){r++,D("runtime.poll.round-start",`\u7B2C ${r} \u8F6E race \u5F00\u59CB: timeoutMs=${n} silent=${l}`);const c=new AbortController,m=a.waitForAnyCompletion(),f=l?{...o,_aws_silent_poll:!0}:o,g=Date.now(),k=this.callMcpToolWithTimeout(e,t,f,n,!0,c.signal);try{const T=await Promise.race([k.then(d=>({type:"mcp",result:d})),m.promise.then(d=>({type:"subagent",notif:d}))]);if(T.type==="subagent"){D("runtime.poll.race-winner-subagent",`\u5B50 agent \u5148\u5B8C\u6210\uFF0Cabort MCP \u8C03\u7528\uFF08\u5DF2\u7B49\u5F85 ${Date.now()-g}ms\uFF09\u540E\u8FD4\u56DE\u5408\u6210\u7ED3\u679C`),c.abort(),k.catch(()=>{});const d=a.takeCompletedSubAgents();return d.length===0&&d.push(T.notif),u(`[ACodeRuntime] poll_message: sub-agent ${T.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),Y.formatSubAgentCompletionAsPollResult(d)}D("runtime.poll.mcp-returned",`MCP \u5148\u8FD4\u56DE\uFF08\u8017\u65F6 ${Date.now()-g}ms\uFF09\uFF0C\u68C0\u67E5\u5F85\u5408\u5E76\u7684\u5B50 agent \u5B8C\u6210`);const b=a.takeCompletedSubAgents();if(b.length>0){u(`[ACodeRuntime] poll_message: MCP returned, merging ${b.length} sub-agent completion(s)`);const d=Y.mergeSubAgentCompletionsIntoMcpResult(T.result,b),A=await this.processMemoryAutoDelegates(d);if(D("runtime.poll.delegate-check",`\u5408\u5E76 ${b.length} \u4E2A\u5B50 agent \u5B8C\u6210\u540E\u59D4\u6258\u68C0\u67E5: processed=${A===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),A!==null){if(this.pollResultHasMessages(A))return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),A;D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),l=!0;continue}const C=await this.processMemoryAutoDelegates(T.result);if(D("runtime.poll.delegate-check",`\u59D4\u6258\u68C0\u67E5: processed=${C===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),C!==null){if(this.pollResultHasMessages(C)){const d=this.summarizePollResultForDebug(C);return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE poll \u7ED3\u679C\u7ED9 LLM: ${d}`),C}D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1Apoll \u7ED3\u679C\u65E0\u5B9E\u9645\u6D88\u606F\uFF08directMessages/groupMessages \u5747\u7A7A\uFF09\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),l=!0}catch(T){throw D("runtime.poll.error",`\u7B2C ${r} \u8F6E MCP \u8C03\u7528\u5F02\u5E38: ${T instanceof Error?T.message:String(T)}`),T}finally{m.cancel()}}}summarizePollResultForDebug(e){try{const t=O(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages:[],a=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${n.length}${n.length>0?JSON.stringify(n.map(i=>({id:i.msgId,ch:i.channel}))):""} gm=${a.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=O(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages.length:0,a=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return n>0||a>0}catch{return!0}}async waitForDelegateRepoll(){u(`[ACodeRuntime] poll_message: all messages delegated, waiting ${ae}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,ae);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((n,a)=>{t=()=>{a(new Error(`${e} interrupted because ACode runtime stopped`))}});return t?(this.stopWaiters.add(t),{promise:o,cancel:()=>{t&&this.stopWaiters.delete(t)}}):{promise:o,cancel:()=>{}}}notifyRuntimeStop(){const e=[...this.stopWaiters];this.stopWaiters.clear();for(const t of e)t()}async appendSyntheticMultimodalUserMessage(e,t,o=this.contextVersion){const n=fe(e);if(!n.hasImages)return;if(!this.state.provider.supportsImageInput){this.emitAcodeEvent("error",{message:"ACode skipped image content from tool result because the provider/model is not configured for image input."}),this.cleanToolMessageAttachments(t,"[Tool result contained images; skipped because the current model does not support image input]");return}let a;try{a=await Fe(n.content)}catch(i){const l=i instanceof Error?i.message:String(i);this.emitAcodeEvent("error",{message:`ACode skipped image content from tool result: ${l}`}),a=Array.isArray(n.content)?n.content.map(r=>r.type==="text"?r:{type:"text",text:`[Image omitted: ${l}]`}):n.content}this.isTurnSuperseded(o)||(this.state.conversation.push({role:"user",content:a}),this.cleanToolMessageAttachments(t,"[Tool result contained images; see user message above]"))}expandCommandsInPolledResult(e){const t=this.state.commandRegistry;if(!t||t.list().length===0)return e;let o;try{o=JSON.parse(e)}catch{return e}if(!v(o))return e;let n=!1;for(const a of["directMessages","groupMessages"]){const i=o[a];if(Array.isArray(i))for(const l of i){if(!v(l))continue;const r=N(l.content);if(!r)continue;const c=t.expand(r);c&&(l.content=c.prompt,n=!0)}}return n?JSON.stringify(o):e}cleanToolMessageAttachments(e,t){const o=this.state.conversation.find(a=>a.role==="tool"&&a.tool_call_id===e);if(!o||typeof o.content!="string")return;let n;try{const a=JSON.parse(o.content);if(typeof a=="object"&&a!==null){const i={...a};"attachments"in i&&(delete i.attachments,n=JSON.stringify(i))}}catch{}if(n===void 0){const a=o.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();a!==o.content&&(n=a)}n!==void 0&&(o.content=n.length>0?n:t)}appendToolFailureResult(e,t,o){const n=yo(t,o);u(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${n.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${oe(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,toolUseId:e.id,result:n,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:n})}filterSharedMcpConnectionsForSubAgent(e){const t=this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0?this.config.subAgentAllowedTools:null;return e.map(o=>({...o,tools:o.tools.filter(n=>t?ke(n,t):vt.has(n.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[n,a]of Object.entries(e))try{const i=new et({name:"acode",version:"0.1.0"}),l=this.createMcpTransport(a);await x(i.connect(l),t,`ACode MCP server ${n} connect`);const r={serverName:n,client:i,transport:l,tools:[]};i.setNotificationHandler(nt,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:c}=await x(i.listTools(),t,`ACode MCP server ${n} listTools`);r.tools=ve(n,c),o.push(r)}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${n}: ${i instanceof Error?i.message:String(i)}`})}return o}requestMcpToolsRefresh(e){const t=this.state.mcpConnections.filter(o=>!e||o.serverName===e);for(const o of t)this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs)}async refreshMcpConnectionTools(e,t){try{const{tools:n}=await x(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=ve(e.serverName,n)}catch(n){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${n instanceof Error?n.message:String(n)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(n=>!(n.kind==="mcp"&&n.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitExposedToolsStatus()}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");const o=new ot({command:e.command,args:e.args,cwd:e.cwd||this.config.workingDirectory,env:{...this.config.env??{},...e.env??{}},stderr:"pipe"});return o.stderr?.on("data",()=>{}),o}if(!e.url)throw new Error("remote MCP server requires url");const t=e.headers?{headers:e.headers}:void 0;return e.type==="sse"?new tt(new URL(e.url),{requestInit:t}):new st(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(n=>n.toolName==="get_profile"))try{const n=await x(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:re}),re,"ACode startup get_profile"),a=this.extractProfileFromToolResult(n);return bo(a)}catch(n){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${n instanceof Error?n.message:String(n)}`}),""}return""}extractProfileFromToolResult(e){if(!v(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(v(o)&&typeof o.text=="string"&&o.text.trim())try{const n=JSON.parse(o.text);if(v(n))return n}catch{}}return v(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1;return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1,await Promise.all(e.map(t=>ee(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}Y.SKILL_REFRESH_DEBOUNCE_MS=500;export{Y as ACodeRuntime};
108
+ \u5B8C\u6210\u540E\u7CFB\u7EDF\u4F1A\u901A\u8FC7\u67E5\u8BE2\u670D\u52A1\u7AEF\u771F\u5B9E\u72B6\u6001\u8FDB\u884C\u4E8C\u6B21\u9A8C\u8BC1\uFF08\u4E0D\u4F9D\u8D56\u4F60\u7684\u81EA\u62A5\u7ED3\u679C\uFF09\u3002\u82E5\u9A8C\u8BC1\u53D1\u73B0\u4ECD\u6709 memory \u7684 memory_status \u4E3A "updating"\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`}async processMemoryAutoDelegates(e){const t=this.config.subAgentManager;if(!t)return e;let o;try{o=O(e)}catch{return e}let n;try{n=JSON.parse(o)}catch{return e}const a=n.directMessages;if(!Array.isArray(a)||a.length===0)return e;const i=[];let l=0;for(const c of a){const m=c._acodeAutoDelegate;if(m&&(m.type==="memory_expiration"||m.type==="memory_file_change"||m.type==="memory_cleanup")){l++;const f=Date.now(),g=m.uris.filter(d=>this.pendingMemorySubAgents.has(d)).length,k=m.uris.filter(d=>{const A=this.memoryDelegateCooldownUntil.get(d);return A!==void 0&&f<A}).length,T=m.uris.filter(d=>{if(this.pendingMemorySubAgents.has(d))return!1;const A=this.memoryDelegateCooldownUntil.get(d);return!(A!==void 0&&f<A)});if(T.length===0){u(`[ACodeRuntime] Memory ${m.type} skipped: ${g} in-progress, ${k} in cooldown (total ${m.uris.length} URIs)`);continue}const b=Array.isArray(m.fileChanges)?m.fileChanges.filter(d=>T.includes(d.uri)):void 0,_=this.buildMemoryDelegatePrompt({type:m.type,uris:T,fileChanges:b});try{const d=Mt("explore",[],$e(await this.buildAllocatableToolList())).patterns,A=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:St,description:`Memory ${m.type} auto-delegate (${T.length} items)`,prompt:_,...d.length>0?{allowedTools:d}:{},workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const w of T)this.pendingMemorySubAgents.set(w,A);const M=new Set(T);t.subscribe(A,()=>{const w=t.getSubAgent(A);if(w&&(w.status==="completed"||w.status==="failed"||w.status==="cancelled")){const E=Date.now();for(const p of M)this.pendingMemorySubAgents.get(p)===A&&this.pendingMemorySubAgents.delete(p),this.memoryDelegateCooldownUntil.set(p,E+De);for(const[p,y]of this.memoryDelegateCooldownUntil)y<=E&&this.memoryDelegateCooldownUntil.delete(p);u(`[ACodeRuntime] Memory delegate sub-agent ${A} finished (${w.status}), ${M.size} URI(s) entered ${De}ms cooldown`)}});const C=m.type,S=async(w,E)=>this.recheckMemoryDelegate(C,T,w,E);await t.startWithRecheck(A,S,3),u(`[ACodeRuntime] Auto-delegated memory ${m.type} to sub-agent ${A} (${T.length} URIs, ${m.uris.length-T.length} already in progress)`)}catch(d){for(const A of T)this.pendingMemorySubAgents.delete(A);u(`[ACodeRuntime] Failed to auto-delegate memory ${m.type} (suppressed, will retry next poll): ${d instanceof Error?d.message:String(d)}`)}}else i.push(c)}if(l===0)return e;if(i.length===0)return null;const r={...n,directMessages:i};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,n){const a=this.config.subAgentManager;if(!a)return D("runtime.poll.no-subagent-manager","\u65E0 SubAgentManager\uFF0C\u76F4\u63A5\u8D70\u666E\u901A MCP \u8C03\u7528"),await this.callMcpToolWithTimeout(e,t,o,n,!0);const i=a.takeCompletedSubAgents();if(i.length>0)return u(`[ACodeRuntime] poll_message: ${i.length} sub-agent(s) already completed, returning synthetic result`),D("runtime.poll.subagent-synthetic",`${i.length} \u4E2A\u5B50 agent \u5DF2\u5B8C\u6210\uFF0C\u76F4\u63A5\u8FD4\u56DE\u5408\u6210\u7ED3\u679C\uFF08\u4E0D\u8C03 MCP\uFF09`),Y.formatSubAgentCompletionAsPollResult(i);let l=!1,r=0;for(;;){r++,D("runtime.poll.round-start",`\u7B2C ${r} \u8F6E race \u5F00\u59CB: timeoutMs=${n} silent=${l}`);const c=new AbortController,m=a.waitForAnyCompletion(),f=l?{...o,_aws_silent_poll:!0}:o,g=Date.now(),k=this.callMcpToolWithTimeout(e,t,f,n,!0,c.signal);try{const T=await Promise.race([k.then(d=>({type:"mcp",result:d})),m.promise.then(d=>({type:"subagent",notif:d}))]);if(T.type==="subagent"){D("runtime.poll.race-winner-subagent",`\u5B50 agent \u5148\u5B8C\u6210\uFF0Cabort MCP \u8C03\u7528\uFF08\u5DF2\u7B49\u5F85 ${Date.now()-g}ms\uFF09\u540E\u8FD4\u56DE\u5408\u6210\u7ED3\u679C`),c.abort(),k.catch(()=>{});const d=a.takeCompletedSubAgents();return d.length===0&&d.push(T.notif),u(`[ACodeRuntime] poll_message: sub-agent ${T.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),Y.formatSubAgentCompletionAsPollResult(d)}D("runtime.poll.mcp-returned",`MCP \u5148\u8FD4\u56DE\uFF08\u8017\u65F6 ${Date.now()-g}ms\uFF09\uFF0C\u68C0\u67E5\u5F85\u5408\u5E76\u7684\u5B50 agent \u5B8C\u6210`);const b=a.takeCompletedSubAgents();if(b.length>0){u(`[ACodeRuntime] poll_message: MCP returned, merging ${b.length} sub-agent completion(s)`);const d=Y.mergeSubAgentCompletionsIntoMcpResult(T.result,b),A=await this.processMemoryAutoDelegates(d);if(D("runtime.poll.delegate-check",`\u5408\u5E76 ${b.length} \u4E2A\u5B50 agent \u5B8C\u6210\u540E\u59D4\u6258\u68C0\u67E5: processed=${A===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),A!==null){if(this.pollResultHasMessages(A))return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),A;D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),l=!0;continue}const _=await this.processMemoryAutoDelegates(T.result);if(D("runtime.poll.delegate-check",`\u59D4\u6258\u68C0\u67E5: processed=${_===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),_!==null){if(this.pollResultHasMessages(_)){const d=this.summarizePollResultForDebug(_);return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE poll \u7ED3\u679C\u7ED9 LLM: ${d}`),_}D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1Apoll \u7ED3\u679C\u65E0\u5B9E\u9645\u6D88\u606F\uFF08directMessages/groupMessages \u5747\u7A7A\uFF09\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),l=!0}catch(T){throw D("runtime.poll.error",`\u7B2C ${r} \u8F6E MCP \u8C03\u7528\u5F02\u5E38: ${T instanceof Error?T.message:String(T)}`),T}finally{m.cancel()}}}summarizePollResultForDebug(e){try{const t=O(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages:[],a=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${n.length}${n.length>0?JSON.stringify(n.map(i=>({id:i.msgId,ch:i.channel}))):""} gm=${a.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=O(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages.length:0,a=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return n>0||a>0}catch{return!0}}async waitForDelegateRepoll(){u(`[ACodeRuntime] poll_message: all messages delegated, waiting ${ae}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,ae);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((n,a)=>{t=()=>{a(new Error(`${e} interrupted because ACode runtime stopped`))}});return t?(this.stopWaiters.add(t),{promise:o,cancel:()=>{t&&this.stopWaiters.delete(t)}}):{promise:o,cancel:()=>{}}}notifyRuntimeStop(){const e=[...this.stopWaiters];this.stopWaiters.clear();for(const t of e)t()}async appendSyntheticMultimodalUserMessage(e,t,o=this.contextVersion){const n=fe(e);if(!n.hasImages)return;if(!this.state.provider.supportsImageInput){this.emitAcodeEvent("error",{message:"ACode skipped image content from tool result because the provider/model is not configured for image input."}),this.cleanToolMessageAttachments(t,"[Tool result contained images; skipped because the current model does not support image input]");return}let a;try{a=await Fe(n.content)}catch(i){const l=i instanceof Error?i.message:String(i);this.emitAcodeEvent("error",{message:`ACode skipped image content from tool result: ${l}`}),a=Array.isArray(n.content)?n.content.map(r=>r.type==="text"?r:{type:"text",text:`[Image omitted: ${l}]`}):n.content}this.isTurnSuperseded(o)||(this.state.conversation.push({role:"user",content:a}),this.cleanToolMessageAttachments(t,"[Tool result contained images; see user message above]"))}expandCommandsInPolledResult(e){const t=this.state.commandRegistry;if(!t||t.list().length===0)return e;let o;try{o=JSON.parse(e)}catch{return e}if(!R(o))return e;let n=!1;for(const a of["directMessages","groupMessages"]){const i=o[a];if(Array.isArray(i))for(const l of i){if(!R(l))continue;const r=N(l.content);if(!r)continue;const c=t.expand(r);c&&(l.content=c.prompt,n=!0)}}return n?JSON.stringify(o):e}cleanToolMessageAttachments(e,t){const o=this.state.conversation.find(a=>a.role==="tool"&&a.tool_call_id===e);if(!o||typeof o.content!="string")return;let n;try{const a=JSON.parse(o.content);if(typeof a=="object"&&a!==null){const i={...a};"attachments"in i&&(delete i.attachments,n=JSON.stringify(i))}}catch{}if(n===void 0){const a=o.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();a!==o.content&&(n=a)}n!==void 0&&(o.content=n.length>0?n:t)}appendToolFailureResult(e,t,o){const n=yo(t,o);u(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${n.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${oe(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,toolUseId:e.id,result:n,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:n})}filterSharedMcpConnectionsForSubAgent(e){const t=this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0?this.config.subAgentAllowedTools:null;return e.map(o=>({...o,tools:o.tools.filter(n=>t?ke(n,t):Rt.has(n.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[n,a]of Object.entries(e))try{const i=new et({name:"acode",version:"0.1.0"}),l=this.createMcpTransport(a);await x(i.connect(l),t,`ACode MCP server ${n} connect`);const r={serverName:n,client:i,transport:l,tools:[]};i.setNotificationHandler(nt,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:c}=await x(i.listTools(),t,`ACode MCP server ${n} listTools`);r.tools=Re(n,c),o.push(r)}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${n}: ${i instanceof Error?i.message:String(i)}`})}return o}requestMcpToolsRefresh(e){const t=this.state.mcpConnections.filter(o=>!e||o.serverName===e);for(const o of t)this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs)}async refreshMcpConnectionTools(e,t){try{const{tools:n}=await x(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Re(e.serverName,n)}catch(n){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${n instanceof Error?n.message:String(n)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(n=>!(n.kind==="mcp"&&n.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitExposedToolsStatus()}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");const o=new ot({command:e.command,args:e.args,cwd:e.cwd||this.config.workingDirectory,env:{...this.config.env??{},...e.env??{}},stderr:"pipe"});return o.stderr?.on("data",()=>{}),o}if(!e.url)throw new Error("remote MCP server requires url");const t=e.headers?{headers:e.headers}:void 0;return e.type==="sse"?new tt(new URL(e.url),{requestInit:t}):new st(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(n=>n.toolName==="get_profile"))try{const n=await x(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:re}),re,"ACode startup get_profile"),a=this.extractProfileFromToolResult(n);return bo(a)}catch(n){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${n instanceof Error?n.message:String(n)}`}),""}return""}extractProfileFromToolResult(e){if(!R(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(R(o)&&typeof o.text=="string"&&o.text.trim())try{const n=JSON.parse(o.text);if(R(n))return n}catch{}}return R(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1;return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1,await Promise.all(e.map(t=>ee(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}Y.SKILL_REFRESH_DEBOUNCE_MS=500;export{Y as ACodeRuntime};
109
109
 
@@ -47,9 +47,9 @@ export declare class McpServer {
47
47
 
48
48
  private cachedPluginCatalog;
49
49
 
50
- private pluginCatalogDeliveredRevision;
51
- private pluginCatalogDeliveredCompactionSeq;
50
+ private deliveredPluginNames;
52
51
  private pluginCatalogDrainCompactionSeq;
52
+ private pluginCatalogLastSeenCompactionSeq;
53
53
  private static readonly MEETING_HYDRATE_RETRY_COUNT;
54
54
  private static readonly MEETING_HYDRATE_RETRY_DELAY_MS;
55
55