aws-runtime-bridge 1.9.153 → 1.9.162

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 (78) hide show
  1. package/CHANGELOG.md +462 -0
  2. package/dist/adapter/AcodeSdkAdapter.d.ts +29 -6
  3. package/dist/adapter/AcodeSdkAdapter.js +6 -5
  4. package/dist/adapter/prompts.d.ts +1 -1
  5. package/dist/adapter/prompts.js +1 -1
  6. package/dist/adapter/types.d.ts +0 -16
  7. package/dist/routes/acode-todos.js +1 -1
  8. package/dist/routes/ltr.js +1 -1
  9. package/dist/routes/sessions.d.ts +18 -74
  10. package/dist/routes/sessions.js +1 -1
  11. package/dist/routes/terminal.d.ts +8 -0
  12. package/dist/routes/terminal.js +24 -24
  13. package/dist/services/instance-features.d.ts +16 -2
  14. package/dist/services/instance-features.js +1 -1
  15. package/dist/services/workspace-files.js +1 -1
  16. package/dist/services/workspace-watch.js +1 -1
  17. package/package/acode/dist/ask-user-question-tool.js +1 -1
  18. package/package/acode/dist/await-complete-tool.js +1 -1
  19. package/package/acode/dist/background-command-manager.js +1 -1
  20. package/package/acode/dist/background-command-tools.js +1 -1
  21. package/package/acode/dist/built-in-file-tools.d.ts +18 -2
  22. package/package/acode/dist/built-in-file-tools.js +2 -2
  23. package/package/acode/dist/built-in-symbols-tool.js +1 -1
  24. package/package/acode/dist/context-overflow.d.ts +19 -0
  25. package/package/acode/dist/context-overflow.js +2 -0
  26. package/package/acode/dist/grammars/grammars/tree-sitter-lua.wasm +0 -0
  27. package/package/acode/dist/index.d.ts +3 -1
  28. package/package/acode/dist/index.js +1 -1
  29. package/package/acode/dist/parsers/ast-cache.d.ts +12 -1
  30. package/package/acode/dist/parsers/ast-cache.js +1 -1
  31. package/package/acode/dist/parsers/language-queries.js +1 -1
  32. package/package/acode/dist/parsers/symbol-extractor.js +2 -2
  33. package/package/acode/dist/parsers/tree-sitter-loader.d.ts +1 -1
  34. package/package/acode/dist/parsers/tree-sitter-loader.js +1 -1
  35. package/package/acode/dist/plugin-types.d.ts +5 -0
  36. package/package/acode/dist/plugin-types.js +1 -0
  37. package/package/acode/dist/read-file-state.d.ts +48 -0
  38. package/package/acode/dist/read-file-state.js +2 -0
  39. package/package/acode/dist/runtime.d.ts +63 -9
  40. package/package/acode/dist/runtime.js +30 -27
  41. package/package/acode/dist/skill-tool.js +3 -3
  42. package/package/acode/dist/sub-agent-manager.js +1 -1
  43. package/package/acode/dist/sub-agent-tools.js +5 -5
  44. package/package/acode/dist/todo-tool.js +3 -3
  45. package/package/acode/dist/tool-concurrency/index.d.ts +5 -0
  46. package/package/acode/dist/tool-concurrency/index.js +2 -0
  47. package/package/acode/dist/tool-concurrency/observability.d.ts +46 -0
  48. package/package/acode/dist/tool-concurrency/observability.js +3 -0
  49. package/package/acode/dist/tool-concurrency/resource-lock.d.ts +25 -0
  50. package/package/acode/dist/tool-concurrency/resource-lock.js +2 -0
  51. package/package/acode/dist/tool-concurrency/scheduler.d.ts +30 -0
  52. package/package/acode/dist/tool-concurrency/scheduler.js +2 -0
  53. package/package/acode/dist/tool-concurrency/types.d.ts +80 -0
  54. package/package/acode/dist/tool-concurrency/types.js +2 -0
  55. package/package/acode/dist/tool-group-manager.d.ts +116 -0
  56. package/package/acode/dist/tool-group-manager.js +14 -0
  57. package/package/acode/dist/types.d.ts +12 -2
  58. package/package/acode/package.json +2 -2
  59. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +3 -27
  60. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  61. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +46 -8
  62. package/package/aws-client-agent-mcp/dist/mcp-server.js +30 -30
  63. package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +29 -3
  64. package/package/aws-client-agent-mcp/dist/mcp-tools.js +146 -21
  65. package/package/aws-client-agent-mcp/dist/office/office-equation.d.ts +5 -0
  66. package/package/aws-client-agent-mcp/dist/office/office-equation.js +2 -0
  67. package/package/aws-client-agent-mcp/dist/office/office-image.d.ts +12 -0
  68. package/package/aws-client-agent-mcp/dist/office/office-image.js +2 -0
  69. package/package/aws-client-agent-mcp/dist/office/office-workspace.d.ts +25 -0
  70. package/package/aws-client-agent-mcp/dist/office/office-workspace.js +2 -0
  71. package/package/aws-client-agent-mcp/dist/tool-groups.js +2 -2
  72. package/package/aws-client-agent-mcp/dist/types.d.ts +6 -2
  73. package/package/aws-client-agent-mcp/package.json +2 -1
  74. package/package.json +1 -1
  75. package/package/acode/dist/capability-prompt.d.ts +0 -16
  76. package/package/acode/dist/capability-prompt.js +0 -3
  77. package/package/acode/dist/plugin-tools.d.ts +0 -14
  78. package/package/acode/dist/plugin-tools.js +0 -9
