aws-runtime-bridge 1.9.151 → 1.9.153
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/dist/adapter/AcodeSdkAdapter.d.ts +27 -0
- package/dist/adapter/AcodeSdkAdapter.js +5 -5
- package/dist/adapter/types.d.ts +16 -0
- package/dist/desktop/built-in-desktop-tools.js +1 -1
- package/dist/routes/ltr.js +1 -1
- package/dist/routes/sessions.d.ts +87 -0
- package/dist/routes/sessions.js +1 -1
- package/dist/routes/terminal.js +20 -20
- package/dist/services/instance-features.d.ts +11 -1
- package/dist/services/instance-features.js +1 -1
- package/dist/utils/file-utils.d.ts +2 -0
- package/dist/utils/file-utils.js +2 -2
- package/package/acode/dist/capability-prompt.d.ts +16 -0
- package/package/acode/dist/capability-prompt.js +3 -0
- package/package/acode/dist/runtime.d.ts +6 -0
- package/package/acode/dist/runtime.js +23 -22
- package/package/acode/dist/types.d.ts +3 -0
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +28 -4
- package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +1 -1
- package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +24 -17
- package/package/aws-client-agent-mcp/dist/mcp-server.js +28 -28
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +20 -0
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +25 -8
- package/package/aws-client-agent-mcp/dist/tool-groups.d.ts +57 -0
- package/package/aws-client-agent-mcp/dist/tool-groups.js +3 -0
- package/package/aws-client-agent-mcp/dist/types.d.ts +23 -0
- package/package.json +1 -1
|
@@ -1,34 +1,35 @@
|
|
|
1
|
-
import{EventEmitter as Ve}from"node:events";import{randomUUID as Xe}from"node:crypto";import F from"node:fs";import Ze from"node:os";import H from"node:path";import{Client as et}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as tt}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as ot}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as st}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as nt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as it,DEFAULT_TOOL_PERMISSION_POLICY as Ae}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as rt,createAskUserQuestionTool as at}from"./ask-user-question-tool.js";import{createSkillTool as lt}from"./skill-tool.js";import{createTodoWriteTool as ct,createTodoReadTool as ut}from"./todo-tool.js";import{createSubAgentTools as mt}from"./sub-agent-tools.js";import{createAwaitCompleteTool as dt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as ht}from"./builtins/commandArtifacts.js";import{buildRuntimeEnvironmentPrompt as pt}from"./runtime-environment.js";import{backgroundCommandManager as X}from"./background-command-manager.js";import{createTerminalTool as ft}from"./terminal-tool.js";import{buildPluginPrompt as gt,createPluginTools as Tt}from"./plugin-tools.js";import{loadAcodeCommands as yt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as Ce}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as At,COMPACTION_LLM_PROMPT_TEMPLATE as Ct,conversationSizeKB as Z,estimateConversationTokens as se,performCompaction as _e,pruneToolOutputs as _t,summarizeConversation as be}from"./compaction.js";import{loadAcodeConfig as bt,loadAcodeSkillGroup as wt}from"./config.js";import{ACodeHookBus as $t,findDeniedHookResult as ue}from"./hooks/hookBus.js";import{isMcpPollingToolName as kt,isMcpBlockingToolName as St,getSemanticToolName as we}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as D}from"./meeting-debug-log.js";import{buildToolCatalog as $e,matchesToolAllocation as ke,mergeAllocatableTools as ne,PRESET_EXPLORE as Mt,rebindDefaultAgentId as Se,resolveToolAllocation as Rt,SUB_AGENT_ALLOWED_MCP_TOOLS as vt}from"./tool-allocation.js";function xt(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 Et(s){return s.type==="text"?{type:"text",text:s.text}:{type:"image_url",image_url:{url:s.image_url.url}}}function Nt(s){return{id:s.id,type:"function",function:{name:s.function.name,arguments:s.function.arguments}}}function Pt(s){const e={role:s.role,content:Array.isArray(s.content)?s.content.map(Et):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(Nt)),e}function me(s){return s.map(Pt)}function It(s,e){const t=q(s.prompt_cache_hit_tokens),o=q(s.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const n=q(s.cache_read_input_tokens),a=q(s.cache_creation_input_tokens);if(n!==void 0||a!==void 0){const c=q(s.input_tokens)??0;return{cacheHitTokens:n??0,cacheMissTokens:(a??0)+c}}const i=q(s.cache_hit_tokens),l=q(s.cache_miss_tokens);if(i!==void 0||l!==void 0)return{cacheHitTokens:i??0,cacheMissTokens:l??0};const r=q(s.prompt_tokens_details?.cached_tokens);if(r!==void 0){const c=e!==void 0?Math.max(0,e-r):0;return{cacheHitTokens:r,cacheMissTokens:c}}}function q(s){const e=typeof s=="number"?s:typeof s=="string"&&s.trim()?Number(s):NaN;if(!(!Number.isFinite(e)||e<0))return e}function Dt(s,e){if(!s)return e;const t=o=>{const n=e[o],a=s[o];return o==="prompt_tokens_details"?{...a,...n}:n??a};return{prompt_tokens:t("prompt_tokens"),completion_tokens:t("completion_tokens"),input_tokens:t("input_tokens"),output_tokens:t("output_tokens"),prompt_cache_hit_tokens:t("prompt_cache_hit_tokens"),prompt_cache_miss_tokens:t("prompt_cache_miss_tokens"),cache_read_input_tokens:t("cache_read_input_tokens"),cache_creation_input_tokens:t("cache_creation_input_tokens"),cache_hit_tokens:t("cache_hit_tokens"),cache_miss_tokens:t("cache_miss_tokens"),prompt_tokens_details:t("prompt_tokens_details")}}function Lt(){return new Date().toISOString()}function R(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function Me(s){return R(s)}function Re(s,e){return e.map(t=>({serverName:s,toolName:t.name,kind:"mcp",exposedName:$o(s,t.name),description:t.description,inputSchema:Me(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function N(s){return String(s??"").trim()||void 0}const ve=6e4,xe=30*6e4,Ee=6e4,Ne=6e4,ie=-1,Pe=ie,Ot=1e3,Ut=3e4,re=6e4,Ie=0,Bt=2147483647,qt=10*6e4+2e3,Ft=1e4,ae=5e3,De=10*60*1e3,K=10*1024*1024,Le=800*1024,le=process.env.ACODE_COMPACTION_DEBUG==="1",Oe=le?H.join(Ze.tmpdir(),"acode-compaction-debug.log"):"";function u(...s){le&&console.log(...s)}const zt=process.env.ACODE_TOKEN_DEBUG==="1";function G(...s){zt&&console.log("[TokenDebug][Runtime]",...s)}const jt=64e3;function de(s){const e=s.contextLimit&&s.contextLimit>0?s.contextLimit:jt,t=s.maxOutput&&s.maxOutput>0?s.maxOutput:8192,o=s.inputLimit&&s.inputLimit>0?s.inputLimit:void 0,n=At(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:n}}async function x(s,e,t,o){if(e<=0)return await s;let n;try{return await new Promise((a,i)=>{n=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),s.then(a,i)})}finally{n&&clearTimeout(n)}}async function ee(s,e,t,o=Ft){try{await x(e,o,s)}catch(n){t(n instanceof Error?n.message:String(n))}}function Q(s,e){if(s===0||s==="0")return 0;const t=typeof s=="number"?s:Number(s);return t===ie?ie:Number.isFinite(t)&&t>0?Math.floor(t):e}function te(s,e){const t=Q(s,e);return t>0?t:e}const Ue=3;function he(s){return s?Math.ceil(s.length/Ue):0}function Wt(s,e){let t=s.length;for(const o of e){const n=(o.kind==="mcp",o.toolName);if(t+=n.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const a=o;a.inputSchema&&(t+=JSON.stringify(a.inputSchema).length)}}return Math.ceil(t/Ue)}function Be(s){if(s.length===0)return 0;const e=JSON.stringify(Ke(s));return he(e)}async function Jt(s){await new Promise(e=>setTimeout(e,s))}function Ht(s){return typeof s=="boolean"}function Kt(s,e,t){if(Ht(t?.supportsImageInput))return t.supportsImageInput;const o=R(e)?e.models:void 0,n=R(o)?o[s]:void 0;if(!R(n))return!1;const a=n.modalities;return!R(a)||!Array.isArray(a.input)?!1:a.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function pe(s,e,t,o){if(s!==void 0)return s;if(!e)return;const n=e.models;if(R(n)){const a=n[t];if(R(a)){const i=a[o];if(i!==void 0)return i}}return e[o]}function Gt(s,e){const t=e.provider?.default,o=t?.options,n=s.model||t?.model||e.model||"acode-default",a=N(s.effort)||N(o?.effort)||N(t?.effort)||void 0;return{model:n,baseURL:N(o?.baseURL||o?.baseUrl),apiKey:N(o?.apiKey),effort:a,systemPrompt:s.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:te(o?.requestTimeoutMs??o?.timeoutMs,ve),requestTotalTimeoutMs:te(o?.requestTotalTimeoutMs,xe),requestRetryCount:Q(o?.requestRetryCount,Pe),requestFirstByteTimeoutMs:te(o?.requestFirstByteTimeoutMs,Ee),requestStreamIdleTimeoutMs:te(o?.requestStreamIdleTimeoutMs,Ne),mcpToolTimeoutMs:te(o?.mcpToolTimeoutMs,re),mcpPollingToolTimeoutMs:Q(o?.mcpPollingToolTimeoutMs,Ie),supportsImageInput:Kt(n,t,o),contextLimit:Q(pe(o?.contextLimit,t,n,"contextLimit"),0)||void 0,inputLimit:Q(pe(o?.inputLimit,t,n,"inputLimit"),0)||void 0,maxOutput:Q(pe(o?.maxOutput,t,n,"maxOutput"),0)||void 0}}function z(s,e){const t=e.replace(/\s+/g," ").trim();t&&s.push({type:"text",text:t})}function Qt(s,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${s||"image/png"};base64,${t}`}function Yt(s){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(s.trim())}function Vt(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 Xt(s){const e=await s.arrayBuffer();if(e.byteLength>K)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${K} bytes`);return Buffer.from(e).toString("base64")}async function Zt(s){const e=s.trim();if(Yt(e)){if(e.slice(e.indexOf(",")+1).length*.75>K)throw new Error(`ACode inline image exceeds the ${K} byte size limit`);return e}Vt(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 Xt(t)}`}function eo(s){const e=N(s.base64Data??s.base64??s.data);return e?e.length*.75>K?void 0:Qt(N(s.mediaType??s.mimeType)||"image/png",e):N(s.url??s.serverUrl)}function qe(s,e,t,o){return`[Attached file: ${[s?`name=${s}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(a=>!!a).join(", ")}]`}function to(s){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,n=0,a=e.exec(s);for(;a!==null;){z(t,s.slice(n,a.index));const i=a[1],l=(a[2]||"").trim();if(i==="\u56FE\u7247"&&l)t.push({type:"image_url",image_url:{url:l}}),o=!0;else if(i==="\u6587\u4EF6"&&l){const[r="",c="",m="",f=""]=l.split("|").map(g=>g.trim());z(t,qe(r,c,m,f))}else z(t,a[0]);n=a.index+a[0].length,a=e.exec(s)}return t.length===0?{content:s,hasImages:!1}:(z(t,s.slice(n)),{content:t,hasImages:o})}function oo(s,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const n of o)if(Array.isArray(n))for(const a of n){if(!R(a))continue;const i=N(a.content);if(!i)continue;const l=N(a.senderName);z(s,l?`Message from ${l}:`:"Message:");const r=fe(i);Array.isArray(r.content)?s.push(...r.content):z(s,r.content),t=t||r.hasImages}return t}function so(s){let e;try{e=JSON.parse(s)}catch{return}if(!R(e))return;const t=[];let o=oo(t,e);const n=N(e.text)||"",a=Array.isArray(e.attachments)?e.attachments:[];z(t,n);for(const i of a){if(!R(i))continue;const l=i;if(String(l.type??l.kind??"").toLowerCase()==="image"){const m=eo(l);m?(t.push({type:"image_url",image_url:{url:m}}),o=!0):N(l.base64Data??l.base64??l.data)&&z(t,`[Image attachment omitted: ${N(l.name)||"unnamed"} exceeds the ${K} byte inline limit]`);continue}const c=N(l.url??l.serverUrl)||"";z(t,qe(N(l.name)||"",c,N(l.mediaType??l.mimeType)||"",N(l.size)||""))}return t.length===0?{content:s,hasImages:!1}:{content:t,hasImages:o}}function fe(s){return so(s)??to(s)}async function Fe(s){if(!Array.isArray(s))return s;const e=[];for(const t of s){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await Zt(t.image_url.url)}})}return e}function no(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function io(s,e){const t=s.permissions??e.permissions??{},o=s.permissions?[]:e.allowedTools??[],n=s.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(a=>a.trim()).filter(Boolean),deny:[...t.deny??[],...n].map(a=>a.trim()).filter(Boolean)}}function ro(s,e){return s==="*"?!0:s.endsWith("*")?e.startsWith(s.slice(0,-1)):s===e}function ao(s){return s.kind==="builtin"?[s.exposedName,s.toolName,`builtin.${s.toolName}`]:[s.exposedName,s.toolName,`${s.serverName}.${s.toolName}`,`mcp.${s.serverName}.${s.toolName}`]}function ze(s,e){return ao(e).some(t=>ro(s,t))}function je(s,e,t){if(e.length>0&&!e.some(o=>ze(o,s)))throw new Error(t)}function ge(s,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>ze(o,s)))throw new Error(`ACode tool denied by permission rule: ${s.exposedName}`);je(s,e.allow,`ACode tool is not in allowed permission rules: ${s.exposedName}`),je(s,t??[],`ACode slash command does not allow tool: ${s.exposedName}`)}}function lo(s,e,t){try{return ge(s,e,t),!0}catch{return!1}}function ce(s){const e=s.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function co(s){try{const e=new URL(s);e.search="",e.hash="";const t=new URL(ce(e.toString()));return`${t.origin}${t.pathname}`}catch{return ce(s).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function uo(s){const e=[...s].reverse().find(o=>o.role==="user"),t=no(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function We(s){try{const e=JSON.parse(s);return Me(e)?e:{}}catch{return{}}}function mo(s,e,t){if(new Set([rt,"await_complete"]).has(s.toolName))return 0;if(s.toolName!=="Bash")return t;const n=e.timeout_ms??e.timeoutMs,a=typeof n=="number"?n:typeof n=="string"?Number(n):NaN;return!Number.isFinite(a)||a<=0?Math.max(t,qt):Math.min(Math.floor(a),10*6e4)+2e3}function ho(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(!R(s))return String(s??"");const e=s.content;if(Array.isArray(e)){const t=e.map(o=>R(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
|
|
2
|
-
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
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(`
|
|
5
6
|
|
|
6
|
-
`),
|
|
7
|
+
`),P=f=>f?.trim()?[{role:"system",content:f.trim()}]:[],Q=[this.config.rolePrompt,l].map(f=>f?.trim()).filter(f=>!!f).join(`
|
|
7
8
|
|
|
8
|
-
`),
|
|
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(`
|
|
9
10
|
|
|
10
|
-
`);this.initialConversation=
|
|
11
|
-
`,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;u(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${t}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const o=this.submitQueue.then(()=>(u(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmitGuarded(e,t)));return this.submitQueue=o.catch(()=>{u("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),u("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}executeSubmitGuarded(e,t){const o={};this.activeTurnToken=o;const n=this.executeSubmit(e,t),a=new Promise(i=>{this.forceSettleWaiters.set(o,i)});return n.finally(()=>{this.forceSettleWaiters.delete(o),this.activeTurnToken===o&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([n,a])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=No();this.abortForceSettleTimer=setTimeout(()=>{this.abortForceSettleTimer=null,this.activeTurn&&this.activeTurnToken===e&&this.forceSettleActiveTurn(`turn still unsettled ${t}ms after abort()`)},t),typeof this.abortForceSettleTimer.unref=="function"&&this.abortForceSettleTimer.unref()}forceSettleActiveTurn(e){const t=this.activeTurnToken;console.error(`[ACodeRuntime] \u{1F6A8} FORCE SETTLE: active turn ignored abort() (${e}). Force-settling to unblock submitQueue; late executeSubmit continuation will be superseded.`),this.contextVersion+=1,this.activeTurn=!1,this.abortRequested=!1,this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.emitAcodeEvent("error",{message:`ACode turn force-settled: ${e}`}),this.emitAcodeEvent("turn_complete",{failed:!0});const o=t?this.forceSettleWaiters.get(t):void 0;t&&this.forceSettleWaiters.delete(t),this.activeTurnToken=null,o?.()}notifyForceMessage(){this.forceMessagePending=!0,u("[ACodeRuntime] \u{1F514} Force message pending flag set")}addBuiltInTools(e){if(!this.state||!this.exposedToolsInitialized||!Array.isArray(e))return 0;const t=new Set(this.state.exposedTools.map(n=>n.exposedName)),o=[];for(const n of e)xt(n)&&(t.has(n.exposedName)||(t.add(n.exposedName),o.push(n)));return o.length===0?0:(this.state.exposedTools=[...this.state.exposedTools,...o],this.emitExposedToolsStatus(),o.length)}removeBuiltInToolsByPrefix(e){if(!this.state||!this.exposedToolsInitialized||!e)return 0;const t=this.state.exposedTools.length;this.state.exposedTools=this.state.exposedTools.filter(n=>!n.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}addPluginCommands(e){if(!this.state||e.length===0)return;this.state.commandRegistry.addCommands(e);const t=new Set(this.state.commands.map(o=>o.name));this.state.commands=[...this.state.commands,...e.filter(o=>!t.has(o.name))]}emitExposedToolsStatus(){this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(e=>e.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(e=>({name:e.exposedName,source:e.kind==="mcp"?`${e.serverName}.${e.toolName}`:`builtin.${e.toolName}`,description:e.description||""}))})}async injectForceMessage(){if(!this.forceMessagePending)return!1;this.forceMessagePending=!1;const e=this.state.mcpConnections.find(t=>t.tools.some(o=>o.toolName==="get_message"));if(!e)return u("[ACodeRuntime] injectForceMessage: no connection with get_message found"),!1;try{const t=await x(e.client.callTool({name:"get_message",arguments:{_aws_force_inject:!0}},void 0,{timeout:1e4}),1e4,"injectForceMessage get_message"),o=U(t);let n=[];try{const r=JSON.parse(o);Array.isArray(r?.directMessages)&&(n=r.directMessages.filter(c=>c?.force===!0))}catch{return!1}if(n.length===0)return!1;const a=JSON.stringify({directMessages:n,groupMessages:[]}),i=`forced_get_msg_${Date.now()}`,l=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:i,type:"function",function:{name:l,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:i,content:a}),u(`[ACodeRuntime] injectForceMessage: injected ${n.length} force message(s) into conversation`),!0}catch(t){return u(`[ACodeRuntime] injectForceMessage failed: ${t}`),!1}}async resetContext(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");this.contextVersion+=1,this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.state.conversation=me(this.initialConversation),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t){const o=Date.now();if(u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),u("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),u(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),u(`[ACodeRuntime] \u{1F522} Context version: ${t}`),u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const n=this.activeTurnToken,a=e.trim();let i=!1;try{u("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const l=Date.now(),r=await this.hookBus.dispatch("UserPromptSubmit",{prompt:a}),c=Date.now()-l;if(u(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${c}ms, results: ${r.length}`),this.isTurnSuperseded(t)){u("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const m=ue(r);if(m){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${m.message}`),this.emitAcodeEvent("error",{message:m.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}u("[ACodeRuntime] \u{1F50D} Expanding command if any...");const f=this.state.commandRegistry.expand(a),g=f?.prompt.trim()||a,k=f?.command.allowedTools;if(f){u(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${f.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:f.command.name,arguments:f.argumentsText,sourcePath:f.command.sourcePath});const C=f.command.plugin;C&&(u(`[ACodeRuntime] \u{1F4CB} Slash command belongs to plugin: ${C}`),this.config.pluginBridge?.exposePlugin?.(C))}if(!this.state.provider.baseURL){u("[ACodeRuntime] \u26A0\uFE0F No provider baseURL configured, using fallback response");const C=ho(g,this.state);this.emitAcodeEvent("assistant_delta",{text:C}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:C.length}}),i=!0,u("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}u("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const T=fe(g);if(T.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");u("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const b=await Fe(T.content);if(this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}u("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:b}),u(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),u("[ACodeRuntime] Starting runModelTurn...");const _=Date.now(),d=await this.runModelTurn(k,t),A=Date.now()-_;if(u(`[ACodeRuntime] \u2705 runModelTurn completed in ${A}ms`),u(`[ACodeRuntime] \u{1F4DD} Result: text=${d.text?d.text.slice(0,80)+(d.text.length>80?"...":""):"(empty)"}, finishReason=${d.finishReason||"(none)"}`),this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}d.text&&!this.state.provider.stream&&(u("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:d.text})),u("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length},...d.responseBody?{responseBody:d.responseBody}:{},...d.finishReason?{finishReason:d.finishReason}:{}}),G(`turn_complete emitted: usage=${JSON.stringify(d.usage??{inputTokens:g.length,outputTokens:d.totalOutputTextLength??d.text.length})} (providerUsage=${d.usage?"real":"FALLBACK-text-length"}) textLength=${d.text.length} totalOutputTextLength=${d.totalOutputTextLength}`),u(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(d.usage?"":" (estimated, no provider usage)")),i=!0;const M=Date.now()-o;u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),u(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${M}ms`),u("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(l){const r=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${r}ms:`,l instanceof Error?l.message:String(l)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",l instanceof Error?l.stack:"(no stack)"),this.isTurnSuperseded(t)){u("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){u("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),i=!0;return}u("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:l instanceof Error?l.message:String(l)}),this.emitAcodeEvent("turn_complete",{failed:!0}),i=!0}finally{const l=Date.now()-o;u(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${l}ms`),u(`[ACodeRuntime] \u{1F50D} turnCompleted=${i}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===n&&(this.activeTurn=!1,this.abortRequested=!1),!i&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${l}ms. This indicates a code path that should have emitted turn_complete but didn't. Forcing failed turn_complete to prevent state stuck.`),this.emitAcodeEvent("error",{message:"ACode turn completed without proper completion event (internal error)"}),this.emitAcodeEvent("turn_complete",{failed:!0}),u("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(u(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.armAbortForceSettle()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,n)=>{this.questionWaiters.set(e,{resolve:o,reject:n,contextVersion:t})})}}async buildAllocatableToolList(){const e=this.state?.exposedTools??[],t=this.config.subAgentSuiteTools??[];let o=[];if(this.config.subAgentSuiteToolProvider)try{o=await this.config.subAgentSuiteToolProvider([])}catch{o=[]}return ne(e,ne(t,o))}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,n=this.config.workingDirectory,a=this.config;return{spawnSubAgent:async i=>{let l=this.config.subAgentSuiteTools;if(i.allowedTools&&i.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const c=await this.config.subAgentSuiteToolProvider(i.allowedTools);c.length>0&&(l=l?ne(l,c):c)}catch{}const r=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,...i.allowedTools&&i.allowedTools.length>0?{allowedTools:i.allowedTools}:{},workingDirectory:n,parentConfig:{...a,sharedMcpConnections:this.state?.mcpConnections,...l&&l.length>0?{subAgentSuiteTools:l}:{}}});return await e.start(r),{subId:r}},listSubAgentToolCatalog:async()=>$e(await this.buildAllocatableToolList()),listSubAgents:async()=>{const i=e.listByParent(t),l=[],r=[];for(const c of i){const m={subId:c.subId,subagentType:c.subagentType,description:c.description,status:c.status,startedAt:c.startedAt,endedAt:c.endedAt,durationMs:c.durationMs};c.status==="pending"||c.status==="running"?l.push(m):r.push(m)}return r.sort((c,m)=>(m.endedAt??0)-(c.endedAt??0)),{running:l,history:r}},getSubAgentStatus:async i=>{const l=e.getSubAgent(i);return l?{subId:l.subId,subagentType:l.subagentType,description:l.description,status:l.status,startedAt:l.startedAt,endedAt:l.endedAt,durationMs:l.durationMs,prompt:l.prompt,result:l.result,errorMessage:l.errorMessage,contextSnapshot:l.contextSnapshot}:null},awaitSubAgents:async(i,l)=>{const r=new Set;for(const c of i)this.pendingAwaitedSubIds.add(c),r.add(c);try{return await e.awaitCompletion(i,l)}finally{for(const c of r)this.pendingAwaitedSubIds.delete(c)}},abortSubAgent:i=>e.abort(i)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,n)=>{for(const a of o)this.pendingAwaitedSubIds.add(a);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,n)}finally{for(const a of o)this.pendingAwaitedSubIds.delete(a)}}:null,awaitBgCommands:(o,n)=>{for(const a of o)this.pendingAwaitedBgTaskIds.add(a);try{return X.awaitCompletion(e,o,n)}finally{for(const a of o)this.pendingAwaitedBgTaskIds.delete(a)}}}}submitQuestionAnswer(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}createToolPermissionController(){return{getLevel:e=>this.state.toolPermissionPolicy[e]??"allow",requestPermission:(e,t)=>this.requestToolPermission(e,t)}}requestToolPermission(e,t){const o=Xe();return new Promise(n=>{this.permissionWaiters.set(o,{capability:e,detail:t,resolve:n}),this.emitAcodeEvent("tool_permission_request",{requestId:o,capability:e,agentId:this.config.agentId,...t})})}submitToolPermissionDecision(e,t){const o=this.permissionWaiters.get(e);return o?(this.permissionWaiters.delete(e),o.resolve(t),!0):!1}rejectAllPermissionWaiters(e){if(this.permissionWaiters.size!==0){for(const[,t]of this.permissionWaiters)t.resolve(!1);this.permissionWaiters.clear(),D("tool-permission",`waiters rejected: ${e}`)}}setToolPermissionPolicy(e){this.state.toolPermissionPolicy={...this.state.toolPermissionPolicy,...e}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);u(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(n=>{u(`[ACodeRuntime] \u26A0\uFE0F manager.abort(${o}) threw: ${n instanceof Error?n.message:String(n)}`)})}cancelPendingAwaitedBgTasks(){if(this.pendingAwaitedBgTaskIds.size===0)return;const e=this.config.agentId??"unknown",t=Array.from(this.pendingAwaitedBgTaskIds);u(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),X.interruptAwaits(e,t)}detachCurrentToolExecution(){const e=this.toolSettleSlot;return!e||!e.settlable||e.settled?!1:(e.settled=!0,e.resolveSettle?.(),u(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${e.toolName} (toolCallId=${e.toolCallId}) to background`),!0)}beginToolSettle(e,t,o){const n=e.toolName==="Bash",a=++this.toolSettleSeq;let i;const l=n?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:a,toolName:e.toolName,toolCallId:o,settlable:n,settled:!1,resolveSettle:i??null},{seq:a,signal:l}}clearToolSettle(e){this.toolSettleSlot?.seq===e&&(this.toolSettleSlot=null)}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.armAbortForceSettle(),this.rejectAllQuestionWaiters("session terminated"),this.rejectAllPermissionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await ee("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await ee("ACode background commands shutdown",X.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),ee("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await ee("ACode Stop hooks",this.hookBus.dispatch("Stop",{reason:"session_stop"}),t=>{this.emitAcodeEvent("error",{message:t})}),this.state.terminated=!0,this.sessionCompleteEmitted||(this.sessionCompleteEmitted=!0,this.emitAcodeEvent("session_complete",{exitCode:0})),this.stopCompactionDebugLog(),this.stopSkillWatchers(),le)try{F.promises.appendFile(Oe,`[${new Date().toISOString()}] runtime stopped | ---
|
|
12
|
-
`,"utf-8").catch(()=>{})}catch{}}discoverPluginCommandDirs(){const e=this.config.pluginsDir;if(!e)return[];let t;try{t=
|
|
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).
|
|
13
14
|
|
|
14
15
|
--- Conversation Start ---
|
|
15
16
|
${e.conversationText}
|
|
16
17
|
--- Conversation End ---
|
|
17
18
|
|
|
18
|
-
`+Ct}]},i=new AbortController;this.abortController=i;let l=!1;try{return await x((async()=>{const r=await x(fetch(ce(o),{method:"POST",headers:n,body:JSON.stringify(a),signal:i.signal}),t.requestTotalTimeoutMs,"ACode LLM summarization",()=>{l=!0,i.abort()});if(!r.ok){const f=await x(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{l=!0,i.abort()}),g=f.length>500?`${f.slice(0,500)}...(truncated, total ${f.length} chars)`:f;throw new Error(`ACode LLM summarization request failed: ${r.status} ${g}`)}const m=(await x(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{l=!0,i.abort()})).choices?.[0]?.message?.content;if(!m||m.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return m})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{i.abort()})}catch(r){throw r instanceof Error&&r.name==="AbortError"?l?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):r}finally{this.abortController===i&&(this.abortController=null)}}async requestChatCompletion(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured");const{contextLimit:n,maxOutput:a,inputLimit:i,threshold:l}=de(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,c=se(this.state.conversation)+Be(this.state.exposedTools),m=Math.max(r,c),f=m>=l;if(u(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${c}, effectiveUsed=${m}, contextLimit=${n}, inputLimit=${i??"n/a"}, maxOutput=${a}, triggerThreshold=${l}, shouldCompact=${f}`),f){const p=Z(this.state.conversation),y=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:y,sizeKB:p,estimatedTokens:c,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:r>=l?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(y,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${m} tokens, \u9608\u503C: ${l}, \u89E6\u53D1: ${r>=l?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const v=await _e(this.state.conversation,n,a,{llmSummarizer:$=>this.summarizeConversationWithLLM($),onPhase:$=>this.handleCompactionPhase(y,$),actualUsedTokens:m}),P=Z(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:y,sizeBeforeKB:p,sizeAfterKB:P,freedKB:Math.round((p-P)*10)/10,strategy:v.strategy,freedTokens:v.freedTokens,tokensBefore:v.tokensBefore,tokensAfter:v.tokensAfter,prunedToolMessages:v.prunedToolMessages,summarizedMessages:v.summarizedMessages,messageCountBefore:v.messageCountBefore,messageCountAfter:v.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const g=await fo(this.state.conversation,Le,n,a,p=>this.summarizeConversationWithLLM(p));g>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${g} older messages to fit within ${Le} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const k=this.state.exposedTools.filter(p=>lo(p,this.state.permissions,e)),T=()=>{const p={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(p.reasoning_effort=t.effort),t.stream&&(p.stream_options={include_usage:!0}),k.length>0&&(p.tools=Ke(k),p.tool_choice="auto"),p},b="POST",_=co(o),d=ko(t),A=So(d),M=p=>{const y=JSON.stringify(p,null,2);u(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${_}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:_,requestMethod:b,requestUrl:_,requestHeaders:A,stream:t.stream,messageCount:this.state.conversation.length,toolCount:k.length,lastUserMessagePreview:uo(this.state.conversation),estimatedContextTokens:he(y),requestBody:y,...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),G(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${k.length} estimatedContextTokens=${he(y)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let C=T();M(C);const S=t.requestRetryCount===ie,w=S?1/0:t.requestRetryCount+1;let E=!1;for(let p=1;S||p<=w;p+=1){this.state.terminated||(this.abortRequested=!1),p>1&&M(C);const y=new AbortController;this.abortController=y;let v=!1;try{return await x((async()=>{const P=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,$=await x(fetch(ce(o),{method:b,headers:d,body:JSON.stringify(C),signal:y.signal}),P,"ACode provider request",()=>{v=!0,y.abort()});if(!$.ok){const O=await x($.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{v=!0,y.abort()}),W=O.length>500?`${O.slice(0,500)}...(truncated, total ${O.length} chars)`:O;throw new Error(`ACode provider request failed: ${$.status} ${W}`)}const L=$.headers?.get?.("content-type")||"";if(t.stream&&L.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream($,t.requestStreamIdleTimeoutMs,y,t.requestFirstByteTimeoutMs);const j=await x($.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{v=!0,y.abort()});return R(j)?j:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof j}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{y.abort()})}catch(P){let $;if(P instanceof Error&&P.name==="AbortError"?v?$=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?$=new Error("ACode provider request aborted by user"):$=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):$=P instanceof Error?P:new Error(String(P)),!E&&!this.abortRequested&&!this.state.terminated&&Je($)){const W=Z(this.state.conversation),J=se(this.state.conversation),V=this.state.conversation.length,I=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:I,sizeKB:W,estimatedTokens:J,messageCount:V,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(I,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${V}\u6761, \u5927\u5C0F: ${W}KB`),this.emitCompactionPhase(I,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const h=_t(this.state.conversation,n);this.emitCompactionPhase(I,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${h.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${h.freedTokens} tokens`),this.emitCompactionPhase(I,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const B=await be(this.state.conversation,{llmSummarizer:Ye=>this.summarizeConversationWithLLM(Ye),contextLimit:n});this.emitCompactionPhase(I,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${B} \u6761\u6D88\u606F`);const Te=Z(this.state.conversation),Ge=se(this.state.conversation),Qe=this.state.conversation.length;E=!0;const ye=h.prunedCount+B;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:I,sizeBeforeKB:W,sizeAfterKB:Te,freedKB:Math.round((W-Te)*10)/10,tokensBefore:J,tokensAfter:Ge,messageCountBefore:V,messageCountAfter:Qe,strategy:B>0?"summarize":"prune",freedTokens:h.freedTokens,prunedToolMessages:h.prunedCount,summarizedMessages:B,trigger:"provider_overflow_error"}),ye===0)throw $;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${ye} older messages and rebuilt the request instead of retrying the same oversized payload`}),C=T(),M(C),p-=1;continue}if(!((S||p<w)&&!this.abortRequested&&!this.state.terminated&&go($)))throw $;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${p}${S?"":`/${w}`} failed; retrying: ${$.message}`,nonFatal:!0});const j=Math.min(Ut,Ot*Math.pow(2,p-1)),O=Math.random()*1e3;await Jt(j+O)}finally{this.abortController===y&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,n){if(!e.body)throw new Error("ACode provider stream response has no body");const a=e.body.getReader(),i=new TextDecoder,l=new Map;let r="",c="",m;const f=k=>{for(const T of vo(k)){if(T==="[DONE]")continue;const b=JSON.parse(T);if(!R(b))continue;const _=b.usage;_&&(m=Dt(m,_),G(`stream usage chunk received: ${JSON.stringify(_)} -> merged: ${JSON.stringify(m)}`));const A=b.choices?.[0]?.delta,M=Co(A);M&&this.emitAcodeEvent("thinking_delta",{text:M});const C=typeof A?.content=="string"?A.content:"";C&&(r+=C,this.emitAcodeEvent("assistant_delta",{text:C}));const S=Array.isArray(A?.tool_calls)?A.tool_calls:[];for(const w of S)xo(l,w)}};let g=!0;for(;;){const k=g&&n?n:t,{done:T,value:b}=await x(a.read(),k,g?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(g=!1,T)break;c+=i.decode(b,{stream:!0});const _=c.split(/\r?\n\r?\n/);c=_.pop()??"";for(const d of _)f(d)}return c+=i.decode(),c.trim()&&f(c),{choices:[{message:{content:r||null,tool_calls:Eo(l)}}],...m?{usage:m}:{}}}async handleToolCalls(e,t,o=this.contextVersion){u(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const n=i=>we(i.function.name)==="poll_message",a=[...e.filter(i=>!n(i)),...e.filter(i=>n(i))];e.length>1&&a.some((i,l)=>i!==e[l])&&u(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${a.map(i=>i.function.name).join(", ")}`);for(const i of a){if(this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const l=i.function.name;u(`[ACodeRuntime] \u{1F50D} Looking up tool: ${l}`);let r=this.state.exposedTools.find(c=>c.exposedName===l);if(r||(r=this.state.exposedTools.find(c=>c.toolName===l),r&&u(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${l} -> ${r.exposedName}`)),!r){console.error(`[ACodeRuntime] \u274C Tool not found: ${l}, available tools: ${this.state.exposedTools.map(c=>c.exposedName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP tool not found: ${l}`});continue}u(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const C=We(i.function.arguments);u(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(C).slice(0,200)}`),ge(r,this.state.permissions,t);const S=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:C});if(this.isTurnSuperseded(o))return;const w=ue(S);if(w)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${w.message}`),new Error(w.message||`ACode tool denied by hook: ${r.exposedName}`);u(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:C,argumentsPreview:He(C)});const E=Date.now(),p=mo(r,C,this.state.provider.mcpToolTimeoutMs);u(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${p}ms, abortRequested: ${this.abortRequested})`),p<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${p})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const y=this.beginToolSettle(r,C,i.id);try{const v=await x(r.execute(C,{onOutput:L=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:L.stream,text:L.text,sequence:L.sequence,cwd:L.cwd,commandLineCount:L.commandLineCount,...L.commandFilePath?{commandFilePath:L.commandFilePath}:{}})},toolCallId:i.id,...y.signal?{settleSignal:y.signal}:{}}),p,`ACode built-in tool ${r.toolName}`),P=Date.now()-E;if(u(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${P}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,result:U(v)}),this.isTurnSuperseded(o)))return;const $=U(v);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${$.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,toolUseId:i.id,result:$}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:$}),await this.appendSyntheticMultimodalUserMessage($,i.id,o)}finally{this.clearToolSettle(y.seq)}continue}const c=this.state.mcpConnections.find(C=>C.serverName===r.serverName);if(!c){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(C=>C.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const m=We(i.function.arguments);u(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(m).slice(0,200)}`),ge(r,this.state.permissions,t);const f=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:m});if(this.isTurnSuperseded(o))return;const g=ue(f);if(g)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${g.message}`),new Error(g.message||`ACode tool denied by hook: ${r.exposedName}`);u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.serverName,tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:m,argumentsPreview:He(m)});const k=kt(r.toolName),T=St(r.toolName),b=k?this.state.provider.mcpPollingToolTimeoutMs:T?0:this.state.provider.mcpToolTimeoutMs,_=Date.now();u(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${b}ms, polling: ${k})`);const d=k&&we(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(c,r,m,b):await this.callMcpToolWithTimeout(c,r,m,b,k),A=Date.now()-_;if(u(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${A}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:U(d)}),this.isTurnSuperseded(o)))return;let M=U(d);k&&(M=this.expandCommandsInPolledResult(M)),u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${M.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,toolUseId:i.id,result:M}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:M}),await this.appendSyntheticMultimodalUserMessage(M,i.id,o)}catch(c){const m=c instanceof Error&&c.message.includes("timed out after"),f=c instanceof Error&&c.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${m}, isAbortError=${f}`,c instanceof Error?c.message:String(c)),this.isTurnSuperseded(o)){u("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw u(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),u(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,toolUseId:i.id,result:`[aborted] ${c instanceof Error?c.message:String(c)}`,failed:!0,aborted:!0}),c instanceof Error?c:new Error(String(c));u(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${m})`),this.appendToolFailureResult(i,r,c)}}u(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,n,a,i){const l=n>0?n:Bt,c=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const m=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await x(Promise.race([e.client.callTool({name:t.toolName,arguments:c},void 0,{timeout:l,...i?{signal:i}:{}}),m.promise]),n,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(f){if(i?.aborted||!a||n>0||!To(f))throw f;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{m.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const n=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
|
|
19
|
+
`+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}
|
|
19
20
|
Error: ${o.error}`:`Sub-agent ${o.subId} [${o.status}]: ${o.description}
|
|
20
|
-
Output: ${o.output.length>500?o.output.slice(0,500)+"... (truncated)":o.output}`;return{msgId:`subagent-completion-${o.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content: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(
|
|
21
|
-
Error: ${
|
|
22
|
-
Output: ${
|
|
23
|
-
`);return
|
|
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
|
|
24
25
|
${n}
|
|
25
26
|
|
|
26
|
-
\u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],n=Date.now();if(await Promise.all(t.map(async i=>{const
|
|
27
|
-
`);return
|
|
28
|
-
${
|
|
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}
|
|
29
30
|
|
|
30
|
-
\u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const
|
|
31
|
-
`);return
|
|
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
|
|
32
33
|
${i}
|
|
33
34
|
|
|
34
35
|
\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(`
|
|
@@ -83,11 +84,11 @@ ${t}
|
|
|
83
84
|
\u5B8C\u6210\u540E\u7CFB\u7EDF\u4F1A\u901A\u8FC7\u67E5\u8BE2\u670D\u52A1\u7AEF\u771F\u5B9E\u72B6\u6001\u8FDB\u884C\u4E8C\u6B21\u9A8C\u8BC1\uFF08\u4E0D\u4F9D\u8D56\u4F60\u7684\u81EA\u62A5\u7ED3\u679C\uFF09\u3002\u82E5\u9A8C\u8BC1\u53D1\u73B0\u4ECD\u6709\u7C7B\u578B/\u57DF\u8D85\u8FC7\u5BB9\u91CF\u4E0A\u9650\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`:`\u4F60\u662F\u4E00\u6761\u4E13\u95E8\u5904\u7406\u6C38\u4E45\u8BB0\u5FC6\u6587\u4EF6\u53D8\u66F4\u66F4\u65B0\u7684\u5B50 agent\u3002
|
|
84
85
|
|
|
85
86
|
\u4EE5\u4E0B ${e.uris.length} \u4E2A\u6C38\u4E45\u8BB0\u5FC6\u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D1\u751F\u53D8\u66F4\uFF1A
|
|
86
|
-
${e.uris.map(o=>{const n=e.fileChanges?.find(r=>r.uri===o);if(!n)return`- ${o}`;const
|
|
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(`
|
|
87
88
|
`):n.boundFiles&&n.boundFiles.length>0?n.boundFiles.map(r=>` \xB7 ${r}`).join(`
|
|
88
89
|
`):" \u65E0\uFF08\u8BF7\u901A\u8FC7 read_memory \u67E5\u770B bound_files\uFF09";return`- ${o}
|
|
89
90
|
- \u7ED1\u5B9A\u6587\u4EF6:
|
|
90
|
-
${
|
|
91
|
+
${a}`}).join(`
|
|
91
92
|
`)}
|
|
92
93
|
|
|
93
94
|
\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
|
|
@@ -105,5 +106,5 @@ ${l}`}).join(`
|
|
|
105
106
|
- \u2705 \u82E5\u5168\u90E8 memory_status \u4E3A "normal"\uFF1A\u9759\u9ED8\u7ED3\u675F
|
|
106
107
|
|
|
107
108
|
\u6CE8\u610F\uFF1A\u4F60\u8FD0\u884C\u5728\u72EC\u7ACB\u7684\u4E0A\u4E0B\u6587\u7A97\u53E3\u4E2D\uFF0C\u4E0D\u5F71\u54CD\u4E3B agent \u7684\u4E3B\u7EBF\u4EFB\u52A1\u3002\u8BF7\u9AD8\u6548\u5B8C\u6210\uFF0C\u4E0D\u8981\u8BE2\u95EE\u7528\u6237\u3002
|
|
108
|
-
\u5B8C\u6210\u540E\u7CFB\u7EDF\u4F1A\u901A\u8FC7\u67E5\u8BE2\u670D\u52A1\u7AEF\u771F\u5B9E\u72B6\u6001\u8FDB\u884C\u4E8C\u6B21\u9A8C\u8BC1\uFF08\u4E0D\u4F9D\u8D56\u4F60\u7684\u81EA\u62A5\u7ED3\u679C\uFF09\u3002\u82E5\u9A8C\u8BC1\u53D1\u73B0\u4ECD\u6709 memory \u7684 memory_status \u4E3A "updating"\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`}async processMemoryAutoDelegates(e){const t=this.config.subAgentManager;if(!t)return e;let o;try{o=U(e)}catch{return e}let n;try{n=JSON.parse(o)}catch{return e}const a=n.directMessages;if(!Array.isArray(a)||a.length===0)return e;const i=[];let l=0;for(const c of a){const m=c._acodeAutoDelegate;if(m&&(m.type==="memory_expiration"||m.type==="memory_file_change"||m.type==="memory_cleanup")){l++;const f=Date.now(),g=m.uris.filter(d=>this.pendingMemorySubAgents.has(d)).length,k=m.uris.filter(d=>{const A=this.memoryDelegateCooldownUntil.get(d);return A!==void 0&&f<A}).length,T=m.uris.filter(d=>{if(this.pendingMemorySubAgents.has(d))return!1;const A=this.memoryDelegateCooldownUntil.get(d);return!(A!==void 0&&f<A)});if(T.length===0){u(`[ACodeRuntime] Memory ${m.type} skipped: ${g} in-progress, ${k} in cooldown (total ${m.uris.length} URIs)`);continue}const b=Array.isArray(m.fileChanges)?m.fileChanges.filter(d=>T.includes(d.uri)):void 0,_=this.buildMemoryDelegatePrompt({type:m.type,uris:T,fileChanges:b});try{const d=Rt("explore",[],$e(await this.buildAllocatableToolList())).patterns,A=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:Mt,description:`Memory ${m.type} auto-delegate (${T.length} items)`,prompt:_,...d.length>0?{allowedTools:d}:{},workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const w of T)this.pendingMemorySubAgents.set(w,A);const M=new Set(T);t.subscribe(A,()=>{const w=t.getSubAgent(A);if(w&&(w.status==="completed"||w.status==="failed"||w.status==="cancelled")){const E=Date.now();for(const p of M)this.pendingMemorySubAgents.get(p)===A&&this.pendingMemorySubAgents.delete(p),this.memoryDelegateCooldownUntil.set(p,E+De);for(const[p,y]of this.memoryDelegateCooldownUntil)y<=E&&this.memoryDelegateCooldownUntil.delete(p);u(`[ACodeRuntime] Memory delegate sub-agent ${A} finished (${w.status}), ${M.size} URI(s) entered ${De}ms cooldown`)}});const C=m.type,S=async(w,E)=>this.recheckMemoryDelegate(C,T,w,E);await t.startWithRecheck(A,S,3),u(`[ACodeRuntime] Auto-delegated memory ${m.type} to sub-agent ${A} (${T.length} URIs, ${m.uris.length-T.length} already in progress)`)}catch(d){for(const A of T)this.pendingMemorySubAgents.delete(A);u(`[ACodeRuntime] Failed to auto-delegate memory ${m.type} (suppressed, will retry next poll): ${d instanceof Error?d.message:String(d)}`)}}else i.push(c)}if(l===0)return e;if(i.length===0)return null;const r={...n,directMessages:i};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,n){const a=this.config.subAgentManager;if(!a)return D("runtime.poll.no-subagent-manager","\u65E0 SubAgentManager\uFF0C\u76F4\u63A5\u8D70\u666E\u901A MCP \u8C03\u7528"),await this.callMcpToolWithTimeout(e,t,o,n,!0);const i=a.takeCompletedSubAgents();if(i.length>0)return u(`[ACodeRuntime] poll_message: ${i.length} sub-agent(s) already completed, returning synthetic result`),D("runtime.poll.subagent-synthetic",`${i.length} \u4E2A\u5B50 agent \u5DF2\u5B8C\u6210\uFF0C\u76F4\u63A5\u8FD4\u56DE\u5408\u6210\u7ED3\u679C\uFF08\u4E0D\u8C03 MCP\uFF09`),Y.formatSubAgentCompletionAsPollResult(i);let l=!1,r=0;for(;;){r++,D("runtime.poll.round-start",`\u7B2C ${r} \u8F6E race \u5F00\u59CB: timeoutMs=${n} silent=${l}`);const c=new AbortController,m=a.waitForAnyCompletion(),f=l?{...o,_aws_silent_poll:!0}:o,g=Date.now(),k=this.callMcpToolWithTimeout(e,t,f,n,!0,c.signal);try{const T=await Promise.race([k.then(d=>({type:"mcp",result:d})),m.promise.then(d=>({type:"subagent",notif:d}))]);if(T.type==="subagent"){D("runtime.poll.race-winner-subagent",`\u5B50 agent \u5148\u5B8C\u6210\uFF0Cabort MCP \u8C03\u7528\uFF08\u5DF2\u7B49\u5F85 ${Date.now()-g}ms\uFF09\u540E\u8FD4\u56DE\u5408\u6210\u7ED3\u679C`),c.abort(),k.catch(()=>{});const d=a.takeCompletedSubAgents();return d.length===0&&d.push(T.notif),u(`[ACodeRuntime] poll_message: sub-agent ${T.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),Y.formatSubAgentCompletionAsPollResult(d)}D("runtime.poll.mcp-returned",`MCP \u5148\u8FD4\u56DE\uFF08\u8017\u65F6 ${Date.now()-g}ms\uFF09\uFF0C\u68C0\u67E5\u5F85\u5408\u5E76\u7684\u5B50 agent \u5B8C\u6210`);const b=a.takeCompletedSubAgents();if(b.length>0){u(`[ACodeRuntime] poll_message: MCP returned, merging ${b.length} sub-agent completion(s)`);const d=Y.mergeSubAgentCompletionsIntoMcpResult(T.result,b),A=await this.processMemoryAutoDelegates(d);if(D("runtime.poll.delegate-check",`\u5408\u5E76 ${b.length} \u4E2A\u5B50 agent \u5B8C\u6210\u540E\u59D4\u6258\u68C0\u67E5: processed=${A===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),A!==null){if(this.pollResultHasMessages(A))return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),A;D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),l=!0;continue}const _=await this.processMemoryAutoDelegates(T.result);if(D("runtime.poll.delegate-check",`\u59D4\u6258\u68C0\u67E5: processed=${_===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),_!==null){if(this.pollResultHasMessages(_)){const d=this.summarizePollResultForDebug(_);return D("runtime.poll.final-return",`\u7B2C ${r} \u8F6E\uFF1A\u8FD4\u56DE poll \u7ED3\u679C\u7ED9 LLM: ${d}`),_}D("runtime.poll.empty-repoll",`\u7B2C ${r} \u8F6E\uFF1Apoll \u7ED3\u679C\u65E0\u5B9E\u9645\u6D88\u606F\uFF08directMessages/groupMessages \u5747\u7A7A\uFF09\uFF0C\u7B49\u5F85 ${ae}ms \u540E\u91CD\u65B0 poll`)}await this.waitForDelegateRepoll(),l=!0}catch(T){throw D("runtime.poll.error",`\u7B2C ${r} \u8F6E MCP \u8C03\u7528\u5F02\u5E38: ${T instanceof Error?T.message:String(T)}`),T}finally{m.cancel()}}}summarizePollResultForDebug(e){try{const t=U(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages:[],a=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${n.length}${n.length>0?JSON.stringify(n.map(i=>({id:i.msgId,ch:i.channel}))):""} gm=${a.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=U(e),o=JSON.parse(t),n=Array.isArray(o.directMessages)?o.directMessages.length:0,a=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return n>0||a>0}catch{return!0}}async waitForDelegateRepoll(){u(`[ACodeRuntime] poll_message: all messages delegated, waiting ${ae}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,ae);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((n,a)=>{t=()=>{a(new Error(`${e} interrupted because ACode runtime stopped`))}});return t?(this.stopWaiters.add(t),{promise:o,cancel:()=>{t&&this.stopWaiters.delete(t)}}):{promise:o,cancel:()=>{}}}notifyRuntimeStop(){const e=[...this.stopWaiters];this.stopWaiters.clear();for(const t of e)t()}async appendSyntheticMultimodalUserMessage(e,t,o=this.contextVersion){const n=fe(e);if(!n.hasImages)return;if(!this.state.provider.supportsImageInput){this.emitAcodeEvent("error",{message:"ACode skipped image content from tool result because the provider/model is not configured for image input."}),this.cleanToolMessageAttachments(t,"[Tool result contained images; skipped because the current model does not support image input]");return}let a;try{a=await Fe(n.content)}catch(i){const l=i instanceof Error?i.message:String(i);this.emitAcodeEvent("error",{message:`ACode skipped image content from tool result: ${l}`}),a=Array.isArray(n.content)?n.content.map(r=>r.type==="text"?r:{type:"text",text:`[Image omitted: ${l}]`}):n.content}this.isTurnSuperseded(o)||(this.state.conversation.push({role:"user",content:a}),this.cleanToolMessageAttachments(t,"[Tool result contained images; see user message above]"))}expandCommandsInPolledResult(e){const t=this.state.commandRegistry;if(!t||t.list().length===0)return e;let o;try{o=JSON.parse(e)}catch{return e}if(!R(o))return e;let n=!1;for(const a of["directMessages","groupMessages"]){const i=o[a];if(Array.isArray(i))for(const l of i){if(!R(l))continue;const r=N(l.content);if(!r)continue;const c=t.expand(r);c&&(l.content=c.prompt,n=!0)}}return n?JSON.stringify(o):e}cleanToolMessageAttachments(e,t){const o=this.state.conversation.find(a=>a.role==="tool"&&a.tool_call_id===e);if(!o||typeof o.content!="string")return;let n;try{const a=JSON.parse(o.content);if(typeof a=="object"&&a!==null){const i={...a};"attachments"in i&&(delete i.attachments,n=JSON.stringify(i))}}catch{}if(n===void 0){const a=o.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();a!==o.content&&(n=a)}n!==void 0&&(o.content=n.length>0?n:t)}appendToolFailureResult(e,t,o){const n=Ao(t,o);u(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${n.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${oe(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,toolUseId:e.id,result:n,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:n})}filterSharedMcpConnectionsForSubAgent(e){const t=this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0?this.config.subAgentAllowedTools:null;return e.map(o=>({...o,tools:o.tools.filter(n=>t?ke(n,t):vt.has(n.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[n,a]of Object.entries(e))try{const i=new et({name:"acode",version:"0.1.0"}),l=this.createMcpTransport(a);await x(i.connect(l),t,`ACode MCP server ${n} connect`);const r={serverName:n,client:i,transport:l,tools:[]};i.setNotificationHandler(nt,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:c}=await x(i.listTools(),t,`ACode MCP server ${n} listTools`);r.tools=Re(n,c),o.push(r)}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${n}: ${i instanceof Error?i.message:String(i)}`})}return o}requestMcpToolsRefresh(e){const t=this.state.mcpConnections.filter(o=>!e||o.serverName===e);for(const o of t)this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs)}async refreshMcpConnectionTools(e,t){try{const{tools:n}=await x(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Re(e.serverName,n)}catch(n){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${n instanceof Error?n.message:String(n)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(n=>!(n.kind==="mcp"&&n.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitExposedToolsStatus()}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");const o=new ot({command:e.command,args:e.args,cwd:e.cwd||this.config.workingDirectory,env:{...this.config.env??{},...e.env??{}},stderr:"pipe"});return o.stderr?.on("data",()=>{}),o}if(!e.url)throw new Error("remote MCP server requires url");const t=e.headers?{headers:e.headers}:void 0;return e.type==="sse"?new tt(new URL(e.url),{requestInit:t}):new st(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(n=>n.toolName==="get_profile"))try{const n=await x(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:re}),re,"ACode startup get_profile"),a=this.extractProfileFromToolResult(n);return wo(a)}catch(n){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${n instanceof Error?n.message:String(n)}`}),""}return""}extractProfileFromToolResult(e){if(!R(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(R(o)&&typeof o.text=="string"&&o.text.trim())try{const n=JSON.parse(o.text);if(R(n))return n}catch{}}return R(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1;return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1,await Promise.all(e.map(t=>ee(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}Y.SKILL_REFRESH_DEBOUNCE_MS=500;export{Y as ACodeRuntime};
|
|
109
|
+
\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};
|
|
109
110
|
|
|
@@ -2,6 +2,7 @@ import type { SubAgentManager } from "./sub-agent-manager.js";
|
|
|
2
2
|
import type { ACodeMcpConnection } from "./runtime.js";
|
|
3
3
|
import type { TerminalManager } from "./terminal-types.js";
|
|
4
4
|
import type { ACodePluginBridge } from "./plugin-types.js";
|
|
5
|
+
import type { CapabilityState } from "./capability-prompt.js";
|
|
5
6
|
export interface ACodeMcpServerSpec {
|
|
6
7
|
type?: "stdio" | "sse" | "http";
|
|
7
8
|
command?: string;
|
|
@@ -146,6 +147,8 @@ export interface ACodeRuntimeConfig {
|
|
|
146
147
|
subAgentSuiteTools?: import("./built-in-file-tools.js").ACodeBuiltInTool[];
|
|
147
148
|
|
|
148
149
|
subAgentSuiteToolProvider?: (patterns: string[]) => Promise<import("./built-in-file-tools.js").ACodeBuiltInTool[]>;
|
|
150
|
+
|
|
151
|
+
capabilityState?: (featureKey: string) => CapabilityState;
|
|
149
152
|
}
|
|
150
153
|
export interface ACodeResolvedProviderConfig {
|
|
151
154
|
model: string;
|