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