aws-runtime-bridge 1.9.124 → 1.9.126

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.
Files changed (75) hide show
  1. package/README.md +23 -2
  2. package/dist/adapter/AcodeSdkAdapter.js +4 -4
  3. package/dist/adapter/OpencodeSdkAdapter.js +2 -2
  4. package/dist/adapter/types.js +1 -1
  5. package/dist/config.d.ts +30 -4
  6. package/dist/config.js +3 -1
  7. package/dist/index.js +1 -1
  8. package/dist/routes/acode-todos.js +1 -1
  9. package/dist/routes/background-tasks.js +1 -1
  10. package/dist/routes/dashboard.js +58 -3
  11. package/dist/routes/git.d.ts +28 -0
  12. package/dist/routes/git.js +32 -31
  13. package/dist/routes/terminal.js +24 -24
  14. package/dist/services/auto-register.d.ts +2 -2
  15. package/dist/services/auto-register.js +1 -1
  16. package/dist/services/aws-client-agent-mcp.d.ts +2 -1
  17. package/dist/services/aws-client-agent-mcp.js +2 -2
  18. package/dist/services/cc-switch-sdk.js +1 -1
  19. package/dist/services/cli-commands.js +5 -5
  20. package/dist/services/fileSnapshotStore.js +1 -1
  21. package/dist/services/instance-ai-config-service.js +1 -1
  22. package/dist/services/instance-features.d.ts +2 -0
  23. package/dist/services/instance-features.js +1 -1
  24. package/dist/services/panel-auth.d.ts +2 -0
  25. package/dist/services/panel-auth.js +1 -1
  26. package/dist/services/startup-config-wizard.js +6 -6
  27. package/dist/services/tunnel-client.js +1 -1
  28. package/dist/services/update-notifier.js +2 -2
  29. package/package/acode/dist/ask-user-question-tool.js +2 -2
  30. package/package/acode/dist/background-command-store.js +1 -1
  31. package/package/acode/dist/builtins/commandArtifacts.js +3 -3
  32. package/package/acode/dist/mcpToolNames.d.ts +2 -0
  33. package/package/acode/dist/mcpToolNames.js +1 -1
  34. package/package/acode/dist/meeting-debug-log.d.ts +1 -0
  35. package/package/acode/dist/meeting-debug-log.js +3 -0
  36. package/package/acode/dist/paths.d.ts +2 -0
  37. package/package/acode/dist/paths.js +2 -0
  38. package/package/acode/dist/runtime.d.ts +4 -0
  39. package/package/acode/dist/runtime.js +20 -20
  40. package/package/acode/dist/sub-agent-manager.d.ts +1 -0
  41. package/package/acode/dist/sub-agent-manager.js +1 -1
  42. package/package/acode/dist/sub-agent-store.js +3 -3
  43. package/package/acode/dist/sub-agent-tools.js +27 -31
  44. package/package/acode/dist/sub-agent-types.d.ts +1 -1
  45. package/package/acode/dist/todo-store.js +1 -1
  46. package/package/acode/dist/tool-allocation.d.ts +18 -4
  47. package/package/acode/dist/tool-allocation.js +1 -1
  48. package/package/acode/dist/types.d.ts +0 -3
  49. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +17 -0
  50. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  51. package/package/aws-client-agent-mcp/dist/agent-client.test.js +251 -1
  52. package/package/aws-client-agent-mcp/dist/config.d.ts +2 -0
  53. package/package/aws-client-agent-mcp/dist/config.js +1 -1
  54. package/package/aws-client-agent-mcp/dist/config.test.js +93 -1
  55. package/package/aws-client-agent-mcp/dist/http-client.d.ts +2 -0
  56. package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
  57. package/package/aws-client-agent-mcp/dist/launch-config-tools.test.js +6 -2
  58. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +21 -0
  59. package/package/aws-client-agent-mcp/dist/mcp-server.js +28 -28
  60. package/package/aws-client-agent-mcp/dist/mcp-server.test.js +628 -7
  61. package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +10 -0
  62. package/package/aws-client-agent-mcp/dist/mcp-tools.js +12 -10
  63. package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +38 -0
  64. package/package/aws-client-agent-mcp/dist/meeting-debug-log.d.ts +13 -0
  65. package/package/aws-client-agent-mcp/dist/meeting-debug-log.js +3 -0
  66. package/package/aws-client-agent-mcp/dist/message-buffer.d.ts +2 -0
  67. package/package/aws-client-agent-mcp/dist/message-buffer.js +1 -1
  68. package/package/aws-client-agent-mcp/dist/message-buffer.test.js +60 -0
  69. package/package/aws-client-agent-mcp/dist/runtime-launch-binding.d.ts +14 -0
  70. package/package/aws-client-agent-mcp/dist/runtime-launch-binding.js +1 -1
  71. package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.js +39 -1
  72. package/package/aws-client-agent-mcp/dist/types.d.ts +11 -1
  73. package/package/aws-client-agent-mcp/dist/websocket-client.js +1 -1
  74. package/package/aws-client-agent-mcp/package.json +1 -1
  75. package/package.json +1 -1