@@ -1,37 +1,40 @@
1
- import{EventEmitter as et}from"node:events";import{randomUUID as tt}from"node:crypto";import B from"node:fs";import Ce from"node:os";import G from"node:path";import{Client as ot}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as st}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as nt}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as it}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as rt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as at,DEFAULT_TOOL_PERMISSION_POLICY as _e}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as ct,createAskUserQuestionTool as lt}from"./ask-user-question-tool.js";import{createSkillTool as ut}from"./skill-tool.js";import{createTodoWriteTool as mt,createTodoReadTool as dt}from"./todo-tool.js";import{createSubAgentTools as pt}from"./sub-agent-tools.js";import{createAwaitCompleteTool as ht}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as ft}from"./builtins/commandArtifacts.js";import{buildRuntimeEnvironmentPrompt as gt}from"./runtime-environment.js";import{backgroundCommandManager as Z}from"./background-command-manager.js";import{createTerminalTool as yt}from"./terminal-tool.js";import{buildPluginPrompt as Tt,createPluginTools as At}from"./plugin-tools.js";import{buildCapabilityPrompt as Ct}from"./capability-prompt.js";import{loadAcodeCommands as _t}from"./commands/commandLoader.js";import{ACodeCommandRegistry as be}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as bt,COMPACTION_LLM_PROMPT_TEMPLATE as wt,conversationSizeKB as ee,estimateConversationTokens as ne,performCompaction as we,pruneToolOutputs as $t,summarizeConversation as $e}from"./compaction.js";import{loadAcodeConfig as St,loadAcodeSkillGroup as kt}from"./config.js";import{ACodeHookBus as Mt,findDeniedHookResult as me}from"./hooks/hookBus.js";import{isMcpPollingToolName as vt,isMcpBlockingToolName as Rt,getSemanticToolName as Se}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as D}from"./meeting-debug-log.js";import{buildToolCatalog as ke,matchesToolAllocation as Me,mergeAllocatableTools as ie,PRESET_EXPLORE as xt,rebindDefaultAgentId as ve,resolveToolAllocation as Et,SUB_AGENT_ALLOWED_MCP_TOOLS as Nt}from"./tool-allocation.js";function It(s){if(typeof s!="object"||s===null)return!1;const e=s;return e.kind==="builtin"&&typeof e.toolName=="string"&&typeof e.exposedName=="string"&&typeof e.description=="string"&&typeof e.execute=="function"&&typeof e.inputSchema=="object"&&e.inputSchema!==null}function Pt(s){return s.type==="text"?{type:"text",text:s.text}:{type:"image_url",image_url:{url:s.image_url.url}}}function Dt(s){return{id:s.id,type:"function",function:{name:s.function.name,arguments:s.function.arguments}}}function Ot(s){const e={role:s.role,content:Array.isArray(s.content)?s.content.map(Pt):s.content};return s.tool_call_id&&(e.tool_call_id=s.tool_call_id),s.tool_calls&&(e.tool_calls=s.tool_calls.map(Dt)),e}function de(s){return s.map(Ot)}function Lt(s,e){const t=q(s.prompt_cache_hit_tokens),o=q(s.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const n=q(s.cache_read_input_tokens),c=q(s.cache_creation_input_tokens);if(n!==void 0||c!==void 0){const l=q(s.input_tokens)??0;return{cacheHitTokens:n??0,cacheMissTokens:(c??0)+l}}const i=q(s.cache_hit_tokens),a=q(s.cache_miss_tokens);if(i!==void 0||a!==void 0)return{cacheHitTokens:i??0,cacheMissTokens:a??0};const r=q(s.prompt_tokens_details?.cached_tokens);if(r!==void 0){const l=e!==void 0?Math.max(0,e-r):0;return{cacheHitTokens:r,cacheMissTokens:l}}}function q(s){const e=typeof s=="number"?s:typeof s=="string"&&s.trim()?Number(s):NaN;if(!(!Number.isFinite(e)||e<0))return e}function Ut(s,e){if(!s)return e;const t=o=>{const n=e[o],c=s[o];return o==="prompt_tokens_details"?{...c,...n}:n??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 Bt(){return new Date().toISOString()}function v(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function Re(s){return v(s)}function xe(s,e){return e.map(t=>({serverName:s,toolName:t.name,kind:"mcp",exposedName:Eo(s,t.name),description:t.description,inputSchema:Re(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function N(s){return String(s??"").trim()||void 0}const Ee=6e4,Ne=30*6e4,Ie=6e4,Pe=6e4,pe=-1,De=0,qt=1e3,Ft=3e4,re=6e4,Oe=0,zt=2147483647,jt=10*6e4+2e3,Wt=1e4,ae=5e3,Le=10*60*1e3,Y=10*1024*1024,Ue=800*1024,ce=process.env.ACODE_COMPACTION_DEBUG==="1",Be=ce?G.join(Ce.tmpdir(),"acode-compaction-debug.log"):"";function m(...s){ce&&console.log(...s)}const Jt=process.env.ACODE_IMAGE_DIAG==="1",Ht=process.env.ACODE_IMAGE_DIAG_LOG||G.join(Ce.tmpdir(),"acode-image-inject.log");function le(s){if(!Jt)return;const e=`[${new Date().toISOString()}] ${JSON.stringify(s)}
2
- `;B.promises.appendFile(Ht,e).catch(()=>{})}const Kt=process.env.ACODE_TOKEN_DEBUG==="1";function V(...s){Kt&&console.log("[TokenDebug][Runtime]",...s)}const Gt=64e3;function he(s){const e=s.contextLimit&&s.contextLimit>0?s.contextLimit:Gt,t=s.maxOutput&&s.maxOutput>0?s.maxOutput:8192,o=s.inputLimit&&s.inputLimit>0?s.inputLimit:void 0,n=bt(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:n}}async function E(s,e,t,o){if(e<=0)return await s;let n;try{return await new Promise((c,i)=>{n=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),s.then(c,i)})}finally{n&&clearTimeout(n)}}async function te(s,e,t,o=Wt){try{await E(e,o,s)}catch(n){t(n instanceof Error?n.message:String(n))}}function X(s,e){if(s===0||s==="0")return 0;const t=typeof s=="number"?s:Number(s);return t===pe?pe:Number.isFinite(t)&&t>0?Math.floor(t):e}function oe(s,e){const t=X(s,e);return t>0?t:e}const qe=3;function fe(s){return s?Math.ceil(s.length/qe):0}function Qt(s,e){let t=s.length;for(const o of e){const n=(o.kind==="mcp",o.toolName);if(t+=n.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const c=o;c.inputSchema&&(t+=JSON.stringify(c.inputSchema).length)}}return Math.ceil(t/qe)}function Fe(s){if(s.length===0)return 0;const e=JSON.stringify(Qe(s));return fe(e)}async function Yt(s){await new Promise(e=>setTimeout(e,s))}function Vt(s){return typeof s=="boolean"}function Xt(s,e,t){if(Vt(t?.supportsImageInput))return t.supportsImageInput;const o=v(e)?e.models:void 0,n=v(o)?o[s]:void 0;if(!v(n))return!1;const c=n.modalities;return!v(c)||!Array.isArray(c.input)?!1:c.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function ge(s,e,t,o){if(s!==void 0)return s;if(!e)return;const n=e.models;if(v(n)){const c=n[t];if(v(c)){const i=c[o];if(i!==void 0)return i}}return e[o]}function Zt(s,e){const t=e.provider?.default,o=t?.options,n=s.model||t?.model||e.model||"acode-default",c=N(s.effort)||N(o?.effort)||N(t?.effort)||void 0;return{model:n,baseURL:N(o?.baseURL||o?.baseUrl),apiKey:N(o?.apiKey),effort:c,systemPrompt:s.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:oe(o?.requestTimeoutMs??o?.timeoutMs,Ee),requestTotalTimeoutMs:oe(o?.requestTotalTimeoutMs,Ne),requestRetryCount:X(o?.requestRetryCount,De),requestFirstByteTimeoutMs:oe(o?.requestFirstByteTimeoutMs,Ie),requestStreamIdleTimeoutMs:oe(o?.requestStreamIdleTimeoutMs,Pe),mcpToolTimeoutMs:oe(o?.mcpToolTimeoutMs,re),mcpPollingToolTimeoutMs:X(o?.mcpPollingToolTimeoutMs,Oe),supportsImageInput:Xt(n,t,o),contextLimit:X(ge(o?.contextLimit,t,n,"contextLimit"),0)||void 0,inputLimit:X(ge(o?.inputLimit,t,n,"inputLimit"),0)||void 0,maxOutput:X(ge(o?.maxOutput,t,n,"maxOutput"),0)||void 0}}function z(s,e){const t=e.replace(/\s+/g," ").trim();t&&s.push({type:"text",text:t})}function eo(s,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${s||"image/png"};base64,${t}`}function to(s){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(s.trim())}function oo(s){let e;try{e=new URL(s)}catch{throw new Error(`ACode image URL is invalid: ${s}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`ACode image URL protocol is not supported: ${e.protocol}`)}async function so(s){const e=await s.arrayBuffer();if(e.byteLength>Y)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${Y} bytes`);return Buffer.from(e).toString("base64")}async function no(s){const e=s.trim();if(to(e)){if(e.slice(e.indexOf(",")+1).length*.75>Y)throw new Error(`ACode inline image exceeds the ${Y} byte size limit`);return e}oo(e);const t=await fetch(e);if(!t.ok)throw new Error(`ACode image fetch failed: ${t.status} ${await t.text()}`);const o=t.headers.get("content-type")||"",n=o.split(";")[0]?.trim().toLowerCase()||"";if(!n.startsWith("image/"))throw new Error(`ACode image URL did not return an image content type: ${o||"unknown"}`);return`data:${n};base64,${await so(t)}`}function io(s){const e=N(s.base64Data??s.base64??s.data);return e?e.length*.75>Y?void 0:eo(N(s.mediaType??s.mimeType)||"image/png",e):N(s.url??s.serverUrl)}function ze(s,e,t,o){return`[Attached file: ${[s?`name=${s}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(c=>!!c).join(", ")}]`}function ro(s){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,n=0,c=e.exec(s);for(;c!==null;){z(t,s.slice(n,c.index));const i=c[1],a=(c[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="",l="",u="",p=""]=a.split("|").map(g=>g.trim());z(t,ze(r,l,u,p))}else z(t,c[0]);n=c.index+c[0].length,c=e.exec(s)}return t.length===0?{content:s,hasImages:!1}:(z(t,s.slice(n)),{content:t,hasImages:o})}function ao(s,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const n of o)if(Array.isArray(n))for(const c of n){if(!v(c))continue;const i=N(c.content);if(!i)continue;const a=N(c.senderName);z(s,a?`Message from ${a}:`:"Message:");const r=ye(i);Array.isArray(r.content)?s.push(...r.content):z(s,r.content),t=t||r.hasImages}return t}function co(s){for(const e of["directMessages","groupMessages","messages"]){const t=s[e];if(Array.isArray(t))for(const o of t){if(!v(o))continue;const n=o.content;typeof n!="string"||!n.trim()||(o.content=lo(n))}}}function lo(s){let e;try{e=JSON.parse(s)}catch{return s.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim()||s}if(v(e)&&"attachments"in e){const t={...e};return t.attachments=[],JSON.stringify(t)}return s}function uo(s){let e;try{e=JSON.parse(s)}catch{return}if(!v(e))return;const t=[];let o=ao(t,e);const n=N(e.text)||"",c=Array.isArray(e.attachments)?e.attachments:[];z(t,n);for(const i of c){if(!v(i))continue;const a=i;if(String(a.type??a.kind??"").toLowerCase()==="image"){const u=io(a);u?(t.push({type:"image_url",image_url:{url:u}}),o=!0):N(a.base64Data??a.base64??a.data)&&z(t,`[Image attachment omitted: ${N(a.name)||"unnamed"} exceeds the ${Y} byte inline limit]`);continue}const l=N(a.url??a.serverUrl)||"";z(t,ze(N(a.name)||"",l,N(a.mediaType??a.mimeType)||"",N(a.size)||""))}return t.length===0?{content:s,hasImages:!1}:{content:t,hasImages:o}}function ye(s){return uo(s)??ro(s)}async function je(s){if(!Array.isArray(s))return s;const e=[];for(const t of s){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await no(t.image_url.url)}})}return e}function mo(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function po(s,e){const t=s.permissions??e.permissions??{},o=s.permissions?[]:e.allowedTools??[],n=s.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(c=>c.trim()).filter(Boolean),deny:[...t.deny??[],...n].map(c=>c.trim()).filter(Boolean)}}function ho(s,e){return s==="*"?!0:s.endsWith("*")?e.startsWith(s.slice(0,-1)):s===e}function fo(s){return s.kind==="builtin"?[s.exposedName,s.toolName,`builtin.${s.toolName}`]:[s.exposedName,s.toolName,`${s.serverName}.${s.toolName}`,`mcp.${s.serverName}.${s.toolName}`]}function We(s,e){return fo(e).some(t=>ho(s,t))}function Je(s,e,t){if(e.length>0&&!e.some(o=>We(o,s)))throw new Error(t)}function Te(s,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>We(o,s)))throw new Error(`ACode tool denied by permission rule: ${s.exposedName}`);Je(s,e.allow,`ACode tool is not in allowed permission rules: ${s.exposedName}`),Je(s,t??[],`ACode slash command does not allow tool: ${s.exposedName}`)}}function go(s,e,t){try{return Te(s,e,t),!0}catch{return!1}}function ue(s){const e=s.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function yo(s){try{const e=new URL(s);e.search="",e.hash="";const t=new URL(ue(e.toString()));return`${t.origin}${t.pathname}`}catch{return ue(s).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function To(s){const e=[...s].reverse().find(o=>o.role==="user"),t=mo(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function He(s){try{const e=JSON.parse(s);return Re(e)?e:{}}catch{return{}}}function Ao(s,e,t){if(new Set([ct,"await_complete"]).has(s.toolName))return 0;if(s.toolName!=="Bash")return t;const n=e.timeout_ms??e.timeoutMs,c=typeof n=="number"?n:typeof n=="string"?Number(n):NaN;return!Number.isFinite(c)||c<=0?Math.max(t,jt):Math.min(Math.floor(c),10*6e4)+2e3}function Co(s,e){const t=s.trim();return`ACode \u5DF2\u63A5\u6536\u4EFB\u52A1\u3002\u5F53\u524D\u5DF2\u52A0\u8F7D ${e.configMcpCount} \u4E2A MCP \u914D\u7F6E\u3001${e.exposedTools.length} \u4E2A MCP Tool \u4E0E ${e.skills.length} \u4E2A Skill\u3002${t?`\u8F93\u5165\u6458\u8981\uFF1A${t.slice(0,200)}`:""}`}function U(s){if(!v(s))return String(s??"");const e=s.content;if(Array.isArray(e)){const t=e.map(o=>v(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
3
- `)}return JSON.stringify(s)}function se(s){return s instanceof Error?s.message:String(s)}function _o(s){let e=16;if(typeof s.content=="string")e+=s.content.length*2;else if(Array.isArray(s.content))for(const t of s.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return s.tool_calls&&(e+=JSON.stringify(s.tool_calls).length),s.tool_call_id&&(e+=s.tool_call_id.length),e}async function bo(s,e,t,o,n){let c=0;for(const a of s)c+=_o(a);if(c<=e)return 0;const i=await we(s,t,o,{llmSummarizer:n});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:$e(s,{llmSummarizer:n,contextLimit:t})}function Ke(s){const e=se(s).toLowerCase();return e.includes("context_length_exceeded")||e.includes("context length")||e.includes("maximum context")||e.includes("max context")||e.includes("token limit")||e.includes("tokens exceed")||e.includes("too many tokens")||e.includes("input is too long")||e.includes("prompt is too long")||e.includes("request too large")||e.includes("413")}function wo(s){const e=se(s).toLowerCase();return Ke(s)?!1:e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||/\b(408|429|500|502|503|504|520|521|522|523|524)\b/.test(e)}function $o(s){if(typeof s!="object"||s===null)return!1;const e=Reflect.get(s,"code"),t=se(s).toLowerCase();return e===-32001||t.includes("request timed out")}function So(s){if(typeof s=="object"&&s!==null){const e=Reflect.get(s,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(s,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function ko(s,e){return JSON.stringify({ok:!1,tool:s.exposedName,error:{type:So(e),message:se(e)}})}function Ge(s){const e=JSON.stringify(s);return e.length>500?`${e.slice(0,500)}\u2026`:e}function Mo(s){const e=[s?.reasoning_content,s?.reasoning_text,s?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(v(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function vo(s){return s.length===0?"":["Skills are available for this session.","Use the `skill` tool to load specialized skill instructions when a user task matches one of the available skills listed in the tool description.","Do not attempt to follow skill instructions from memory \u2014 always invoke the `skill` tool first to load the full content."].join(" ")}function Ro(s){return s.length===0?"":["Available slash commands:",...s.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
4
- `)}function xo(s){if(!s||typeof s!="object")return"";const e=s,t=[],o=e.displayName,n=e.roleName,c=e.instanceName,i=e.projectId,a=e.workspacePath,r=e.runtimeMode,l=e.describe;return typeof o=="string"&&o.trim()&&t.push(`Display Name: ${o.trim()}`),typeof n=="string"&&n.trim()&&t.push(`Role: ${n.trim()}`),typeof c=="string"&&c.trim()&&t.push(`Instance: ${c.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 l=="string"&&l.trim()&&t.push(`Description: ${l.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
5
- `)}function Qe(s){return s.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function Eo(s,e){return`${s}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function No(s){const e={"Content-Type":"application/json"};return s.apiKey&&(e.Authorization=`Bearer ${s.apiKey}`),e}function Io(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,Po(e)?Do(t):t]))}function Po(s){const e=s.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function Do(s){return s.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function Oo(s){return s.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function Ye(s){if(!v(s))return null;const e=s.error;if(v(e)){const t=typeof e.message=="string"?e.message:"",o=e.code??e.status??e.type,n=o==null?"":String(o);return t||n?[n,t].filter(Boolean).join(" "):null}if(typeof e=="string"&&e)return e;if(s.type==="error"||s.object==="error"){const t=typeof s.message=="string"?s.message:"",o=s.code??s.status,n=o==null?"":String(o);if(t||n)return[n,t].filter(Boolean).join(" ")}return null}function Lo(s,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=s.get(t)??{id:e.id||`call-${t}`,type:"function",function:{name:"",arguments:""}};e.id&&(o.id=e.id),e.function?.name&&(o.function.name+=e.function.name),e.function?.arguments&&(o.function.arguments+=e.function.arguments),s.set(t,o)}function Uo(s){return[...s.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}function Bo(){const s=process.env.ACODE_ABORT_FORCE_SETTLE_GRACE_MS;if(s===void 0||s.trim()==="")return 6e4;const e=Number(s.trim());return Number.isFinite(e)&&e>=0?Math.floor(e):6e4}class J extends et{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:Ee,requestTotalTimeoutMs:Ne,requestRetryCount:De,requestFirstByteTimeoutMs:Ie,requestStreamIdleTimeoutMs:Pe,mcpToolTimeoutMs:re,mcpPollingToolTimeoutMs:Oe,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new be([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:{..._e}},this.abortController=null,this.exposedToolsInitialized=!1,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.submitQueue=Promise.resolve(),this.activeTurnToken=null,this.forceSettleWaiters=new Map,this.abortForceSettleTimer=null,this.activeTurn=!1,this.forceMessagePending=!1,this.abortRequested=!1,this.toolSettleSlot=null,this.toolSettleSeq=0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.permissionWaiters=new Map,this.recoveredToolNames=new Set,this.hookBus=new Mt({sessionId:e.sessionId,onError:(t,o)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${t.name}: ${o instanceof Error?o.message:String(o)}`})}});for(const t of e.hooks??[])this.hookBus.register(t);e.toolPermissionPolicy&&(this.state.toolPermissionPolicy={..._e,...e.toolPermissionPolicy})}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:Bt(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,n){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:n})}handleCompactionPhase(e,t){switch(t.phase){case"prune_start":this.emitCompactionPhase(e,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u6B63\u5728\u88C1\u526A ${t.messageCount??0} \u6761\u6D88\u606F\u4E2D\u7684\u5DE5\u5177\u8F93\u51FA...`);break;case"prune_end":this.emitCompactionPhase(e,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${t.prunedCount??0} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${t.freedTokens??0} tokens`);break;case"summarize_start":this.emitCompactionPhase(e,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6B63\u5728\u6458\u8981 ${t.messageCount??0} \u6761\u65E9\u671F\u5BF9\u8BDD...`);break;case"summarize_end":this.emitCompactionPhase(e,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${t.summarizedCount??0} \u6761\u6D88\u606F${t.usedLLM?" (LLM \u6458\u8981)":" (\u89C4\u5219\u6458\u8981)"}`);break}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await St(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:n}=await this.loadAllSkills(),c=Zt(this.config,e);m(`[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 i=po(this.config,e),a=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},c.mcpToolTimeoutMs),r=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const l=await this.fetchProfilePrompt(a),u=this.config.agentId||"unknown";ft(u),Z.reconcileOrphans(u);const p=at(this.config.workingDirectory,u,this.config.onFileChange,{manager:Z,emitCompleted:f=>{this.emitAcodeEvent("background_command_completed",f)}},this.createToolPermissionController()),g=lt(this.buildAskUserQuestionDeps(),()=>this.contextVersion),_=ut(t);this.skillTool=_;const h=mt(u),T=dt(u),b=this.config.subAgentManager?pt(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],d=ht(this.buildAwaitCompleteDeps()),w=this.config.terminalManager?yt(u,{terminalManager:this.config.terminalManager}):null,M=At({pluginBridge:this.config.pluginBridge}),C=[...p,g,_,h,T,...b,d,...w?[w]:[],...M,...a.flatMap(f=>f.tools),...ve(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const f=ve(this.config.subAgentSuiteTools??[],this.config.agentId??""),W=ie(C,f);C.length=0,C.push(...W)}let $=C;const S=this.config.subAgentAllowedTools;S&&S.length>0&&($=$.filter(f=>Me(f,S)));const R=this.resolveCommandDirs(e);let y=[...R,...this.discoverPluginCommandDirs()];if(this.config.pluginBridge?.getCommandDirs)try{const f=await this.config.pluginBridge.getCommandDirs();f.length>0&&(y=[...y,...f])}catch(f){m(`[ACodeRuntime] \u63D2\u4EF6\u547D\u4EE4\u76EE\u5F55\u83B7\u53D6\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${f instanceof Error?f.message:String(f)}`)}y=[...new Set(y)],this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const A=await _t(y),x=new be(A),I=vo(t),k=Ro(A),O=this.config.pluginBridge?Tt():void 0,j=Ct(this.config.capabilityState??(()=>"disabled")),H=[c.systemPrompt,I,k,O,j].map(f=>f?.trim()).filter(f=>!!f).join(`
1
+ import{EventEmitter as ot}from"node:events";import{randomUUID as st}from"node:crypto";import D from"node:fs";import _e from"node:os";import z from"node:path";import{Client as nt}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as it}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as rt}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as at}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as lt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as ct,DEFAULT_TOOL_PERMISSION_POLICY as be}from"./built-in-file-tools.js";import{ReadFileStateTracker as ut}from"./read-file-state.js";import{ASK_USER_QUESTION_TOOL_NAME as mt,createAskUserQuestionTool as dt}from"./ask-user-question-tool.js";import{createSkillTool as pt}from"./skill-tool.js";import{createTodoWriteTool as ht,createTodoReadTool as ft}from"./todo-tool.js";import{createSubAgentTools as gt}from"./sub-agent-tools.js";import{createAwaitCompleteTool as Tt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as yt}from"./builtins/commandArtifacts.js";import{buildRuntimeEnvironmentPrompt as Ct}from"./runtime-environment.js";import{backgroundCommandManager as Y}from"./background-command-manager.js";import{createTerminalTool as At}from"./terminal-tool.js";import{ToolGroupManager as _t,createExpandToolsTool as bt,createCallToolTool as wt}from"./tool-group-manager.js";import{loadAcodeCommands as kt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as we}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as St,COMPACTION_LLM_PROMPT_TEMPLATE as $t,conversationSizeKB as V,estimateConversationTokens as se,performCompaction as ke,pruneToolOutputs as Mt,summarizeConversation as Se}from"./compaction.js";import{isContextOverflowError as pe,resolveFinishReasonOverflow as vt}from"./context-overflow.js";import{loadAcodeConfig as xt,loadAcodeSkillGroup as Et}from"./config.js";import{ACodeHookBus as Rt,findDeniedHookResult as $e}from"./hooks/hookBus.js";import{isMcpPollingToolName as It,isMcpBlockingToolName as Me,getSemanticToolName as ve}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as P}from"./meeting-debug-log.js";import{buildToolCatalog as xe,matchesToolAllocation as Ee,mergeAllocatableTools as ne,PRESET_EXPLORE as Nt,rebindDefaultAgentId as Re,resolveToolAllocation as Pt,SUB_AGENT_ALLOWED_MCP_TOOLS as Ot}from"./tool-allocation.js";import{ConcurrencyLimiter as Ie,getSharedResourceLock as Dt,ToolConcurrencyScheduler as Lt,ToolTraceRecorder as Ne}from"./tool-concurrency/index.js";function Ut(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 Bt(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function qt(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function Ft(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(Bt):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(qt)),e}function he(n){return n.map(Ft)}function zt(n,e){const t=L(n.prompt_cache_hit_tokens),o=L(n.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const s=L(n.cache_read_input_tokens),i=L(n.cache_creation_input_tokens);if(s!==void 0||i!==void 0){const c=L(n.input_tokens)??0;return{cacheHitTokens:s??0,cacheMissTokens:(i??0)+c}}const a=L(n.cache_hit_tokens),r=L(n.cache_miss_tokens);if(a!==void 0||r!==void 0)return{cacheHitTokens:a??0,cacheMissTokens:r??0};const l=L(n.prompt_tokens_details?.cached_tokens);if(l!==void 0){const c=e!==void 0?Math.max(0,e-l):0;return{cacheHitTokens:l,cacheMissTokens:c}}}function L(n){const e=typeof n=="number"?n:typeof n=="string"&&n.trim()?Number(n):NaN;if(!(!Number.isFinite(e)||e<0))return e}function jt(n,e){if(!n)return e;const t=o=>{const s=e[o],i=n[o];return o==="prompt_tokens_details"?{...i,...s}:s??i};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 Wt(){return new Date().toISOString()}function $(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function Pe(n){return $(n)}function Oe(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:Fo(n,t.name),description:t.description,inputSchema:Pe(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function I(n){return String(n??"").trim()||void 0}const De=6e4,Le=30*6e4,Ue=6e4,Be=6e4,fe=-1,qe=0,Jt=1e3,Gt=3e4,ie=6e4,Fe=0,Kt=2147483647,Ht=8,Qt=10*6e4+2e3,Yt=1e4,re=5e3,ze=10*60*1e3,W=10*1024*1024,je=800*1024,ae=process.env.ACODE_COMPACTION_DEBUG==="1",We=ae?z.join(_e.tmpdir(),"acode-compaction-debug.log"):"";function d(...n){ae&&console.log(...n)}const Vt=process.env.ACODE_IMAGE_DIAG==="1",Xt=process.env.ACODE_IMAGE_DIAG_LOG||z.join(_e.tmpdir(),"acode-image-inject.log");function le(n){if(!Vt)return;const e=`[${new Date().toISOString()}] ${JSON.stringify(n)}
2
+ `;D.promises.appendFile(Xt,e).catch(()=>{})}const Zt=process.env.ACODE_TOKEN_DEBUG==="1";function J(...n){Zt&&console.log("[TokenDebug][Runtime]",...n)}const eo=64e3;function ge(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:eo,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=St(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((i,a)=>{s=setTimeout(()=>{o?.(),a(new Error(`${t} timed out after ${e}ms`))},e),n.then(i,a)})}finally{s&&clearTimeout(s)}}async function X(n,e,t,o=Yt){try{await E(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function G(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===fe?fe:Number.isFinite(t)&&t>0?Math.floor(t):e}function Z(n,e){const t=G(n,e);return t>0?t:e}const Je=3;function Te(n){return n?Math.ceil(n.length/Je):0}function to(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 i=o;i.inputSchema&&(t+=JSON.stringify(i.inputSchema).length)}}return Math.ceil(t/Je)}function Ge(n){if(n.length===0)return 0;const e=JSON.stringify(Xe(n));return Te(e)}async function oo(n){await new Promise(e=>setTimeout(e,n))}function so(n){return typeof n=="boolean"}function no(n,e,t){if(so(t?.supportsImageInput))return t.supportsImageInput;const o=$(e)?e.models:void 0,s=$(o)?o[n]:void 0;if(!$(s))return!1;const i=s.modalities;return!$(i)||!Array.isArray(i.input)?!1:i.input.some(a=>String(a||"").trim().toLowerCase()==="image")}function ye(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if($(s)){const i=s[t];if($(i)){const a=i[o];if(a!==void 0)return a}}return e[o]}function io(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",i=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:i,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:Z(o?.requestTimeoutMs??o?.timeoutMs,De),requestTotalTimeoutMs:Z(o?.requestTotalTimeoutMs,Le),requestRetryCount:G(o?.requestRetryCount,qe),requestFirstByteTimeoutMs:Z(o?.requestFirstByteTimeoutMs,Ue),requestStreamIdleTimeoutMs:Z(o?.requestStreamIdleTimeoutMs,Be),mcpToolTimeoutMs:Z(o?.mcpToolTimeoutMs,ie),mcpPollingToolTimeoutMs:G(o?.mcpPollingToolTimeoutMs,Fe),supportsImageInput:no(s,t,o),contextLimit:G(ye(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:G(ye(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:G(ye(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function U(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function ro(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function ao(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function lo(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 co(n){const e=await n.arrayBuffer();if(e.byteLength>W)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${W} bytes`);return Buffer.from(e).toString("base64")}async function uo(n){const e=n.trim();if(ao(e)){if(e.slice(e.indexOf(",")+1).length*.75>W)throw new Error(`ACode inline image exceeds the ${W} byte size limit`);return e}lo(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 co(t)}`}function mo(n){const e=I(n.base64Data??n.base64??n.data);return e?e.length*.75>W?void 0:ro(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function Ke(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(i=>!!i).join(", ")}]`}function po(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,i=e.exec(n);for(;i!==null;){U(t,n.slice(s,i.index));const a=i[1],r=(i[2]||"").trim();if(a==="\u56FE\u7247"&&r)t.push({type:"image_url",image_url:{url:r}}),o=!0;else if(a==="\u6587\u4EF6"&&r){const[l="",c="",u="",m=""]=r.split("|").map(h=>h.trim());U(t,Ke(l,c,u,m))}else U(t,i[0]);s=i.index+i[0].length,i=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(U(t,n.slice(s)),{content:t,hasImages:o})}function ho(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const i of s){if(!$(i))continue;const a=I(i.content);if(!a)continue;const r=I(i.senderName);U(n,r?`Message from ${r}:`:"Message:");const l=Ce(a);Array.isArray(l.content)?n.push(...l.content):U(n,l.content),t=t||l.hasImages}return t}function fo(n){for(const e of["directMessages","groupMessages","messages"]){const t=n[e];if(Array.isArray(t))for(const o of t){if(!$(o))continue;const s=o.content;typeof s!="string"||!s.trim()||(o.content=go(s))}}}function go(n){let e;try{e=JSON.parse(n)}catch{return n.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim()||n}if($(e)&&"attachments"in e){const t={...e};return t.attachments=[],JSON.stringify(t)}return n}function To(n){let e;try{e=JSON.parse(n)}catch{return}if(!$(e))return;const t=[];let o=ho(t,e);const s=I(e.text)||"",i=Array.isArray(e.attachments)?e.attachments:[];U(t,s);for(const a of i){if(!$(a))continue;const r=a;if(String(r.type??r.kind??"").toLowerCase()==="image"){const u=mo(r);u?(t.push({type:"image_url",image_url:{url:u}}),o=!0):I(r.base64Data??r.base64??r.data)&&U(t,`[Image attachment omitted: ${I(r.name)||"unnamed"} exceeds the ${W} byte inline limit]`);continue}const c=I(r.url??r.serverUrl)||"";U(t,Ke(I(r.name)||"",c,I(r.mediaType??r.mimeType)||"",I(r.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function Ce(n){return To(n)??po(n)}async function He(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 uo(t.image_url.url)}})}return e}function yo(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function Co(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(i=>i.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(i=>i.trim()).filter(Boolean)}}function Ao(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function _o(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 Qe(n,e){return _o(e).some(t=>Ao(n,t))}function Ye(n,e,t){if(e.length>0&&!e.some(o=>Qe(o,n)))throw new Error(t)}function Ve(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>Qe(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);Ye(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),Ye(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function bo(n,e,t){try{return Ve(n,e,t),!0}catch{return!1}}function ce(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function wo(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(ce(e.toString()));return`${t.origin}${t.pathname}`}catch{return ce(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function ko(n){const e=[...n].reverse().find(o=>o.role==="user"),t=yo(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function So(n){try{const e=JSON.parse(n);return Pe(e)?e:{}}catch{return{}}}function $o(n,e,t){if(new Set([mt,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,i=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(i)||i<=0?Math.max(t,Qt):Math.min(Math.floor(i),10*6e4)+2e3}function Mo(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 B(n){if(!$(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>$(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
3
+ `)}return JSON.stringify(n)}function ue(n){return n instanceof Error?n.message:String(n)}function vo(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}function xo(n){const e={orphanToolMessages:0,repairedToolCalls:0,downgradedAssistants:0};if(n.length===0)return e;const t=new Set;for(const a of n)if(a.role==="assistant"&&Array.isArray(a.tool_calls))for(const r of a.tool_calls)r&&typeof r.id=="string"&&r.id&&t.add(r.id);for(const a of n)if(a.role==="tool"&&a.tool_call_id&&!t.has(a.tool_call_id)){const r=typeof a.content=="string"?a.content:JSON.stringify(a.content??""),l=a.tool_call_id;a.role="user",delete a.tool_call_id,a.content=`[\u7CFB\u7EDF\u63D0\u793A] \u4EE5\u4E0B\u4E3A\u4E00\u6B21\u5DE5\u5177\u6267\u884C\u7684\u7ED3\u679C\uFF08tool_call_id=${l}\uFF09\uFF0C\u5176\u5BF9\u5E94\u7684\u5DE5\u5177\u8C03\u7528\u4E0A\u4E0B\u6587\u5DF2\u4E0D\u5728\u4F1A\u8BDD\u4E2D\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF1A
4
+ ${r}`,e.orphanToolMessages+=1}const o=()=>{const a=new Set;for(const r of n)r.role==="tool"&&r.tool_call_id&&a.add(r.tool_call_id);return a};let s=o();const i="\uFF08\u8BE5\u5DE5\u5177\u8C03\u7528\u7ED3\u679C\u7F3A\u5931\uFF1A\u6240\u5C5E\u8F6E\u6B21\u88AB\u4E2D\u65AD\u6216\u4E0A\u4E0B\u6587\u538B\u7F29\u65F6\u5DF2\u79FB\u9664\uFF0C\u8BF7\u52FF\u57FA\u4E8E\u8BE5\u8C03\u7528\u7EE7\u7EED\u63A8\u65AD\uFF0C\u5FC5\u8981\u65F6\u91CD\u65B0\u8C03\u7528\u5DE5\u5177\u3002\uFF09";for(let a=0;a<n.length;a++){const r=n[a];if(r.role!=="assistant"||!Array.isArray(r.tool_calls))continue;const l=r.tool_calls.map(m=>m?.id).filter(m=>typeof m=="string"&&m.length>0&&!s.has(m));if(l.length===0)continue;let c=-1;for(let m=a+1;m<n.length;m++){if(n[m].role==="tool"){c=m+1;continue}break}if(c>a){const m=l.map(h=>({role:"tool",tool_call_id:h,content:i}));n.splice(c,0,...m),a+=m.length,e.repairedToolCalls+=l.length,s=o();continue}if(a===n.length-1){for(const m of l)n.push({role:"tool",tool_call_id:m,content:i});e.repairedToolCalls+=l.length,s=o();continue}const u=new Set(r.tool_calls.map(m=>m?.id).filter(m=>typeof m=="string"&&m.length>0));delete r.tool_calls,(r.content===null||r.content===void 0)&&(r.content="");for(const m of n)if(m.role==="tool"&&m.tool_call_id&&u.has(m.tool_call_id)){const h=typeof m.content=="string"?m.content:JSON.stringify(m.content??""),A=m.tool_call_id;m.role="user",delete m.tool_call_id,m.content=`[\u7CFB\u7EDF\u63D0\u793A] \u4EE5\u4E0B\u4E3A\u4E00\u6B21\u5DE5\u5177\u6267\u884C\u7684\u7ED3\u679C\uFF08tool_call_id=${A}\uFF09\uFF0C\u5176\u5BF9\u5E94\u7684\u5DE5\u5177\u8C03\u7528\u4E0A\u4E0B\u6587\u5DF2\u4E0D\u5728\u4F1A\u8BDD\u4E2D\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF1A
5
+ ${h}`,e.orphanToolMessages+=1}s=o(),e.downgradedAssistants+=1}return e}async function Eo(n,e,t,o,s){let i=0;for(const r of n)i+=vo(r);if(i<=e)return 0;const a=await ke(n,t,o,{llmSummarizer:s});return a.strategy!=="none"?a.prunedToolMessages+a.summarizedMessages:Se(n,{llmSummarizer:s,contextLimit:t})}function Ro(n){return pe(n)}function Io(n){const e=ue(n).toLowerCase();return Ro(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 No(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=ue(n).toLowerCase();return e===-32001||t.includes("request timed out")}function Po(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 Oo(n,e){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:Po(e),message:ue(e)}})}function Do(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function Lo(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if($(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function Uo(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 Bo(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(`
6
+ `)}function qo(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,i=e.instanceName,a=e.projectId,r=e.workspacePath,l=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 i=="string"&&i.trim()&&t.push(`Instance: ${i.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Project: ${a.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Workspace: ${r.trim()}`),typeof l=="string"&&l.trim()&&t.push(`Runtime Mode: ${l.trim()}`),typeof c=="string"&&c.trim()&&t.push(`Description: ${c.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
7
+ `)}function Xe(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function Fo(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function zo(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function jo(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Wo(e)?Jo(t):t]))}function Wo(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function Jo(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function Go(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function Ze(n){if(!$(n))return null;const e=n.error;if($(e)){const t=typeof e.message=="string"?e.message:"",o=e.code??e.status??e.type,s=o==null?"":String(o);return t||s?[s,t].filter(Boolean).join(" "):null}if(typeof e=="string"&&e)return e;if(n.type==="error"||n.object==="error"){const t=typeof n.message=="string"?n.message:"",o=n.code??n.status,s=o==null?"":String(o);if(t||s)return[s,t].filter(Boolean).join(" ")}return null}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 Ho(n){return[...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}function Qo(){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 K extends ot{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:De,requestTotalTimeoutMs:Le,requestRetryCount:qe,requestFirstByteTimeoutMs:Ue,requestStreamIdleTimeoutMs:Be,mcpToolTimeoutMs:ie,mcpPollingToolTimeoutMs:Fe,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new we([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,skipNextCompaction:!1,toolPermissionPolicy:{...be}},this.abortController=null,this.exposedToolsInitialized=!1,this.recoveredToolNames=new Set,this.readFileStateTracker=new ut,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.toolGroupManager=null,this.submitQueue=Promise.resolve(),this.activeTurnToken=null,this.forceSettleWaiters=new Map,this.abortForceSettleTimer=null,this.activeTurn=!1,this.forceMessagePending=!1,this.turnPromptPushed=!1,this.turnSkipProactiveCompaction=!1,this.abortRequested=!1,this.toolSettleSlots=new Map,this.toolSettleSeq=0,this.toolResourceLock=Dt(),this.toolConcurrencyScheduler=new Lt,this.toolReadOnlyLimiter=null,this.toolBashLimiter=null,this.toolConcurrencyEnabled=!0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.permissionWaiters=new Map,this.hookBus=new Rt({sessionId:e.sessionId,onError:(i,a)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${i.name}: ${a instanceof Error?a.message:String(a)}`})}});for(const i of e.hooks??[])this.hookBus.register(i);e.toolPermissionPolicy&&(this.state.toolPermissionPolicy={...be,...e.toolPermissionPolicy});const t=e.toolConcurrency;this.toolConcurrencyEnabled=t?.enabled!==!1;const o=t?.maxReadOnly??8;this.toolReadOnlyLimiter=new Ie(o);const s=t?.maxBash??0;this.toolBashLimiter=s>0?new Ie(s):null}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:Wt(),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 xt(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),i=io(this.config,e);d(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${i.model}, baseURL=${i.baseURL??"(none)"}, apiKey=${i.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const a=Co(this.config,e),r=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},i.mcpToolTimeoutMs),l=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const c=await this.fetchProfilePrompt(r),u=this.config.agentId||"unknown";yt(u),Y.reconcileOrphans(u);const m=ct(this.config.workingDirectory,u,this.config.onFileChange,{manager:Y,emitCompleted:g=>{this.emitAcodeEvent("background_command_completed",g)}},this.createToolPermissionController(),{tracker:this.readFileStateTracker,enabled:this.config.enableStaleFileGuard!==!1}),h=dt(this.buildAskUserQuestionDeps(),()=>this.contextVersion),A=pt(t);this.skillTool=A;const f=ht(u),p=ft(u),k=this.config.subAgentManager?gt(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],T=Tt(this.buildAwaitCompleteDeps()),y=this.config.terminalManager?At(u,{terminalManager:this.config.terminalManager}):null,_=new _t({stateOf:this.config.capabilityState??(()=>"disabled")});_.register({key:"pencil",label:"\u8BBE\u8BA1\u753B\u5E03(pencil)",summary:"UI design editor",collapsible:!0}),_.register({key:"draw",label:"\u7ED8\u56FE",summary:"\u7ED8\u5236 draw.io \u6D41\u7A0B\u56FE/\u6CF3\u9053\u56FE",collapsible:!0}),_.register({key:"office",label:"Office \u6587\u4EF6",summary:"\u521B\u5EFA/\u7F16\u8F91 Word/PPT/Excel",collapsible:!0}),_.register({key:"launch",label:"\u542F\u52A8\u9879\u7BA1\u7406",summary:"\u7BA1\u7406\u5F00\u53D1\u670D\u52A1\u8FDB\u7A0B",collapsible:!0}),_.register({key:"hire",label:"\u62DB\u8058\u5DE5\u5177",summary:"\u62DB\u8058\u65B0\u7684\u540C\u4E8B Agent",collapsible:!0}),_.register({key:"browser",label:"\u6D4F\u89C8\u5668\u64CD\u4F5C",summary:"\u542F\u52A8\u6D4F\u89C8\u5668\u4F1A\u8BDD\u3001\u5BFC\u822A\u3001\u622A\u56FE\u4E0E\u9875\u9762\u4EA4\u4E92",collapsible:!0}),_.register({key:"desktop",label:"\u684C\u9762\u64CD\u4F5C",summary:"\u622A\u5C4F\u3001\u9F20\u6807\u952E\u76D8\u63A7\u5236\u4E0E UI \u81EA\u52A8\u5316",collapsible:!1}),_.register({key:"task",label:"\u6D41\u7A0B\u4EFB\u52A1",summary:"\u5904\u7406\u6D41\u7A0B\u7EBF\u4EFB\u52A1\uFF1A\u67E5\u770B\u5F53\u524D\u4EFB\u52A1\u3001\u63D0\u4EA4\u6267\u884C\u7ED3\u679C\u3001\u62D2\u7EDD/\u7EC8\u6B62/\u56DE\u9000\u4EFB\u52A1\u3001\u7ED9\u6D41\u7A0B\u5B9E\u4F8B\u7559\u8A00",collapsible:!0,toolNames:["my_task","submit_task_result","reject_task","terminate_task","start_task_rollback","finish_task_rollback","create_task_instance_comment"]}),_.register({key:"meeting",label:"\u4F1A\u8BAE",summary:"\u521B\u5EFA/\u52A0\u5165\u4F1A\u8BAE\u3001\u53D1\u8A00\u3001\u67E5\u770B\u4F1A\u8BAE\u4FE1\u606F\u3001\u79BB\u5F00/\u7ED3\u675F\u4F1A\u8BAE",collapsible:!0,toolNames:["create_meeting","leave_meeting","end_meeting","meeting_speak","get_meeting_info","my_meetings"]}),_.register({key:"debug",label:"\u8C03\u8BD5\u65E5\u5FD7",summary:"\u6309\u6761\u4EF6\u5206\u9875\u67E5\u8BE2 Debug \u65E5\u5FD7\u4E0E\u83B7\u53D6\u65E5\u5FD7\u4E0A\u62A5\u914D\u7F6E",collapsible:!0,toolNames:["get_debug_log_config","query_debug_logs"]}),_.register({key:"fileHistory",label:"\u6587\u4EF6\u53D8\u66F4\u5386\u53F2",summary:"\u6309\u89D2\u8272/\u5B9E\u4F8B/\u6587\u4EF6\u8DEF\u5F84\u8FC7\u6EE4\u67E5\u8BE2\u6587\u4EF6\u53D8\u66F4\u5386\u53F2",collapsible:!0,toolNames:["query_file_changes_history"]}),this.toolGroupManager=_;const R=bt({toolGroupManager:_,getAllTools:()=>this.state.exposedTools,capabilityToolRelay:this.config.capabilityToolRelay}),x=wt({toolGroupManager:_,pluginBridge:this.config.pluginBridge,capabilityToolRelay:this.config.capabilityToolRelay,findTool:g=>{const O=this.state.exposedTools.find(Ae=>Ae.exposedName===g||Ae.toolName===g);if(!O)return;const de=_.getGroupForExposedName(O.exposedName);return{kind:O.kind,group:de,toolName:O.toolName}},dispatchTool:(g,O,de)=>this.executeSingleToolByName(g,O,de)}),S=[...m,h,A,f,p,...k,T,...y?[y]:[],R,x,...r.flatMap(g=>g.tools),...Re(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const g=Re(this.config.subAgentSuiteTools??[],this.config.agentId??""),O=ne(S,g);S.length=0,S.push(...O)}let C=S;const b=this.config.subAgentAllowedTools;b&&b.length>0&&(C=C.filter(g=>Ee(g,b)));const M=this.resolveCommandDirs(e);let v=[...M,...this.discoverPluginCommandDirs()];if(this.config.pluginBridge?.getCommandDirs)try{const g=await this.config.pluginBridge.getCommandDirs();g.length>0&&(v=[...v,...g])}catch(g){d(`[ACodeRuntime] \u63D2\u4EF6\u547D\u4EE4\u76EE\u5F55\u83B7\u53D6\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${g instanceof Error?g.message:String(g)}`)}v=[...new Set(v)],this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const w=await kt(v),q=new we(w),N=Uo(t),H=Bo(w),F=_.buildCapabilityPrompt(),ee=this.config.pluginBridge?["","## \u63D2\u4EF6\u7CFB\u7EDF","\u63D2\u4EF6\u5DE5\u5177\u4E0D\u5728\u4F60\u7684\u9759\u6001\u5DE5\u5177\u5217\u8868\u4E2D\uFF1A\u7D27\u51D1\u76EE\u5F55\u968F poll_message \u7ED3\u679C\u7684 pluginCatalog \u5B57\u6BB5\u8FD4\u56DE\uFF1B",'\u7528 call_tool \u8C03\u7528\uFF08action="catalog" \u53D6\u76EE\u5F55\uFF0Caction="schema" \u53D6\u5B9A\u4E49\uFF0C','\u6216 action="call"\uFF08\u9ED8\u8BA4\uFF09+ name="\u63D2\u4EF6\u540D.\u5DE5\u5177\u540D" + arguments={...} \u8C03\u7528\uFF09\u3002',"\u63D2\u4EF6\u4E8B\u4EF6\u5C3E\u90E8\u6709 toolHints\uFF08\u5EFA\u8BAE\u8C03\u7528\u7684\u5DE5\u5177\uFF09\uFF0C\u6309\u63D0\u793A\u7528 call_tool \u5904\u7406\u3002","\u63D2\u4EF6\u751F\u547D\u5468\u671F\uFF08\u5B89\u88C5/\u5378\u8F7D/\u91CD\u8F7D/\u542F\u505C/\u5217\u8868\uFF09\u4E5F\u662F\u63D2\u4EF6\u5DE5\u5177\uFF1A",'\u7ECF call_tool \u8C03\u7528 plugin-manager.manage\uFF0C\u5373 call_tool({name: "plugin-manager.manage", arguments:{action:"...", ...}})\u3002',"\u672A\u7ECF\u7528\u6237\u660E\u786E\u8981\u6C42\u4E0D\u8981\u5B89\u88C5\u6216\u5378\u8F7D\u63D2\u4EF6\u3002"].join(`
8
+ `):"",j=F+ee,te=[i.systemPrompt,N,H,j].map(g=>g?.trim()).filter(g=>!!g).join(`
6
9
 
7
- `),P=f=>f?.trim()?[{role:"system",content:f.trim()}]:[],Q=[this.config.rolePrompt,l].map(f=>f?.trim()).filter(f=>!!f).join(`
10
+ `),oe=g=>g?.trim()?[{role:"system",content:g.trim()}]:[],et=[this.config.rolePrompt,c].map(g=>g?.trim()).filter(g=>!!g).join(`
8
11
 
9
- `),K=[...P(this.config.globalPrompt),...P(Q),...P(this.config.memory),...H?[{role:"system",content:H}]:[],...P(gt())],F=K.map(f=>f.content).filter(Boolean).join(`
12
+ `),me=[...oe(this.config.globalPrompt),...oe(et),...oe(this.config.memory),...te?[{role:"system",content:te}]:[],...oe(Ct())],tt=me.map(g=>g.content).filter(Boolean).join(`
10
13
 
11
- `);this.initialConversation=de(K),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:c,permissions:i,mcpConnections:a,ownsMcpConnections:r,exposedTools:$,commands:A,commandRegistry:x,conversation:de(K),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:this.state.toolPermissionPolicy},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:c.model,commandCount:A.length});const L=he(c);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:c.model,commandCount:A.length,estimatedContextTokens:Qt(F,$),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:$.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:$.map(f=>({name:f.exposedName,source:f.kind==="mcp"?`${f.serverName}.${f.toolName}`:`builtin.${f.toolName}`,description:f.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(f=>({name:f.name,description:f.description,directory:f.directory})),skillGroups:o.map(f=>({dir:f.dir,exists:f.exists,skills:f.skills.map(W=>({name:W.name,description:W.description,directory:W.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:A.length,commandDirs:R,commands:A.map(f=>({name:f.name,description:f.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(n)}async loadAllSkills(){const e=this.config.skillsDir??"",t=G.join(this.config.workingDirectory,".acode","skills"),o=G.join(this.config.workingDirectory,".agentswork","skills"),n=new Set,c=[],i=[];for(const l of[e,t,o]){if(!l)continue;const u=G.resolve(l);if(!n.has(u)){n.add(u),c.push(await kt(l));try{await B.promises.access(u),i.push(u)}catch{}}}const a=new Map;for(const l of c)for(const u of l.skills)a.set(u.name,u);return{skills:[...a.values()],skillGroups:c,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=B.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=B.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()},J.SKILL_REFRESH_DEBOUNCE_MS)}async refreshSkills(){if(!(!this.state.started||this.state.terminated))try{const{skills:e,skillGroups:t}=await this.loadAllSkills();this.skillTool&&this.skillTool.refresh(e),this.state.skills=e,this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:e.length,skills:e.map(o=>({name:o.name,description:o.description,directory:o.directory})),skillGroups:t.map(o=>({dir:o.dir,exists:o.exists,skills:o.skills.map(n=>({name:n.name,description:n.description,directory:n.directory}))}))}),m(`[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(!ce||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:n,threshold:c}=he(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,a=ne(this.state.conversation)+Fe(this.state.exposedTools),r=Math.max(i,a),l=ee(this.state.conversation),u=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=${l}KB`,`estimation=${a} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${n??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${c}`,`remainingToTrigger=${Math.max(0,c-i)}`,`isRunning=${u}`,`shouldCompact=${u?r>=c:!1}`,"---"].join(" | ");B.promises.appendFile(Be,p+`
12
- `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;m(`[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(()=>(m(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmitGuarded(e,t)));return this.submitQueue=o.catch(()=>{m("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),m("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}executeSubmitGuarded(e,t){const o={};this.activeTurnToken=o;const n=this.executeSubmit(e,t),c=new Promise(i=>{this.forceSettleWaiters.set(o,i)});return n.finally(()=>{this.forceSettleWaiters.delete(o),this.activeTurnToken===o&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([n,c])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=Bo();this.abortForceSettleTimer=setTimeout(()=>{this.abortForceSettleTimer=null,this.activeTurn&&this.activeTurnToken===e&&this.forceSettleActiveTurn(`turn still unsettled ${t}ms after abort()`)},t),typeof this.abortForceSettleTimer.unref=="function"&&this.abortForceSettleTimer.unref()}forceSettleActiveTurn(e){const t=this.activeTurnToken;console.error(`[ACodeRuntime] \u{1F6A8} FORCE SETTLE: active turn ignored abort() (${e}). Force-settling to unblock submitQueue; late executeSubmit continuation will be superseded.`),this.contextVersion+=1,this.activeTurn=!1,this.abortRequested=!1,this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.emitAcodeEvent("error",{message:`ACode turn force-settled: ${e}`}),this.emitAcodeEvent("turn_complete",{failed:!0});const o=t?this.forceSettleWaiters.get(t):void 0;t&&this.forceSettleWaiters.delete(t),this.activeTurnToken=null,o?.()}notifyForceMessage(){this.forceMessagePending=!0,m("[ACodeRuntime] \u{1F514} Force message pending flag set")}addBuiltInTools(e){if(!this.state||!this.exposedToolsInitialized||!Array.isArray(e))return 0;const t=new Set(this.state.exposedTools.map(n=>n.exposedName)),o=[];for(const n of e)It(n)&&(t.has(n.exposedName)||(t.add(n.exposedName),o.push(n)));return o.length===0?0:(this.state.exposedTools=[...this.state.exposedTools,...o],this.emitExposedToolsStatus(),o.length)}removeBuiltInToolsByPrefix(e){if(!this.state||!this.exposedToolsInitialized||!e)return 0;const t=this.state.exposedTools.length;this.state.exposedTools=this.state.exposedTools.filter(n=>!n.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}addPluginCommands(e){if(!this.state||e.length===0)return;this.state.commandRegistry.addCommands(e);const t=new Set(this.state.commands.map(o=>o.name));this.state.commands=[...this.state.commands,...e.filter(o=>!t.has(o.name))]}emitExposedToolsStatus(){this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(e=>e.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(e=>({name:e.exposedName,source:e.kind==="mcp"?`${e.serverName}.${e.toolName}`:`builtin.${e.toolName}`,description:e.description||""}))})}async injectForceMessage(){if(!this.forceMessagePending)return!1;this.forceMessagePending=!1;const e=this.state.mcpConnections.find(t=>t.tools.some(o=>o.toolName==="get_message"));if(!e)return m("[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=U(t);let n=[];try{const r=JSON.parse(o);Array.isArray(r?.directMessages)&&(n=r.directMessages.filter(l=>l?.force===!0))}catch{return!1}if(n.length===0)return!1;const c=JSON.stringify({directMessages:n,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:c}),m(`[ACodeRuntime] injectForceMessage: injected ${n.length} force message(s) into conversation`),!0}catch(t){return m(`[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=de(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(m("[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"),m("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),m(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),m(`[ACodeRuntime] \u{1F522} Context version: ${t}`),m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const n=this.activeTurnToken,c=e.trim();let i=!1;try{m("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const a=Date.now(),r=await this.hookBus.dispatch("UserPromptSubmit",{prompt:c}),l=Date.now()-a;if(m(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${l}ms, results: ${r.length}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const u=me(r);if(u){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${u.message}`),this.emitAcodeEvent("error",{message:u.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}m("[ACodeRuntime] \u{1F50D} Expanding command if any...");const p=this.state.commandRegistry.expand(c),g=p?.prompt.trim()||c,_=p?.command.allowedTools;if(p){m(`[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});const C=p.command.plugin;C&&(m(`[ACodeRuntime] \u{1F4CB} Slash command belongs to plugin: ${C}`),this.config.pluginBridge?.exposePlugin?.(C))}if(!this.state.provider.baseURL){m("[ACodeRuntime] \u26A0\uFE0F No provider baseURL configured, using fallback response");const C=Co(g,this.state);this.emitAcodeEvent("assistant_delta",{text:C}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:C.length}}),i=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}m("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const h=ye(g);if(h.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.");m("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const T=await je(h.content);if(this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}m("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:T}),m(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),m("[ACodeRuntime] Starting runModelTurn...");const b=Date.now(),d=await this.runModelTurn(_,t),w=Date.now()-b;if(m(`[ACodeRuntime] \u2705 runModelTurn completed in ${w}ms`),m(`[ACodeRuntime] \u{1F4DD} Result: text=${d.text?d.text.slice(0,80)+(d.text.length>80?"...":""):"(empty)"}, finishReason=${d.finishReason||"(none)"}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}d.text&&!this.state.provider.stream&&(m("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:d.text})),m("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length},...d.responseBody?{responseBody:d.responseBody}:{},...d.finishReason?{finishReason:d.finishReason}:{}}),V(`turn_complete emitted: usage=${JSON.stringify(d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length})} (providerUsage=${d.usage?"real":"FALLBACK-text-length"}) textLength=${d.text.length} totalOutputTextLength=${d.totalOutputTextLength}`),m(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(d.usage?"":" (estimated, no provider usage)")),i=!0;const M=Date.now()-o;m("[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"),m(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${M}ms`),m("[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)){m("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){m("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),i=!0;return}m("[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;m(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${a}ms`),m(`[ACodeRuntime] \u{1F50D} turnCompleted=${i}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===n&&(this.activeTurn=!1,this.abortRequested=!1),!i&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${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}),m("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(m(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.armAbortForceSettle()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,n)=>{this.questionWaiters.set(e,{resolve:o,reject:n,contextVersion:t})})}}async buildAllocatableToolList(){const e=this.state?.exposedTools??[],t=this.config.subAgentSuiteTools??[];let o=[];if(this.config.subAgentSuiteToolProvider)try{o=await this.config.subAgentSuiteToolProvider([])}catch{o=[]}return ie(e,ie(t,o))}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,n=this.config.workingDirectory,c=this.config;return{spawnSubAgent:async i=>{let a=this.config.subAgentSuiteTools;if(i.allowedTools&&i.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const l=await this.config.subAgentSuiteToolProvider(i.allowedTools);l.length>0&&(a=a?ie(a,l):l)}catch{}const r=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,...i.allowedTools&&i.allowedTools.length>0?{allowedTools:i.allowedTools}:{},workingDirectory:n,parentConfig:{...c,sharedMcpConnections:this.state?.mcpConnections,...a&&a.length>0?{subAgentSuiteTools:a}:{}}});return await e.start(r),{subId:r}},listSubAgentToolCatalog:async()=>ke(await this.buildAllocatableToolList()),listSubAgents:async()=>{const i=e.listByParent(t),a=[],r=[];for(const l of i){const u={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(u):r.push(u)}return r.sort((l,u)=>(u.endedAt??0)-(l.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 l of i)this.pendingAwaitedSubIds.add(l),r.add(l);try{return await e.awaitCompletion(i,a)}finally{for(const l of r)this.pendingAwaitedSubIds.delete(l)}},abortSubAgent:i=>e.abort(i)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,n)=>{for(const c of o)this.pendingAwaitedSubIds.add(c);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,n)}finally{for(const c of o)this.pendingAwaitedSubIds.delete(c)}}:null,awaitBgCommands:(o,n)=>{for(const c of o)this.pendingAwaitedBgTaskIds.add(c);try{return Z.awaitCompletion(e,o,n)}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()}}createToolPermissionController(){return{getLevel:e=>this.state.toolPermissionPolicy[e]??"allow",requestPermission:(e,t)=>this.requestToolPermission(e,t)}}requestToolPermission(e,t){const o=tt();return new Promise(n=>{this.permissionWaiters.set(o,{capability:e,detail:t,resolve:n}),this.emitAcodeEvent("tool_permission_request",{requestId:o,capability:e,agentId:this.config.agentId,...t})})}submitToolPermissionDecision(e,t){const o=this.permissionWaiters.get(e);return o?(this.permissionWaiters.delete(e),o.resolve(t),!0):!1}rejectAllPermissionWaiters(e){if(this.permissionWaiters.size!==0){for(const[,t]of this.permissionWaiters)t.resolve(!1);this.permissionWaiters.clear(),D("tool-permission",`waiters rejected: ${e}`)}}setToolPermissionPolicy(e){this.state.toolPermissionPolicy={...this.state.toolPermissionPolicy,...e}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(n=>{m(`[ACodeRuntime] \u26A0\uFE0F manager.abort(${o}) threw: ${n instanceof Error?n.message:String(n)}`)})}cancelPendingAwaitedBgTasks(){if(this.pendingAwaitedBgTaskIds.size===0)return;const e=this.config.agentId??"unknown",t=Array.from(this.pendingAwaitedBgTaskIds);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),Z.interruptAwaits(e,t)}detachCurrentToolExecution(){const e=this.toolSettleSlot;return!e||!e.settlable||e.settled?!1:(e.settled=!0,e.resolveSettle?.(),m(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${e.toolName} (toolCallId=${e.toolCallId}) to background`),!0)}beginToolSettle(e,t,o){const n=e.toolName==="Bash",c=++this.toolSettleSeq;let i;const a=n?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:c,toolName:e.toolName,toolCallId:o,settlable:n,settled:!1,resolveSettle:i??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.rejectAllPermissionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await te("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await te("ACode background commands shutdown",Z.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),te("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await te("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(),ce)try{B.promises.appendFile(Be,`[${new Date().toISOString()}] runtime stopped | ---
13
- `,"utf-8").catch(()=>{})}catch{}}discoverPluginCommandDirs(){const e=this.config.pluginsDir;if(!e)return[];let t;try{t=B.readdirSync(e)}catch{return[]}const o=[];for(const n of t){if(n.startsWith("."))continue;const c=G.join(e,n);let i;try{i=B.statSync(c)}catch{continue}if(!i.isDirectory())continue;const a=G.join(c,"commands");let r;try{B.existsSync(a)&&(r=B.statSync(a))}catch{r=void 0}r?.isDirectory()&&o.push(a)}return o}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",n,c,i,a="",r=0;this.lastIterationUsage=void 0,m(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const l=50;for(let u=0;u<l;u+=1){if(m(`[ACodeRuntime] \u{1F504} Iteration ${u+1} starting...`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${u+1}, aborting`),{text:"",totalOutputTextLength:a.length};await this.injectForceMessage();const p=Date.now(),g=await this.requestChatCompletion(e),_=Date.now()-p;if(m(`[ACodeRuntime] \u{1F916} AI request completed in ${_}ms, choices: ${g.choices?.length||0}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${u+1}`),{text:"",totalOutputTextLength:a.length};if(this.state.terminated)throw m(`[ACodeRuntime] Runtime terminated at iteration ${u+1}`),new Error("ACode runtime was stopped during the active turn");const h=g.choices?.[0];c=JSON.stringify(g,null,2),i=typeof h?.finish_reason=="string"?h.finish_reason:void 0;const T=h?.message,b=typeof T?.content=="string"?T.content:"",d=Array.isArray(T?.tool_calls)?T.tool_calls:[];if(m(`[ACodeRuntime] AI response: content=${b?b.slice(0,100)+(b.length>100?"...":""):"(empty)"}, toolCalls=${d.length}, finishReason=${i||"(none)"}`),g.usage){const $=q(g.usage.prompt_tokens??g.usage.input_tokens),S=q(g.usage.completion_tokens??g.usage.output_tokens),R=$!==void 0,y=S!==void 0;if(V(`provider usage parsed: raw=${JSON.stringify(g.usage)} input=${$} output=${S} hasInput=${R} hasOutput=${y} iteration=${u+1}`),R||y){const A=Lt(g.usage,$),x=n?.outputTokens??a.length+b.length;this.state.accumulatedCacheHitTokens+=A?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=A?.cacheMissTokens??0,n={inputTokens:R?$:n?.inputTokens??0,outputTokens:y?S:x,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=n,r+=R?$:0,this.state.accumulatedInputTokens=R?$:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=y?S:this.state.accumulatedOutputTokens,V(`finalUsage updated: ${JSON.stringify(n)} (cacheUsage=${JSON.stringify(A??null)})`),m(`[ACodeRuntime] \u{1F4B0} Token usage: input=${n.inputTokens}, output=${n.outputTokens} (turn accumulated cost: input=${r})`),m(A?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${A.cacheHitTokens}, miss=${A.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else V(`provider response has NO usage field (fallback to text-length estimate), iteration=${u+1}`);if(this.state.conversation.push({role:"assistant",content:b||null,tool_calls:d.length>0?d:void 0}),b&&(o=b,a+=b,m(`[ACodeRuntime] \u2728 Captured assistant text: ${b.slice(0,80)}...`)),d.length===0)return m(`[ACodeRuntime] \u2705 No tool calls at iteration ${u+1}, completing turn`),{text:o,usage:n,responseBody:c,finishReason:i,totalOutputTextLength:a.length};const w=d.map($=>$.function.name).join(", ");m(`[ACodeRuntime] \u{1F527} Executing ${d.length} tool(s) at iteration ${u+1}: ${w}`);const M=Date.now();await this.handleToolCalls(d,e,t);const C=Date.now()-M;if(m(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${C}ms at iteration ${u+1}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${u+1}`),{text:"",totalOutputTextLength:a.length};m(`[ACodeRuntime] \u{1F504} Preparing iteration ${u+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:n,responseBody:c,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 n={"Content-Type":"application/json"};t.apiKey&&(n.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).
14
+ `);this.initialConversation=he(me),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:i,permissions:a,mcpConnections:r,ownsMcpConnections:l,exposedTools:C,commands:w,commandRegistry:q,conversation:he(me),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:this.state.toolPermissionPolicy,skipNextCompaction:this.state.skipNextCompaction},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:i.model,commandCount:w.length});const Q=ge(i);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:i.model,commandCount:w.length,estimatedContextTokens:to(tt,C),contextLimit:Q.contextLimit,maxOutput:Q.maxOutput,...Q.inputLimit!==void 0?{inputLimit:Q.inputLimit}:{},compactionThreshold:Q.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:r.length,builtInToolCount:m.length,toolCount:C.length,permissionMode:a.mode,allowedToolRules:a.allow,deniedToolRules:a.deny,tools:C.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(O=>({name:O.name,description:O.description,directory:O.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:w.length,commandDirs:M,commands:w.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=z.join(this.config.workingDirectory,".acode","skills"),o=z.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,i=[],a=[];for(const c of[e,t,o]){if(!c)continue;const u=z.resolve(c);if(!s.has(u)){s.add(u),i.push(await Et(c));try{await D.promises.access(u),a.push(u)}catch{}}}const r=new Map;for(const c of i)for(const u of c.skills)r.set(u.name,u);return{skills:[...r.values()],skillGroups:i,watchedDirs:a}}startSkillWatchers(e){for(const t of e){let o=null;try{o=D.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=D.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()},K.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}))}))}),d(`[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:i}=ge(e);this.compactionDebugTimer=setInterval(()=>{try{const a=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,r=se(this.state.conversation)+Ge(this.state.exposedTools),l=Math.max(a,r),c=V(this.state.conversation),u=this.state.started&&!this.state.terminated,m=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${c}KB`,`estimation=${r} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${a}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${i}`,`remainingToTrigger=${Math.max(0,i-a)}`,`isRunning=${u}`,`shouldCompact=${u?l>=i:!1}`,"---"].join(" | ");D.promises.appendFile(We,m+`
15
+ `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e,t){const o=this.contextVersion;d(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${o}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const s=this.submitQueue.then(()=>(d(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${o}`),this.executeSubmitGuarded(e,o,t)));return this.submitQueue=s.catch(()=>{d("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),d("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),s}executeSubmitGuarded(e,t,o){const s={};this.activeTurnToken=s;const i=this.executeSubmit(e,t,o),a=new Promise(r=>{this.forceSettleWaiters.set(s,r)});return i.finally(()=>{this.forceSettleWaiters.delete(s),this.activeTurnToken===s&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([i,a])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=Qo();this.abortForceSettleTimer=setTimeout(()=>{this.abortForceSettleTimer=null,this.activeTurn&&this.activeTurnToken===e&&this.forceSettleActiveTurn(`turn still unsettled ${t}ms after abort()`)},t),typeof this.abortForceSettleTimer.unref=="function"&&this.abortForceSettleTimer.unref()}forceSettleActiveTurn(e){const t=this.activeTurnToken;console.error(`[ACodeRuntime] \u{1F6A8} FORCE SETTLE: active turn ignored abort() (${e}). Force-settling to unblock submitQueue; late executeSubmit continuation will be superseded.`),this.contextVersion+=1,this.activeTurn=!1,this.abortRequested=!1,this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.emitAcodeEvent("error",{message:`ACode turn force-settled: ${e}`}),this.emitAcodeEvent("turn_complete",{failed:!0});const o=t?this.forceSettleWaiters.get(t):void 0;t&&this.forceSettleWaiters.delete(t),this.activeTurnToken=null,o?.()}notifyForceMessage(){this.forceMessagePending=!0,d("[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)Ut(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}addPluginCommands(e){if(!this.state||e.length===0)return;this.state.commandRegistry.addCommands(e);const t=new Set(this.state.commands.map(o=>o.name));this.state.commands=[...this.state.commands,...e.filter(o=>!t.has(o.name))]}emitExposedToolsStatus(){this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(e=>e.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(e=>({name:e.exposedName,source:e.kind==="mcp"?`${e.serverName}.${e.toolName}`:`builtin.${e.toolName}`,description:e.description||""}))})}async injectForceMessage(){if(!this.forceMessagePending)return!1;this.forceMessagePending=!1;const e=this.state.mcpConnections.find(t=>t.tools.some(o=>o.toolName==="get_message"));if(!e)return d("[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=B(t);let s=[];try{const l=JSON.parse(o);Array.isArray(l?.directMessages)&&(s=l.directMessages.filter(c=>c?.force===!0))}catch{return!1}if(s.length===0)return!1;const i=JSON.stringify({directMessages:s,groupMessages:[]}),a=`forced_get_msg_${Date.now()}`,r=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:a,type:"function",function:{name:r,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:a,content:i}),d(`[ACodeRuntime] injectForceMessage: injected ${s.length} force message(s) into conversation`),!0}catch(t){return d(`[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=he(this.initialConversation),this.turnPromptPushed=!1,this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t,o){const s=Date.now();if(d("[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"),d("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),d(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),d(`[ACodeRuntime] \u{1F522} Context version: ${t}`),d("[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 i=this.activeTurnToken,a=e.trim();let r=!1;const l=o?.resume===!0&&this.turnPromptPushed;l||(this.turnPromptPushed=!1),this.turnSkipProactiveCompaction=l||o?.skipProactiveCompaction===!0||this.state.skipNextCompaction,this.state.skipNextCompaction=!1;try{let c;if(l)d("[ACodeRuntime] \u{1F501} resume turn: skip UserPromptSubmit hook (already ran in failed turn)"),c=[];else{d("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const y=Date.now();c=await this.hookBus.dispatch("UserPromptSubmit",{prompt:a});const _=Date.now()-y;d(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${_}ms, results: ${c.length}`)}if(this.isTurnSuperseded(t)){d("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const u=$e(c);if(u){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${u.message}`),this.emitAcodeEvent("error",{message:u.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),r=!0,d("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}d("[ACodeRuntime] \u{1F50D} Expanding command if any...");const m=this.state.commandRegistry.expand(a),h=m?.prompt.trim()||a,A=m?.command.allowedTools;if(m&&!l){d(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${m.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:m.command.name,arguments:m.argumentsText,sourcePath:m.command.sourcePath});const y=m.command.plugin;y&&(d(`[ACodeRuntime] \u{1F4CB} Slash command belongs to plugin: ${y}`),this.config.pluginBridge?.exposePlugin?.(y))}if(!this.state.provider.baseURL){d("[ACodeRuntime] \u26A0\uFE0F No provider baseURL configured, using fallback response");const y=Mo(h,this.state);this.emitAcodeEvent("assistant_delta",{text:y}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:h.length,outputTokens:y.length}}),r=!0,d("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}if(l){if(d("[ACodeRuntime] \u{1F501} resume turn: user message already in conversation, skipping push"),this.isTurnSuperseded(t)){d("[ACodeRuntime] \uFE0F Turn superseded before resume runModelTurn, aborting");return}}else{d("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const y=Ce(h);if(y.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.");d("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const _=await He(y.content);if(this.isTurnSuperseded(t)){d("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}d("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:_}),this.turnPromptPushed=!0,d(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`)}d("[ACodeRuntime] Starting runModelTurn...");const f=Date.now(),p=await this.runModelTurn(A,t),k=Date.now()-f;if(d(`[ACodeRuntime] \u2705 runModelTurn completed in ${k}ms`),d(`[ACodeRuntime] \u{1F4DD} Result: text=${p.text?p.text.slice(0,80)+(p.text.length>80?"...":""):"(empty)"}, finishReason=${p.finishReason||"(none)"}`),this.isTurnSuperseded(t)){d("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}p.text&&!this.state.provider.stream&&(d("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:p.text})),d("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:p.usage??{inputTokens:h.length,outputTokens:p.totalOutputTextLength??p.text.length},...p.responseBody?{responseBody:p.responseBody}:{},...p.finishReason?{finishReason:p.finishReason}:{}}),J(`turn_complete emitted: usage=${JSON.stringify(p.usage??{inputTokens:h.length,outputTokens:p.totalOutputTextLength??p.text.length})} (providerUsage=${p.usage?"real":"FALLBACK-text-length"}) textLength=${p.text.length} totalOutputTextLength=${p.totalOutputTextLength}`),d(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(p.usage?"":" (estimated, no provider usage)")),r=!0,this.turnPromptPushed=!1;const T=Date.now()-s;d("[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"),d(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${T}ms`),d("[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(c){const u=Date.now()-s;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${u}ms:`,c instanceof Error?c.message:String(c)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",c instanceof Error?c.stack:"(no stack)"),this.isTurnSuperseded(t)){d("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){d("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),r=!0;return}d("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:c instanceof Error?c.message:String(c)}),this.emitAcodeEvent("turn_complete",{failed:!0}),r=!0}finally{const c=Date.now()-s;d(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${c}ms`),d(`[ACodeRuntime] \u{1F50D} turnCompleted=${r}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===i&&(this.activeTurn=!1,this.abortRequested=!1,this.turnSkipProactiveCompaction=!1),!r&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${c}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}),d("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}markSkipNextCompaction(){this.state.skipNextCompaction=!0}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(d(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.armAbortForceSettle()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,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,i=this.config;return{spawnSubAgent:async a=>{let r=this.config.subAgentSuiteTools;if(a.allowedTools&&a.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const c=await this.config.subAgentSuiteToolProvider(a.allowedTools);c.length>0&&(r=r?ne(r,c):c)}catch{}const l=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:a.subagentType,description:a.description,prompt:a.prompt,...a.allowedTools&&a.allowedTools.length>0?{allowedTools:a.allowedTools}:{},workingDirectory:s,parentConfig:{...i,sharedMcpConnections:this.state?.mcpConnections,...r&&r.length>0?{subAgentSuiteTools:r}:{}}});return await e.start(l),{subId:l}},listSubAgentToolCatalog:async()=>xe(await this.buildAllocatableToolList()),listSubAgents:async()=>{const a=e.listByParent(t),r=[],l=[];for(const c of a){const u={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"?r.push(u):l.push(u)}return l.sort((c,u)=>(u.endedAt??0)-(c.endedAt??0)),{running:r,history:l}},getSubAgentStatus:async a=>{const r=e.getSubAgent(a);return r?{subId:r.subId,subagentType:r.subagentType,description:r.description,status:r.status,startedAt:r.startedAt,endedAt:r.endedAt,durationMs:r.durationMs,prompt:r.prompt,result:r.result,errorMessage:r.errorMessage,contextSnapshot:r.contextSnapshot}:null},awaitSubAgents:async(a,r)=>{const l=new Set;for(const c of a)this.pendingAwaitedSubIds.add(c),l.add(c);try{return await e.awaitCompletion(a,r)}finally{for(const c of l)this.pendingAwaitedSubIds.delete(c)}},abortSubAgent:a=>e.abort(a)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,s)=>{for(const i of o)this.pendingAwaitedSubIds.add(i);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const i of o)this.pendingAwaitedSubIds.delete(i)}}:null,awaitBgCommands:(o,s)=>{for(const i of o)this.pendingAwaitedBgTaskIds.add(i);try{return Y.awaitCompletion(e,o,s)}finally{for(const i of o)this.pendingAwaitedBgTaskIds.delete(i)}}}}submitQuestionAnswer(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}createToolPermissionController(){return{getLevel:e=>this.state.toolPermissionPolicy[e]??"allow",requestPermission:(e,t)=>this.requestToolPermission(e,t)}}requestToolPermission(e,t){const o=st();return new Promise(s=>{this.permissionWaiters.set(o,{capability:e,detail:t,resolve:s}),this.emitAcodeEvent("tool_permission_request",{requestId:o,capability:e,agentId:this.config.agentId,...t})})}submitToolPermissionDecision(e,t){const o=this.permissionWaiters.get(e);return o?(this.permissionWaiters.delete(e),o.resolve(t),!0):!1}rejectAllPermissionWaiters(e){if(this.permissionWaiters.size!==0){for(const[,t]of this.permissionWaiters)t.resolve(!1);this.permissionWaiters.clear(),P("tool-permission",`waiters rejected: ${e}`)}}setToolPermissionPolicy(e){this.state.toolPermissionPolicy={...this.state.toolPermissionPolicy,...e}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);d(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(s=>{d(`[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);d(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),Y.interruptAwaits(e,t)}detachCurrentToolExecution(e){const t=e?this.toolSettleSlots.get(e):this.pickSettleCandidate();return!t||!t.settlable||t.settled?!1:(t.settled=!0,t.resolveSettle?.(),d(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${t.toolName} (toolCallId=${t.toolCallId}) to background`),!0)}pickSettleCandidate(){let e=null;for(const t of this.toolSettleSlots.values())!t.settlable||t.settled||(e===null||t.order<e.order)&&(e=t);return e}beginToolSettle(e,t,o){const s=e.toolName==="Bash",i=++this.toolSettleSeq;let a;const r=s?new Promise(l=>{a=l}):void 0;return this.toolSettleSlots.set(o,{seq:i,toolName:e.toolName,toolCallId:o,settlable:s,settled:!1,resolveSettle:a??null,order:i}),{seq:i,signal:r}}clearToolSettle(e,t){if(t!==void 0){this.toolSettleSlots.get(t)?.seq===e&&this.toolSettleSlots.delete(t);return}for(const[o,s]of this.toolSettleSlots)if(s.seq===e){this.toolSettleSlots.delete(o);return}}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.armAbortForceSettle(),this.rejectAllQuestionWaiters("session terminated"),this.rejectAllPermissionWaiters("session terminated"),this.readFileStateTracker.clear(),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await X("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await X("ACode background commands shutdown",Y.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),X("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await X("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{D.promises.appendFile(We,`[${new Date().toISOString()}] runtime stopped | ---
16
+ `,"utf-8").catch(()=>{})}catch{}}discoverPluginCommandDirs(){const e=this.config.pluginsDir;if(!e)return[];let t;try{t=D.readdirSync(e)}catch{return[]}const o=[];for(const s of t){if(s.startsWith("."))continue;const i=z.join(e,s);let a;try{a=D.statSync(i)}catch{continue}if(!a.isDirectory())continue;const r=z.join(i,"commands");let l;try{D.existsSync(r)&&(l=D.statSync(r))}catch{l=void 0}l?.isDirectory()&&o.push(r)}return o}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",s,i,a,r="",l=0;this.lastIterationUsage=void 0,d(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const c=50;for(let u=0;u<c;u+=1){if(d(`[ACodeRuntime] \u{1F504} Iteration ${u+1} starting...`),this.isTurnSuperseded(t))return d(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${u+1}, aborting`),{text:"",totalOutputTextLength:r.length};await this.injectForceMessage();const m=Date.now(),h=await this.requestChatCompletion(e),A=Date.now()-m;if(d(`[ACodeRuntime] \u{1F916} AI request completed in ${A}ms, choices: ${h.choices?.length||0}`),this.isTurnSuperseded(t))return d(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${u+1}`),{text:"",totalOutputTextLength:r.length};if(this.state.terminated)throw d(`[ACodeRuntime] Runtime terminated at iteration ${u+1}`),new Error("ACode runtime was stopped during the active turn");const f=h.choices?.[0];i=JSON.stringify(h,null,2),a=typeof f?.finish_reason=="string"?f.finish_reason:void 0;const p=f?.message,k=typeof p?.content=="string"?p.content:"",T=Array.isArray(p?.tool_calls)?p.tool_calls:[];if(d(`[ACodeRuntime] AI response: content=${k?k.slice(0,100)+(k.length>100?"...":""):"(empty)"}, toolCalls=${T.length}, finishReason=${a||"(none)"}`),h.usage){const x=L(h.usage.prompt_tokens??h.usage.input_tokens),S=L(h.usage.completion_tokens??h.usage.output_tokens),C=x!==void 0,b=S!==void 0;if(J(`provider usage parsed: raw=${JSON.stringify(h.usage)} input=${x} output=${S} hasInput=${C} hasOutput=${b} iteration=${u+1}`),C||b){const M=zt(h.usage,x),v=s?.outputTokens??r.length+k.length;this.state.accumulatedCacheHitTokens+=M?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=M?.cacheMissTokens??0,s={inputTokens:C?x:s?.inputTokens??0,outputTokens:b?S:v,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=s,this.emitAcodeEvent("iteration_usage",{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheHitTokens:s.cacheHitTokens,cacheMissTokens:s.cacheMissTokens}),l+=C?x:0,this.state.accumulatedInputTokens=C?x:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=b?S:this.state.accumulatedOutputTokens,J(`finalUsage updated: ${JSON.stringify(s)} (cacheUsage=${JSON.stringify(M??null)})`),d(`[ACodeRuntime] \u{1F4B0} Token usage: input=${s.inputTokens}, output=${s.outputTokens} (turn accumulated cost: input=${l})`),d(M?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${M.cacheHitTokens}, miss=${M.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else J(`provider response has NO usage field (fallback to text-length estimate), iteration=${u+1}`);if(this.state.conversation.push({role:"assistant",content:k||null,tool_calls:T.length>0?T:void 0}),k&&(o=k,r+=k,d(`[ACodeRuntime] \u2728 Captured assistant text: ${k.slice(0,80)}...`)),T.length===0)return d(`[ACodeRuntime] \u2705 No tool calls at iteration ${u+1}, completing turn`),{text:o,usage:s,responseBody:i,finishReason:a,totalOutputTextLength:r.length};const y=T.map(x=>x.function.name).join(", ");d(`[ACodeRuntime] \u{1F527} Executing ${T.length} tool(s) at iteration ${u+1}: ${y}`);const _=Date.now();await this.handleToolCalls(T,e,t);const R=Date.now()-_;if(d(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${R}ms at iteration ${u+1}`),this.isTurnSuperseded(t))return d(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${u+1}`),{text:"",totalOutputTextLength:r.length};d(`[ACodeRuntime] \u{1F504} Preparing iteration ${u+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:i,finishReason:a||"safety_iteration_limit_reached",totalOutputTextLength:r.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 i={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).
14
17
 
15
18
  --- Conversation Start ---
16
19
  ${e.conversationText}
17
20
  --- Conversation End ---
18
21
 
19
- `+wt}]},i=new AbortController;this.abortController=i;let a=!1;try{return await E((async()=>{const r=await E(fetch(ue(o),{method:"POST",headers:n,body:JSON.stringify(c),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()}),g=p.length>500?`${p.slice(0,500)}...(truncated, total ${p.length} chars)`:p;throw new Error(`ACode LLM summarization request failed: ${r.status} ${g}`)}const u=(await E(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{a=!0,i.abort()})).choices?.[0]?.message?.content;if(!u||u.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return u})(),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:n,maxOutput:c,inputLimit:i,threshold:a}=he(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,l=ne(this.state.conversation)+Fe(this.state.exposedTools),u=Math.max(r,l),p=u>=a;if(m(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${l}, effectiveUsed=${u}, contextLimit=${n}, inputLimit=${i??"n/a"}, maxOutput=${c}, triggerThreshold=${a}, shouldCompact=${p}`),p){const y=ee(this.state.conversation),A=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:A,sizeKB:y,estimatedTokens:l,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(A,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${u} tokens, \u9608\u503C: ${a}, \u89E6\u53D1: ${r>=a?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const x=await we(this.state.conversation,n,c,{llmSummarizer:k=>this.summarizeConversationWithLLM(k),onPhase:k=>this.handleCompactionPhase(A,k),actualUsedTokens:u}),I=ee(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:A,sizeBeforeKB:y,sizeAfterKB:I,freedKB:Math.round((y-I)*10)/10,strategy:x.strategy,freedTokens:x.freedTokens,tokensBefore:x.tokensBefore,tokensAfter:x.tokensAfter,prunedToolMessages:x.prunedToolMessages,summarizedMessages:x.summarizedMessages,messageCountBefore:x.messageCountBefore,messageCountAfter:x.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const g=await bo(this.state.conversation,Ue,n,c,y=>this.summarizeConversationWithLLM(y));g>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${g} older messages to fit within ${Ue} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const _=this.state.exposedTools.filter(y=>go(y,this.state.permissions,e)),h=()=>{const y={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(y.reasoning_effort=t.effort),t.stream&&(y.stream_options={include_usage:!0}),_.length>0&&(y.tools=Qe(_),y.tool_choice="auto"),y},T="POST",b=yo(o),d=No(t),w=Io(d),M=y=>{const A=JSON.stringify(y,null,2);m(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${b}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:b,requestMethod:T,requestUrl:b,requestHeaders:w,stream:t.stream,messageCount:this.state.conversation.length,toolCount:_.length,lastUserMessagePreview:To(this.state.conversation),estimatedContextTokens:fe(A),requestBody:A,...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),V(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${_.length} estimatedContextTokens=${fe(A)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let C=h();M(C);const $=t.requestRetryCount===pe,S=$?1/0:t.requestRetryCount+1;let R=!1;for(let y=1;$||y<=S;y+=1){this.state.terminated||(this.abortRequested=!1),y>1&&M(C);const A=new AbortController;this.abortController=A;let x=!1;try{return await E((async()=>{const I=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,k=await E(fetch(ue(o),{method:T,headers:d,body:JSON.stringify(C),signal:A.signal}),I,"ACode provider request",()=>{x=!0,A.abort()});if(!k.ok){const P=await E(k.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{x=!0,A.abort()}),Q=P.length>500?`${P.slice(0,500)}...(truncated, total ${P.length} chars)`:P;throw new Error(`ACode provider request failed: ${k.status} ${Q}`)}const O=k.headers?.get?.("content-type")||"";if(t.stream&&O.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(k,t.requestStreamIdleTimeoutMs,A,t.requestFirstByteTimeoutMs);const j=await E(k.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{x=!0,A.abort()});if(!v(j))return this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof j}); treating as empty response`}),{};const H=Ye(j);if(H)throw new Error(`ACode provider request failed: ${H}`);return j})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{A.abort()})}catch(I){let k;if(I instanceof Error&&I.name==="AbortError"?x?k=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?k=new Error("ACode provider request aborted by user"):k=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):k=I instanceof Error?I:new Error(String(I)),!R&&!this.abortRequested&&!this.state.terminated&&Ke(k)){const P=ee(this.state.conversation),Q=ne(this.state.conversation),K=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:Q,messageCount:K,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(F,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${K}\u6761, \u5927\u5C0F: ${P}KB`),this.emitCompactionPhase(F,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const L=$t(this.state.conversation,n);this.emitCompactionPhase(F,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${L.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${L.freedTokens} tokens`),this.emitCompactionPhase(F,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const f=await $e(this.state.conversation,{llmSummarizer:Ze=>this.summarizeConversationWithLLM(Ze),contextLimit:n});this.emitCompactionPhase(F,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${f} \u6761\u6D88\u606F`);const W=ee(this.state.conversation),Ve=ne(this.state.conversation),Xe=this.state.conversation.length;R=!0;const Ae=L.prunedCount+f;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:F,sizeBeforeKB:P,sizeAfterKB:W,freedKB:Math.round((P-W)*10)/10,tokensBefore:Q,tokensAfter:Ve,messageCountBefore:K,messageCountAfter:Xe,strategy:f>0?"summarize":"prune",freedTokens:L.freedTokens,prunedToolMessages:L.prunedCount,summarizedMessages:f,trigger:"provider_overflow_error"}),Ae===0)throw k;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${Ae} older messages and rebuilt the request instead of retrying the same oversized payload`}),C=h(),M(C),y-=1;continue}if(!(($||y<S)&&!this.abortRequested&&!this.state.terminated&&wo(k)))throw k;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${y}${$?"":`/${S}`} failed; retrying: ${k.message}`,nonFatal:!0});const j=Math.min(Ft,qt*Math.pow(2,y-1)),H=Math.random()*1e3;await Yt(j+H)}finally{this.abortController===A&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,n){if(!e.body)throw new Error("ACode provider stream response has no body");const c=e.body.getReader(),i=new TextDecoder,a=new Map;let r="",l="",u;const p=_=>{for(const h of Oo(_)){if(h==="[DONE]")continue;const T=JSON.parse(h);if(!v(T))continue;const b=Ye(T);if(b)throw o?.abort(),new Error(`ACode provider request failed: ${b}`);const d=T.usage;d&&(u=Ut(u,d),V(`stream usage chunk received: ${JSON.stringify(d)} -> merged: ${JSON.stringify(u)}`));const M=T.choices?.[0]?.delta,C=Mo(M);C&&this.emitAcodeEvent("thinking_delta",{text:C});const $=typeof M?.content=="string"?M.content:"";$&&(r+=$,this.emitAcodeEvent("assistant_delta",{text:$}));const S=Array.isArray(M?.tool_calls)?M.tool_calls:[];for(const R of S)Lo(a,R)}};let g=!0;for(;;){const _=g&&n?n:t,{done:h,value:T}=await E(c.read(),_,g?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(g=!1,h)break;l+=i.decode(T,{stream:!0});const b=l.split(/\r?\n\r?\n/);l=b.pop()??"";for(const d of b)p(d)}return l+=i.decode(),l.trim()&&p(l),{choices:[{message:{content:r||null,tool_calls:Uo(a)}}],...u?{usage:u}:{}}}async handleToolCalls(e,t,o=this.contextVersion){m(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const n=i=>Se(i.function.name)==="poll_message",c=[...e.filter(i=>!n(i)),...e.filter(i=>n(i))];e.length>1&&c.some((i,a)=>i!==e[a])&&m(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${c.map(i=>i.function.name).join(", ")}`);for(const i of c){if(this.isTurnSuperseded(o)){m("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const a=i.function.name;m(`[ACodeRuntime] \u{1F50D} Looking up tool: ${a}`);let r=this.state.exposedTools.find(l=>l.exposedName===a);if(r||(r=this.state.exposedTools.find(l=>l.toolName===a),r&&m(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${a} -> ${r.exposedName}`)),r||await this.recoverHiddenMcpTool(a)&&(r=this.state.exposedTools.find(l=>l.exposedName===a)??this.state.exposedTools.find(l=>l.toolName===a),m(`[ACodeRuntime] \u21A9\uFE0F \u540C\u8F6E\u5C55\u5F00\u515C\u5E95: ${a} \u91CD\u62C9\u540E${r?"\u547D\u4E2D":"\u4ECD\u672A\u627E\u5230"}`)),!r){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:i.id,content:`ACode MCP tool not found: ${a}`});continue}m(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const C=He(i.function.arguments);m(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(C).slice(0,200)}`),Te(r,this.state.permissions,t);const $=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:C});if(this.isTurnSuperseded(o))return;const S=me($);if(S)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${S.message}`),new Error(S.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:C,argumentsPreview:Ge(C)});const R=Date.now(),y=Ao(r,C,this.state.provider.mcpToolTimeoutMs);m(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${y}ms, abortRequested: ${this.abortRequested})`),y<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${y})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const A=this.beginToolSettle(r,C,i.id);try{const x=await E(r.execute(C,{onOutput:O=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:O.stream,text:O.text,sequence:O.sequence,cwd:O.cwd,commandLineCount:O.commandLineCount,...O.commandFilePath?{commandFilePath:O.commandFilePath}:{}})},toolCallId:i.id,...A.signal?{settleSignal:A.signal}:{}}),y,`ACode built-in tool ${r.toolName}`),I=Date.now()-R;if(m(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${I}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,result:U(x)}),this.isTurnSuperseded(o)))return;const k=U(x);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${k.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,toolUseId:i.id,result:k}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:k}),await this.appendSyntheticMultimodalUserMessage(k,i.id,o)}finally{this.clearToolSettle(A.seq)}continue}const l=this.state.mcpConnections.find(C=>C.serverName===r.serverName);if(!l){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(C=>C.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const u=He(i.function.arguments);m(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(u).slice(0,200)}`),Te(r,this.state.permissions,t);const p=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:u});if(this.isTurnSuperseded(o))return;const g=me(p);if(g)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${g.message}`),new Error(g.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[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:u,argumentsPreview:Ge(u)});const _=vt(r.toolName),h=Rt(r.toolName),T=_?this.state.provider.mcpPollingToolTimeoutMs:h?0:this.state.provider.mcpToolTimeoutMs,b=Date.now();m(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${T}ms, polling: ${_})`);const d=_&&Se(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(l,r,u,T):await this.callMcpToolWithTimeout(l,r,u,T,_),w=Date.now()-b;if(m(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${w}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:U(d)}),this.isTurnSuperseded(o)))return;let M=U(d);_&&(M=this.expandCommandsInPolledResult(M)),m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${M.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,toolUseId:i.id,result:M}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:M}),await this.appendSyntheticMultimodalUserMessage(M,i.id,o)}catch(l){const u=l instanceof Error&&l.message.includes("timed out after"),p=l instanceof Error&&l.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${u}, isAbortError=${p}`,l instanceof Error?l.message:String(l)),this.isTurnSuperseded(o)){m("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw m(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,toolUseId:i.id,result:`[aborted] ${l instanceof Error?l.message:String(l)}`,failed:!0,aborted:!0}),l instanceof Error?l:new Error(String(l));m(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${u})`),this.appendToolFailureResult(i,r,l)}}m(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,n,c,i){const a=n>0?n:zt,l=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const u=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await E(Promise.race([e.client.callTool({name:t.toolName,arguments:l},void 0,{timeout:a,...i?{signal:i}:{}}),u.promise]),n,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(p){if(i?.aborted||!c||n>0||!$o(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{u.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const n=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
22
+ `+$t}]},a=new AbortController;this.abortController=a;let r=!1;try{return await E((async()=>{const l=await E(fetch(ce(o),{method:"POST",headers:s,body:JSON.stringify(i),signal:a.signal}),t.requestTotalTimeoutMs,"ACode LLM summarization",()=>{r=!0,a.abort()});if(!l.ok){const m=await E(l.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{r=!0,a.abort()}),h=m.length>500?`${m.slice(0,500)}...(truncated, total ${m.length} chars)`:m;throw new Error(`ACode LLM summarization request failed: ${l.status} ${h}`)}const u=(await E(l.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{r=!0,a.abort()})).choices?.[0]?.message?.content;if(!u||u.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return u})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{a.abort()})}catch(l){throw l instanceof Error&&l.name==="AbortError"?r?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):l}finally{this.abortController===a&&(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:i,inputLimit:a,threshold:r}=ge(t),l=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,c=se(this.state.conversation)+Ge(this.state.exposedTools),u=Math.max(l,c);if(this.turnSkipProactiveCompaction||this.state.skipNextCompaction)this.state.skipNextCompaction=!1,d("[ACodeRuntime] \u{1F507} Compaction skipped: retry turn flagged skipProactiveCompaction (timeout/request retries must not mutate context, incl. byte-cap truncation)");else{const C=u>=r;if(d(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${l}, estimation=${c}, effectiveUsed=${u}, contextLimit=${s}, inputLimit=${a??"n/a"}, maxOutput=${i}, triggerThreshold=${r}, shouldCompact=${C}`),C){const M=V(this.state.conversation),v=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:v,sizeKB:M,estimatedTokens:c,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:l>=r?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(v,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${u} tokens, \u9608\u503C: ${r}, \u89E6\u53D1: ${l>=r?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const w=await ke(this.state.conversation,s,i,{llmSummarizer:N=>this.summarizeConversationWithLLM(N),onPhase:N=>this.handleCompactionPhase(v,N),actualUsedTokens:u}),q=V(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:v,sizeBeforeKB:M,sizeAfterKB:q,freedKB:Math.round((M-q)*10)/10,strategy:w.strategy,freedTokens:w.freedTokens,tokensBefore:w.tokensBefore,tokensAfter:w.tokensAfter,prunedToolMessages:w.prunedToolMessages,summarizedMessages:w.summarizedMessages,messageCountBefore:w.messageCountBefore,messageCountAfter:w.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const b=await Eo(this.state.conversation,je,s,i,M=>this.summarizeConversationWithLLM(M));b>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${b} older messages to fit within ${je} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0)}const m=xo(this.state.conversation);(m.orphanToolMessages>0||m.repairedToolCalls>0||m.downgradedAssistants>0)&&(d(`[ACodeRuntime] \u{1FA79} sanitizeToolCallSequence: orphanTools=${m.orphanToolMessages} repairedCalls=${m.repairedToolCalls} downgradedAssistants=${m.downgradedAssistants}`),this.emitAcodeEvent("warning",{message:`\u68C0\u6D4B\u5230\u5DE5\u5177\u8C03\u7528\u5E8F\u5217\u4E0D\u5B8C\u6574\uFF0C\u5DF2\u81EA\u52A8\u4FEE\u590D\uFF08\u5B64\u513F\u5DE5\u5177\u7ED3\u679C ${m.orphanToolMessages} \u6761\u3001\u8865\u5360\u4F4D\u7ED3\u679C ${m.repairedToolCalls} \u4E2A\u3001\u964D\u7EA7 assistant \u6D88\u606F ${m.downgradedAssistants} \u6761\uFF09\uFF0C\u907F\u514D provider 400 (tool_call_sequence_broken) \u6B7B\u5FAA\u73AF\u3002`}));const h=this.state.exposedTools.filter(C=>this.toolGroupManager&&!this.toolGroupManager.shouldShowToLLMByName(C.exposedName)?!1:bo(C,this.state.permissions,e)),A=()=>{const C={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(C.reasoning_effort=t.effort),t.stream&&(C.stream_options={include_usage:!0}),h.length>0&&(C.tools=Xe(h),C.tool_choice="auto"),C},f="POST",p=wo(o),k=zo(t),T=jo(k),y=C=>{const b=JSON.stringify(C,null,2);d(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${p}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:p,requestMethod:f,requestUrl:p,requestHeaders:T,stream:t.stream,messageCount:this.state.conversation.length,toolCount:h.length,lastUserMessagePreview:ko(this.state.conversation),estimatedContextTokens:Te(b),requestBody:b,...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),J(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${h.length} estimatedContextTokens=${Te(b)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let _=A();y(_);const R=t.requestRetryCount===fe,x=R?1/0:t.requestRetryCount+1;let S=!1;for(let C=1;R||C<=x;C+=1){this.state.terminated||(this.abortRequested=!1),C>1&&y(_);const b=new AbortController;this.abortController=b;let M=!1;try{const v=await E((async()=>{const q=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,N=await E(fetch(ce(o),{method:f,headers:k,body:JSON.stringify(_),signal:b.signal}),q,"ACode provider request",()=>{M=!0,b.abort()});if(!N.ok){const j=await E(N.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{M=!0,b.abort()}),te=j.length>500?`${j.slice(0,500)}...(truncated, total ${j.length} chars)`:j;throw new Error(`ACode provider request failed: ${N.status} ${te}`)}const H=N.headers?.get?.("content-type")||"";if(t.stream&&H.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(N,t.requestStreamIdleTimeoutMs,b,t.requestFirstByteTimeoutMs);const F=await E(N.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{M=!0,b.abort()});if(!$(F))return this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof F}); treating as empty response`}),{};const ee=Ze(F);if(ee)throw new Error(`ACode provider request failed: ${ee}`);return F})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{b.abort()}),w=vt({finishReason:v.choices?.[0]?.finish_reason,stopReason:v.choices?.[0]?.stop_reason});if(w.kind==="context_overflow"){if(!S&&await this.compactForContextOverflow({contextLimit:s,trigger:"finish_reason_context_overflow",warningMessage:`ACode provider reported context overflow via ${w.source} (${w.marker}); summarized older messages and rebuilt the request instead of accepting the truncated payload`})>0){S=!0,_=A(),y(_),C-=1;continue}this.emitAcodeEvent("warning",{message:`ACode provider reported context overflow via ${w.source} (${w.marker}), but no further compaction was possible`})}return v}catch(v){let w;if(v instanceof Error&&v.name==="AbortError"?M?w=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?w=new Error("ACode provider request aborted by user"):w=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):w=v instanceof Error?v:new Error(String(v)),!S&&!this.abortRequested&&!this.state.terminated&&(pe(v)||pe(w))){if(await this.compactForContextOverflow({contextLimit:s,trigger:"provider_overflow_error",warningMessage:"ACode provider context limit exceeded; summarized older messages and rebuilt the request instead of retrying the same oversized payload"})===0)throw w;S=!0,_=A(),y(_),C-=1;continue}if(!((R||C<x)&&!this.abortRequested&&!this.state.terminated&&Io(w)))throw w;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${C}${R?"":`/${x}`} failed; retrying: ${w.message}`,nonFatal:!0});const N=Math.min(Gt,Jt*Math.pow(2,C-1)),H=Math.random()*1e3;await oo(N+H)}finally{this.abortController===b&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async compactForContextOverflow(e){const{contextLimit:t,trigger:o,warningMessage:s}=e,i=V(this.state.conversation),a=se(this.state.conversation),r=this.state.conversation.length,l=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:l,sizeKB:i,estimatedTokens:a,messageCount:r,model:this.state.provider.model,trigger:o}),this.emitCompactionPhase(l,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${r}\u6761, \u5927\u5C0F: ${i}KB`),this.emitCompactionPhase(l,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const c=Mt(this.state.conversation,t);this.emitCompactionPhase(l,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${c.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${c.freedTokens} tokens`),this.emitCompactionPhase(l,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const u=await Se(this.state.conversation,{llmSummarizer:p=>this.summarizeConversationWithLLM(p),contextLimit:t});this.emitCompactionPhase(l,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${u} \u6761\u6D88\u606F`);const m=V(this.state.conversation),h=se(this.state.conversation),A=this.state.conversation.length,f=c.prunedCount+u;return this.emitAcodeEvent("context_compaction",{action:"end",compactionId:l,sizeBeforeKB:i,sizeAfterKB:m,freedKB:Math.round((i-m)*10)/10,tokensBefore:a,tokensAfter:h,messageCountBefore:r,messageCountAfter:A,strategy:u>0?"summarize":"prune",freedTokens:c.freedTokens,prunedToolMessages:c.prunedCount,summarizedMessages:u,trigger:o}),f===0?0:(this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:s}),f)}async readChatCompletionStream(e,t,o,s){if(!e.body)throw new Error("ACode provider stream response has no body");const i=e.body.getReader(),a=new TextDecoder,r=new Map;let l="",c="",u,m,h;const A=p=>{for(const k of Go(p)){if(k==="[DONE]")continue;const T=JSON.parse(k);if(!$(T))continue;const y=Ze(T);if(y)throw o?.abort(),new Error(`ACode provider request failed: ${y}`);const _=T.usage;_&&(u=jt(u,_),J(`stream usage chunk received: ${JSON.stringify(_)} -> merged: ${JSON.stringify(u)}`));const R=T.choices?.[0];typeof R?.finish_reason=="string"&&R.finish_reason&&(m=R.finish_reason),typeof R?.stop_reason=="string"&&R.stop_reason&&(h=R.stop_reason);const x=R?.delta,S=Lo(x);S&&this.emitAcodeEvent("thinking_delta",{text:S});const C=typeof x?.content=="string"?x.content:"";C&&(l+=C,this.emitAcodeEvent("assistant_delta",{text:C}));const b=Array.isArray(x?.tool_calls)?x.tool_calls:[];for(const M of b)Ko(r,M)}};let f=!0;for(;;){const p=f&&s?s:t,{done:k,value:T}=await E(i.read(),p,f?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(f=!1,k)break;c+=a.decode(T,{stream:!0});const y=c.split(/\r?\n\r?\n/);c=y.pop()??"";for(const _ of y)A(_)}return c+=a.decode(),c.trim()&&A(c),{choices:[{message:{content:l||null,tool_calls:Ho(r)},...m?{finish_reason:m}:{},...h?{stop_reason:h}:{}}],...u?{usage:u}:{}}}async handleToolCalls(e,t,o=this.contextVersion){d(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=[];for(const i of e){if(this.isTurnSuperseded(o))break;s.push(await this.prepareToolCall(i,t,o))}for(let i=s.length;i<e.length;i++)s.push({toolCall:e[i],tool:void 0,arguments:{},mode:"blocking",scope:"unknown",access:"exclusive",claims:[],immediateError:void 0});this.toolConcurrencyEnabled&&s.length>1?await this.executePreparedToolCallsConcurrently(s,o):await this.executePreparedToolCallsSerially(s,o),d(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async executePreparedToolCallsConcurrently(e,t){const o=e.map(u=>({toolCallId:u.toolCall.id,toolName:u.tool?.exposedName??u.toolCall.function.name,mode:u.mode,scope:u.scope,claims:u.claims})),s=this.toolConcurrencyScheduler.schedule(o),i=`toolbatch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,a=new Ne(i);for(const u of e)a.register({toolCallId:u.toolCall.id,toolName:u.tool?.exposedName??u.toolCall.function.name,mode:u.mode,resourceKeys:(s.plans.get(u.toolCall.id)?.claims??[]).map(m=>m.key)});const r=new Map,l=new Map(e.map(u=>[u.toolCall.id,u]));for(const u of s.waves){if(this.isTurnSuperseded(t))break;const m=u.planIds.map(A=>l.get(A)).filter(A=>A!==void 0);if(m.length===0)continue;(await Promise.allSettled(m.map(A=>this.executeOnePreparedTool(A,a,t)))).forEach((A,f)=>{const p=m[f];r.set(p.toolCall.id,A.status==="fulfilled"?A.value:{toolCallId:p.toolCall.id,status:"failed",error:A.reason})})}await this.commitPreparedToolOutcomes(e,r,a,t);const c=a.finalize();d(`[ACodeRuntime] \u26A1 Tool batch ${i}: tools=${c.toolCount} speedup=${c.speedup}x parallelism=${c.parallelism}x wall=${c.wallClockMs}ms contentions=${c.contentionCount} failures=${c.failureCount}`),this.emitAcodeEvent("mcp_status",{action:"tool_batch_metrics",server:"builtin",batchId:i,toolCount:c.toolCount,parallelism:c.parallelism,speedup:c.speedup,wallClockMs:c.wallClockMs,totalWaitMs:c.totalWaitMs,contentionCount:c.contentionCount,failureCount:c.failureCount,maxConcurrentObserved:c.maxConcurrentObserved,traces:c.traces.map(u=>({toolCallId:u.toolCallId,toolName:u.toolName,mode:u.mode,resourceKeys:u.resourceKeys,waitMs:u.waitDurationMs,runMs:u.executionDurationMs,status:u.status}))})}async executePreparedToolCallsSerially(e,t){const o=new Ne(`toolbatch-serial-${Date.now().toString(36)}`),s=new Map;for(const i of e)o.register({toolCallId:i.toolCall.id,toolName:i.tool?.exposedName??i.toolCall.function.name,mode:i.mode,resourceKeys:i.claims.map(a=>a.key)}),!this.isTurnSuperseded(t)&&s.set(i.toolCall.id,await this.executeOnePreparedTool(i,o,t));await this.commitPreparedToolOutcomes(e,s,o,t)}async commitPreparedToolOutcomes(e,t,o,s){for(const i of e){if(this.isTurnSuperseded(s)){this.commitSupersededToolResult(i),o.transition(i.toolCall.id,"superseded");continue}const a=t.get(i.toolCall.id);if(!a){await this.commitToolOutcome(i,{toolCallId:i.toolCall.id,status:"failed",error:i.immediateError??new Error("Tool was not executed")},s),o.transition(i.toolCall.id,"committed");continue}o.transition(i.toolCall.id,"committing"),await this.commitToolOutcome(i,a,s),o.transition(i.toolCall.id,"committed")}}async executeOnePreparedTool(e,t,o){if(e.immediateError!==void 0||!e.tool){t.transition(e.toolCall.id,"failed");const r=e.immediateError??new Error("Tool not found");return t.setError(e.toolCall.id,r instanceof Error?r.message:String(r)),{toolCallId:e.toolCall.id,status:"failed",error:r}}t.transition(e.toolCall.id,"waiting_resource");const s=await this.toolResourceLock.acquire(e.claims,e.access),i=this.resolveToolLimiter(e),a=i?await i.acquire():()=>{};try{if(this.isTurnSuperseded(o))return{toolCallId:e.toolCall.id,status:"superseded"};t.transition(e.toolCall.id,"running");const r=e.tool.kind==="builtin"?await this.runBuiltInToolCall(e,o):await this.runMcpToolCall(e,o);return t.transition(e.toolCall.id,r.status),r.error!==void 0&&t.setError(e.toolCall.id,r.error instanceof Error?r.error.message:String(r.error)),r}catch(r){const l=r instanceof Error?r.message:String(r);return d(`[ACodeRuntime] \u274C Tool ${e.tool.exposedName} threw unexpectedly: ${l}`),t.transition(e.toolCall.id,"failed"),t.setError(e.toolCall.id,l),{toolCallId:e.toolCall.id,status:"failed",error:r}}finally{a(),s()}}resolveToolLimiter(e){return e.tool?.kind!=="builtin"?null:e.mode==="read"?this.toolReadOnlyLimiter:e.tool.toolName==="Bash"?this.toolBashLimiter:null}async prepareToolCall(e,t,o){const s=e.function.name;let i=this.state.exposedTools.find(c=>c.exposedName===s);i||(i=this.state.exposedTools.find(c=>c.toolName===s),i&&d(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${s} -> ${i.exposedName}`));const a=So(e.function.arguments),r={toolCall:e,tool:i,arguments:a,mode:"exclusive",scope:"exact",access:"exclusive",claims:[],immediateError:void 0};if(!i)return console.error(`[ACodeRuntime] \u274C Tool not found: ${s}, available tools: ${this.state.exposedTools.map(c=>c.exposedName).join(", ")}`),r.immediateError=`ACode MCP tool not found: ${s}`,r;if(i.kind==="mcp"&&!this.state.mcpConnections.find(u=>u.serverName===i.serverName))return console.error(`[ACodeRuntime] \u274C MCP server not connected: ${i.serverName}, connected servers: ${this.state.mcpConnections.map(u=>u.serverName).join(", ")}`),r.immediateError=`ACode MCP server not connected: ${i.serverName}`,r;try{Ve(i,this.state.permissions,t);const c=await this.hookBus.dispatch("PreToolUse",{source:i.kind==="mcp"?"mcp":"builtin",...i.kind==="mcp"?{serverName:i.serverName}:{},toolName:i.toolName,exposedName:i.exposedName,arguments:a}),u=$e(c);if(u)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${i.exposedName}: ${u.message}`),new Error(u.message||`ACode tool denied by hook: ${i.exposedName}`)}catch(c){return r.immediateError=c,r}if(this.isTurnSuperseded(o))return r;const l=this.resolveToolConcurrencyDeclaration(i,a);return r.mode=l.mode,r.scope=l.scope,r.access=l.access,r.claims=l.claims,this.emitAcodeEvent("mcp_status",{action:"call_tool",server:i.kind==="mcp"?i.serverName:"builtin",tool:i.toolName,exposedName:i.exposedName,toolUseId:e.id,arguments:a,argumentsPreview:Do(a)}),r}resolveToolConcurrencyDeclaration(e,t){if(e.kind!=="builtin")return ve(e.toolName)==="poll_message"||Me(e.toolName)?{mode:"blocking",scope:"unknown",access:"exclusive",claims:[]}:{mode:"exclusive",scope:"unknown",access:"exclusive",claims:[]};const o=e.concurrencyMode,s=e.resourceScope??"exact";if(!o)return{mode:"exclusive",scope:s,access:"exclusive",claims:[]};if(o==="blocking")return{mode:"blocking",scope:s,access:"exclusive",claims:[]};const i=o;let a=[];if(e.resourceKeys)try{a=e.resourceKeys(t)??[]}catch(r){d(`[ACodeRuntime] \u26A0\uFE0F resourceKeys() threw for ${e.exposedName}, falling back to exclusive: ${r instanceof Error?r.message:String(r)}`),a=[]}return a.length===0&&s==="unknown"?{mode:"exclusive",scope:s,access:"exclusive",claims:[]}:{mode:o,scope:s,access:i,claims:a}}async runBuiltInToolCall(e,t){const o=e.tool;if(o.kind!=="builtin")return{toolCallId:e.toolCall.id,status:"failed",error:new Error("not builtin")};const s=e.arguments,i=$o(o,s,this.state.provider.mcpToolTimeoutMs);i<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${o.exposedName} has NO timeout (timeoutMs=${i})!`);const a=this.beginToolSettle(o,s,e.toolCall.id);try{const r=await E(o.execute(s,{onOutput:l=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:o.toolName,exposedName:o.exposedName,toolUseId:e.toolCall.id,stream:l.stream,text:l.text,sequence:l.sequence,cwd:l.cwd,commandLineCount:l.commandLineCount,...l.commandFilePath?{commandFilePath:l.commandFilePath}:{}})},toolCallId:e.toolCall.id,...a.signal?{settleSignal:a.signal}:{}}),i,`ACode built-in tool ${o.toolName}`);return{toolCallId:e.toolCall.id,status:"completed",resultText:B(r)}}catch(r){return this.classifyToolError(e,r)}finally{this.clearToolSettle(a.seq,e.toolCall.id)}}async runMcpToolCall(e,t){const o=e.tool;if(o.kind!=="mcp")return{toolCallId:e.toolCall.id,status:"failed",error:new Error("not mcp")};const s=this.state.mcpConnections.find(c=>c.serverName===o.serverName);if(!s)return{toolCallId:e.toolCall.id,status:"failed",error:new Error(`ACode MCP server not connected: ${o.serverName}`)};const i=e.arguments,a=It(o.toolName),r=Me(o.toolName),l=a?this.state.provider.mcpPollingToolTimeoutMs:r?0:this.state.provider.mcpToolTimeoutMs;try{const c=a&&ve(o.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(s,o,i,l):await this.callMcpToolWithTimeout(s,o,i,l,a);let u=B(c);return a&&(u=this.expandCommandsInPolledResult(u)),{toolCallId:e.toolCall.id,status:"completed",resultText:u}}catch(c){return this.classifyToolError(e,c)}}classifyToolError(e,t){const s=(t instanceof Error?t.message:String(t)).includes("timed out after")?"timeout":t instanceof Error&&t.name==="AbortError"?"aborted":"failed";return{toolCallId:e.toolCall.id,status:s,error:t}}async commitToolOutcome(e,t,o){const s=e.tool,i=s?.kind==="mcp"?s.serverName:"builtin",a=s?.toolName??e.toolCall.function.name;if(t.status==="completed"&&t.resultText!==void 0){const c=t.resultText;s&&await this.hookBus.dispatch("PostToolUse",{source:s.kind==="mcp"?"mcp":"builtin",...s.kind==="mcp"?{serverName:s.serverName}:{},toolName:s.toolName,exposedName:s.exposedName,result:c}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:i,tool:a,toolUseId:e.toolCall.id,result:c}),this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:c}),await this.appendSyntheticMultimodalUserMessage(c,e.toolCall.id,o);return}if(t.status==="superseded"){this.commitSupersededToolResult(e);return}const r=t.error??new Error("Tool execution failed"),l=r instanceof Error?r.message:String(r);if(this.abortRequested||this.state.terminated){this.emitAcodeEvent("mcp_status",{action:"tool_result",server:i,tool:a,toolUseId:e.toolCall.id,result:`[aborted] ${l}`,failed:!0,aborted:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:`[aborted] ${l}`});return}if(!s){this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:l}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:i,tool:a,toolUseId:e.toolCall.id,result:l,failed:!0});return}this.appendToolFailureResult(e.toolCall,s,r)}commitSupersededToolResult(e){const t=e.immediateError!==void 0?`[cancelled] ${e.immediateError instanceof Error?e.immediateError.message:String(e.immediateError)}`:"[cancelled] Tool execution was superseded by a newer turn.";this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:t}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:e.tool?.kind==="mcp"?e.tool.serverName:"builtin",tool:e.tool?.toolName??e.toolCall.function.name,toolUseId:e.toolCall.id,result:t,failed:!0,aborted:!0})}async executeSingleToolByName(e,t,o){let s=this.state.exposedTools.find(a=>a.exposedName===e);if(s||(s=this.state.exposedTools.find(a=>a.toolName===e)),!s)throw new Error(`Tool not found: ${e}`);if(s.kind==="builtin")return s.execute(t,{toolCallId:o?.toolCallId});const i=this.state.mcpConnections.find(a=>a.serverName===s.serverName);if(!i)throw new Error(`MCP server not found: ${s.serverName}`);return this.callMcpToolWithTimeout(i,s,t,this.state.provider.mcpToolTimeoutMs,!1)}async callMcpToolWithTimeout(e,t,o,s,i,a){const r=s>0?s:Kt,c=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const u=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:r,...a?{signal:a}:{}}),u.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(m){if(a?.aborted||!i||s>0||!No(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{u.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
20
23
  Error: ${o.error}`:`Sub-agent ${o.subId} [${o.status}]: ${o.description}
21
- Output: ${o.output.length>500?o.output.slice(0,500)+"... (truncated)":o.output}`;return{msgId:`subagent-completion-${o.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:n,requireReply:!1,prompt:`Sub-agent ${o.subId} (${o.description}) has reached terminal state: ${o.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}});return{content:[{type:"text",text:JSON.stringify({directMessages:t,groupMessages:[],fromBuffer:!1,systemMessages:[]},null,2)}]}}static mergeSubAgentCompletionsIntoMcpResult(e,t){if(t.length===0)return e;const o=U(e);let n;try{n=JSON.parse(o)}catch{return e}const i=[...t.map(a=>{const r=a.error?`Sub-agent ${a.subId} [${a.status}]: ${a.description}
22
- Error: ${a.error}`:`Sub-agent ${a.subId} [${a.status}]: ${a.description}
23
- 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()}}),...n.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...n,directMessages:i},null,2)}]}}async recheckMemoryDelegate(e,t,o,n){const c=this.state.mcpConnections.find(i=>i.serverName==="aws-client-agent-mcp");if(!c)return m("[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(i){return m(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${n}): ${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}`),n=U(o),c=JSON.parse(n);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 i=await this.readMemoryViaMcp(e,c);i&&i.memory_status==="updating"&&o.push(c)})),o.length===0)return m(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const n=o.map(c=>`- ${c}`).join(`
24
- `);return m(`[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
25
- ${n}
26
-
27
- \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=[],n=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,l=a.memory_status==="recalling",u=typeof r=="string"&&new Date(r).getTime()<n;(l||u)&&o.push(i)})),o.length===0)return m(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const c=o.map(i=>`- ${i}`).join(`
28
- `);return m(`[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
29
- ${c}
30
-
31
- \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=U(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 n=o.by_type??{},c=[];for(const a of t){const r=a.indexOf("/");if(r<0)continue;const l=a.slice(0,r),u=a.slice(r+1),g=n[l]?.by_domain?.[u];g?.exceeded&&c.push(`${l}/${u} (\u5F53\u524D ${g.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${g.limit??"?"})`)}if(c.length===0)return m(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const i=c.map(a=>`- ${a}`).join(`
32
- `);return m(`[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
24
+ 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=B(e);let s;try{s=JSON.parse(o)}catch{return e}const a=[...t.map(r=>{const l=r.error?`Sub-agent ${r.subId} [${r.status}]: ${r.description}
25
+ Error: ${r.error}`:`Sub-agent ${r.subId} [${r.status}]: ${r.description}
26
+ Output: ${r.output.length>500?r.output.slice(0,500)+"... (truncated)":r.output}`;return{msgId:`subagent-completion-${r.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:l,requireReply:!1,prompt:`Sub-agent ${r.subId} (${r.description}) has reached terminal state: ${r.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:a},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const i=this.state.mcpConnections.find(a=>a.serverName==="aws-client-agent-mcp");if(!i)return d("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(i,t):e==="memory_expiration"?await this.recheckMemoryExpiration(i,t):await this.recheckMemoryCleanup(i,t)}catch(a){return d(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${a instanceof Error?a.message:String(a)}, 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${a instanceof Error?a.message:String(a)}\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=B(o),i=JSON.parse(s);return i==null||typeof i!="object"||Array.isArray(i)?null:i}catch(o){throw o}}async recheckMemoryFileChange(e,t){const o=[];if(await Promise.all(t.map(async i=>{const a=await this.readMemoryViaMcp(e,i);a&&a.memory_status==="updating"&&o.push(i)})),o.length===0)return d(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(i=>`- ${i}`).join(`
27
+ `);return d(`[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
28
+ ${s}
29
+
30
+ \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 a=>{const r=await this.readMemoryViaMcp(e,a);if(!r)return;const l=r.expiresAt??r.expires_at,c=r.memory_status==="recalling",u=typeof l=="string"&&new Date(l).getTime()<s;(c||u)&&o.push(a)})),o.length===0)return d(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const i=o.map(a=>`- ${a}`).join(`
31
+ `);return d(`[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
33
32
  ${i}
34
33
 
34
+ \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 r=await E(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),l=B(r);o=JSON.parse(l)}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??{},i=[];for(const r of t){const l=r.indexOf("/");if(l<0)continue;const c=r.slice(0,l),u=r.slice(l+1),h=s[c]?.by_domain?.[u];h?.exceeded&&i.push(`${c}/${u} (\u5F53\u524D ${h.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${h.limit??"?"})`)}if(i.length===0)return d(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const a=i.map(r=>`- ${r}`).join(`
35
+ `);return d(`[ACodeRuntime] recheck memory_cleanup: ${i.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
36
+ ${a}
37
+
35
38
  \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(`
36
39
  `);return e.type==="memory_expiration"?`\u4F60\u662F\u4E00\u6761\u4E13\u95E8\u5904\u7406 memory \u8FC7\u671F\u6574\u7406\u7684\u5B50 agent\u3002
37
40
 
@@ -84,11 +87,11 @@ ${t}
84
87
  \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
85
88
 
86
89
  \u4EE5\u4E0B ${e.uris.length} \u4E2A\u6C38\u4E45\u8BB0\u5FC6\u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D1\u751F\u53D8\u66F4\uFF1A
87
- ${e.uris.map(o=>{const n=e.fileChanges?.find(r=>r.uri===o);if(!n)return`- ${o}`;const c={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},i=n.fileStatuses&&n.fileStatuses.length>0?n.fileStatuses:[],a=i.length>0?i.map(r=>{if(r.status==="no_change")return` \xB7 ${r.path}`;const l=c[r.status]??r.status,u=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${l}${u}\uFF09`}).join(`
88
- `):n.boundFiles&&n.boundFiles.length>0?n.boundFiles.map(r=>` \xB7 ${r}`).join(`
90
+ ${e.uris.map(o=>{const s=e.fileChanges?.find(l=>l.uri===o);if(!s)return`- ${o}`;const i={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},a=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],r=a.length>0?a.map(l=>{if(l.status==="no_change")return` \xB7 ${l.path}`;const c=i[l.status]??l.status,u=l.status==="content_changed"&&l.localMd5&&l.serverMd5?` \u672C\u5730: ${l.localMd5} Server: ${l.serverMd5}`:l.status==="not_found"&&l.serverMd5?` Server: ${l.serverMd5}`:"";return` \xB7 ${l.path}\uFF08${c}${u}\uFF09`}).join(`
91
+ `):s.boundFiles&&s.boundFiles.length>0?s.boundFiles.map(l=>` \xB7 ${l}`).join(`
89
92
  `):" \u65E0\uFF08\u8BF7\u901A\u8FC7 read_memory \u67E5\u770B bound_files\uFF09";return`- ${o}
90
93
  - \u7ED1\u5B9A\u6587\u4EF6:
91
- ${a}`}).join(`
94
+ ${r}`}).join(`
92
95
  `)}
93
96
 
94
97
  \u8BF7\u6267\u884C\u4EE5\u4E0B\u6B65\u9AA4\uFF08\u6838\u5FC3\u903B\u8F91\uFF1A\u66F4\u65B0 \u2192 \u9A8C\u8BC1 \u2192 \u672A\u5B8C\u6210\u5219\u7EE7\u7EED\uFF09\uFF1A
@@ -106,5 +109,5 @@ ${a}`}).join(`
106
109
  - \u2705 \u82E5\u5168\u90E8 memory_status \u4E3A "normal"\uFF1A\u9759\u9ED8\u7ED3\u675F
107
110
 
108
111
  \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
109
- \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=U(e)}catch{return e}let n;try{n=JSON.parse(o)}catch{return e}const c=n.directMessages;if(!Array.isArray(c)||c.length===0)return e;const i=[];let a=0;for(const l of c){const u=l._acodeAutoDelegate;if(u&&(u.type==="memory_expiration"||u.type==="memory_file_change"||u.type==="memory_cleanup")){a++;const p=Date.now(),g=u.uris.filter(d=>this.pendingMemorySubAgents.has(d)).length,_=u.uris.filter(d=>{const w=this.memoryDelegateCooldownUntil.get(d);return w!==void 0&&p<w}).length,h=u.uris.filter(d=>{if(this.pendingMemorySubAgents.has(d))return!1;const w=this.memoryDelegateCooldownUntil.get(d);return!(w!==void 0&&p<w)});if(h.length===0){m(`[ACodeRuntime] Memory ${u.type} skipped: ${g} in-progress, ${_} in cooldown (total ${u.uris.length} URIs)`);continue}const T=Array.isArray(u.fileChanges)?u.fileChanges.filter(d=>h.includes(d.uri)):void 0,b=this.buildMemoryDelegatePrompt({type:u.type,uris:h,fileChanges:T});try{const d=Et("explore",[],ke(await this.buildAllocatableToolList())).patterns,w=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:xt,description:`Memory ${u.type} auto-delegate (${h.length} items)`,prompt:b,...d.length>0?{allowedTools:d}:{},workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const S of h)this.pendingMemorySubAgents.set(S,w);const M=new Set(h);t.subscribe(w,()=>{const S=t.getSubAgent(w);if(S&&(S.status==="completed"||S.status==="failed"||S.status==="cancelled")){const R=Date.now();for(const y of M)this.pendingMemorySubAgents.get(y)===w&&this.pendingMemorySubAgents.delete(y),this.memoryDelegateCooldownUntil.set(y,R+Le);for(const[y,A]of this.memoryDelegateCooldownUntil)A<=R&&this.memoryDelegateCooldownUntil.delete(y);m(`[ACodeRuntime] Memory delegate sub-agent ${w} finished (${S.status}), ${M.size} URI(s) entered ${Le}ms cooldown`)}});const C=u.type,$=async(S,R)=>this.recheckMemoryDelegate(C,h,S,R);await t.startWithRecheck(w,$,3),m(`[ACodeRuntime] Auto-delegated memory ${u.type} to sub-agent ${w} (${h.length} URIs, ${u.uris.length-h.length} already in progress)`)}catch(d){for(const w of h)this.pendingMemorySubAgents.delete(w);m(`[ACodeRuntime] Failed to auto-delegate memory ${u.type} (suppressed, will retry next poll): ${d instanceof Error?d.message:String(d)}`)}}else i.push(l)}if(a===0)return e;if(i.length===0)return null;const r={...n,directMessages:i};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,n){const c=this.config.subAgentManager;if(!c)return D("runtime.poll.no-subagent-manager","\u65E0 SubAgentManager\uFF0C\u76F4\u63A5\u8D70\u666E\u901A MCP \u8C03\u7528"),await this.callMcpToolWithTimeout(e,t,o,n,!0);const i=c.takeCompletedSubAgents();if(i.length>0)return m(`[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`),J.formatSubAgentCompletionAsPollResult(i);let a=!1,r=0;for(;;){r++,D("runtime.poll.round-start",`\u7B2C ${r} \u8F6E race \u5F00\u59CB: timeoutMs=${n} silent=${a}`);const l=new AbortController,u=c.waitForAnyCompletion(),p=a?{...o,_aws_silent_poll:!0}:o,g=Date.now(),_=this.callMcpToolWithTimeout(e,t,p,n,!0,l.signal);try{const h=await Promise.race([_.then(d=>({type:"mcp",result:d})),u.promise.then(d=>({type:"subagent",notif:d}))]);if(h.type==="subagent"){D("runtime.poll.race-winner-subagent",`\u5B50 agent \u5148\u5B8C\u6210\uFF0Cabort MCP \u8C03\u7528\uFF08\u5DF2\u7B49\u5F85 ${Date.now()-g}ms\uFF09\u540E\u8FD4\u56DE\u5408\u6210\u7ED3\u679C`),l.abort(),_.catch(()=>{});const d=c.takeCompletedSubAgents();return d.length===0&&d.push(h.notif),m(`[ACodeRuntime] poll_message: sub-agent ${h.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),J.formatSubAgentCompletionAsPollResult(d)}D("runtime.poll.mcp-returned",`MCP \u5148\u8FD4\u56DE\uFF08\u8017\u65F6 ${Date.now()-g}ms\uFF09\uFF0C\u68C0\u67E5\u5F85\u5408\u5E76\u7684\u5B50 agent \u5B8C\u6210`);const T=c.takeCompletedSubAgents();if(T.length>0){m(`[ACodeRuntime] poll_message: MCP returned, merging ${T.length} sub-agent completion(s)`);const d=J.mergeSubAgentCompletionsIntoMcpResult(h.result,T),w=await this.processMemoryAutoDelegates(d);if(D("runtime.poll.delegate-check",`\u5408\u5E76 ${T.length} \u4E2A\u5B50 agent \u5B8C\u6210\u540E\u59D4\u6258\u68C0\u67E5: processed=${w===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),w!==null){if(this.pollResultHasMessages(w))return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),w;D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),a=!0;continue}const b=await this.processMemoryAutoDelegates(h.result);if(D("runtime.poll.delegate-check",`\u59D4\u6258\u68C0\u67E5: processed=${b===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),b!==null){if(this.pollResultHasMessages(b)){const d=this.summarizePollResultForDebug(b);return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE poll \u7ED3\u679C\u7ED9 LLM: ${d}`),b}D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1Apoll \u7ED3\u679C\u65E0\u5B9E\u9645\u6D88\u606F\uFF08directMessages/groupMessages \u5747\u7A7A\uFF09\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),a=!0}catch(h){throw D("runtime.poll.error",`\u7B2C ${r} \u8F6E MCP \u8C03\u7528\u5F02\u5E38: ${h instanceof Error?h.message:String(h)}`),h}finally{u.cancel()}}}summarizePollResultForDebug(e){try{const t=U(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages:[],c=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${n.length}${n.length>0?JSON.stringify(n.map(i=>({id:i.msgId,ch:i.channel}))):""} gm=${c.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=U(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages.length:0,c=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return n>0||c>0}catch{return!0}}async waitForDelegateRepoll(){m(`[ACodeRuntime] poll_message: all messages delegated, waiting ${ae}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,ae);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((n,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 n=ye(e);{const i=e.slice(0,200);let a="unknown";try{const r=JSON.parse(e);r&&typeof r=="object"&&!Array.isArray(r)?a=`keys=[${Object.keys(r).join(",")}]`:Array.isArray(r)?a="array":a=typeof r}catch{a="non-json"}le({stage:"entry",toolCallId:t.slice(0,12),contentLen:e.length,topLevelShape:a,prefix:i})}if(!n.hasImages){let i=null;try{const a=JSON.parse(e);if(a&&typeof a=="object"&&!Array.isArray(a)){const r=[a.directMessages,a.groupMessages];i=[];for(const l of r)if(Array.isArray(l))for(const u of l){if(!u||typeof u!="object")continue;const p=u,g=typeof p.content=="string"?p.content:"",_={senderName:typeof p.senderName=="string"?p.senderName:"",msgId:typeof p.msgId=="string"?p.msgId:"",contentLen:g.length};let h=null;try{const T=JSON.parse(g);T&&typeof T=="object"&&!Array.isArray(T)&&(h=T)}catch{}h?(_.contentKind="json",_.hasAttachmentsField=Array.isArray(h.attachments),_.attachmentCount=Array.isArray(h.attachments)?h.attachments.length:0,_.attachmentKinds=Array.isArray(h.attachments)?h.attachments.map(T=>String(T.type??T.kind??"").toLowerCase()||"(empty)"):[],_.attachmentBase64Lens=Array.isArray(h.attachments)?h.attachments.map(T=>(typeof T.base64Data=="string"?T.base64Data:typeof T.base64=="string"?T.base64:typeof T.data=="string"?T.data:"").length):[]):(_.contentKind="non-json",_.contentPrefix=g.slice(0,60)),i.push(_)}}}catch{}le({stage:"hasImages_false",toolCallId:t.slice(0,12),contentLen:e.length,parsedContentKind:Array.isArray(n.content)?"parts":typeof n.content,partsCount:Array.isArray(n.content)?n.content.length:null,dmProbe:i});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."}),le({stage:"supportsImageInput_false",toolCallId:t.slice(0,12),providerSupportsImageInput:this.state.provider.supportsImageInput,partsCount:Array.isArray(n.content)?n.content.length:null}),this.cleanToolMessageAttachments(t,"[Tool result contained images; skipped because the current model does not support image input]");return}let c;try{c=await je(n.content)}catch(i){const a=i instanceof Error?i.message:String(i),r=Array.isArray(n.content)?n.content.filter(l=>l.type==="image_url").map(l=>{const u=l.image_url.url,p=u.indexOf(",");return{urlHead:u.slice(0,Math.min(30,u.length)),base64Len:p>=0?u.length-p-1:null,isDataUrl:/^data:image\//i.test(u)}}):null;le({stage:"materialize_threw",toolCallId:t.slice(0,12),errMessage:a,imagePartsCount:r?r.length:0,imageParts:r}),this.emitAcodeEvent("error",{message:`ACode skipped image content from tool result: ${a}`}),c=Array.isArray(n.content)?n.content.map(l=>l.type==="text"?l:{type:"text",text:`[Image omitted: ${a}]`}):n.content}this.isTurnSuperseded(o)||(this.state.conversation.push({role:"user",content:c}),this.cleanToolMessageAttachments(t,"[Tool result contained images; see user message above]"))}expandCommandsInPolledResult(e){const t=this.state.commandRegistry;if(!t||t.list().length===0)return e;let o;try{o=JSON.parse(e)}catch{return e}if(!v(o))return e;let n=!1;for(const c of["directMessages","groupMessages"]){const i=o[c];if(Array.isArray(i))for(const a of i){if(!v(a))continue;const r=N(a.content);if(!r)continue;const l=t.expand(r);l&&(a.content=l.prompt,n=!0)}}return n?JSON.stringify(o):e}cleanToolMessageAttachments(e,t){const o=this.state.conversation.find(c=>c.role==="tool"&&c.tool_call_id===e);if(!o||typeof o.content!="string")return;let n;try{const c=JSON.parse(o.content);if(typeof c=="object"&&c!==null){const i={...c};"attachments"in i&&delete i.attachments,co(i),n=JSON.stringify(i)}}catch{}if(n===void 0){const c=o.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();c!==o.content&&(n=c)}n!==void 0&&(o.content=n.length>0?n:t)}appendToolFailureResult(e,t,o){const n=ko(t,o);m(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${n.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${se(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,toolUseId:e.id,result:n,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:n})}filterSharedMcpConnectionsForSubAgent(e){const t=this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0?this.config.subAgentAllowedTools:null;return e.map(o=>({...o,tools:o.tools.filter(n=>t?Me(n,t):Nt.has(n.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[n,c]of Object.entries(e))try{const i=new ot({name:"acode",version:"0.1.0"}),a=this.createMcpTransport(c);await E(i.connect(a),t,`ACode MCP server ${n} connect`);const r={serverName:n,client:i,transport:a,tools:[]};i.setNotificationHandler(rt,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:l}=await E(i.listTools(),t,`ACode MCP server ${n} listTools`);r.tools=xe(n,l),o.push(r)}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${n}: ${i instanceof Error?i.message:String(i)}`})}return o}requestMcpToolsRefresh(e){const t=this.state.mcpConnections.filter(o=>!e||o.serverName===e);for(const o of t)this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs)}async refreshMcpConnectionTools(e,t){try{const{tools:n}=await E(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=xe(e.serverName,n)}catch(n){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${n instanceof Error?n.message:String(n)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(n=>!(n.kind==="mcp"&&n.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitExposedToolsStatus()}async recoverHiddenMcpTool(e){if(this.recoveredToolNames.has(e)||this.recoveredToolNames.size>=J.MAX_RECOVERY_ATTEMPTS)return!1;const t=this.state.mcpConnections.filter(o=>o.tools.some(n=>n.toolName==="expand_tools"));if(t.length===0)return!1;this.recoveredToolNames.add(e);try{await Promise.all(t.map(o=>this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs)))}catch{return!1}return this.state.exposedTools.some(o=>o.exposedName===e||o.toolName===e)}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");const o=new nt({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 st(new URL(e.url),{requestInit:t}):new it(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(n=>n.toolName==="get_profile"))try{const n=await E(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:re}),re,"ACode startup get_profile"),c=this.extractProfileFromToolResult(n);return xo(c)}catch(n){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${n instanceof Error?n.message:String(n)}`}),""}return""}extractProfileFromToolResult(e){if(!v(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(v(o)&&typeof o.text=="string"&&o.text.trim())try{const n=JSON.parse(o.text);if(v(n))return n}catch{}}return v(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1;return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1,await Promise.all(e.map(t=>te(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}J.SKILL_REFRESH_DEBOUNCE_MS=500,J.MAX_RECOVERY_ATTEMPTS=8;export{J as ACodeRuntime};
112
+ \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=B(e)}catch{return e}let s;try{s=JSON.parse(o)}catch{return e}const i=s.directMessages;if(!Array.isArray(i)||i.length===0)return e;const a=[];let r=0;for(const c of i){const u=c._acodeAutoDelegate;if(u&&(u.type==="memory_expiration"||u.type==="memory_file_change"||u.type==="memory_cleanup")){r++;const m=Date.now(),h=u.uris.filter(T=>this.pendingMemorySubAgents.has(T)).length,A=u.uris.filter(T=>{const y=this.memoryDelegateCooldownUntil.get(T);return y!==void 0&&m<y}).length,f=u.uris.filter(T=>{if(this.pendingMemorySubAgents.has(T))return!1;const y=this.memoryDelegateCooldownUntil.get(T);return!(y!==void 0&&m<y)});if(f.length===0){d(`[ACodeRuntime] Memory ${u.type} skipped: ${h} in-progress, ${A} in cooldown (total ${u.uris.length} URIs)`);continue}const p=Array.isArray(u.fileChanges)?u.fileChanges.filter(T=>f.includes(T.uri)):void 0,k=this.buildMemoryDelegatePrompt({type:u.type,uris:f,fileChanges:p});try{const T=Pt("explore",[],xe(await this.buildAllocatableToolList())).patterns,y=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:Nt,description:`Memory ${u.type} auto-delegate (${f.length} items)`,prompt:k,...T.length>0?{allowedTools:T}:{},workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const S of f)this.pendingMemorySubAgents.set(S,y);const _=new Set(f);t.subscribe(y,()=>{const S=t.getSubAgent(y);if(S&&(S.status==="completed"||S.status==="failed"||S.status==="cancelled")){const C=Date.now();for(const b of _)this.pendingMemorySubAgents.get(b)===y&&this.pendingMemorySubAgents.delete(b),this.memoryDelegateCooldownUntil.set(b,C+ze);for(const[b,M]of this.memoryDelegateCooldownUntil)M<=C&&this.memoryDelegateCooldownUntil.delete(b);d(`[ACodeRuntime] Memory delegate sub-agent ${y} finished (${S.status}), ${_.size} URI(s) entered ${ze}ms cooldown`)}});const R=u.type,x=async(S,C)=>this.recheckMemoryDelegate(R,f,S,C);await t.startWithRecheck(y,x,3),d(`[ACodeRuntime] Auto-delegated memory ${u.type} to sub-agent ${y} (${f.length} URIs, ${u.uris.length-f.length} already in progress)`)}catch(T){for(const y of f)this.pendingMemorySubAgents.delete(y);d(`[ACodeRuntime] Failed to auto-delegate memory ${u.type} (suppressed, will retry next poll): ${T instanceof Error?T.message:String(T)}`)}}else a.push(c)}if(r===0)return e;if(a.length===0)return null;const l={...s,directMessages:a};return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,s){const i=this.config.subAgentManager;if(!i)return P("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 a=i.takeCompletedSubAgents();if(a.length>0)return d(`[ACodeRuntime] poll_message: ${a.length} sub-agent(s) already completed, returning synthetic result`),P("runtime.poll.subagent-synthetic",`${a.length} \u4E2A\u5B50 agent \u5DF2\u5B8C\u6210\uFF0C\u76F4\u63A5\u8FD4\u56DE\u5408\u6210\u7ED3\u679C\uFF08\u4E0D\u8C03 MCP\uFF09`),K.formatSubAgentCompletionAsPollResult(a);let r=!1,l=0;for(;;){l++,P("runtime.poll.round-start",`\u7B2C ${l} \u8F6E race \u5F00\u59CB: timeoutMs=${s} silent=${r}`);const c=new AbortController,u=i.waitForAnyCompletion(),m=r?{...o,_aws_silent_poll:!0}:o,h=Date.now(),A=this.callMcpToolWithTimeout(e,t,m,s,!0,c.signal);try{const f=await Promise.race([A.then(T=>({type:"mcp",result:T})),u.promise.then(T=>({type:"subagent",notif:T}))]);if(f.type==="subagent"){P("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(),A.catch(()=>{});const T=i.takeCompletedSubAgents();return T.length===0&&T.push(f.notif),d(`[ACodeRuntime] poll_message: sub-agent ${f.notif.subId} completed during race, returning synthetic result (${T.length} notification(s))`),K.formatSubAgentCompletionAsPollResult(T)}P("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 p=i.takeCompletedSubAgents();if(p.length>0){d(`[ACodeRuntime] poll_message: MCP returned, merging ${p.length} sub-agent completion(s)`);const T=K.mergeSubAgentCompletionsIntoMcpResult(f.result,p),y=await this.processMemoryAutoDelegates(T);if(P("runtime.poll.delegate-check",`\u5408\u5E76 ${p.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 P("runtime.poll.final-return",`\u7B2C ${l} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),y;P("runtime.poll.empty-repoll",`\u7B2C ${l} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${re}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),r=!0;continue}const k=await this.processMemoryAutoDelegates(f.result);if(P("runtime.poll.delegate-check",`\u59D4\u6258\u68C0\u67E5: processed=${k===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),k!==null){if(this.pollResultHasMessages(k)){const T=this.summarizePollResultForDebug(k);return P("runtime.poll.final-return",`\u7B2C ${l} \u8F6E\uFF1A\u8FD4\u56DE poll \u7ED3\u679C\u7ED9 LLM: ${T}`),k}P("runtime.poll.empty-repoll",`\u7B2C ${l} \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(),r=!0}catch(f){throw P("runtime.poll.error",`\u7B2C ${l} \u8F6E MCP \u8C03\u7528\u5F02\u5E38: ${f instanceof Error?f.message:String(f)}`),f}finally{u.cancel()}}}summarizePollResultForDebug(e){try{const t=B(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages:[],i=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${s.length}${s.length>0?JSON.stringify(s.map(a=>({id:a.msgId,ch:a.channel}))):""} gm=${i.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=B(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,i=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||i>0}catch{return!0}}async waitForDelegateRepoll(){d(`[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,i)=>{t=()=>{i(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=Ce(e);{const a=e.slice(0,200);let r="unknown";try{const l=JSON.parse(e);l&&typeof l=="object"&&!Array.isArray(l)?r=`keys=[${Object.keys(l).join(",")}]`:Array.isArray(l)?r="array":r=typeof l}catch{r="non-json"}le({stage:"entry",toolCallId:t.slice(0,12),contentLen:e.length,topLevelShape:r,prefix:a})}if(!s.hasImages){let a=null;try{const r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r)){const l=[r.directMessages,r.groupMessages];a=[];for(const c of l)if(Array.isArray(c))for(const u of c){if(!u||typeof u!="object")continue;const m=u,h=typeof m.content=="string"?m.content:"",A={senderName:typeof m.senderName=="string"?m.senderName:"",msgId:typeof m.msgId=="string"?m.msgId:"",contentLen:h.length};let f=null;try{const p=JSON.parse(h);p&&typeof p=="object"&&!Array.isArray(p)&&(f=p)}catch{}f?(A.contentKind="json",A.hasAttachmentsField=Array.isArray(f.attachments),A.attachmentCount=Array.isArray(f.attachments)?f.attachments.length:0,A.attachmentKinds=Array.isArray(f.attachments)?f.attachments.map(p=>String(p.type??p.kind??"").toLowerCase()||"(empty)"):[],A.attachmentBase64Lens=Array.isArray(f.attachments)?f.attachments.map(p=>(typeof p.base64Data=="string"?p.base64Data:typeof p.base64=="string"?p.base64:typeof p.data=="string"?p.data:"").length):[]):(A.contentKind="non-json",A.contentPrefix=h.slice(0,60)),a.push(A)}}}catch{}le({stage:"hasImages_false",toolCallId:t.slice(0,12),contentLen:e.length,parsedContentKind:Array.isArray(s.content)?"parts":typeof s.content,partsCount:Array.isArray(s.content)?s.content.length:null,dmProbe:a});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."}),le({stage:"supportsImageInput_false",toolCallId:t.slice(0,12),providerSupportsImageInput:this.state.provider.supportsImageInput,partsCount:Array.isArray(s.content)?s.content.length:null}),this.cleanToolMessageAttachments(t,"[Tool result contained images; skipped because the current model does not support image input]");return}let i;try{i=await He(s.content)}catch(a){const r=a instanceof Error?a.message:String(a),l=Array.isArray(s.content)?s.content.filter(c=>c.type==="image_url").map(c=>{const u=c.image_url.url,m=u.indexOf(",");return{urlHead:u.slice(0,Math.min(30,u.length)),base64Len:m>=0?u.length-m-1:null,isDataUrl:/^data:image\//i.test(u)}}):null;le({stage:"materialize_threw",toolCallId:t.slice(0,12),errMessage:r,imagePartsCount:l?l.length:0,imageParts:l}),this.emitAcodeEvent("error",{message:`ACode skipped image content from tool result: ${r}`}),i=Array.isArray(s.content)?s.content.map(c=>c.type==="text"?c:{type:"text",text:`[Image omitted: ${r}]`}):s.content}this.isTurnSuperseded(o)||(this.state.conversation.push({role:"user",content:i}),this.cleanToolMessageAttachments(t,"[Tool result contained images; see user message above]"))}expandCommandsInPolledResult(e){const t=this.state.commandRegistry;if(!t||t.list().length===0)return e;let o;try{o=JSON.parse(e)}catch{return e}if(!$(o))return e;let s=!1;for(const i of["directMessages","groupMessages"]){const a=o[i];if(Array.isArray(a))for(const r of a){if(!$(r))continue;const l=I(r.content);if(!l)continue;const c=t.expand(l);c&&(r.content=c.prompt,s=!0)}}return s?JSON.stringify(o):e}cleanToolMessageAttachments(e,t){const o=this.state.conversation.find(i=>i.role==="tool"&&i.tool_call_id===e);if(!o||typeof o.content!="string")return;let s;try{const i=JSON.parse(o.content);if(typeof i=="object"&&i!==null){const a={...i};"attachments"in a&&delete a.attachments,fo(a),s=JSON.stringify(a)}}catch{}if(s===void 0){const i=o.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();i!==o.content&&(s=i)}s!==void 0&&(o.content=s.length>0?s:t)}appendToolFailureResult(e,t,o){const s=Oo(t,o);d(`[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}: ${ue(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,toolUseId:e.id,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?Ee(s,t):Ot.has(s.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[s,i]of Object.entries(e))try{const a=new nt({name:"acode",version:"0.1.0"}),r=this.createMcpTransport(i);await E(a.connect(r),t,`ACode MCP server ${s} connect`);const l={serverName:s,client:a,transport:r,tools:[]};a.setNotificationHandler(lt,()=>{this.refreshMcpConnectionTools(l,t)});const{tools:c}=await E(a.listTools(),t,`ACode MCP server ${s} listTools`);l.tools=Oe(s,c),o.push(l)}catch(a){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${s}: ${a instanceof Error?a.message:String(a)}`})}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 recoverHiddenMcpTool(e){if(this.recoveredToolNames.has(e)||this.recoveredToolNames.size>=Ht)return!1;this.recoveredToolNames.add(e);const t=this.state.mcpConnections.filter(o=>o.tools.some(s=>s.toolName==="expand_tools"||s.exposedName==="expand_tools"||s.exposedName.endsWith("__expand_tools")));if(t.length===0)return!1;for(const o of t)await this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs);return this.state.exposedTools.some(o=>o.toolName===e||o.exposedName===e)}async refreshMcpConnectionTools(e,t){try{const{tools:s}=await E(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Oe(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 rt({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 it(new URL(e.url),{requestInit:t}):new at(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"),i=this.extractProfileFromToolResult(s);return qo(i)}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(!$(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if($(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if($(s))return s}catch{}}return $(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=>X(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}K.SKILL_REFRESH_DEBOUNCE_MS=500;export{K as ACodeRuntime};
110
113