@@ -1,35 +1,35 @@
1
- import{EventEmitter as Ge}from"node:events";import H from"node:fs";import Qe from"node:os";import ee from"node:path";import{Client as Ye}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Ve}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as Xe}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Ze}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as et}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as tt}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as ot,createAskUserQuestionTool as nt}from"./ask-user-question-tool.js";import{createSkillTool as st}from"./skill-tool.js";import{createTodoWriteTool as it,createTodoReadTool as rt}from"./todo-tool.js";import{createSubAgentTools as at}from"./sub-agent-tools.js";import{createAwaitCompleteTool as ct}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as lt}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as K}from"./background-command-manager.js";import{createTerminalTool as ut}from"./terminal-tool.js";import{loadAcodeCommands as mt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as ge}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as dt,COMPACTION_LLM_PROMPT_TEMPLATE as ht,conversationSizeKB as G,estimateConversationTokens as te,performCompaction as Te,pruneToolOutputs as pt,summarizeConversation as ye}from"./compaction.js";import{loadAcodeConfig as ft,loadAcodeSkillGroup as gt}from"./config.js";import{ACodeHookBus as Tt,findDeniedHookResult as ae}from"./hooks/hookBus.js";import{isMcpPollingToolName as yt,getSemanticToolName as Ae}from"./mcpToolNames.js";import{buildToolCatalog as At,matchesToolAllocation as Ce,mergeAllocatableTools as oe,rebindDefaultAgentId as _e}from"./tool-allocation.js";function Ct(n){if(typeof n!="object"||n===null)return!1;const e=n;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 _t(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function bt(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function wt(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(_t):n.content};return n.tool_call_id&&(e.tool_call_id=n.tool_call_id),n.tool_calls&&(e.tool_calls=n.tool_calls.map(bt)),e}function ce(n){return n.map(wt)}function $t(n,e){const t=O(n.prompt_cache_hit_tokens),o=O(n.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const s=O(n.cache_read_input_tokens),c=O(n.cache_creation_input_tokens);if(s!==void 0||c!==void 0){const l=O(n.input_tokens)??0;return{cacheHitTokens:s??0,cacheMissTokens:(c??0)+l}}const r=O(n.cache_hit_tokens),a=O(n.cache_miss_tokens);if(r!==void 0||a!==void 0)return{cacheHitTokens:r??0,cacheMissTokens:a??0};const i=O(n.prompt_tokens_details?.cached_tokens);if(i!==void 0){const l=e!==void 0?Math.max(0,e-i):0;return{cacheHitTokens:i,cacheMissTokens:l}}}function O(n){const e=typeof n=="number"?n:typeof n=="string"&&n.trim()?Number(n):NaN;if(!(!Number.isFinite(e)||e<0))return e}function kt(n,e){if(!n)return e;const t=o=>{const s=e[o],c=n[o];return o==="prompt_tokens_details"?{...c,...s}:s??c};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 St(){return new Date().toISOString()}function x(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function be(n){return x(n)}function we(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:go(n,t.name),description:t.description,inputSchema:be(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function I(n){return String(n??"").trim()||void 0}const $e=6e4,ke=30*6e4,Se=6e4,Me=6e4,ne=-1,Re=ne,Mt=1e3,Rt=3e4,se=6e4,ve=0,vt=2147483647,xt=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),Et=new Set(["write_file","edit_file","delete_file"]),Nt=10*6e4+2e3,It=1e4,xe=5e3,Ee=10*60*1e3,Ne=10*1024*1024,Ie=800*1024,ie=process.env.ACODE_COMPACTION_DEBUG==="1",Pe=ie?ee.join(Qe.tmpdir(),"acode-compaction-debug.log"):"";function u(...n){ie&&console.log(...n)}const Pt=process.env.ACODE_TOKEN_DEBUG==="1";function z(...n){Pt&&console.log("[TokenDebug][Runtime]",...n)}const Ot=64e3;function le(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:Ot,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=dt(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:s}}async function E(n,e,t,o){if(e<=0)return await n;let s;try{return await new Promise((c,r)=>{s=setTimeout(()=>{o?.(),r(new Error(`${t} timed out after ${e}ms`))},e),n.then(c,r)})}finally{s&&clearTimeout(s)}}async function Q(n,e,t,o=It){try{await E(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function j(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===ne?ne:Number.isFinite(t)&&t>0?Math.floor(t):e}function Y(n,e){const t=j(n,e);return t>0?t:e}const Oe=3;function ue(n){return n?Math.ceil(n.length/Oe):0}function Lt(n,e){let t=n.length;for(const o of e){const s=(o.kind==="mcp",o.toolName);if(t+=s.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const c=o;c.inputSchema&&(t+=JSON.stringify(c.inputSchema).length)}}return Math.ceil(t/Oe)}function Le(n){if(n.length===0)return 0;const e=JSON.stringify(We(n));return ue(e)}async function Dt(n){await new Promise(e=>setTimeout(e,n))}function Ut(n){return typeof n=="boolean"}function Bt(n,e,t){if(Ut(t?.supportsImageInput))return t.supportsImageInput;const o=x(e)?e.models:void 0,s=x(o)?o[n]:void 0;if(!x(s))return!1;const c=s.modalities;return!x(c)||!Array.isArray(c.input)?!1:c.input.some(r=>String(r||"").trim().toLowerCase()==="image")}function me(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(x(s)){const c=s[t];if(x(c)){const r=c[o];if(r!==void 0)return r}}return e[o]}function qt(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",c=I(n.effort)||I(o?.effort)||I(t?.effort)||void 0;return{model:s,baseURL:I(o?.baseURL||o?.baseUrl),apiKey:I(o?.apiKey),effort:c,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:Y(o?.requestTimeoutMs??o?.timeoutMs,$e),requestTotalTimeoutMs:Y(o?.requestTotalTimeoutMs,ke),requestRetryCount:j(o?.requestRetryCount,Re),requestFirstByteTimeoutMs:Y(o?.requestFirstByteTimeoutMs,Se),requestStreamIdleTimeoutMs:Y(o?.requestStreamIdleTimeoutMs,Me),mcpToolTimeoutMs:Y(o?.mcpToolTimeoutMs,se),mcpPollingToolTimeoutMs:j(o?.mcpPollingToolTimeoutMs,ve),supportsImageInput:Bt(s,t,o),contextLimit:j(me(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:j(me(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:j(me(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function q(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function Ft(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function zt(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function jt(n){let e;try{e=new URL(n)}catch{throw new Error(`ACode image URL is invalid: ${n}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`ACode image URL protocol is not supported: ${e.protocol}`)}async function Wt(n){const e=await n.arrayBuffer();if(e.byteLength>Ne)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${Ne} bytes`);return Buffer.from(e).toString("base64")}async function Jt(n){const e=n.trim();if(zt(e))return e;jt(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")||"",s=o.split(";")[0]?.trim().toLowerCase()||"";if(!s.startsWith("image/"))throw new Error(`ACode image URL did not return an image content type: ${o||"unknown"}`);return`data:${s};base64,${await Wt(t)}`}function Ht(n){const e=I(n.base64Data??n.base64??n.data);return e?Ft(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function De(n,e,t,o){return`[Attached file: ${[n?`name=${n}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(c=>!!c).join(", ")}]`}function Kt(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,c=e.exec(n);for(;c!==null;){q(t,n.slice(s,c.index));const r=c[1],a=(c[2]||"").trim();if(r==="\u56FE\u7247"&&a)t.push({type:"image_url",image_url:{url:a}}),o=!0;else if(r==="\u6587\u4EF6"&&a){const[i="",l="",m="",g=""]=a.split("|").map(h=>h.trim());q(t,De(i,l,m,g))}else q(t,c[0]);s=c.index+c[0].length,c=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(q(t,n.slice(s)),{content:t,hasImages:o})}function Gt(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const c of s){if(!x(c))continue;const r=I(c.content);if(!r)continue;const a=I(c.senderName);q(n,a?`Message from ${a}:`:"Message:");const i=de(r);Array.isArray(i.content)?n.push(...i.content):q(n,i.content),t=t||i.hasImages}return t}function Qt(n){let e;try{e=JSON.parse(n)}catch{return}if(!x(e))return;const t=[];let o=Gt(t,e);const s=I(e.text)||"",c=Array.isArray(e.attachments)?e.attachments:[];q(t,s);for(const r of c){if(!x(r))continue;const a=r;if(String(a.type??a.kind??"").toLowerCase()==="image"){const m=Ht(a);m&&(t.push({type:"image_url",image_url:{url:m}}),o=!0);continue}const l=I(a.url??a.serverUrl)||"";q(t,De(I(a.name)||"",l,I(a.mediaType??a.mimeType)||"",I(a.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function de(n){return Qt(n)??Kt(n)}async function Ue(n){if(!Array.isArray(n))return n;const e=[];for(const t of n){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await Jt(t.image_url.url)}})}return e}function Yt(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function Vt(n,e){const t=n.permissions??e.permissions??{},o=n.permissions?[]:e.allowedTools??[],s=n.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(c=>c.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(c=>c.trim()).filter(Boolean)}}function Xt(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function Zt(n){return n.kind==="builtin"?[n.exposedName,n.toolName,`builtin.${n.toolName}`]:[n.exposedName,n.toolName,`${n.serverName}.${n.toolName}`,`mcp.${n.serverName}.${n.toolName}`]}function Be(n,e){return Zt(e).some(t=>Xt(n,t))}function qe(n,e,t){if(e.length>0&&!e.some(o=>Be(o,n)))throw new Error(t)}function he(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>Be(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);qe(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),qe(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function eo(n,e,t){try{return he(n,e,t),!0}catch{return!1}}function re(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function to(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(re(e.toString()));return`${t.origin}${t.pathname}`}catch{return re(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function oo(n){const e=[...n].reverse().find(o=>o.role==="user"),t=Yt(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function Fe(n){try{const e=JSON.parse(n);return be(e)?e:{}}catch{return{}}}function no(n,e,t){if(new Set([ot,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,c=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(c)||c<=0?Math.max(t,Nt):Math.min(Math.floor(c),10*6e4)+2e3}function so(n,e){const t=n.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 L(n){if(!x(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>x(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
- `)}return JSON.stringify(n)}function V(n){return n instanceof Error?n.message:String(n)}function io(n){let e=16;if(typeof n.content=="string")e+=n.content.length*2;else if(Array.isArray(n.content))for(const t of n.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return n.tool_calls&&(e+=JSON.stringify(n.tool_calls).length),n.tool_call_id&&(e+=n.tool_call_id.length),e}async function ro(n,e,t,o,s){let c=0;for(const a of n)c+=io(a);if(c<=e)return 0;const r=await Te(n,t,o,{llmSummarizer:s});return r.strategy!=="none"?r.prunedToolMessages+r.summarizedMessages:ye(n,{llmSummarizer:s,contextLimit:t})}function ze(n){const e=V(n).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 ao(n){const e=V(n).toLowerCase();return ze(n)?!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 co(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=V(n).toLowerCase();return e===-32001||t.includes("request timed out")}function lo(n){if(typeof n=="object"&&n!==null){const e=Reflect.get(n,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(n,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function uo(n,e){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:lo(e),message:V(e)}})}function je(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function mo(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(x(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function ho(n){return n.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 po(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
3
- `)}function fo(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,c=e.instanceName,r=e.projectId,a=e.workspacePath,i=e.runtimeMode,l=e.describe;return typeof o=="string"&&o.trim()&&t.push(`Display Name: ${o.trim()}`),typeof s=="string"&&s.trim()&&t.push(`Role: ${s.trim()}`),typeof c=="string"&&c.trim()&&t.push(`Instance: ${c.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Project: ${r.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Workspace: ${a.trim()}`),typeof i=="string"&&i.trim()&&t.push(`Runtime Mode: ${i.trim()}`),typeof l=="string"&&l.trim()&&t.push(`Description: ${l.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
4
- `)}function We(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function go(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function To(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function yo(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Ao(e)?Co(t):t]))}function Ao(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function Co(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function _o(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function bo(n,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=n.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),n.set(t,o)}function wo(n){return[...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}function $o(){const n=process.env.ACODE_ABORT_FORCE_SETTLE_GRACE_MS;if(n===void 0||n.trim()==="")return 6e4;const e=Number(n.trim());return Number.isFinite(e)&&e>=0?Math.floor(e):6e4}class W extends Ge{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:$e,requestTotalTimeoutMs:ke,requestRetryCount:Re,requestFirstByteTimeoutMs:Se,requestStreamIdleTimeoutMs:Me,mcpToolTimeoutMs:se,mcpPollingToolTimeoutMs:ve,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new ge([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0},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.hookBus=new Tt({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)}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:St(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s})}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 ft(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),c=qt(this.config,e);u(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${c.model}, baseURL=${c.baseURL??"(none)"}, apiKey=${c.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const r=Vt(this.config,e),a=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},c.mcpToolTimeoutMs),i=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const l=await this.fetchProfilePrompt(a),m=this.config.agentId||"unknown";lt(m),K.reconcileOrphans(m);const g=tt(this.config.workingDirectory,m,this.config.onFileChange,{manager:K,emitCompleted:p=>{this.emitAcodeEvent("background_command_completed",p)}}),h=nt(this.buildAskUserQuestionDeps(),()=>this.contextVersion),S=st(t);this.skillTool=S;const f=it(m),M=rt(m),_=this.config.subAgentManager?at(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],d=ct(this.buildAwaitCompleteDeps()),C=this.config.terminalManager?ut(m,{terminalManager:this.config.terminalManager}):null,b=[...g,h,S,f,M,..._,d,...C?[C]:[],...a.flatMap(p=>p.tools),..._e(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const p=_e(this.config.subAgentSuiteTools??[],this.config.agentId??""),U=oe(b,p);b.length=0,b.push(...U)}let $=b;const y=this.config.subAgentAllowedTools;y&&y.length>0&&($=$.filter(p=>Ce(p,y))),this.config.subagentType==="explore"&&($=$.filter(p=>!Et.has(p.exposedName)));const R=this.resolveCommandDirs(e);this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const k=await mt(R),T=new ge(k),w=ho(t),v=po(k),N=[c.systemPrompt,w,v].map(p=>p?.trim()).filter(p=>!!p).join(`
1
+ import{EventEmitter as Ve}from"node:events";import G from"node:fs";import Xe from"node:os";import te from"node:path";import{Client as Ze}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as et}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as tt}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as ot}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as nt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as st}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as it,createAskUserQuestionTool as rt}from"./ask-user-question-tool.js";import{createSkillTool as at}from"./skill-tool.js";import{createTodoWriteTool as lt,createTodoReadTool as ct}from"./todo-tool.js";import{createSubAgentTools as ut}from"./sub-agent-tools.js";import{createAwaitCompleteTool as mt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as dt}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as Q}from"./background-command-manager.js";import{createTerminalTool as ht}from"./terminal-tool.js";import{loadAcodeCommands as pt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as ye}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as ft,COMPACTION_LLM_PROMPT_TEMPLATE as gt,conversationSizeKB as Y,estimateConversationTokens as oe,performCompaction as Ae,pruneToolOutputs as Tt,summarizeConversation as Ce}from"./compaction.js";import{loadAcodeConfig as yt,loadAcodeSkillGroup as At}from"./config.js";import{ACodeHookBus as Ct,findDeniedHookResult as ce}from"./hooks/hookBus.js";import{isMcpPollingToolName as _t,isMcpBlockingToolName as bt,getSemanticToolName as _e}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as D}from"./meeting-debug-log.js";import{buildToolCatalog as be,matchesToolAllocation as we,mergeAllocatableTools as ne,PRESET_EXPLORE as $e,rebindDefaultAgentId as ke,resolveToolAllocation as wt,SUB_AGENT_ALLOWED_MCP_TOOLS as $t}from"./tool-allocation.js";function kt(n){if(typeof n!="object"||n===null)return!1;const e=n;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 St(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function Mt(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function Rt(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(St):n.content};return n.tool_call_id&&(e.tool_call_id=n.tool_call_id),n.tool_calls&&(e.tool_calls=n.tool_calls.map(Mt)),e}function ue(n){return n.map(Rt)}function vt(n,e){const t=U(n.prompt_cache_hit_tokens),o=U(n.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const s=U(n.cache_read_input_tokens),l=U(n.cache_creation_input_tokens);if(s!==void 0||l!==void 0){const c=U(n.input_tokens)??0;return{cacheHitTokens:s??0,cacheMissTokens:(l??0)+c}}const i=U(n.cache_hit_tokens),a=U(n.cache_miss_tokens);if(i!==void 0||a!==void 0)return{cacheHitTokens:i??0,cacheMissTokens:a??0};const r=U(n.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 U(n){const e=typeof n=="number"?n:typeof n=="string"&&n.trim()?Number(n):NaN;if(!(!Number.isFinite(e)||e<0))return e}function xt(n,e){if(!n)return e;const t=o=>{const s=e[o],l=n[o];return o==="prompt_tokens_details"?{...l,...s}:s??l};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 Et(){return new Date().toISOString()}function x(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function Se(n){return x(n)}function Me(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:Ao(n,t.name),description:t.description,inputSchema:Se(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function I(n){return String(n??"").trim()||void 0}const Re=6e4,ve=30*6e4,xe=6e4,Ee=6e4,se=-1,Ne=se,Nt=1e3,It=3e4,ie=6e4,Ie=0,Pt=2147483647,Lt=10*6e4+2e3,Dt=1e4,re=5e3,Pe=10*60*1e3,Le=10*1024*1024,De=800*1024,ae=process.env.ACODE_COMPACTION_DEBUG==="1",Oe=ae?te.join(Xe.tmpdir(),"acode-compaction-debug.log"):"";function u(...n){ae&&console.log(...n)}const Ot=process.env.ACODE_TOKEN_DEBUG==="1";function W(...n){Ot&&console.log("[TokenDebug][Runtime]",...n)}const Ut=64e3;function me(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:Ut,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=ft(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:s}}async function E(n,e,t,o){if(e<=0)return await n;let s;try{return await new Promise((l,i)=>{s=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),n.then(l,i)})}finally{s&&clearTimeout(s)}}async function V(n,e,t,o=Dt){try{await E(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function J(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===se?se:Number.isFinite(t)&&t>0?Math.floor(t):e}function X(n,e){const t=J(n,e);return t>0?t:e}const Ue=3;function de(n){return n?Math.ceil(n.length/Ue):0}function Bt(n,e){let t=n.length;for(const o of e){const s=(o.kind==="mcp",o.toolName);if(t+=s.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const l=o;l.inputSchema&&(t+=JSON.stringify(l.inputSchema).length)}}return Math.ceil(t/Ue)}function Be(n){if(n.length===0)return 0;const e=JSON.stringify(Ke(n));return de(e)}async function qt(n){await new Promise(e=>setTimeout(e,n))}function Ft(n){return typeof n=="boolean"}function zt(n,e,t){if(Ft(t?.supportsImageInput))return t.supportsImageInput;const o=x(e)?e.models:void 0,s=x(o)?o[n]:void 0;if(!x(s))return!1;const l=s.modalities;return!x(l)||!Array.isArray(l.input)?!1:l.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function he(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(x(s)){const l=s[t];if(x(l)){const i=l[o];if(i!==void 0)return i}}return e[o]}function jt(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",l=I(n.effort)||I(o?.effort)||I(t?.effort)||void 0;return{model:s,baseURL:I(o?.baseURL||o?.baseUrl),apiKey:I(o?.apiKey),effort:l,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:X(o?.requestTimeoutMs??o?.timeoutMs,Re),requestTotalTimeoutMs:X(o?.requestTotalTimeoutMs,ve),requestRetryCount:J(o?.requestRetryCount,Ne),requestFirstByteTimeoutMs:X(o?.requestFirstByteTimeoutMs,xe),requestStreamIdleTimeoutMs:X(o?.requestStreamIdleTimeoutMs,Ee),mcpToolTimeoutMs:X(o?.mcpToolTimeoutMs,ie),mcpPollingToolTimeoutMs:J(o?.mcpPollingToolTimeoutMs,Ie),supportsImageInput:zt(s,t,o),contextLimit:J(he(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:J(he(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:J(he(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function z(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function Wt(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function Jt(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function Ht(n){let e;try{e=new URL(n)}catch{throw new Error(`ACode image URL is invalid: ${n}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`ACode image URL protocol is not supported: ${e.protocol}`)}async function Kt(n){const e=await n.arrayBuffer();if(e.byteLength>Le)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${Le} bytes`);return Buffer.from(e).toString("base64")}async function Gt(n){const e=n.trim();if(Jt(e))return e;Ht(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")||"",s=o.split(";")[0]?.trim().toLowerCase()||"";if(!s.startsWith("image/"))throw new Error(`ACode image URL did not return an image content type: ${o||"unknown"}`);return`data:${s};base64,${await Kt(t)}`}function Qt(n){const e=I(n.base64Data??n.base64??n.data);return e?Wt(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function qe(n,e,t,o){return`[Attached file: ${[n?`name=${n}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(l=>!!l).join(", ")}]`}function Yt(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,l=e.exec(n);for(;l!==null;){z(t,n.slice(s,l.index));const i=l[1],a=(l[2]||"").trim();if(i==="\u56FE\u7247"&&a)t.push({type:"image_url",image_url:{url:a}}),o=!0;else if(i==="\u6587\u4EF6"&&a){const[r="",c="",m="",p=""]=a.split("|").map(h=>h.trim());z(t,qe(r,c,m,p))}else z(t,l[0]);s=l.index+l[0].length,l=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(z(t,n.slice(s)),{content:t,hasImages:o})}function Vt(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const l of s){if(!x(l))continue;const i=I(l.content);if(!i)continue;const a=I(l.senderName);z(n,a?`Message from ${a}:`:"Message:");const r=pe(i);Array.isArray(r.content)?n.push(...r.content):z(n,r.content),t=t||r.hasImages}return t}function Xt(n){let e;try{e=JSON.parse(n)}catch{return}if(!x(e))return;const t=[];let o=Vt(t,e);const s=I(e.text)||"",l=Array.isArray(e.attachments)?e.attachments:[];z(t,s);for(const i of l){if(!x(i))continue;const a=i;if(String(a.type??a.kind??"").toLowerCase()==="image"){const m=Qt(a);m&&(t.push({type:"image_url",image_url:{url:m}}),o=!0);continue}const c=I(a.url??a.serverUrl)||"";z(t,qe(I(a.name)||"",c,I(a.mediaType??a.mimeType)||"",I(a.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function pe(n){return Xt(n)??Yt(n)}async function Fe(n){if(!Array.isArray(n))return n;const e=[];for(const t of n){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await Gt(t.image_url.url)}})}return e}function Zt(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function eo(n,e){const t=n.permissions??e.permissions??{},o=n.permissions?[]:e.allowedTools??[],s=n.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(l=>l.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(l=>l.trim()).filter(Boolean)}}function to(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function oo(n){return n.kind==="builtin"?[n.exposedName,n.toolName,`builtin.${n.toolName}`]:[n.exposedName,n.toolName,`${n.serverName}.${n.toolName}`,`mcp.${n.serverName}.${n.toolName}`]}function ze(n,e){return oo(e).some(t=>to(n,t))}function je(n,e,t){if(e.length>0&&!e.some(o=>ze(o,n)))throw new Error(t)}function fe(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>ze(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);je(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),je(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function no(n,e,t){try{return fe(n,e,t),!0}catch{return!1}}function le(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function so(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(le(e.toString()));return`${t.origin}${t.pathname}`}catch{return le(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function io(n){const e=[...n].reverse().find(o=>o.role==="user"),t=Zt(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function We(n){try{const e=JSON.parse(n);return Se(e)?e:{}}catch{return{}}}function ro(n,e,t){if(new Set([it,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,l=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(l)||l<=0?Math.max(t,Lt):Math.min(Math.floor(l),10*6e4)+2e3}function ao(n,e){const t=n.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(n){if(!x(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>x(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
+ `)}return JSON.stringify(n)}function Z(n){return n instanceof Error?n.message:String(n)}function lo(n){let e=16;if(typeof n.content=="string")e+=n.content.length*2;else if(Array.isArray(n.content))for(const t of n.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return n.tool_calls&&(e+=JSON.stringify(n.tool_calls).length),n.tool_call_id&&(e+=n.tool_call_id.length),e}async function co(n,e,t,o,s){let l=0;for(const a of n)l+=lo(a);if(l<=e)return 0;const i=await Ae(n,t,o,{llmSummarizer:s});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:Ce(n,{llmSummarizer:s,contextLimit:t})}function Je(n){const e=Z(n).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 uo(n){const e=Z(n).toLowerCase();return Je(n)?!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 mo(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=Z(n).toLowerCase();return e===-32001||t.includes("request timed out")}function ho(n){if(typeof n=="object"&&n!==null){const e=Reflect.get(n,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(n,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function po(n,e){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:ho(e),message:Z(e)}})}function He(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function fo(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(x(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function go(n){return n.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 To(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
3
+ `)}function yo(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,l=e.instanceName,i=e.projectId,a=e.workspacePath,r=e.runtimeMode,c=e.describe;return typeof o=="string"&&o.trim()&&t.push(`Display Name: ${o.trim()}`),typeof s=="string"&&s.trim()&&t.push(`Role: ${s.trim()}`),typeof l=="string"&&l.trim()&&t.push(`Instance: ${l.trim()}`),typeof i=="string"&&i.trim()&&t.push(`Project: ${i.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Workspace: ${a.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(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function Ao(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function Co(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function _o(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,bo(e)?wo(t):t]))}function bo(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function wo(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function $o(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function ko(n,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=n.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),n.set(t,o)}function So(n){return[...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}function Mo(){const n=process.env.ACODE_ABORT_FORCE_SETTLE_GRACE_MS;if(n===void 0||n.trim()==="")return 6e4;const e=Number(n.trim());return Number.isFinite(e)&&e>=0?Math.floor(e):6e4}class H 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:ve,requestRetryCount:Ne,requestFirstByteTimeoutMs:xe,requestStreamIdleTimeoutMs:Ee,mcpToolTimeoutMs:ie,mcpPollingToolTimeoutMs:Ie,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new ye([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0},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.hookBus=new Ct({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)}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:Et(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s})}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 yt(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),l=jt(this.config,e);u(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${l.model}, baseURL=${l.baseURL??"(none)"}, apiKey=${l.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const i=eo(this.config,e),a=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},l.mcpToolTimeoutMs),r=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const c=await this.fetchProfilePrompt(a),m=this.config.agentId||"unknown";dt(m),Q.reconcileOrphans(m);const p=st(this.config.workingDirectory,m,this.config.onFileChange,{manager:Q,emitCompleted:g=>{this.emitAcodeEvent("background_command_completed",g)}}),h=rt(this.buildAskUserQuestionDeps(),()=>this.contextVersion),k=at(t);this.skillTool=k;const T=lt(m),w=ct(m),C=this.config.subAgentManager?ut(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],d=mt(this.buildAwaitCompleteDeps()),y=this.config.terminalManager?ht(m,{terminalManager:this.config.terminalManager}):null,S=[...p,h,k,T,w,...C,d,...y?[y]:[],...a.flatMap(g=>g.tools),...ke(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const g=ke(this.config.subAgentSuiteTools??[],this.config.agentId??""),q=ne(S,g);S.length=0,S.push(...q)}let A=S;const M=this.config.subAgentAllowedTools;M&&M.length>0&&(A=A.filter(g=>we(g,M)));const $=this.resolveCommandDirs(e);this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const R=await pt($),f=new ye(R),_=go(t),v=To(R),N=[l.systemPrompt,_,v].map(g=>g?.trim()).filter(g=>!!g).join(`
5
5
 
6
- `),A=p=>p?.trim()?[{role:"system",content:p.trim()}]:[],X=[this.config.rolePrompt,l].map(p=>p?.trim()).filter(p=>!!p).join(`
6
+ `),b=g=>g?.trim()?[{role:"system",content:g.trim()}]:[],P=[this.config.rolePrompt,c].map(g=>g?.trim()).filter(g=>!!g).join(`
7
7
 
8
- `),D=[...A(this.config.globalPrompt),...A(X),...A(this.config.memory),...N?[{role:"system",content:N}]:[]],B=D.map(p=>p.content).filter(Boolean).join(`
8
+ `),B=[...b(this.config.globalPrompt),...b(P),...b(this.config.memory),...N?[{role:"system",content:N}]:[]],F=B.map(g=>g.content).filter(Boolean).join(`
9
9
 
10
- `);this.initialConversation=ce(D),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:c,permissions:r,mcpConnections:a,ownsMcpConnections:i,exposedTools:$,commands:k,commandRegistry:T,conversation:ce(D),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:c.model,commandCount:k.length});const P=le(c);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:c.model,commandCount:k.length,estimatedContextTokens:Lt(B,$),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:a.length,builtInToolCount:g.length,toolCount:$.length,permissionMode:r.mode,allowedToolRules:r.allow,deniedToolRules:r.deny,tools:$.map(p=>({name:p.exposedName,source:p.kind==="mcp"?`${p.serverName}.${p.toolName}`:`builtin.${p.toolName}`,description:p.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(p=>({name:p.name,description:p.description,directory:p.directory})),skillGroups:o.map(p=>({dir:p.dir,exists:p.exists,skills:p.skills.map(U=>({name:U.name,description:U.description,directory:U.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:k.length,commandDirs:R,commands:k.map(p=>({name:p.name,description:p.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=ee.join(this.config.workingDirectory,".acode","skills"),o=ee.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,c=[],r=[];for(const l of[e,t,o]){if(!l)continue;const m=ee.resolve(l);if(!s.has(m)){s.add(m),c.push(await gt(l));try{await H.promises.access(m),r.push(m)}catch{}}}const a=new Map;for(const l of c)for(const m of l.skills)a.set(m.name,m);return{skills:[...a.values()],skillGroups:c,watchedDirs:r}}startSkillWatchers(e){for(const t of e){let o=null;try{o=H.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=H.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()},W.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(s=>({name:s.name,description:s.description,directory:s.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(!ie||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:c}=le(e);this.compactionDebugTimer=setInterval(()=>{try{const r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,a=te(this.state.conversation)+Le(this.state.exposedTools),i=Math.max(r,a),l=G(this.state.conversation),m=this.state.started&&!this.state.terminated,g=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${l}KB`,`estimation=${a} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${r}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${c}`,`remainingToTrigger=${Math.max(0,c-r)}`,`isRunning=${m}`,`shouldCompact=${m?i>=c:!1}`,"---"].join(" | ");H.promises.appendFile(Pe,g+`
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 s=this.executeSubmit(e,t),c=new Promise(r=>{this.forceSettleWaiters.set(o,r)});return s.finally(()=>{this.forceSettleWaiters.delete(o),this.activeTurnToken===o&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([s,c])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=$o();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.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(s=>s.exposedName)),o=[];for(const s of e)Ct(s)&&(t.has(s.exposedName)||(t.add(s.exposedName),o.push(s)));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(s=>!s.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}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 E(e.client.callTool({name:"get_message",arguments:{_aws_force_inject:!0}},void 0,{timeout:1e4}),1e4,"injectForceMessage get_message"),o=L(t);let s=[];try{const i=JSON.parse(o);Array.isArray(i?.directMessages)&&(s=i.directMessages.filter(l=>l?.force===!0))}catch{return!1}if(s.length===0)return!1;const c=JSON.stringify({directMessages:s,groupMessages:[]}),r=`forced_get_msg_${Date.now()}`,a=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:r,type:"function",function:{name:a,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:r,content:c}),u(`[ACodeRuntime] injectForceMessage: injected ${s.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=ce(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 s=this.activeTurnToken,c=e.trim();let r=!1;try{u("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const a=Date.now(),i=await this.hookBus.dispatch("UserPromptSubmit",{prompt:c}),l=Date.now()-a;if(u(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${l}ms, results: ${i.length}`),this.isTurnSuperseded(t)){u("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const m=ae(i);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}),r=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}u("[ACodeRuntime] \u{1F50D} Expanding command if any...");const g=this.state.commandRegistry.expand(c),h=g?.prompt.trim()||c,S=g?.command.allowedTools;if(g&&(u(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${g.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:g.command.name,arguments:g.argumentsText,sourcePath:g.command.sourcePath})),!this.state.provider.baseURL||!this.state.provider.apiKey){u("[ACodeRuntime] \u26A0\uFE0F No provider configured, using fallback response");const $=so(h,this.state);this.emitAcodeEvent("assistant_delta",{text:$}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:h.length,outputTokens:$.length}}),r=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}u("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const f=de(h);if(f.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 M=await Ue(f.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:M}),u(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),u("[ACodeRuntime] Starting runModelTurn...");const _=Date.now(),d=await this.runModelTurn(S,t),C=Date.now()-_;if(u(`[ACodeRuntime] \u2705 runModelTurn completed in ${C}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:h.length,outputTokens:d.totalOutputTextLength??d.text.length},...d.responseBody?{responseBody:d.responseBody}:{},...d.finishReason?{finishReason:d.finishReason}:{}}),z(`turn_complete emitted: usage=${JSON.stringify(d.usage??{inputTokens:h.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)")),r=!0;const b=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 ${b}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(a){const i=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${i}ms:`,a instanceof Error?a.message:String(a)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",a instanceof Error?a.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}),r=!0;return}u("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:a instanceof Error?a.message:String(a)}),this.emitAcodeEvent("turn_complete",{failed:!0}),r=!0}finally{const a=Date.now()-o;u(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${a}ms`),u(`[ACodeRuntime] \u{1F50D} turnCompleted=${r}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===s&&(this.activeTurn=!1,this.abortRequested=!1),!r&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${a}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.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,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,contextVersion:t})})}}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,s=this.config.workingDirectory,c=this.config;return{spawnSubAgent:async r=>{let a=this.config.subAgentSuiteTools;if(r.allowedTools&&r.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const l=await this.config.subAgentSuiteToolProvider(r.allowedTools);l.length>0&&(a=a?oe(a,l):l)}catch{}const i=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:r.subagentType,description:r.description,prompt:r.prompt,...r.allowedTools&&r.allowedTools.length>0?{allowedTools:r.allowedTools}:{},workingDirectory:s,parentConfig:{...c,sharedMcpConnections:this.state?.mcpConnections,...a&&a.length>0?{subAgentSuiteTools:a}:{}}});return await e.start(i),{subId:i}},listSubAgentToolCatalog:async()=>{const r=this.state?.exposedTools??[],a=this.config.subAgentSuiteTools??[];let i=[];if(this.config.subAgentSuiteToolProvider)try{i=await this.config.subAgentSuiteToolProvider([])}catch{i=[]}const l=oe(r,oe(a,i));return At(l)},listSubAgents:async()=>{const r=e.listByParent(t),a=[],i=[];for(const l of r){const m={subId:l.subId,subagentType:l.subagentType,description:l.description,status:l.status,startedAt:l.startedAt,endedAt:l.endedAt,durationMs:l.durationMs};l.status==="pending"||l.status==="running"?a.push(m):i.push(m)}return i.sort((l,m)=>(m.endedAt??0)-(l.endedAt??0)),{running:a,history:i}},getSubAgentStatus:async r=>{const a=e.getSubAgent(r);return a?{subId:a.subId,subagentType:a.subagentType,description:a.description,status:a.status,startedAt:a.startedAt,endedAt:a.endedAt,durationMs:a.durationMs,prompt:a.prompt,result:a.result,errorMessage:a.errorMessage,contextSnapshot:a.contextSnapshot}:null},awaitSubAgents:async(r,a)=>{const i=new Set;for(const l of r)this.pendingAwaitedSubIds.add(l),i.add(l);try{return await e.awaitCompletion(r,a)}finally{for(const l of i)this.pendingAwaitedSubIds.delete(l)}},abortSubAgent:r=>e.abort(r)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,s)=>{for(const c of o)this.pendingAwaitedSubIds.add(c);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const c of o)this.pendingAwaitedSubIds.delete(c)}}:null,awaitBgCommands:(o,s)=>{for(const c of o)this.pendingAwaitedBgTaskIds.add(c);try{return K.awaitCompletion(e,o,s)}finally{for(const c of o)this.pendingAwaitedBgTaskIds.delete(c)}}}}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()}}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(s=>{u(`[ACodeRuntime] \u26A0\uFE0F manager.abort(${o}) threw: ${s instanceof Error?s.message:String(s)}`)})}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(", ")}`),K.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 s=e.toolName==="Bash"&&typeof t.wait_seconds=="number"&&t.wait_seconds>0,c=++this.toolSettleSeq;let r;const a=s?new Promise(i=>{r=i}):void 0;return this.toolSettleSlot={seq:c,toolName:e.toolName,toolCallId:o,settlable:s,settled:!1,resolveSettle:r??null},{seq:c,signal:a}}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.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await Q("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await Q("ACode background commands shutdown",K.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),Q("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await Q("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(),ie)try{H.promises.appendFile(Pe,`[${new Date().toISOString()}] runtime stopped | ---
12
- `,"utf-8").catch(()=>{})}catch{}}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="",s,c,r,a="",i=0;this.lastIterationUsage=void 0,u(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const l=50;for(let m=0;m<l;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:a.length};await this.injectForceMessage();const g=Date.now(),h=await this.requestChatCompletion(e),S=Date.now()-g;if(u(`[ACodeRuntime] \u{1F916} AI request completed in ${S}ms, choices: ${h.choices?.length||0}`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${m+1}`),{text:"",totalOutputTextLength:a.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 f=h.choices?.[0];c=JSON.stringify(h,null,2),r=typeof f?.finish_reason=="string"?f.finish_reason:void 0;const M=f?.message,_=typeof M?.content=="string"?M.content:"",d=Array.isArray(M?.tool_calls)?M.tool_calls:[];if(u(`[ACodeRuntime] AI response: content=${_?_.slice(0,100)+(_.length>100?"...":""):"(empty)"}, toolCalls=${d.length}, finishReason=${r||"(none)"}`),h.usage){const y=O(h.usage.prompt_tokens??h.usage.input_tokens),R=O(h.usage.completion_tokens??h.usage.output_tokens),k=y!==void 0,T=R!==void 0;if(z(`provider usage parsed: raw=${JSON.stringify(h.usage)} input=${y} output=${R} hasInput=${k} hasOutput=${T} iteration=${m+1}`),k||T){const w=$t(h.usage,y),v=s?.outputTokens??a.length+_.length;this.state.accumulatedCacheHitTokens+=w?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=w?.cacheMissTokens??0,s={inputTokens:k?y:s?.inputTokens??0,outputTokens:T?R:v,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=s,i+=k?y:0,this.state.accumulatedInputTokens=k?y:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=T?R:this.state.accumulatedOutputTokens,z(`finalUsage updated: ${JSON.stringify(s)} (cacheUsage=${JSON.stringify(w??null)})`),u(`[ACodeRuntime] \u{1F4B0} Token usage: input=${s.inputTokens}, output=${s.outputTokens} (turn accumulated cost: input=${i})`),u(w?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${w.cacheHitTokens}, miss=${w.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else z(`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=_,a+=_,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:s,responseBody:c,finishReason:r,totalOutputTextLength:a.length};const C=d.map(y=>y.function.name).join(", ");u(`[ACodeRuntime] \u{1F527} Executing ${d.length} tool(s) at iteration ${m+1}: ${C}`);const b=Date.now();await this.handleToolCalls(d,e,t);const $=Date.now()-b;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:a.length};u(`[ACodeRuntime] \u{1F504} Preparing iteration ${m+2}...`)}return console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: Reached safety limit of ${l} iterations! This indicates a potential infinite loop. Forcing turn completion.`),{text:o||`ACode \u5DF2\u8FBE\u5230\u5B89\u5168\u8FED\u4EE3\u4E0A\u9650\uFF08${l}\u6B21\uFF09\uFF0C\u5F3A\u5236\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD\u3002`,usage:s,responseBody:c,finishReason:r||"safety_iteration_limit_reached",totalOutputTextLength:a.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 s={"Content-Type":"application/json"};t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`);const c={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=ue(B),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:l,permissions:i,mcpConnections:a,ownsMcpConnections:r,exposedTools:A,commands:R,commandRegistry:f,conversation:ue(B),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:l.model,commandCount:R.length});const L=me(l);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:l.model,commandCount:R.length,estimatedContextTokens:Bt(F,A),contextLimit:L.contextLimit,maxOutput:L.maxOutput,...L.inputLimit!==void 0?{inputLimit:L.inputLimit}:{},compactionThreshold:L.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:a.length,builtInToolCount:p.length,toolCount:A.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:A.map(g=>({name:g.exposedName,source:g.kind==="mcp"?`${g.serverName}.${g.toolName}`:`builtin.${g.toolName}`,description:g.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(g=>({name:g.name,description:g.description,directory:g.directory})),skillGroups:o.map(g=>({dir:g.dir,exists:g.exists,skills:g.skills.map(q=>({name:q.name,description:q.description,directory:q.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:R.length,commandDirs:$,commands:R.map(g=>({name:g.name,description:g.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=te.join(this.config.workingDirectory,".acode","skills"),o=te.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,l=[],i=[];for(const c of[e,t,o]){if(!c)continue;const m=te.resolve(c);if(!s.has(m)){s.add(m),l.push(await At(c));try{await G.promises.access(m),i.push(m)}catch{}}}const a=new Map;for(const c of l)for(const m of c.skills)a.set(m.name,m);return{skills:[...a.values()],skillGroups:l,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=G.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=G.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()},H.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(s=>({name:s.name,description:s.description,directory:s.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(!ae||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:l}=me(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,a=oe(this.state.conversation)+Be(this.state.exposedTools),r=Math.max(i,a),c=Y(this.state.conversation),m=this.state.started&&!this.state.terminated,p=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${c}KB`,`estimation=${a} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${l}`,`remainingToTrigger=${Math.max(0,l-i)}`,`isRunning=${m}`,`shouldCompact=${m?r>=l:!1}`,"---"].join(" | ");G.promises.appendFile(Oe,p+`
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 s=this.executeSubmit(e,t),l=new Promise(i=>{this.forceSettleWaiters.set(o,i)});return s.finally(()=>{this.forceSettleWaiters.delete(o),this.activeTurnToken===o&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([s,l])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=Mo();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.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(s=>s.exposedName)),o=[];for(const s of e)kt(s)&&(t.has(s.exposedName)||(t.add(s.exposedName),o.push(s)));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(s=>!s.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}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 E(e.client.callTool({name:"get_message",arguments:{_aws_force_inject:!0}},void 0,{timeout:1e4}),1e4,"injectForceMessage get_message"),o=O(t);let s=[];try{const r=JSON.parse(o);Array.isArray(r?.directMessages)&&(s=r.directMessages.filter(c=>c?.force===!0))}catch{return!1}if(s.length===0)return!1;const l=JSON.stringify({directMessages:s,groupMessages:[]}),i=`forced_get_msg_${Date.now()}`,a=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:i,type:"function",function:{name:a,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:i,content:l}),u(`[ACodeRuntime] injectForceMessage: injected ${s.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=ue(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 s=this.activeTurnToken,l=e.trim();let i=!1;try{u("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const a=Date.now(),r=await this.hookBus.dispatch("UserPromptSubmit",{prompt:l}),c=Date.now()-a;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=ce(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 p=this.state.commandRegistry.expand(l),h=p?.prompt.trim()||l,k=p?.command.allowedTools;if(p&&(u(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${p.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:p.command.name,arguments:p.argumentsText,sourcePath:p.command.sourcePath})),!this.state.provider.baseURL||!this.state.provider.apiKey){u("[ACodeRuntime] \u26A0\uFE0F No provider configured, using fallback response");const A=ao(h,this.state);this.emitAcodeEvent("assistant_delta",{text:A}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:h.length,outputTokens:A.length}}),i=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}u("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const T=pe(h);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 w=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:w}),u(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),u("[ACodeRuntime] Starting runModelTurn...");const C=Date.now(),d=await this.runModelTurn(k,t),y=Date.now()-C;if(u(`[ACodeRuntime] \u2705 runModelTurn completed in ${y}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:h.length,outputTokens:d.totalOutputTextLength??d.text.length},...d.responseBody?{responseBody:d.responseBody}:{},...d.finishReason?{finishReason:d.finishReason}:{}}),W(`turn_complete emitted: usage=${JSON.stringify(d.usage??{inputTokens:h.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 S=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 ${S}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(a){const r=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${r}ms:`,a instanceof Error?a.message:String(a)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",a instanceof Error?a.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:a instanceof Error?a.message:String(a)}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0}finally{const a=Date.now()-o;u(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${a}ms`),u(`[ACodeRuntime] \u{1F50D} turnCompleted=${i}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===s&&(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: ${a}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.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,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,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,s=this.config.workingDirectory,l=this.config;return{spawnSubAgent:async i=>{let a=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&&(a=a?ne(a,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:s,parentConfig:{...l,sharedMcpConnections:this.state?.mcpConnections,...a&&a.length>0?{subAgentSuiteTools:a}:{}}});return await e.start(r),{subId:r}},listSubAgentToolCatalog:async()=>be(await this.buildAllocatableToolList()),listSubAgents:async()=>{const i=e.listByParent(t),a=[],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"?a.push(m):r.push(m)}return r.sort((c,m)=>(m.endedAt??0)-(c.endedAt??0)),{running:a,history:r}},getSubAgentStatus:async i=>{const a=e.getSubAgent(i);return a?{subId:a.subId,subagentType:a.subagentType,description:a.description,status:a.status,startedAt:a.startedAt,endedAt:a.endedAt,durationMs:a.durationMs,prompt:a.prompt,result:a.result,errorMessage:a.errorMessage,contextSnapshot:a.contextSnapshot}:null},awaitSubAgents:async(i,a)=>{const r=new Set;for(const c of i)this.pendingAwaitedSubIds.add(c),r.add(c);try{return await e.awaitCompletion(i,a)}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,s)=>{for(const l of o)this.pendingAwaitedSubIds.add(l);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const l of o)this.pendingAwaitedSubIds.delete(l)}}:null,awaitBgCommands:(o,s)=>{for(const l of o)this.pendingAwaitedBgTaskIds.add(l);try{return Q.awaitCompletion(e,o,s)}finally{for(const l of o)this.pendingAwaitedBgTaskIds.delete(l)}}}}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()}}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(s=>{u(`[ACodeRuntime] \u26A0\uFE0F manager.abort(${o}) threw: ${s instanceof Error?s.message:String(s)}`)})}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(", ")}`),Q.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 s=e.toolName==="Bash"&&typeof t.wait_seconds=="number"&&t.wait_seconds>0,l=++this.toolSettleSeq;let i;const a=s?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:l,toolName:e.toolName,toolCallId:o,settlable:s,settled:!1,resolveSettle:i??null},{seq:l,signal:a}}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.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await V("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await V("ACode background commands shutdown",Q.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),V("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await V("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(),ae)try{G.promises.appendFile(Oe,`[${new Date().toISOString()}] runtime stopped | ---
12
+ `,"utf-8").catch(()=>{})}catch{}}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="",s,l,i,a="",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:a.length};await this.injectForceMessage();const p=Date.now(),h=await this.requestChatCompletion(e),k=Date.now()-p;if(u(`[ACodeRuntime] \u{1F916} AI request completed in ${k}ms, choices: ${h.choices?.length||0}`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${m+1}`),{text:"",totalOutputTextLength:a.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=h.choices?.[0];l=JSON.stringify(h,null,2),i=typeof T?.finish_reason=="string"?T.finish_reason:void 0;const w=T?.message,C=typeof w?.content=="string"?w.content:"",d=Array.isArray(w?.tool_calls)?w.tool_calls:[];if(u(`[ACodeRuntime] AI response: content=${C?C.slice(0,100)+(C.length>100?"...":""):"(empty)"}, toolCalls=${d.length}, finishReason=${i||"(none)"}`),h.usage){const M=U(h.usage.prompt_tokens??h.usage.input_tokens),$=U(h.usage.completion_tokens??h.usage.output_tokens),R=M!==void 0,f=$!==void 0;if(W(`provider usage parsed: raw=${JSON.stringify(h.usage)} input=${M} output=${$} hasInput=${R} hasOutput=${f} iteration=${m+1}`),R||f){const _=vt(h.usage,M),v=s?.outputTokens??a.length+C.length;this.state.accumulatedCacheHitTokens+=_?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=_?.cacheMissTokens??0,s={inputTokens:R?M:s?.inputTokens??0,outputTokens:f?$:v,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=s,r+=R?M:0,this.state.accumulatedInputTokens=R?M:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=f?$:this.state.accumulatedOutputTokens,W(`finalUsage updated: ${JSON.stringify(s)} (cacheUsage=${JSON.stringify(_??null)})`),u(`[ACodeRuntime] \u{1F4B0} Token usage: input=${s.inputTokens}, output=${s.outputTokens} (turn accumulated cost: input=${r})`),u(_?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${_.cacheHitTokens}, miss=${_.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else W(`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,a+=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:s,responseBody:l,finishReason:i,totalOutputTextLength:a.length};const y=d.map(M=>M.function.name).join(", ");u(`[ACodeRuntime] \u{1F527} Executing ${d.length} tool(s) at iteration ${m+1}: ${y}`);const S=Date.now();await this.handleToolCalls(d,e,t);const A=Date.now()-S;if(u(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${A}ms at iteration ${m+1}`),this.isTurnSuperseded(t))return u(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${m+1}`),{text:"",totalOutputTextLength:a.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:s,responseBody:l,finishReason:i||"safety_iteration_limit_reached",totalOutputTextLength:a.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 s={"Content-Type":"application/json"};t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`);const l={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
- `+ht}]},r=new AbortController;this.abortController=r;let a=!1;try{return await E((async()=>{const i=await E(fetch(re(o),{method:"POST",headers:s,body:JSON.stringify(c),signal:r.signal}),t.requestTotalTimeoutMs,"ACode LLM summarization",()=>{a=!0,r.abort()});if(!i.ok){const g=await E(i.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{a=!0,r.abort()}),h=g.length>500?`${g.slice(0,500)}...(truncated, total ${g.length} chars)`:g;throw new Error(`ACode LLM summarization request failed: ${i.status} ${h}`)}const m=(await E(i.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{a=!0,r.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",()=>{r.abort()})}catch(i){throw i instanceof Error&&i.name==="AbortError"?a?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):i}finally{this.abortController===r&&(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:s,maxOutput:c,inputLimit:r,threshold:a}=le(t),i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,l=te(this.state.conversation)+Le(this.state.exposedTools),m=Math.max(i,l),g=m>=a;if(u(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${i}, estimation=${l}, effectiveUsed=${m}, contextLimit=${s}, inputLimit=${r??"n/a"}, maxOutput=${c}, triggerThreshold=${a}, shouldCompact=${g}`),g){const T=G(this.state.conversation),w=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:w,sizeKB:T,estimatedTokens:l,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:i>=a?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(w,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${m} tokens, \u9608\u503C: ${a}, \u89E6\u53D1: ${i>=a?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const v=await Te(this.state.conversation,s,c,{llmSummarizer:A=>this.summarizeConversationWithLLM(A),onPhase:A=>this.handleCompactionPhase(w,A),actualUsedTokens:m}),N=G(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:w,sizeBeforeKB:T,sizeAfterKB:N,freedKB:Math.round((T-N)*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 h=await ro(this.state.conversation,Ie,s,c,T=>this.summarizeConversationWithLLM(T));h>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${h} older messages to fit within ${Ie} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const S=this.state.exposedTools.filter(T=>eo(T,this.state.permissions,e)),f=()=>{const T={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(T.reasoning_effort=t.effort),t.stream&&(T.stream_options={include_usage:!0}),S.length>0&&(T.tools=We(S),T.tool_choice="auto"),T},M="POST",_=to(o),d=To(t),C=yo(d),b=T=>{const w=JSON.stringify(T,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:M,requestUrl:_,requestHeaders:C,stream:t.stream,messageCount:this.state.conversation.length,toolCount:S.length,lastUserMessagePreview:oo(this.state.conversation),estimatedContextTokens:ue(w),requestBody:w,...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),z(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${S.length} estimatedContextTokens=${ue(w)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let $=f();b($);const y=t.requestRetryCount===ne,R=y?1/0:t.requestRetryCount+1;let k=!1;for(let T=1;y||T<=R;T+=1){this.state.terminated||(this.abortRequested=!1),T>1&&b($);const w=new AbortController;this.abortController=w;let v=!1;try{return await E((async()=>{const N=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,A=await E(fetch(re(o),{method:M,headers:d,body:JSON.stringify($),signal:w.signal}),N,"ACode provider request",()=>{v=!0,w.abort()});if(!A.ok){const B=await E(A.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{v=!0,w.abort()}),P=B.length>500?`${B.slice(0,500)}...(truncated, total ${B.length} chars)`:B;throw new Error(`ACode provider request failed: ${A.status} ${P}`)}const X=A.headers?.get?.("content-type")||"";if(t.stream&&X.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(A,t.requestStreamIdleTimeoutMs,w,t.requestFirstByteTimeoutMs);const D=await E(A.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{v=!0,w.abort()});return x(D)?D:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof D}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{w.abort()})}catch(N){let A;if(N instanceof Error&&N.name==="AbortError"?v?A=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?A=new Error("ACode provider request aborted by user"):A=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):A=N instanceof Error?N:new Error(String(N)),!k&&!this.abortRequested&&!this.state.terminated&&ze(A)){const P=G(this.state.conversation),p=te(this.state.conversation),U=this.state.conversation.length,F=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:F,sizeKB:P,estimatedTokens:p,messageCount:U,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(F,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${U}\u6761, \u5927\u5C0F: ${P}KB`),this.emitCompactionPhase(F,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const J=pt(this.state.conversation,s);this.emitCompactionPhase(F,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${J.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${J.freedTokens} tokens`),this.emitCompactionPhase(F,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const Z=await ye(this.state.conversation,{llmSummarizer:Ke=>this.summarizeConversationWithLLM(Ke),contextLimit:s});this.emitCompactionPhase(F,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${Z} \u6761\u6D88\u606F`);const pe=G(this.state.conversation),Je=te(this.state.conversation),He=this.state.conversation.length;k=!0;const fe=J.prunedCount+Z;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:F,sizeBeforeKB:P,sizeAfterKB:pe,freedKB:Math.round((P-pe)*10)/10,tokensBefore:p,tokensAfter:Je,messageCountBefore:U,messageCountAfter:He,strategy:Z>0?"summarize":"prune",freedTokens:J.freedTokens,prunedToolMessages:J.prunedCount,summarizedMessages:Z,trigger:"provider_overflow_error"}),fe===0)throw A;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${fe} older messages and rebuilt the request instead of retrying the same oversized payload`}),$=f(),b($),T-=1;continue}if(!((y||T<R)&&!this.abortRequested&&!this.state.terminated&&ao(A)))throw A;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${T}${y?"":`/${R}`} failed; retrying: ${A.message}`,nonFatal:!0});const D=Math.min(Rt,Mt*Math.pow(2,T-1)),B=Math.random()*1e3;await Dt(D+B)}finally{this.abortController===w&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,s){if(!e.body)throw new Error("ACode provider stream response has no body");const c=e.body.getReader(),r=new TextDecoder,a=new Map;let i="",l="",m;const g=S=>{for(const f of _o(S)){if(f==="[DONE]")continue;const M=JSON.parse(f);if(!x(M))continue;const _=M.usage;_&&(m=kt(m,_),z(`stream usage chunk received: ${JSON.stringify(_)} -> merged: ${JSON.stringify(m)}`));const C=M.choices?.[0]?.delta,b=mo(C);b&&this.emitAcodeEvent("thinking_delta",{text:b});const $=typeof C?.content=="string"?C.content:"";$&&(i+=$,this.emitAcodeEvent("assistant_delta",{text:$}));const y=Array.isArray(C?.tool_calls)?C.tool_calls:[];for(const R of y)bo(a,R)}};let h=!0;for(;;){const S=h&&s?s:t,{done:f,value:M}=await E(c.read(),S,h?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(h=!1,f)break;l+=r.decode(M,{stream:!0});const _=l.split(/\r?\n\r?\n/);l=_.pop()??"";for(const d of _)g(d)}return l+=r.decode(),l.trim()&&g(l),{choices:[{message:{content:i||null,tool_calls:wo(a)}}],...m?{usage:m}:{}}}async handleToolCalls(e,t,o=this.contextVersion){u(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=r=>Ae(r.function.name)==="poll_message",c=[...e.filter(r=>!s(r)),...e.filter(r=>s(r))];e.length>1&&c.some((r,a)=>r!==e[a])&&u(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${c.map(r=>r.function.name).join(", ")}`);for(const r of c){if(this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const a=r.function.name;u(`[ACodeRuntime] \u{1F50D} Looking up tool: ${a}`);let i=this.state.exposedTools.find(l=>l.exposedName===a);if(i||(i=this.state.exposedTools.find(l=>l.toolName===a),i&&u(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${a} -> ${i.exposedName}`)),!i){console.error(`[ACodeRuntime] \u274C Tool not found: ${a}, available tools: ${this.state.exposedTools.map(l=>l.exposedName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:r.id,content:`ACode MCP tool not found: ${a}`});continue}u(`[ACodeRuntime] Found tool: ${i.toolName} (kind: ${i.kind}, source: ${i.kind==="mcp"?i.serverName:"builtin"})`);try{if(i.kind==="builtin"){const b=Fe(r.function.arguments);u(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(b).slice(0,200)}`),he(i,this.state.permissions,t);const $=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:i.toolName,exposedName:i.exposedName,arguments:b});if(this.isTurnSuperseded(o))return;const y=ae($);if(y)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${i.exposedName}: ${y.message}`),new Error(y.message||`ACode tool denied by hook: ${i.exposedName}`);u(`[ACodeRuntime] Emitting mcp_status call_tool for ${i.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:i.toolName,exposedName:i.exposedName,toolUseId:r.id,arguments:b,argumentsPreview:je(b)});const R=Date.now(),k=no(i,b,this.state.provider.mcpToolTimeoutMs);u(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${i.exposedName} (timeout: ${k}ms, abortRequested: ${this.abortRequested})`),k<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${i.exposedName} has NO timeout (timeoutMs=${k})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const T=this.beginToolSettle(i,b,r.id);try{const w=await E(i.execute(b,{onOutput:A=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:i.toolName,exposedName:i.exposedName,toolUseId:r.id,stream:A.stream,text:A.text,sequence:A.sequence,cwd:A.cwd,commandLineCount:A.commandLineCount,...A.commandFilePath?{commandFilePath:A.commandFilePath}:{}})},toolCallId:r.id,...T.signal?{settleSignal:T.signal}:{}}),k,`ACode built-in tool ${i.toolName}`),v=Date.now()-R;if(u(`[ACodeRuntime] \u2705 Built-in tool ${i.exposedName} completed in ${v}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:i.toolName,exposedName:i.exposedName,result:L(w)}),this.isTurnSuperseded(o)))return;const N=L(w);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${i.exposedName}, result length: ${N.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:i.toolName,result:N}),this.state.conversation.push({role:"tool",tool_call_id:r.id,content:N}),await this.appendSyntheticMultimodalUserMessage(N,r.id,o)}finally{this.clearToolSettle(T.seq)}continue}const l=this.state.mcpConnections.find(b=>b.serverName===i.serverName);if(!l){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${i.serverName}, connected servers: ${this.state.mcpConnections.map(b=>b.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:r.id,content:`ACode MCP server not connected: ${i.serverName}`});continue}const m=Fe(r.function.arguments);u(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(m).slice(0,200)}`),he(i,this.state.permissions,t);const g=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:i.serverName,toolName:i.toolName,exposedName:i.exposedName,arguments:m});if(this.isTurnSuperseded(o))return;const h=ae(g);if(h)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${i.exposedName}: ${h.message}`),new Error(h.message||`ACode tool denied by hook: ${i.exposedName}`);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${i.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:i.serverName,tool:i.toolName,exposedName:i.exposedName,toolUseId:r.id,arguments:m,argumentsPreview:je(m)});const S=yt(i.toolName),f=S?this.state.provider.mcpPollingToolTimeoutMs:this.state.provider.mcpToolTimeoutMs,M=Date.now();u(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${i.exposedName} (timeout: ${f}ms, polling: ${S})`);const _=S&&Ae(i.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(l,i,m,f):await this.callMcpToolWithTimeout(l,i,m,f,S),d=Date.now()-M;if(u(`[ACodeRuntime] \u2705 MCP tool ${i.exposedName} completed in ${d}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:i.serverName,toolName:i.toolName,exposedName:i.exposedName,result:L(_)}),this.isTurnSuperseded(o)))return;const C=L(_);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${i.exposedName}, result length: ${C.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:i.serverName,tool:i.toolName,result:C}),this.state.conversation.push({role:"tool",tool_call_id:r.id,content:C}),await this.appendSyntheticMultimodalUserMessage(C,r.id,o)}catch(l){const m=l instanceof Error&&l.message.includes("timed out after"),g=l instanceof Error&&l.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${r.function.name}`,`isTimeout=${m}, isAbortError=${g}`,l instanceof Error?l.message:String(l)),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 ${i.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:i.kind==="mcp"?i.serverName:"builtin",tool:i.toolName,result:`[aborted] ${l instanceof Error?l.message:String(l)}`,failed:!0,aborted:!0}),l instanceof Error?l:new Error(String(l));u(`[ACodeRuntime] Calling appendToolFailureResult for ${i.exposedName} (isTimeout=${m})`),this.appendToolFailureResult(r,i,l)}}u(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,s,c){const r=s>0?s:vt,i=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const l=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await E(Promise.race([e.client.callTool({name:t.toolName,arguments:i},void 0,{timeout:r}),l.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(m){if(!c||s>0||!co(m))throw m;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{l.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
18
+ `+gt}]},i=new AbortController;this.abortController=i;let a=!1;try{return await E((async()=>{const r=await E(fetch(le(o),{method:"POST",headers:s,body:JSON.stringify(l),signal:i.signal}),t.requestTotalTimeoutMs,"ACode LLM summarization",()=>{a=!0,i.abort()});if(!r.ok){const p=await E(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{a=!0,i.abort()}),h=p.length>500?`${p.slice(0,500)}...(truncated, total ${p.length} chars)`:p;throw new Error(`ACode LLM summarization request failed: ${r.status} ${h}`)}const m=(await E(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{a=!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"?a?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:s,maxOutput:l,inputLimit:i,threshold:a}=me(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,c=oe(this.state.conversation)+Be(this.state.exposedTools),m=Math.max(r,c),p=m>=a;if(u(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${c}, effectiveUsed=${m}, contextLimit=${s}, inputLimit=${i??"n/a"}, maxOutput=${l}, triggerThreshold=${a}, shouldCompact=${p}`),p){const f=Y(this.state.conversation),_=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:_,sizeKB:f,estimatedTokens:c,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:r>=a?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(_,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${m} tokens, \u9608\u503C: ${a}, \u89E6\u53D1: ${r>=a?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const v=await Ae(this.state.conversation,s,l,{llmSummarizer:b=>this.summarizeConversationWithLLM(b),onPhase:b=>this.handleCompactionPhase(_,b),actualUsedTokens:m}),N=Y(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:_,sizeBeforeKB:f,sizeAfterKB:N,freedKB:Math.round((f-N)*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 h=await co(this.state.conversation,De,s,l,f=>this.summarizeConversationWithLLM(f));h>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${h} older messages to fit within ${De} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const k=this.state.exposedTools.filter(f=>no(f,this.state.permissions,e)),T=()=>{const f={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(f.reasoning_effort=t.effort),t.stream&&(f.stream_options={include_usage:!0}),k.length>0&&(f.tools=Ke(k),f.tool_choice="auto"),f},w="POST",C=so(o),d=Co(t),y=_o(d),S=f=>{const _=JSON.stringify(f,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:w,requestUrl:C,requestHeaders:y,stream:t.stream,messageCount:this.state.conversation.length,toolCount:k.length,lastUserMessagePreview:io(this.state.conversation),estimatedContextTokens:de(_),requestBody:_,...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),W(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${k.length} estimatedContextTokens=${de(_)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let A=T();S(A);const M=t.requestRetryCount===se,$=M?1/0:t.requestRetryCount+1;let R=!1;for(let f=1;M||f<=$;f+=1){this.state.terminated||(this.abortRequested=!1),f>1&&S(A);const _=new AbortController;this.abortController=_;let v=!1;try{return await E((async()=>{const N=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,b=await E(fetch(le(o),{method:w,headers:d,body:JSON.stringify(A),signal:_.signal}),N,"ACode provider request",()=>{v=!0,_.abort()});if(!b.ok){const F=await E(b.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{v=!0,_.abort()}),L=F.length>500?`${F.slice(0,500)}...(truncated, total ${F.length} chars)`:F;throw new Error(`ACode provider request failed: ${b.status} ${L}`)}const P=b.headers?.get?.("content-type")||"";if(t.stream&&P.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(b,t.requestStreamIdleTimeoutMs,_,t.requestFirstByteTimeoutMs);const B=await E(b.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{v=!0,_.abort()});return x(B)?B:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof B}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{_.abort()})}catch(N){let b;if(N instanceof Error&&N.name==="AbortError"?v?b=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?b=new Error("ACode provider request aborted by user"):b=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):b=N instanceof Error?N:new Error(String(N)),!R&&!this.abortRequested&&!this.state.terminated&&Je(b)){const L=Y(this.state.conversation),g=oe(this.state.conversation),q=this.state.conversation.length,j=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:j,sizeKB:L,estimatedTokens:g,messageCount:q,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(j,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${q}\u6761, \u5927\u5C0F: ${L}KB`),this.emitCompactionPhase(j,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const K=Tt(this.state.conversation,s);this.emitCompactionPhase(j,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${K.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${K.freedTokens} tokens`),this.emitCompactionPhase(j,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const ee=await Ce(this.state.conversation,{llmSummarizer:Ye=>this.summarizeConversationWithLLM(Ye),contextLimit:s});this.emitCompactionPhase(j,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${ee} \u6761\u6D88\u606F`);const ge=Y(this.state.conversation),Ge=oe(this.state.conversation),Qe=this.state.conversation.length;R=!0;const Te=K.prunedCount+ee;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:j,sizeBeforeKB:L,sizeAfterKB:ge,freedKB:Math.round((L-ge)*10)/10,tokensBefore:g,tokensAfter:Ge,messageCountBefore:q,messageCountAfter:Qe,strategy:ee>0?"summarize":"prune",freedTokens:K.freedTokens,prunedToolMessages:K.prunedCount,summarizedMessages:ee,trigger:"provider_overflow_error"}),Te===0)throw b;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${Te} older messages and rebuilt the request instead of retrying the same oversized payload`}),A=T(),S(A),f-=1;continue}if(!((M||f<$)&&!this.abortRequested&&!this.state.terminated&&uo(b)))throw b;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${f}${M?"":`/${$}`} failed; retrying: ${b.message}`,nonFatal:!0});const B=Math.min(It,Nt*Math.pow(2,f-1)),F=Math.random()*1e3;await qt(B+F)}finally{this.abortController===_&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,s){if(!e.body)throw new Error("ACode provider stream response has no body");const l=e.body.getReader(),i=new TextDecoder,a=new Map;let r="",c="",m;const p=k=>{for(const T of $o(k)){if(T==="[DONE]")continue;const w=JSON.parse(T);if(!x(w))continue;const C=w.usage;C&&(m=xt(m,C),W(`stream usage chunk received: ${JSON.stringify(C)} -> merged: ${JSON.stringify(m)}`));const y=w.choices?.[0]?.delta,S=fo(y);S&&this.emitAcodeEvent("thinking_delta",{text:S});const A=typeof y?.content=="string"?y.content:"";A&&(r+=A,this.emitAcodeEvent("assistant_delta",{text:A}));const M=Array.isArray(y?.tool_calls)?y.tool_calls:[];for(const $ of M)ko(a,$)}};let h=!0;for(;;){const k=h&&s?s:t,{done:T,value:w}=await E(l.read(),k,h?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(h=!1,T)break;c+=i.decode(w,{stream:!0});const C=c.split(/\r?\n\r?\n/);c=C.pop()??"";for(const d of C)p(d)}return c+=i.decode(),c.trim()&&p(c),{choices:[{message:{content:r||null,tool_calls:So(a)}}],...m?{usage:m}:{}}}async handleToolCalls(e,t,o=this.contextVersion){u(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=i=>_e(i.function.name)==="poll_message",l=[...e.filter(i=>!s(i)),...e.filter(i=>s(i))];e.length>1&&l.some((i,a)=>i!==e[a])&&u(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${l.map(i=>i.function.name).join(", ")}`);for(const i of l){if(this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const a=i.function.name;u(`[ACodeRuntime] \u{1F50D} Looking up tool: ${a}`);let r=this.state.exposedTools.find(c=>c.exposedName===a);if(r||(r=this.state.exposedTools.find(c=>c.toolName===a),r&&u(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${a} -> ${r.exposedName}`)),!r){console.error(`[ACodeRuntime] \u274C Tool not found: ${a}, 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: ${a}`});continue}u(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const A=We(i.function.arguments);u(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(A).slice(0,200)}`),fe(r,this.state.permissions,t);const M=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:A});if(this.isTurnSuperseded(o))return;const $=ce(M);if($)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${$.message}`),new Error($.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:A,argumentsPreview:He(A)});const R=Date.now(),f=ro(r,A,this.state.provider.mcpToolTimeoutMs);u(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${f}ms, abortRequested: ${this.abortRequested})`),f<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${f})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const _=this.beginToolSettle(r,A,i.id);try{const v=await E(r.execute(A,{onOutput:P=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:P.stream,text:P.text,sequence:P.sequence,cwd:P.cwd,commandLineCount:P.commandLineCount,...P.commandFilePath?{commandFilePath:P.commandFilePath}:{}})},toolCallId:i.id,..._.signal?{settleSignal:_.signal}:{}}),f,`ACode built-in tool ${r.toolName}`),N=Date.now()-R;if(u(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${N}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 b=O(v);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${b.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,result:b}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:b}),await this.appendSyntheticMultimodalUserMessage(b,i.id,o)}finally{this.clearToolSettle(_.seq)}continue}const c=this.state.mcpConnections.find(A=>A.serverName===r.serverName);if(!c){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(A=>A.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)}`),fe(r,this.state.permissions,t);const p=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:m});if(this.isTurnSuperseded(o))return;const h=ce(p);if(h)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${h.message}`),new Error(h.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=bt(r.toolName),w=k?this.state.provider.mcpPollingToolTimeoutMs:T?0:this.state.provider.mcpToolTimeoutMs,C=Date.now();u(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${w}ms, polling: ${k})`);const d=k&&_e(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(c,r,m,w):await this.callMcpToolWithTimeout(c,r,m,w,k),y=Date.now()-C;if(u(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${y}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;const S=O(d);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${S.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,result:S}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:S}),await this.appendSyntheticMultimodalUserMessage(S,i.id,o)}catch(c){const m=c instanceof Error&&c.message.includes("timed out after"),p=c instanceof Error&&c.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${m}, isAbortError=${p}`,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,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,s,l,i){const a=s>0?s:Pt,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 E(Promise.race([e.client.callTool({name:t.toolName,arguments:c},void 0,{timeout:a,...i?{signal:i}:{}}),m.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(p){if(i?.aborted||!l||s>0||!mo(p))throw p;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 s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
19
19
  Error: ${o.error}`:`Sub-agent ${o.subId} [${o.status}]: ${o.description}
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:s,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=L(e);let s;try{s=JSON.parse(o)}catch{return e}const r=[...t.map(a=>{const i=a.error?`Sub-agent ${a.subId} [${a.status}]: ${a.description}
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:s,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 s;try{s=JSON.parse(o)}catch{return e}const i=[...t.map(a=>{const r=a.error?`Sub-agent ${a.subId} [${a.status}]: ${a.description}
21
21
  Error: ${a.error}`:`Sub-agent ${a.subId} [${a.status}]: ${a.description}
22
- Output: ${a.output.length>500?a.output.slice(0,500)+"... (truncated)":a.output}`;return{msgId:`subagent-completion-${a.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:i,requireReply:!1,prompt:`Sub-agent ${a.subId} (${a.description}) has reached terminal state: ${a.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:r},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const c=this.state.mcpConnections.find(r=>r.serverName==="aws-client-agent-mcp");if(!c)return u("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(c,t):e==="memory_expiration"?await this.recheckMemoryExpiration(c,t):await this.recheckMemoryCleanup(c,t)}catch(r){return u(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${r instanceof Error?r.message:String(r)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${r instanceof Error?r.message:String(r)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await E(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=L(o),c=JSON.parse(s);return c==null||typeof c!="object"||Array.isArray(c)?null:c}catch(o){throw o}}async recheckMemoryFileChange(e,t){const o=[];if(await Promise.all(t.map(async c=>{const r=await this.readMemoryViaMcp(e,c);r&&r.memory_status==="updating"&&o.push(c)})),o.length===0)return u(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(c=>`- ${c}`).join(`
22
+ Output: ${a.output.length>500?a.output.slice(0,500)+"... (truncated)":a.output}`;return{msgId:`subagent-completion-${a.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:r,requireReply:!1,prompt:`Sub-agent ${a.subId} (${a.description}) has reached terminal state: ${a.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:i},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const l=this.state.mcpConnections.find(i=>i.serverName==="aws-client-agent-mcp");if(!l)return u("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(l,t):e==="memory_expiration"?await this.recheckMemoryExpiration(l,t):await this.recheckMemoryCleanup(l,t)}catch(i){return u(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${i instanceof Error?i.message:String(i)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${i instanceof Error?i.message:String(i)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await E(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=O(o),l=JSON.parse(s);return l==null||typeof l!="object"||Array.isArray(l)?null:l}catch(o){throw o}}async recheckMemoryFileChange(e,t){const o=[];if(await Promise.all(t.map(async l=>{const i=await this.readMemoryViaMcp(e,l);i&&i.memory_status==="updating"&&o.push(l)})),o.length===0)return u(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(l=>`- ${l}`).join(`
23
23
  `);return u(`[ACodeRuntime] recheck memory_file_change: ${o.length}/${t.length} URIs still updating`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
24
24
  ${s}
25
25
 
26
- \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async r=>{const a=await this.readMemoryViaMcp(e,r);if(!a)return;const i=a.expiresAt??a.expires_at,l=a.memory_status==="recalling",m=typeof i=="string"&&new Date(i).getTime()<s;(l||m)&&o.push(r)})),o.length===0)return u(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const c=o.map(r=>`- ${r}`).join(`
26
+ \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async i=>{const a=await this.readMemoryViaMcp(e,i);if(!a)return;const r=a.expiresAt??a.expires_at,c=a.memory_status==="recalling",m=typeof r=="string"&&new Date(r).getTime()<s;(c||m)&&o.push(i)})),o.length===0)return u(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const l=o.map(i=>`- ${i}`).join(`
27
27
  `);return u(`[ACodeRuntime] recheck memory_expiration: ${o.length}/${t.length} URIs still expired or recalling`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u5904\u7406\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
28
- ${c}
28
+ ${l}
29
29
 
30
- \u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const a=await E(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),i=L(a);o=JSON.parse(i)}catch{return{done:!1,continueMessage:"get_memory_stats \u67E5\u8BE2\u5931\u8D25\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5BB9\u91CF\u662F\u5426\u5DF2\u8FBE\u6807\uFF0C\u8BF7\u91CD\u65B0\u9A8C\u8BC1\u540E\u518D\u7EE7\u7EED\u3002"}}const s=o.by_type??{},c=[];for(const a of t){const i=a.indexOf("/");if(i<0)continue;const l=a.slice(0,i),m=a.slice(i+1),h=s[l]?.by_domain?.[m];h?.exceeded&&c.push(`${l}/${m} (\u5F53\u524D ${h.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${h.limit??"?"})`)}if(c.length===0)return u(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const r=c.map(a=>`- ${a}`).join(`
31
- `);return u(`[ACodeRuntime] recheck memory_cleanup: ${c.length}/${t.length} type/domain pairs still exceeded`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
32
- ${r}
30
+ \u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const a=await E(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),r=O(a);o=JSON.parse(r)}catch{return{done:!1,continueMessage:"get_memory_stats \u67E5\u8BE2\u5931\u8D25\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5BB9\u91CF\u662F\u5426\u5DF2\u8FBE\u6807\uFF0C\u8BF7\u91CD\u65B0\u9A8C\u8BC1\u540E\u518D\u7EE7\u7EED\u3002"}}const s=o.by_type??{},l=[];for(const a of t){const r=a.indexOf("/");if(r<0)continue;const c=a.slice(0,r),m=a.slice(r+1),h=s[c]?.by_domain?.[m];h?.exceeded&&l.push(`${c}/${m} (\u5F53\u524D ${h.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${h.limit??"?"})`)}if(l.length===0)return u(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const i=l.map(a=>`- ${a}`).join(`
31
+ `);return u(`[ACodeRuntime] recheck memory_cleanup: ${l.length}/${t.length} type/domain pairs still exceeded`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
32
+ ${i}
33
33
 
34
34
  \u8BF7\u8C03\u7528 list_memories \u67E5\u770B\u8D85\u9650\u8BB0\u5FC6\uFF0C\u5220\u9664\u4E0D\u518D\u9700\u8981\u7684 recently_memory \u6216\u5BF9 agent_memory \u8C03\u7528 update_memory \u7EED\u671F\u3002`}}buildMemoryDelegatePrompt(e){const t=e.uris.map(o=>`- ${o}`).join(`
35
35
  `);return e.type==="memory_expiration"?`\u4F60\u662F\u4E00\u6761\u4E13\u95E8\u5904\u7406 memory \u8FC7\u671F\u6574\u7406\u7684\u5B50 agent\u3002
@@ -83,8 +83,8 @@ ${t}
83
83
  \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\u7C7B\u578B/\u57DF\u8D85\u8FC7\u5BB9\u91CF\u4E0A\u9650\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`:`\u4F60\u662F\u4E00\u6761\u4E13\u95E8\u5904\u7406\u6C38\u4E45\u8BB0\u5FC6\u6587\u4EF6\u53D8\u66F4\u66F4\u65B0\u7684\u5B50 agent\u3002
84
84
 
85
85
  \u4EE5\u4E0B ${e.uris.length} \u4E2A\u6C38\u4E45\u8BB0\u5FC6\u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D1\u751F\u53D8\u66F4\uFF1A
86
- ${e.uris.map(o=>{const s=e.fileChanges?.find(i=>i.uri===o);if(!s)return`- ${o}`;const c={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},r=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],a=r.length>0?r.map(i=>{if(i.status==="no_change")return` \xB7 ${i.path}`;const l=c[i.status]??i.status,m=i.status==="content_changed"&&i.localMd5&&i.serverMd5?` \u672C\u5730: ${i.localMd5} Server: ${i.serverMd5}`:i.status==="not_found"&&i.serverMd5?` Server: ${i.serverMd5}`:"";return` \xB7 ${i.path}\uFF08${l}${m}\uFF09`}).join(`
87
- `):s.boundFiles&&s.boundFiles.length>0?s.boundFiles.map(i=>` \xB7 ${i}`).join(`
86
+ ${e.uris.map(o=>{const s=e.fileChanges?.find(r=>r.uri===o);if(!s)return`- ${o}`;const l={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},i=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],a=i.length>0?i.map(r=>{if(r.status==="no_change")return` \xB7 ${r.path}`;const c=l[r.status]??r.status,m=r.status==="content_changed"&&r.localMd5&&r.serverMd5?` \u672C\u5730: ${r.localMd5} Server: ${r.serverMd5}`:r.status==="not_found"&&r.serverMd5?` Server: ${r.serverMd5}`:"";return` \xB7 ${r.path}\uFF08${c}${m}\uFF09`}).join(`
87
+ `):s.boundFiles&&s.boundFiles.length>0?s.boundFiles.map(r=>` \xB7 ${r}`).join(`
88
88
  `):" \u65E0\uFF08\u8BF7\u901A\u8FC7 read_memory \u67E5\u770B bound_files\uFF09";return`- ${o}
89
89
  - \u7ED1\u5B9A\u6587\u4EF6:
90
90
  ${a}`}).join(`
@@ -105,5 +105,5 @@ ${a}`}).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=L(e)}catch{return e}let s;try{s=JSON.parse(o)}catch{return e}const c=s.directMessages;if(!Array.isArray(c)||c.length===0)return e;const r=[];let a=0;for(const l of c){const m=l._acodeAutoDelegate;if(m&&(m.type==="memory_expiration"||m.type==="memory_file_change"||m.type==="memory_cleanup")){a++;const g=Date.now(),h=m.uris.filter(d=>this.pendingMemorySubAgents.has(d)).length,S=m.uris.filter(d=>{const C=this.memoryDelegateCooldownUntil.get(d);return C!==void 0&&g<C}).length,f=m.uris.filter(d=>{if(this.pendingMemorySubAgents.has(d))return!1;const C=this.memoryDelegateCooldownUntil.get(d);return!(C!==void 0&&g<C)});if(f.length===0){u(`[ACodeRuntime] Memory ${m.type} skipped: ${h} in-progress, ${S} in cooldown (total ${m.uris.length} URIs)`);continue}const M=Array.isArray(m.fileChanges)?m.fileChanges.filter(d=>f.includes(d.uri)):void 0,_=this.buildMemoryDelegatePrompt({type:m.type,uris:f,fileChanges:M});try{const d=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:"explore",description:`Memory ${m.type} auto-delegate (${f.length} items)`,prompt:_,workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const y of f)this.pendingMemorySubAgents.set(y,d);const C=new Set(f);t.subscribe(d,()=>{const y=t.getSubAgent(d);if(y&&(y.status==="completed"||y.status==="failed"||y.status==="cancelled")){const R=Date.now();for(const k of C)this.pendingMemorySubAgents.get(k)===d&&this.pendingMemorySubAgents.delete(k),this.memoryDelegateCooldownUntil.set(k,R+Ee);for(const[k,T]of this.memoryDelegateCooldownUntil)T<=R&&this.memoryDelegateCooldownUntil.delete(k);u(`[ACodeRuntime] Memory delegate sub-agent ${d} finished (${y.status}), ${C.size} URI(s) entered ${Ee}ms cooldown`)}});const b=m.type,$=async(y,R)=>this.recheckMemoryDelegate(b,f,y,R);await t.startWithRecheck(d,$,3),u(`[ACodeRuntime] Auto-delegated memory ${m.type} to sub-agent ${d} (${f.length} URIs, ${m.uris.length-f.length} already in progress)`)}catch(d){for(const C of f)this.pendingMemorySubAgents.delete(C);u(`[ACodeRuntime] Failed to auto-delegate memory ${m.type} (suppressed, will retry next poll): ${d instanceof Error?d.message:String(d)}`)}}else r.push(l)}if(a===0)return e;if(r.length===0)return null;const i={...s,directMessages:r};return{content:[{type:"text",text:JSON.stringify(i,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,s){const c=this.config.subAgentManager;if(!c)return await this.callMcpToolWithTimeout(e,t,o,s,!0);const r=c.takeCompletedSubAgents();if(r.length>0)return u(`[ACodeRuntime] poll_message: ${r.length} sub-agent(s) already completed, returning synthetic result`),W.formatSubAgentCompletionAsPollResult(r);let a=!1;for(;;){const i=c.waitForAnyCompletion(),l=a?{...o,_aws_silent_poll:!0}:o,m=this.callMcpToolWithTimeout(e,t,l,s,!0);try{const g=await Promise.race([m.then(f=>({type:"mcp",result:f})),i.promise.then(f=>({type:"subagent",notif:f}))]);if(g.type==="subagent"){const f=c.takeCompletedSubAgents();return f.length===0&&f.push(g.notif),u(`[ACodeRuntime] poll_message: sub-agent ${g.notif.subId} completed during race, returning synthetic result (${f.length} notification(s))`),W.formatSubAgentCompletionAsPollResult(f)}const h=c.takeCompletedSubAgents();if(h.length>0){u(`[ACodeRuntime] poll_message: MCP returned, merging ${h.length} sub-agent completion(s)`);const f=W.mergeSubAgentCompletionsIntoMcpResult(g.result,h),M=await this.processMemoryAutoDelegates(f);if(M!==null&&this.pollResultHasMessages(M))return M;await this.waitForDelegateRepoll(),a=!0;continue}const S=await this.processMemoryAutoDelegates(g.result);if(S!==null&&this.pollResultHasMessages(S))return S;await this.waitForDelegateRepoll(),a=!0}finally{i.cancel()}}}pollResultHasMessages(e){try{const t=L(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,c=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||c>0}catch{return!0}}async waitForDelegateRepoll(){u(`[ACodeRuntime] poll_message: all messages delegated, waiting ${xe}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,xe);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((s,c)=>{t=()=>{c(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 s=de(e);if(!s.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."});return}const c=await Ue(s.content);if(this.isTurnSuperseded(o))return;this.state.conversation.push({role:"user",content:c});const r=this.state.conversation.find(a=>a.role==="tool"&&a.tool_call_id===t);if(r&&typeof r.content=="string"){let a;try{const i=JSON.parse(r.content);if(typeof i=="object"&&i!==null){const l={...i};"attachments"in l&&(delete l.attachments,a=JSON.stringify(l))}}catch{}if(a===void 0){const i=r.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();i!==r.content&&(a=i)}a!==void 0&&a.length>0?r.content=a:a!==void 0&&(r.content="[Tool result contained images; see user message above]")}}appendToolFailureResult(e,t,o){const s=uo(t,o);u(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${s.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${V(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,result:s,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:s})}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(s=>t?Ce(s,t):xt.has(s.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[s,c]of Object.entries(e))try{const r=new Ye({name:"acode",version:"0.1.0"}),a=this.createMcpTransport(c);await E(r.connect(a),t,`ACode MCP server ${s} connect`);const i={serverName:s,client:r,transport:a,tools:[]};r.setNotificationHandler(et,()=>{this.refreshMcpConnectionTools(i,t)});const{tools:l}=await E(r.listTools(),t,`ACode MCP server ${s} listTools`);i.tools=we(s,l),o.push(i)}catch(r){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${s}: ${r instanceof Error?r.message:String(r)}`})}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:s}=await E(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=we(e.serverName,s)}catch(s){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${s instanceof Error?s.message:String(s)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.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 Xe({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 Ve(new URL(e.url),{requestInit:t}):new Ze(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(s=>s.toolName==="get_profile"))try{const s=await E(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:se}),se,"ACode startup get_profile"),c=this.extractProfileFromToolResult(s);return fo(c)}catch(s){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${s instanceof Error?s.message:String(s)}`}),""}return""}extractProfileFromToolResult(e){if(!x(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(x(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(x(s))return s}catch{}}return x(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=>Q(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}W.SKILL_REFRESH_DEBOUNCE_MS=500;export{W 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 s;try{s=JSON.parse(o)}catch{return e}const l=s.directMessages;if(!Array.isArray(l)||l.length===0)return e;const i=[];let a=0;for(const c of l){const m=c._acodeAutoDelegate;if(m&&(m.type==="memory_expiration"||m.type==="memory_file_change"||m.type==="memory_cleanup")){a++;const p=Date.now(),h=m.uris.filter(d=>this.pendingMemorySubAgents.has(d)).length,k=m.uris.filter(d=>{const y=this.memoryDelegateCooldownUntil.get(d);return y!==void 0&&p<y}).length,T=m.uris.filter(d=>{if(this.pendingMemorySubAgents.has(d))return!1;const y=this.memoryDelegateCooldownUntil.get(d);return!(y!==void 0&&p<y)});if(T.length===0){u(`[ACodeRuntime] Memory ${m.type} skipped: ${h} in-progress, ${k} in cooldown (total ${m.uris.length} URIs)`);continue}const w=Array.isArray(m.fileChanges)?m.fileChanges.filter(d=>T.includes(d.uri)):void 0,C=this.buildMemoryDelegatePrompt({type:m.type,uris:T,fileChanges:w});try{const d=wt([$e],be(await this.buildAllocatableToolList())).patterns,y=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:$e,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 $ of T)this.pendingMemorySubAgents.set($,y);const S=new Set(T);t.subscribe(y,()=>{const $=t.getSubAgent(y);if($&&($.status==="completed"||$.status==="failed"||$.status==="cancelled")){const R=Date.now();for(const f of S)this.pendingMemorySubAgents.get(f)===y&&this.pendingMemorySubAgents.delete(f),this.memoryDelegateCooldownUntil.set(f,R+Pe);for(const[f,_]of this.memoryDelegateCooldownUntil)_<=R&&this.memoryDelegateCooldownUntil.delete(f);u(`[ACodeRuntime] Memory delegate sub-agent ${y} finished (${$.status}), ${S.size} URI(s) entered ${Pe}ms cooldown`)}});const A=m.type,M=async($,R)=>this.recheckMemoryDelegate(A,T,$,R);await t.startWithRecheck(y,M,3),u(`[ACodeRuntime] Auto-delegated memory ${m.type} to sub-agent ${y} (${T.length} URIs, ${m.uris.length-T.length} already in progress)`)}catch(d){for(const y of T)this.pendingMemorySubAgents.delete(y);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(a===0)return e;if(i.length===0)return null;const r={...s,directMessages:i};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,s){const l=this.config.subAgentManager;if(!l)return D("runtime.poll.no-subagent-manager","\u65E0 SubAgentManager\uFF0C\u76F4\u63A5\u8D70\u666E\u901A MCP \u8C03\u7528"),await this.callMcpToolWithTimeout(e,t,o,s,!0);const i=l.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`),H.formatSubAgentCompletionAsPollResult(i);let a=!1,r=0;for(;;){r++,D("runtime.poll.round-start",`\u7B2C ${r} \u8F6E race \u5F00\u59CB: timeoutMs=${s} silent=${a}`);const c=new AbortController,m=l.waitForAnyCompletion(),p=a?{...o,_aws_silent_poll:!0}:o,h=Date.now(),k=this.callMcpToolWithTimeout(e,t,p,s,!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()-h}ms\uFF09\u540E\u8FD4\u56DE\u5408\u6210\u7ED3\u679C`),c.abort(),k.catch(()=>{});const d=l.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))`),H.formatSubAgentCompletionAsPollResult(d)}D("runtime.poll.mcp-returned",`MCP \u5148\u8FD4\u56DE\uFF08\u8017\u65F6 ${Date.now()-h}ms\uFF09\uFF0C\u68C0\u67E5\u5F85\u5408\u5E76\u7684\u5B50 agent \u5B8C\u6210`);const w=l.takeCompletedSubAgents();if(w.length>0){u(`[ACodeRuntime] poll_message: MCP returned, merging ${w.length} sub-agent completion(s)`);const d=H.mergeSubAgentCompletionsIntoMcpResult(T.result,w),y=await this.processMemoryAutoDelegates(d);if(D("runtime.poll.delegate-check",`\u5408\u5E76 ${w.length} \u4E2A\u5B50 agent \u5B8C\u6210\u540E\u59D4\u6258\u68C0\u67E5: processed=${y===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),y!==null){if(this.pollResultHasMessages(y))return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),y;D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${re}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),a=!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 ${re}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),a=!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),s=Array.isArray(o.directMessages)?o.directMessages:[],l=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${s.length}${s.length>0?JSON.stringify(s.map(i=>({id:i.msgId,ch:i.channel}))):""} gm=${l.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=O(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,l=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||l>0}catch{return!0}}async waitForDelegateRepoll(){u(`[ACodeRuntime] poll_message: all messages delegated, waiting ${re}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,re);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((s,l)=>{t=()=>{l(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 s=pe(e);if(!s.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."});return}const l=await Fe(s.content);if(this.isTurnSuperseded(o))return;this.state.conversation.push({role:"user",content:l});const i=this.state.conversation.find(a=>a.role==="tool"&&a.tool_call_id===t);if(i&&typeof i.content=="string"){let a;try{const r=JSON.parse(i.content);if(typeof r=="object"&&r!==null){const c={...r};"attachments"in c&&(delete c.attachments,a=JSON.stringify(c))}}catch{}if(a===void 0){const r=i.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();r!==i.content&&(a=r)}a!==void 0&&a.length>0?i.content=a:a!==void 0&&(i.content="[Tool result contained images; see user message above]")}}appendToolFailureResult(e,t,o){const s=po(t,o);u(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${s.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${Z(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,result:s,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:s})}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(s=>t?we(s,t):$t.has(s.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[s,l]of Object.entries(e))try{const i=new Ze({name:"acode",version:"0.1.0"}),a=this.createMcpTransport(l);await E(i.connect(a),t,`ACode MCP server ${s} connect`);const r={serverName:s,client:i,transport:a,tools:[]};i.setNotificationHandler(nt,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:c}=await E(i.listTools(),t,`ACode MCP server ${s} listTools`);r.tools=Me(s,c),o.push(r)}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${s}: ${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:s}=await E(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Me(e.serverName,s)}catch(s){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${s instanceof Error?s.message:String(s)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.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 tt({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 et(new URL(e.url),{requestInit:t}):new ot(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(s=>s.toolName==="get_profile"))try{const s=await E(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:ie}),ie,"ACode startup get_profile"),l=this.extractProfileFromToolResult(s);return yo(l)}catch(s){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${s instanceof Error?s.message:String(s)}`}),""}return""}extractProfileFromToolResult(e){if(!x(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(x(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(x(s))return s}catch{}}return x(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=>V(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}H.SKILL_REFRESH_DEBOUNCE_MS=500;export{H as ACodeRuntime};
109
109
 
@@ -21,6 +21,7 @@ export type SubAgentRecheckFn = (output: string, turn: number) => Promise<{
21
21
  export interface SubAgentSpawnOptions {
22
22
  parentAgentId: string;
23
23
  parentSessionId: string;
24
+
24
25
  subagentType: SubAgentType;
25
26
  description: string;
26
27
  prompt: string;