aws-runtime-bridge 1.9.102 → 1.9.103

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +2 -0
  2. package/dist/adapter/AcodeSdkAdapter.d.ts +2 -0
  3. package/dist/adapter/AcodeSdkAdapter.js +3 -3
  4. package/dist/index.js +1 -1
  5. package/dist/remote-desktop/computer-use-backend.d.ts +111 -0
  6. package/dist/remote-desktop/computer-use-backend.js +1 -0
  7. package/dist/remote-desktop/types.d.ts +79 -0
  8. package/dist/routes/computer.d.ts +1 -0
  9. package/dist/routes/computer.js +2 -0
  10. package/dist/routes/file-change-diff.d.ts +27 -0
  11. package/dist/routes/file-change-diff.js +5 -0
  12. package/dist/routes/instance.js +2 -2
  13. package/dist/routes/pty.d.ts +2 -2
  14. package/dist/routes/pty.js +3 -3
  15. package/dist/routes/task-context.js +1 -1
  16. package/dist/routes/terminal.js +28 -28
  17. package/dist/services/auto-register.d.ts +1 -1
  18. package/dist/services/auto-register.js +1 -1
  19. package/dist/services/instance-features.d.ts +10 -0
  20. package/dist/services/instance-features.js +2 -0
  21. package/dist/services/sdk-tool-file-change-recorder.d.ts +12 -0
  22. package/dist/services/sdk-tool-file-change-recorder.js +2 -0
  23. package/dist/services/workspace-files.js +1 -1
  24. package/dist/services/workspaceTaskChangeWatcher.d.ts +9 -1
  25. package/dist/services/workspaceTaskChangeWatcher.js +3 -1
  26. package/package/acode/dist/built-in-file-tools.d.ts +4 -0
  27. package/package/acode/dist/built-in-file-tools.js +2 -2
  28. package/package/acode/dist/runtime.d.ts +13 -0
  29. package/package/acode/dist/runtime.js +18 -18
  30. package/package/aws-client-agent-mcp/README.md +2 -2
  31. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +14 -4
  32. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  33. package/package/aws-client-agent-mcp/dist/agent-client.test.js +36 -36
  34. package/package/aws-client-agent-mcp/dist/config.js +1 -1
  35. package/package/aws-client-agent-mcp/dist/config.test.js +2 -2
  36. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +2 -0
  37. package/package/aws-client-agent-mcp/dist/mcp-server.js +21 -21
  38. package/package/aws-client-agent-mcp/dist/mcp-server.test.js +35 -36
  39. package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +6 -0
  40. package/package/aws-client-agent-mcp/dist/mcp-tools.js +25 -5
  41. package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +17 -1
  42. package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.js +1 -1
  43. package/package/aws-client-agent-mcp/dist/types.d.ts +14 -12
  44. package/package/aws-client-agent-mcp/dist/websocket-client.js +1 -1
  45. package/package.json +3 -2
  46. package/scripts/ensure-playwright-browser.mjs +118 -0
@@ -1,33 +1,33 @@
1
- import{EventEmitter as Fe}from"node:events";import J from"node:fs";import je from"node:os";import V from"node:path";import{Client as We}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as Ke}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Qe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{createBuiltInFileTools as He}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as Ge,createAskUserQuestionTool as Ye}from"./ask-user-question-tool.js";import{createSkillTool as Ve}from"./skill-tool.js";import{createTodoWriteTool as Xe,createTodoReadTool as Ze}from"./todo-tool.js";import{createSubAgentTools as et}from"./sub-agent-tools.js";import{createAwaitCompleteTool as tt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as ot}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as K}from"./background-command-manager.js";import{createTerminalTool as nt}from"./terminal-tool.js";import{loadAcodeCommands as st}from"./commands/commandLoader.js";import{ACodeCommandRegistry as pe}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as it,COMPACTION_LLM_PROMPT_TEMPLATE as rt,conversationSizeKB as Q,estimateConversationTokens as X,performCompaction as he,pruneToolOutputs as at,summarizeConversation as fe}from"./compaction.js";import{loadAcodeConfig as ut,loadAcodeSkillGroup as ct}from"./config.js";import{ACodeHookBus as lt,findDeniedHookResult as se}from"./hooks/hookBus.js";import{isMcpPollingToolName as mt,getSemanticToolName as ge}from"./mcpToolNames.js";function dt(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function pt(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function ht(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(dt):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(pt)),e}function ie(n){return n.map(ht)}function ft(){return new Date().toISOString()}function v(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function ye(n){return v(n)}function I(n){return String(n??"").trim()||void 0}const Z=6e4,Ae=10*6e4,Ce=2e4,Te=3e4,_e=3,re=-1,gt=1e3,yt=3e4,ee=6e4,we=0,At=2147483647,Ct=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),Tt=new Set(["write_file","edit_file","delete_file"]),_t=10*6e4+2e3,wt=1e4,be=5e3,$e=10*60*1e3,Me=10*1024*1024,Re=800*1024,te=process.env.ACODE_COMPACTION_DEBUG==="1",ke=te?V.join(je.tmpdir(),"acode-compaction-debug.log"):"";function m(...n){te&&console.log(...n)}const bt=64e3;function ae(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:bt,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=it(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:s}}async function x(n,e,t,o){if(e<=0)return await n;let s;try{return await new Promise((a,i)=>{s=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),n.then(a,i)})}finally{s&&clearTimeout(s)}}async function H(n,e,t,o=wt){try{await x(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function F(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===re?re:Number.isFinite(t)&&t>0?Math.floor(t):e}function q(n,e){const t=F(n,e);return t>0?t:e}const Se=3;function ve(n){return n?Math.ceil(n.length/Se):0}function $t(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 a=o;a.inputSchema&&(t+=JSON.stringify(a.inputSchema).length)}}return Math.ceil(t/Se)}function Ee(n){if(n.length===0)return 0;const e=JSON.stringify(Ue(n));return ve(e)}async function Mt(n){await new Promise(e=>setTimeout(e,n))}function Rt(n){return typeof n=="boolean"}function kt(n,e,t){if(Rt(t?.supportsImageInput))return t.supportsImageInput;const o=v(e)?e.models:void 0,s=v(o)?o[n]:void 0;if(!v(s))return!1;const a=s.modalities;return!v(a)||!Array.isArray(a.input)?!1:a.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function ue(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(v(s)){const a=s[t];if(v(a)){const i=a[o];if(i!==void 0)return i}}return e[o]}function St(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",a=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:a,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:q(o?.requestTimeoutMs??o?.timeoutMs,Z),requestTotalTimeoutMs:q(o?.requestTotalTimeoutMs,Ae),requestRetryCount:F(o?.requestRetryCount,_e),requestFirstByteTimeoutMs:Math.min(q(o?.requestFirstByteTimeoutMs,Ce),q(o?.requestTimeoutMs??o?.timeoutMs,Z)),requestStreamIdleTimeoutMs:Math.min(q(o?.requestStreamIdleTimeoutMs,Te),q(o?.requestTimeoutMs??o?.timeoutMs,Z)),mcpToolTimeoutMs:q(o?.mcpToolTimeoutMs,ee),mcpPollingToolTimeoutMs:F(o?.mcpPollingToolTimeoutMs,we),supportsImageInput:kt(s,t,o),contextLimit:F(ue(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:F(ue(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:F(ue(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function U(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function vt(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function Et(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function xt(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 Nt(n){const e=await n.arrayBuffer();if(e.byteLength>Me)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${Me} bytes`);return Buffer.from(e).toString("base64")}async function It(n){const e=n.trim();if(Et(e))return e;xt(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 Nt(t)}`}function Dt(n){const e=I(n.base64Data??n.base64??n.data);return e?vt(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function xe(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(a=>!!a).join(", ")}]`}function Pt(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,a=e.exec(n);for(;a!==null;){U(t,n.slice(s,a.index));const i=a[1],u=(a[2]||"").trim();if(i==="\u56FE\u7247"&&u)t.push({type:"image_url",image_url:{url:u}}),o=!0;else if(i==="\u6587\u4EF6"&&u){const[r="",c="",l="",g=""]=u.split("|").map(y=>y.trim());U(t,xe(r,c,l,g))}else U(t,a[0]);s=a.index+a[0].length,a=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(U(t,n.slice(s)),{content:t,hasImages:o})}function Lt(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const a of s){if(!v(a))continue;const i=I(a.content);if(!i)continue;const u=I(a.senderName);U(n,u?`Message from ${u}:`:"Message:");const r=ce(i);Array.isArray(r.content)?n.push(...r.content):U(n,r.content),t=t||r.hasImages}return t}function Ot(n){let e;try{e=JSON.parse(n)}catch{return}if(!v(e))return;const t=[];let o=Lt(t,e);const s=I(e.text)||"",a=Array.isArray(e.attachments)?e.attachments:[];U(t,s);for(const i of a){if(!v(i))continue;const u=i;if(String(u.type??u.kind??"").toLowerCase()==="image"){const l=Dt(u);l&&(t.push({type:"image_url",image_url:{url:l}}),o=!0);continue}const c=I(u.url??u.serverUrl)||"";U(t,xe(I(u.name)||"",c,I(u.mediaType??u.mimeType)||"",I(u.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function ce(n){return Ot(n)??Pt(n)}async function Ne(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 It(t.image_url.url)}})}return e}function Ut(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function Bt(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(a=>a.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(a=>a.trim()).filter(Boolean)}}function qt(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function zt(n){return n.kind==="builtin"?[n.exposedName,n.toolName,`builtin.${n.toolName}`]:[n.exposedName,n.toolName,`${n.serverName}.${n.toolName}`,`mcp.${n.serverName}.${n.toolName}`]}function Ie(n,e){return zt(e).some(t=>qt(n,t))}function De(n,e,t){if(e.length>0&&!e.some(o=>Ie(o,n)))throw new Error(t)}function le(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>Ie(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);De(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),De(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function Ft(n,e,t){try{return le(n,e,t),!0}catch{return!1}}function oe(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function jt(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(oe(e.toString()));return`${t.origin}${t.pathname}`}catch{return oe(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function Wt(n){const e=[...n].reverse().find(o=>o.role==="user"),t=Ut(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function Pe(n){try{const e=JSON.parse(n);return ye(e)?e:{}}catch{return{}}}function Jt(n,e,t){if(new Set([Ge,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(a)||a<=0?Math.max(t,_t):Math.min(Math.floor(a),10*6e4)+2e3}function Kt(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 P(n){if(!v(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>v(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
- `)}return JSON.stringify(n)}function G(n){return n instanceof Error?n.message:String(n)}function Qt(n){let e=16;if(typeof n.content=="string")e+=n.content.length*2;else if(Array.isArray(n.content))for(const t of n.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return n.tool_calls&&(e+=JSON.stringify(n.tool_calls).length),n.tool_call_id&&(e+=n.tool_call_id.length),e}async function Ht(n,e,t,o,s){let a=0;for(const u of n)a+=Qt(u);if(a<=e)return 0;const i=await he(n,t,o,{llmSummarizer:s});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:fe(n,{llmSummarizer:s,contextLimit:t})}function Le(n){const e=G(n).toLowerCase();return e.includes("context_length_exceeded")||e.includes("context length")||e.includes("maximum context")||e.includes("max context")||e.includes("token limit")||e.includes("tokens exceed")||e.includes("too many tokens")||e.includes("input is too long")||e.includes("prompt is too long")||e.includes("request too large")||e.includes("413")}function Gt(n){const e=G(n).toLowerCase();return Le(n)?!1:e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||/\b(408|429|500|502|503|504|520|521|522|523|524)\b/.test(e)}function Yt(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=G(n).toLowerCase();return e===-32001||t.includes("request timed out")}function Vt(n){if(typeof n=="object"&&n!==null){const e=Reflect.get(n,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(n,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function Xt(n,e){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:Vt(e),message:G(e)}})}function Oe(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function Zt(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(v(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function eo(n){return n.length===0?"":["Skills are available for this session.","Use the `skill` tool to load specialized skill instructions when a user task matches one of the available skills listed in the tool description.","Do not attempt to follow skill instructions from memory \u2014 always invoke the `skill` tool first to load the full content."].join(" ")}function to(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
3
- `)}function oo(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,a=e.instanceName,i=e.projectName,u=e.workspacePath,r=e.runtimeMode,c=e.describe;return typeof o=="string"&&o.trim()&&t.push(`Display Name: ${o.trim()}`),typeof s=="string"&&s.trim()&&t.push(`Role: ${s.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Instance: ${a.trim()}`),typeof i=="string"&&i.trim()&&t.push(`Project: ${i.trim()}`),typeof u=="string"&&u.trim()&&t.push(`Workspace: ${u.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Runtime Mode: ${r.trim()}`),typeof c=="string"&&c.trim()&&t.push(`Description: ${c.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
4
- `)}function Ue(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function no(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function so(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function io(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,ro(e)?ao(t):t]))}function ro(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function ao(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function uo(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function co(n,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=n.get(t)??{id:e.id||`call-${t}`,type:"function",function:{name:"",arguments:""}};e.id&&(o.id=e.id),e.function?.name&&(o.function.name+=e.function.name),e.function?.arguments&&(o.function.arguments+=e.function.arguments),n.set(t,o)}function lo(n){return[...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}class j extends Fe{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:Z,requestTotalTimeoutMs:Ae,requestRetryCount:_e,requestFirstByteTimeoutMs:Ce,requestStreamIdleTimeoutMs:Te,mcpToolTimeoutMs:ee,mcpPollingToolTimeoutMs:we,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new pe([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0},this.abortController=null,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.submitQueue=Promise.resolve(),this.activeTurn=!1,this.abortRequested=!1,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.hookBus=new lt({sessionId:e.sessionId,onError:(t,o)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${t.name}: ${o instanceof Error?o.message:String(o)}`})}});for(const t of e.hooks??[])this.hookBus.register(t)}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:ft(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s})}handleCompactionPhase(e,t){switch(t.phase){case"prune_start":this.emitCompactionPhase(e,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u6B63\u5728\u88C1\u526A ${t.messageCount??0} \u6761\u6D88\u606F\u4E2D\u7684\u5DE5\u5177\u8F93\u51FA...`);break;case"prune_end":this.emitCompactionPhase(e,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${t.prunedCount??0} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${t.freedTokens??0} tokens`);break;case"summarize_start":this.emitCompactionPhase(e,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6B63\u5728\u6458\u8981 ${t.messageCount??0} \u6761\u65E9\u671F\u5BF9\u8BDD...`);break;case"summarize_end":this.emitCompactionPhase(e,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${t.summarizedCount??0} \u6761\u6D88\u606F${t.usedLLM?" (LLM \u6458\u8981)":" (\u89C4\u5219\u6458\u8981)"}`);break}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await ut(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),a=St(this.config,e);m(`[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=Bt(this.config,e),u=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},a.mcpToolTimeoutMs),r=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const c=await this.fetchProfilePrompt(u),l=this.config.agentId||"unknown";ot(l),K.reconcileOrphans(l);const g=He(this.config.workingDirectory,l,this.config.onFileChange,{manager:K,emitCompleted:p=>{this.emitAcodeEvent("background_command_completed",p)}}),y=Ye(this.buildAskUserQuestionDeps(),()=>this.contextVersion),b=Ve(t);this.skillTool=b;const d=Xe(l),$=Ze(l),h=this.config.subAgentManager?et(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],f=tt(this.buildAwaitCompleteDeps()),C=this.config.terminalManager?nt(l,{terminalManager:this.config.terminalManager}):null,_=[...g,y,b,d,$,...h,f,...C?[C]:[],...u.flatMap(p=>p.tools),...this.config.extraBuiltInTools??[]],k=this.config.subagentType==="explore"?_.filter(p=>!Tt.has(p.exposedName)):_,A=this.resolveCommandDirs(e);this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const M=await st(A),N=new pe(M),T=eo(t),S=to(M),R=[a.systemPrompt,T,S].map(p=>p?.trim()).filter(p=>!!p).join(`
1
+ import{EventEmitter as je}from"node:events";import J from"node:fs";import We from"node:os";import V from"node:path";import{Client as Je}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Ke}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as He}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Qe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as Ge}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as Ye}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as Ve,createAskUserQuestionTool as Xe}from"./ask-user-question-tool.js";import{createSkillTool as Ze}from"./skill-tool.js";import{createTodoWriteTool as et,createTodoReadTool as tt}from"./todo-tool.js";import{createSubAgentTools as ot}from"./sub-agent-tools.js";import{createAwaitCompleteTool as nt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as st}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as K}from"./background-command-manager.js";import{createTerminalTool as it}from"./terminal-tool.js";import{loadAcodeCommands as rt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as pe}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as at,COMPACTION_LLM_PROMPT_TEMPLATE as lt,conversationSizeKB as H,estimateConversationTokens as X,performCompaction as he,pruneToolOutputs as ut,summarizeConversation as fe}from"./compaction.js";import{loadAcodeConfig as ct,loadAcodeSkillGroup as mt}from"./config.js";import{ACodeHookBus as dt,findDeniedHookResult as se}from"./hooks/hookBus.js";import{isMcpPollingToolName as pt,getSemanticToolName as ge}from"./mcpToolNames.js";function ht(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function ft(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function gt(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(ht):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(ft)),e}function ie(n){return n.map(gt)}function yt(){return new Date().toISOString()}function v(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function ye(n){return v(n)}function Te(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:io(n,t.name),description:t.description,inputSchema:ye(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function I(n){return String(n??"").trim()||void 0}const Z=6e4,Ae=10*6e4,Ce=2e4,_e=3e4,we=3,re=-1,Tt=1e3,At=3e4,ee=6e4,be=0,Ct=2147483647,_t=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),wt=new Set(["write_file","edit_file","delete_file"]),bt=10*6e4+2e3,$t=1e4,$e=5e3,Se=10*60*1e3,Me=10*1024*1024,Re=800*1024,te=process.env.ACODE_COMPACTION_DEBUG==="1",ke=te?V.join(We.tmpdir(),"acode-compaction-debug.log"):"";function m(...n){te&&console.log(...n)}const St=64e3;function ae(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:St,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=at(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((a,i)=>{s=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),n.then(a,i)})}finally{s&&clearTimeout(s)}}async function Q(n,e,t,o=$t){try{await E(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function F(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===re?re:Number.isFinite(t)&&t>0?Math.floor(t):e}function B(n,e){const t=F(n,e);return t>0?t:e}const ve=3;function xe(n){return n?Math.ceil(n.length/ve):0}function Mt(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 a=o;a.inputSchema&&(t+=JSON.stringify(a.inputSchema).length)}}return Math.ceil(t/ve)}function Ee(n){if(n.length===0)return 0;const e=JSON.stringify(qe(n));return xe(e)}async function Rt(n){await new Promise(e=>setTimeout(e,n))}function kt(n){return typeof n=="boolean"}function vt(n,e,t){if(kt(t?.supportsImageInput))return t.supportsImageInput;const o=v(e)?e.models:void 0,s=v(o)?o[n]:void 0;if(!v(s))return!1;const a=s.modalities;return!v(a)||!Array.isArray(a.input)?!1:a.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function le(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(v(s)){const a=s[t];if(v(a)){const i=a[o];if(i!==void 0)return i}}return e[o]}function xt(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",a=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:a,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:B(o?.requestTimeoutMs??o?.timeoutMs,Z),requestTotalTimeoutMs:B(o?.requestTotalTimeoutMs,Ae),requestRetryCount:F(o?.requestRetryCount,we),requestFirstByteTimeoutMs:Math.min(B(o?.requestFirstByteTimeoutMs,Ce),B(o?.requestTimeoutMs??o?.timeoutMs,Z)),requestStreamIdleTimeoutMs:Math.min(B(o?.requestStreamIdleTimeoutMs,_e),B(o?.requestTimeoutMs??o?.timeoutMs,Z)),mcpToolTimeoutMs:B(o?.mcpToolTimeoutMs,ee),mcpPollingToolTimeoutMs:F(o?.mcpPollingToolTimeoutMs,be),supportsImageInput:vt(s,t,o),contextLimit:F(le(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:F(le(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:F(le(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function U(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function Et(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function Nt(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function It(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 Pt(n){const e=await n.arrayBuffer();if(e.byteLength>Me)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${Me} bytes`);return Buffer.from(e).toString("base64")}async function Dt(n){const e=n.trim();if(Nt(e))return e;It(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 Pt(t)}`}function Lt(n){const e=I(n.base64Data??n.base64??n.data);return e?Et(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function Ne(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(a=>!!a).join(", ")}]`}function Ot(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,a=e.exec(n);for(;a!==null;){U(t,n.slice(s,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="",c="",g=""]=l.split("|").map(y=>y.trim());U(t,Ne(r,u,c,g))}else U(t,a[0]);s=a.index+a[0].length,a=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(U(t,n.slice(s)),{content:t,hasImages:o})}function Ut(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const a of s){if(!v(a))continue;const i=I(a.content);if(!i)continue;const l=I(a.senderName);U(n,l?`Message from ${l}:`:"Message:");const r=ue(i);Array.isArray(r.content)?n.push(...r.content):U(n,r.content),t=t||r.hasImages}return t}function qt(n){let e;try{e=JSON.parse(n)}catch{return}if(!v(e))return;const t=[];let o=Ut(t,e);const s=I(e.text)||"",a=Array.isArray(e.attachments)?e.attachments:[];U(t,s);for(const i of a){if(!v(i))continue;const l=i;if(String(l.type??l.kind??"").toLowerCase()==="image"){const c=Lt(l);c&&(t.push({type:"image_url",image_url:{url:c}}),o=!0);continue}const u=I(l.url??l.serverUrl)||"";U(t,Ne(I(l.name)||"",u,I(l.mediaType??l.mimeType)||"",I(l.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function ue(n){return qt(n)??Ot(n)}async function Ie(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 Dt(t.image_url.url)}})}return e}function Bt(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function zt(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(a=>a.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(a=>a.trim()).filter(Boolean)}}function Ft(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function jt(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 Pe(n,e){return jt(e).some(t=>Ft(n,t))}function De(n,e,t){if(e.length>0&&!e.some(o=>Pe(o,n)))throw new Error(t)}function ce(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>Pe(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);De(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),De(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function Wt(n,e,t){try{return ce(n,e,t),!0}catch{return!1}}function oe(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function Jt(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(oe(e.toString()));return`${t.origin}${t.pathname}`}catch{return oe(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function Kt(n){const e=[...n].reverse().find(o=>o.role==="user"),t=Bt(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function Le(n){try{const e=JSON.parse(n);return ye(e)?e:{}}catch{return{}}}function Ht(n,e,t){if(new Set([Ve,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(a)||a<=0?Math.max(t,bt):Math.min(Math.floor(a),10*6e4)+2e3}function Qt(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 D(n){if(!v(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>v(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
+ `)}return JSON.stringify(n)}function G(n){return n instanceof Error?n.message:String(n)}function Gt(n){let e=16;if(typeof n.content=="string")e+=n.content.length*2;else if(Array.isArray(n.content))for(const t of n.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return n.tool_calls&&(e+=JSON.stringify(n.tool_calls).length),n.tool_call_id&&(e+=n.tool_call_id.length),e}async function Yt(n,e,t,o,s){let a=0;for(const l of n)a+=Gt(l);if(a<=e)return 0;const i=await he(n,t,o,{llmSummarizer:s});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:fe(n,{llmSummarizer:s,contextLimit:t})}function Oe(n){const e=G(n).toLowerCase();return e.includes("context_length_exceeded")||e.includes("context length")||e.includes("maximum context")||e.includes("max context")||e.includes("token limit")||e.includes("tokens exceed")||e.includes("too many tokens")||e.includes("input is too long")||e.includes("prompt is too long")||e.includes("request too large")||e.includes("413")}function Vt(n){const e=G(n).toLowerCase();return Oe(n)?!1:e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||/\b(408|429|500|502|503|504|520|521|522|523|524)\b/.test(e)}function Xt(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=G(n).toLowerCase();return e===-32001||t.includes("request timed out")}function Zt(n){if(typeof n=="object"&&n!==null){const e=Reflect.get(n,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(n,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function eo(n,e){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:Zt(e),message:G(e)}})}function Ue(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function to(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(v(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function oo(n){return n.length===0?"":["Skills are available for this session.","Use the `skill` tool to load specialized skill instructions when a user task matches one of the available skills listed in the tool description.","Do not attempt to follow skill instructions from memory \u2014 always invoke the `skill` tool first to load the full content."].join(" ")}function no(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
3
+ `)}function so(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=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 s=="string"&&s.trim()&&t.push(`Role: ${s.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 qe(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function io(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function ro(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function ao(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,lo(e)?uo(t):t]))}function lo(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function uo(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function co(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function mo(n,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=n.get(t)??{id:e.id||`call-${t}`,type:"function",function:{name:"",arguments:""}};e.id&&(o.id=e.id),e.function?.name&&(o.function.name+=e.function.name),e.function?.arguments&&(o.function.arguments+=e.function.arguments),n.set(t,o)}function po(n){return[...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}class j extends je{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:Z,requestTotalTimeoutMs:Ae,requestRetryCount:we,requestFirstByteTimeoutMs:Ce,requestStreamIdleTimeoutMs:_e,mcpToolTimeoutMs:ee,mcpPollingToolTimeoutMs:be,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new pe([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0},this.abortController=null,this.exposedToolsInitialized=!1,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.submitQueue=Promise.resolve(),this.activeTurn=!1,this.abortRequested=!1,this.toolSettleSlot=null,this.toolSettleSeq=0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.hookBus=new dt({sessionId:e.sessionId,onError:(t,o)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${t.name}: ${o instanceof Error?o.message:String(o)}`})}});for(const t of e.hooks??[])this.hookBus.register(t)}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:yt(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s})}handleCompactionPhase(e,t){switch(t.phase){case"prune_start":this.emitCompactionPhase(e,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u6B63\u5728\u88C1\u526A ${t.messageCount??0} \u6761\u6D88\u606F\u4E2D\u7684\u5DE5\u5177\u8F93\u51FA...`);break;case"prune_end":this.emitCompactionPhase(e,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${t.prunedCount??0} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${t.freedTokens??0} tokens`);break;case"summarize_start":this.emitCompactionPhase(e,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6B63\u5728\u6458\u8981 ${t.messageCount??0} \u6761\u65E9\u671F\u5BF9\u8BDD...`);break;case"summarize_end":this.emitCompactionPhase(e,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${t.summarizedCount??0} \u6761\u6D88\u606F${t.usedLLM?" (LLM \u6458\u8981)":" (\u89C4\u5219\u6458\u8981)"}`);break}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await ct(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),a=xt(this.config,e);m(`[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=zt(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),c=this.config.agentId||"unknown";st(c),K.reconcileOrphans(c);const g=Ye(this.config.workingDirectory,c,this.config.onFileChange,{manager:K,emitCompleted:p=>{this.emitAcodeEvent("background_command_completed",p)}}),y=Xe(this.buildAskUserQuestionDeps(),()=>this.contextVersion),w=Ze(t);this.skillTool=w;const d=et(c),b=tt(c),h=this.config.subAgentManager?ot(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],f=nt(this.buildAwaitCompleteDeps()),C=this.config.terminalManager?it(c,{terminalManager:this.config.terminalManager}):null,_=[...g,y,w,d,b,...h,f,...C?[C]:[],...l.flatMap(p=>p.tools),...this.config.extraBuiltInTools??[]],k=this.config.subagentType==="explore"?_.filter(p=>!wt.has(p.exposedName)):_,T=this.resolveCommandDirs(e);this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const $=await rt(T),N=new pe($),A=oo(t),R=no($),x=[a.systemPrompt,A,R].map(p=>p?.trim()).filter(p=>!!p).join(`
5
5
 
6
- `),w=p=>p?.trim()?[{role:"system",content:p.trim()}]:[],E=[this.config.rolePrompt,c].map(p=>p?.trim()).filter(p=>!!p).join(`
6
+ `),M=p=>p?.trim()?[{role:"system",content:p.trim()}]:[],S=[this.config.rolePrompt,u].map(p=>p?.trim()).filter(p=>!!p).join(`
7
7
 
8
- `),L=[...w(this.config.globalPrompt),...w(E),...w(this.config.memory),...R?[{role:"system",content:R}]:[]],O=L.map(p=>p.content).filter(Boolean).join(`
8
+ `),L=[...M(this.config.globalPrompt),...M(S),...M(this.config.memory),...x?[{role:"system",content:x}]:[]],O=L.map(p=>p.content).filter(Boolean).join(`
9
9
 
10
- `);this.initialConversation=ie(L),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:a,permissions:i,mcpConnections:u,ownsMcpConnections:r,exposedTools:k,commands:M,commandRegistry:N,conversation:ie(L),accumulatedInputTokens:0,accumulatedOutputTokens:0},this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:M.length});const D=ae(a);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:M.length,estimatedContextTokens:$t(O,k),contextLimit:D.contextLimit,maxOutput:D.maxOutput,...D.inputLimit!==void 0?{inputLimit:D.inputLimit}:{},compactionThreshold:D.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:u.length,builtInToolCount:g.length,toolCount:k.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:k.map(p=>({name:p.exposedName,source:p.kind==="mcp"?`${p.serverName}.${p.toolName}`:`builtin.${p.toolName}`,description:p.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(p=>({name:p.name,description:p.description,directory:p.directory})),skillGroups:o.map(p=>({dir:p.dir,exists:p.exists,skills:p.skills.map(z=>({name:z.name,description:z.description,directory:z.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:M.length,commandDirs:A,commands:M.map(p=>({name:p.name,description:p.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=V.join(this.config.workingDirectory,".acode","skills"),o=V.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,a=[],i=[];for(const c of[e,t,o]){if(!c)continue;const l=V.resolve(c);if(!s.has(l)){s.add(l),a.push(await ct(c));try{await J.promises.access(l),i.push(l)}catch{}}}const u=new Map;for(const c of a)for(const l of c.skills)u.set(l.name,l);return{skills:[...u.values()],skillGroups:a,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=J.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=J.watch(t,()=>{this.scheduleSkillRefresh()})}catch{continue}}o&&(o.on("error",()=>{}),this.skillWatchers.push(o))}}scheduleSkillRefresh(){this.skillRefreshTimer&&clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=setTimeout(()=>{this.skillRefreshTimer=null,this.refreshSkills()},j.SKILL_REFRESH_DEBOUNCE_MS)}async refreshSkills(){if(!(!this.state.started||this.state.terminated))try{const{skills:e,skillGroups:t}=await this.loadAllSkills();this.skillTool&&this.skillTool.refresh(e),this.state.skills=e,this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:e.length,skills:e.map(o=>({name:o.name,description:o.description,directory:o.directory})),skillGroups:t.map(o=>({dir:o.dir,exists:o.exists,skills:o.skills.map(s=>({name:s.name,description:s.description,directory:s.directory}))}))}),m(`[skill-watch] Skills refreshed: ${e.length} skills (${e.map(o=>o.name).join(", ")||"none"})`,{sessionId:this.config.sessionId})}catch(e){console.error("[skill-watch] Failed to refresh skills:",e instanceof Error?e.message:e)}}stopSkillWatchers(){this.skillRefreshTimer&&(clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=null);for(const e of this.skillWatchers)try{e.close()}catch{}this.skillWatchers=[]}startCompactionDebugLog(){if(!te||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:a}=ae(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,u=X(this.state.conversation)+Ee(this.state.exposedTools),r=Math.max(i,u),c=Q(this.state.conversation),l=this.state.started&&!this.state.terminated,g=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${c}KB`,`estimation=${u} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${a}`,`remainingToTrigger=${Math.max(0,a-i)}`,`isRunning=${l}`,`shouldCompact=${l?r>=a:!1}`,"---"].join(" | ");J.promises.appendFile(ke,g+`
11
- `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;m(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${t}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const o=this.submitQueue.then(()=>(m(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmit(e,t)));return this.submitQueue=o.catch(()=>{m("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),m("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}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=ie(this.initialConversation),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t){const o=Date.now();if(m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),m("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),m(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),m(`[ACodeRuntime] \u{1F522} Context version: ${t}`),m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const s=e.trim();let a=!1;try{m("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const i=Date.now(),u=await this.hookBus.dispatch("UserPromptSubmit",{prompt:s}),r=Date.now()-i;if(m(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${r}ms, results: ${u.length}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const c=se(u);if(c){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${c.message}`),this.emitAcodeEvent("error",{message:c.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}m("[ACodeRuntime] \u{1F50D} Expanding command if any...");const l=this.state.commandRegistry.expand(s),g=l?.prompt.trim()||s,y=l?.command.allowedTools;if(l&&(m(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${l.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:l.command.name,arguments:l.argumentsText,sourcePath:l.command.sourcePath})),!this.state.provider.baseURL||!this.state.provider.apiKey){m("[ACodeRuntime] \u26A0\uFE0F No provider configured, using fallback response");const _=Kt(g,this.state);this.emitAcodeEvent("assistant_delta",{text:_}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:_.length}}),a=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}m("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const b=ce(g);if(b.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");m("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const d=await Ne(b.content);if(this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}m("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:d}),m(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),m("[ACodeRuntime] Starting runModelTurn...");const $=Date.now(),h=await this.runModelTurn(y,t),f=Date.now()-$;if(m(`[ACodeRuntime] \u2705 runModelTurn completed in ${f}ms`),m(`[ACodeRuntime] \u{1F4DD} Result: text=${h.text?h.text.slice(0,80)+(h.text.length>80?"...":""):"(empty)"}, finishReason=${h.finishReason||"(none)"}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}h.text&&!this.state.provider.stream&&(m("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:h.text})),m("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:h.usage??{inputTokens:g.length,outputTokens:h.totalOutputTextLength??h.text.length},...h.responseBody?{responseBody:h.responseBody}:{},...h.finishReason?{finishReason:h.finishReason}:{}}),m(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(h.usage?"":" (estimated, no provider usage)")),a=!0;const C=Date.now()-o;m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),m(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${C}ms`),m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(i){const u=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${u}ms:`,i instanceof Error?i.message:String(i)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",i instanceof Error?i.stack:"(no stack)"),this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){m("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),a=!0;return}m("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:i instanceof Error?i.message:String(i)}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0}finally{const i=Date.now()-o;m(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${i}ms`),m(`[ACodeRuntime] \u{1F50D} turnCompleted=${a}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurn=!1,this.abortRequested=!1,!a&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${i}ms. This indicates a code path that should have emitted turn_complete but didn't. Forcing failed turn_complete to prevent state stuck.`),this.emitAcodeEvent("error",{message:"ACode turn completed without proper completion event (internal error)"}),this.emitAcodeEvent("turn_complete",{failed:!0}),m("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(m(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,contextVersion:t})})}}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,s=this.config.workingDirectory,a=this.config;return{spawnSubAgent:async i=>{const u=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,workingDirectory:s,parentConfig:{...a,sharedMcpConnections:this.state?.mcpConnections}});return await e.start(u),{subId:u}},listSubAgents:async()=>{const i=e.listByParent(t),u=[],r=[];for(const c of i){const l={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"?u.push(l):r.push(l)}return r.sort((c,l)=>(l.endedAt??0)-(c.endedAt??0)),{running:u,history:r}},getSubAgentStatus:async i=>{const u=e.getSubAgent(i);return u?{subId:u.subId,subagentType:u.subagentType,description:u.description,status:u.status,startedAt:u.startedAt,endedAt:u.endedAt,durationMs:u.durationMs,prompt:u.prompt,result:u.result,errorMessage:u.errorMessage,contextSnapshot:u.contextSnapshot}:null},awaitSubAgents:async(i,u)=>{const r=new Set;for(const c of i)this.pendingAwaitedSubIds.add(c),r.add(c);try{return await e.awaitCompletion(i,u)}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 a of o)this.pendingAwaitedSubIds.add(a);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const a of o)this.pendingAwaitedSubIds.delete(a)}}:null,awaitBgCommands:(o,s)=>{for(const a of o)this.pendingAwaitedBgTaskIds.add(a);try{return K.awaitCompletion(e,o,s)}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()}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(s=>{m(`[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);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),K.interruptAwaits(e,t)}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.rejectAllQuestionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await H("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await H("ACode background commands shutdown",K.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),H("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await H("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(),te)try{J.promises.appendFile(ke,`[${new Date().toISOString()}] runtime stopped | ---
12
- `,"utf-8").catch(()=>{})}catch{}}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",s,a,i,u="",r=0;m(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const c=50;for(let l=0;l<c;l+=1){if(m(`[ACodeRuntime] \u{1F504} Iteration ${l+1} starting...`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${l+1}, aborting`),{text:"",totalOutputTextLength:u.length};const g=Date.now(),y=await this.requestChatCompletion(e),b=Date.now()-g;if(m(`[ACodeRuntime] \u{1F916} AI request completed in ${b}ms, choices: ${y.choices?.length||0}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${l+1}`),{text:"",totalOutputTextLength:u.length};if(this.state.terminated)throw m(`[ACodeRuntime] Runtime terminated at iteration ${l+1}`),new Error("ACode runtime was stopped during the active turn");const d=y.choices?.[0];a=JSON.stringify(y,null,2),i=typeof d?.finish_reason=="string"?d.finish_reason:void 0;const $=d?.message,h=typeof $?.content=="string"?$.content:"",f=Array.isArray($?.tool_calls)?$.tool_calls:[];if(m(`[ACodeRuntime] AI response: content=${h?h.slice(0,100)+(h.length>100?"...":""):"(empty)"}, toolCalls=${f.length}, finishReason=${i||"(none)"}`),y.usage){const A=y.usage.prompt_tokens??y.usage.input_tokens,M=y.usage.completion_tokens??y.usage.output_tokens;typeof A=="number"&&typeof M=="number"&&(s={inputTokens:A,outputTokens:M},r+=A,this.state.accumulatedInputTokens=A,this.state.accumulatedOutputTokens=M,m(`[ACodeRuntime] \u{1F4B0} Token usage: input=${A}, output=${M} (turn accumulated cost: input=${r})`))}if(this.state.conversation.push({role:"assistant",content:h||null,tool_calls:f.length>0?f:void 0}),h&&(o=h,u+=h,m(`[ACodeRuntime] \u2728 Captured assistant text: ${h.slice(0,80)}...`)),f.length===0)return m(`[ACodeRuntime] \u2705 No tool calls at iteration ${l+1}, completing turn`),{text:o,usage:s,responseBody:a,finishReason:i,totalOutputTextLength:u.length};const C=f.map(A=>A.function.name).join(", ");m(`[ACodeRuntime] \u{1F527} Executing ${f.length} tool(s) at iteration ${l+1}: ${C}`);const _=Date.now();await this.handleToolCalls(f,e,t);const k=Date.now()-_;if(m(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${k}ms at iteration ${l+1}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${l+1}`),{text:"",totalOutputTextLength:u.length};m(`[ACodeRuntime] \u{1F504} Preparing iteration ${l+2}...`)}return console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: Reached safety limit of ${c} iterations! This indicates a potential infinite loop. Forcing turn completion.`),{text:o||`ACode \u5DF2\u8FBE\u5230\u5B89\u5168\u8FED\u4EE3\u4E0A\u9650\uFF08${c}\u6B21\uFF09\uFF0C\u5F3A\u5236\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD\u3002`,usage:s,responseBody:a,finishReason:i||"safety_iteration_limit_reached",totalOutputTextLength:u.length}}async summarizeConversationWithLLM(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured for LLM summarization");const s={"Content-Type":"application/json"};t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`);const a={model:t.model,stream:!1,messages:[{role:"system",content:"You are a helpful AI assistant tasked with summarizing conversations. When asked to summarize, provide a detailed but concise summary of the conversation. Focus on information that would be helpful for continuing the conversation, especially what was in progress and what needs to happen next. Do not respond to any questions in the conversation, only output the summary."},{role:"user",content:`Below is an earlier conversation (${e.messageCount} messages) that needs to be summarized to free context space (current context limit: ${e.contextLimit} tokens).
10
+ `);this.initialConversation=ie(L),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:a,permissions:i,mcpConnections:l,ownsMcpConnections:r,exposedTools:k,commands:$,commandRegistry:N,conversation:ie(L),accumulatedInputTokens:0,accumulatedOutputTokens:0},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:$.length});const P=ae(a);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:$.length,estimatedContextTokens:Mt(O,k),contextLimit:P.contextLimit,maxOutput:P.maxOutput,...P.inputLimit!==void 0?{inputLimit:P.inputLimit}:{},compactionThreshold:P.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:l.length,builtInToolCount:g.length,toolCount:k.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:k.map(p=>({name:p.exposedName,source:p.kind==="mcp"?`${p.serverName}.${p.toolName}`:`builtin.${p.toolName}`,description:p.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(p=>({name:p.name,description:p.description,directory:p.directory})),skillGroups:o.map(p=>({dir:p.dir,exists:p.exists,skills:p.skills.map(z=>({name:z.name,description:z.description,directory:z.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:$.length,commandDirs:T,commands:$.map(p=>({name:p.name,description:p.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=V.join(this.config.workingDirectory,".acode","skills"),o=V.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,a=[],i=[];for(const u of[e,t,o]){if(!u)continue;const c=V.resolve(u);if(!s.has(c)){s.add(c),a.push(await mt(u));try{await J.promises.access(c),i.push(c)}catch{}}}const l=new Map;for(const u of a)for(const c of u.skills)l.set(c.name,c);return{skills:[...l.values()],skillGroups:a,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=J.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=J.watch(t,()=>{this.scheduleSkillRefresh()})}catch{continue}}o&&(o.on("error",()=>{}),this.skillWatchers.push(o))}}scheduleSkillRefresh(){this.skillRefreshTimer&&clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=setTimeout(()=>{this.skillRefreshTimer=null,this.refreshSkills()},j.SKILL_REFRESH_DEBOUNCE_MS)}async refreshSkills(){if(!(!this.state.started||this.state.terminated))try{const{skills:e,skillGroups:t}=await this.loadAllSkills();this.skillTool&&this.skillTool.refresh(e),this.state.skills=e,this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:e.length,skills:e.map(o=>({name:o.name,description:o.description,directory:o.directory})),skillGroups:t.map(o=>({dir:o.dir,exists:o.exists,skills:o.skills.map(s=>({name:s.name,description:s.description,directory:s.directory}))}))}),m(`[skill-watch] Skills refreshed: ${e.length} skills (${e.map(o=>o.name).join(", ")||"none"})`,{sessionId:this.config.sessionId})}catch(e){console.error("[skill-watch] Failed to refresh skills:",e instanceof Error?e.message:e)}}stopSkillWatchers(){this.skillRefreshTimer&&(clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=null);for(const e of this.skillWatchers)try{e.close()}catch{}this.skillWatchers=[]}startCompactionDebugLog(){if(!te||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:a}=ae(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,l=X(this.state.conversation)+Ee(this.state.exposedTools),r=Math.max(i,l),u=H(this.state.conversation),c=this.state.started&&!this.state.terminated,g=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${u}KB`,`estimation=${l} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${a}`,`remainingToTrigger=${Math.max(0,a-i)}`,`isRunning=${c}`,`shouldCompact=${c?r>=a:!1}`,"---"].join(" | ");J.promises.appendFile(ke,g+`
11
+ `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;m(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${t}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const o=this.submitQueue.then(()=>(m(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmit(e,t)));return this.submitQueue=o.catch(()=>{m("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),m("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}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=ie(this.initialConversation),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t){const o=Date.now();if(m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),m("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),m(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),m(`[ACodeRuntime] \u{1F522} Context version: ${t}`),m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const s=e.trim();let a=!1;try{m("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const i=Date.now(),l=await this.hookBus.dispatch("UserPromptSubmit",{prompt:s}),r=Date.now()-i;if(m(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${r}ms, results: ${l.length}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const u=se(l);if(u){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${u.message}`),this.emitAcodeEvent("error",{message:u.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}m("[ACodeRuntime] \u{1F50D} Expanding command if any...");const c=this.state.commandRegistry.expand(s),g=c?.prompt.trim()||s,y=c?.command.allowedTools;if(c&&(m(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${c.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:c.command.name,arguments:c.argumentsText,sourcePath:c.command.sourcePath})),!this.state.provider.baseURL||!this.state.provider.apiKey){m("[ACodeRuntime] \u26A0\uFE0F No provider configured, using fallback response");const _=Qt(g,this.state);this.emitAcodeEvent("assistant_delta",{text:_}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:_.length}}),a=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}m("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const w=ue(g);if(w.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");m("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const d=await Ie(w.content);if(this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}m("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:d}),m(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),m("[ACodeRuntime] Starting runModelTurn...");const b=Date.now(),h=await this.runModelTurn(y,t),f=Date.now()-b;if(m(`[ACodeRuntime] \u2705 runModelTurn completed in ${f}ms`),m(`[ACodeRuntime] \u{1F4DD} Result: text=${h.text?h.text.slice(0,80)+(h.text.length>80?"...":""):"(empty)"}, finishReason=${h.finishReason||"(none)"}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}h.text&&!this.state.provider.stream&&(m("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:h.text})),m("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:h.usage??{inputTokens:g.length,outputTokens:h.totalOutputTextLength??h.text.length},...h.responseBody?{responseBody:h.responseBody}:{},...h.finishReason?{finishReason:h.finishReason}:{}}),m(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(h.usage?"":" (estimated, no provider usage)")),a=!0;const C=Date.now()-o;m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),m(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${C}ms`),m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(i){const l=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${l}ms:`,i instanceof Error?i.message:String(i)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",i instanceof Error?i.stack:"(no stack)"),this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){m("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),a=!0;return}m("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:i instanceof Error?i.message:String(i)}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0}finally{const i=Date.now()-o;m(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${i}ms`),m(`[ACodeRuntime] \u{1F50D} turnCompleted=${a}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurn=!1,this.abortRequested=!1,!a&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${i}ms. This indicates a code path that should have emitted turn_complete but didn't. Forcing failed turn_complete to prevent state stuck.`),this.emitAcodeEvent("error",{message:"ACode turn completed without proper completion event (internal error)"}),this.emitAcodeEvent("turn_complete",{failed:!0}),m("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(m(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,contextVersion:t})})}}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,s=this.config.workingDirectory,a=this.config;return{spawnSubAgent:async i=>{const l=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,workingDirectory:s,parentConfig:{...a,sharedMcpConnections:this.state?.mcpConnections}});return await e.start(l),{subId:l}},listSubAgents:async()=>{const i=e.listByParent(t),l=[],r=[];for(const u of i){const c={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(c):r.push(c)}return r.sort((u,c)=>(c.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,s)=>{for(const a of o)this.pendingAwaitedSubIds.add(a);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const a of o)this.pendingAwaitedSubIds.delete(a)}}:null,awaitBgCommands:(o,s)=>{for(const a of o)this.pendingAwaitedBgTaskIds.add(a);try{return K.awaitCompletion(e,o,s)}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()}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(s=>{m(`[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);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),K.interruptAwaits(e,t)}detachCurrentToolExecution(){const e=this.toolSettleSlot;return!e||!e.settlable||e.settled?!1:(e.settled=!0,e.resolveSettle?.(),m(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${e.toolName} (toolCallId=${e.toolCallId}) to background`),!0)}beginToolSettle(e,t,o){const s=e.toolName==="Bash"&&typeof t.wait_seconds=="number"&&t.wait_seconds>0,a=++this.toolSettleSeq;let i;const l=s?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:a,toolName:e.toolName,toolCallId:o,settlable:s,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.rejectAllQuestionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await Q("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await Q("ACode background commands shutdown",K.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),Q("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await Q("ACode Stop hooks",this.hookBus.dispatch("Stop",{reason:"session_stop"}),t=>{this.emitAcodeEvent("error",{message:t})}),this.state.terminated=!0,this.sessionCompleteEmitted||(this.sessionCompleteEmitted=!0,this.emitAcodeEvent("session_complete",{exitCode:0})),this.stopCompactionDebugLog(),this.stopSkillWatchers(),te)try{J.promises.appendFile(ke,`[${new Date().toISOString()}] runtime stopped | ---
12
+ `,"utf-8").catch(()=>{})}catch{}}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",s,a,i,l="",r=0;m(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const u=50;for(let c=0;c<u;c+=1){if(m(`[ACodeRuntime] \u{1F504} Iteration ${c+1} starting...`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${c+1}, aborting`),{text:"",totalOutputTextLength:l.length};const g=Date.now(),y=await this.requestChatCompletion(e),w=Date.now()-g;if(m(`[ACodeRuntime] \u{1F916} AI request completed in ${w}ms, choices: ${y.choices?.length||0}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${c+1}`),{text:"",totalOutputTextLength:l.length};if(this.state.terminated)throw m(`[ACodeRuntime] Runtime terminated at iteration ${c+1}`),new Error("ACode runtime was stopped during the active turn");const d=y.choices?.[0];a=JSON.stringify(y,null,2),i=typeof d?.finish_reason=="string"?d.finish_reason:void 0;const b=d?.message,h=typeof b?.content=="string"?b.content:"",f=Array.isArray(b?.tool_calls)?b.tool_calls:[];if(m(`[ACodeRuntime] AI response: content=${h?h.slice(0,100)+(h.length>100?"...":""):"(empty)"}, toolCalls=${f.length}, finishReason=${i||"(none)"}`),y.usage){const T=y.usage.prompt_tokens??y.usage.input_tokens,$=y.usage.completion_tokens??y.usage.output_tokens;typeof T=="number"&&typeof $=="number"&&(s={inputTokens:T,outputTokens:$},r+=T,this.state.accumulatedInputTokens=T,this.state.accumulatedOutputTokens=$,m(`[ACodeRuntime] \u{1F4B0} Token usage: input=${T}, output=${$} (turn accumulated cost: input=${r})`))}if(this.state.conversation.push({role:"assistant",content:h||null,tool_calls:f.length>0?f:void 0}),h&&(o=h,l+=h,m(`[ACodeRuntime] \u2728 Captured assistant text: ${h.slice(0,80)}...`)),f.length===0)return m(`[ACodeRuntime] \u2705 No tool calls at iteration ${c+1}, completing turn`),{text:o,usage:s,responseBody:a,finishReason:i,totalOutputTextLength:l.length};const C=f.map(T=>T.function.name).join(", ");m(`[ACodeRuntime] \u{1F527} Executing ${f.length} tool(s) at iteration ${c+1}: ${C}`);const _=Date.now();await this.handleToolCalls(f,e,t);const k=Date.now()-_;if(m(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${k}ms at iteration ${c+1}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${c+1}`),{text:"",totalOutputTextLength:l.length};m(`[ACodeRuntime] \u{1F504} Preparing iteration ${c+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:s,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 s={"Content-Type":"application/json"};t.apiKey&&(s.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
- `+rt}]},i=new AbortController;this.abortController=i;let u=!1;try{return await x((async()=>{const r=await x(fetch(oe(o),{method:"POST",headers:s,body:JSON.stringify(a),signal:i.signal}),t.requestTimeoutMs,"ACode LLM summarization",()=>{u=!0,i.abort()});if(!r.ok){const g=await x(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{u=!0,i.abort()}),y=g.length>500?`${g.slice(0,500)}...(truncated, total ${g.length} chars)`:g;throw new Error(`ACode LLM summarization request failed: ${r.status} ${y}`)}const l=(await x(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{u=!0,i.abort()})).choices?.[0]?.message?.content;if(!l||l.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return l})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{i.abort()})}catch(r){throw r instanceof Error&&r.name==="AbortError"?u?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:a,inputLimit:i,threshold:u}=ae(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,c=X(this.state.conversation)+Ee(this.state.exposedTools),l=Math.max(r,c),g=l>=u;if(m(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${c}, effectiveUsed=${l}, contextLimit=${s}, inputLimit=${i??"n/a"}, maxOutput=${a}, triggerThreshold=${u}, shouldCompact=${g}`),g){const T=Q(this.state.conversation),S=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:S,sizeKB:T,estimatedTokens:c,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:r>=u?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(S,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${l} tokens, \u9608\u503C: ${u}, \u89E6\u53D1: ${r>=u?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const R=await he(this.state.conversation,s,a,{llmSummarizer:E=>this.summarizeConversationWithLLM(E),onPhase:E=>this.handleCompactionPhase(S,E),actualUsedTokens:l}),w=Q(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:S,sizeBeforeKB:T,sizeAfterKB:w,freedKB:Math.round((T-w)*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 y=await Ht(this.state.conversation,Re,s,a,T=>this.summarizeConversationWithLLM(T));y>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${y} older messages to fit within ${Re} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const b=this.state.exposedTools.filter(T=>Ft(T,this.state.permissions,e)),d=()=>{const T={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(T.reasoning_effort=t.effort),t.stream&&(T.stream_options={include_usage:!0}),b.length>0&&(T.tools=Ue(b),T.tool_choice="auto"),T},$="POST",h=jt(o),f=so(t),C=io(f),_=T=>{const S=JSON.stringify(T,null,2);m(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${h}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:h,requestMethod:$,requestUrl:h,requestHeaders:C,stream:t.stream,messageCount:this.state.conversation.length,toolCount:b.length,lastUserMessagePreview:Wt(this.state.conversation),estimatedContextTokens:ve(S),requestBody:S})};let k=d();_(k);const A=t.requestRetryCount===re,M=A?1/0:t.requestRetryCount+1;let N=!1;for(let T=1;A||T<=M;T+=1){this.state.terminated||(this.abortRequested=!1),T>1&&_(k);const S=new AbortController;this.abortController=S;let R=!1;try{return await x((async()=>{const w=await x(fetch(oe(o),{method:$,headers:f,body:JSON.stringify(k),signal:S.signal}),t.requestFirstByteTimeoutMs,"ACode provider request",()=>{R=!0,S.abort()});if(!w.ok){const O=await x(w.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{R=!0,S.abort()}),D=O.length>500?`${O.slice(0,500)}...(truncated, total ${O.length} chars)`:O;throw new Error(`ACode provider request failed: ${w.status} ${D}`)}const E=w.headers?.get?.("content-type")||"";if(t.stream&&E.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(w,t.requestStreamIdleTimeoutMs,S,t.requestFirstByteTimeoutMs);const L=await x(w.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{R=!0,S.abort()});return v(L)?L:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof L}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{S.abort()})}catch(w){let E;if(w instanceof Error&&w.name==="AbortError"?R?E=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?E=new Error("ACode provider request aborted by user"):E=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):E=w instanceof Error?w:new Error(String(w)),!N&&!this.abortRequested&&!this.state.terminated&&Le(E)){const p=Q(this.state.conversation),z=X(this.state.conversation),ne=this.state.conversation.length,B=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:B,sizeKB:p,estimatedTokens:z,messageCount:ne,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(B,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${ne}\u6761, \u5927\u5C0F: ${p}KB`),this.emitCompactionPhase(B,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const W=at(this.state.conversation,s);this.emitCompactionPhase(B,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${W.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${W.freedTokens} tokens`),this.emitCompactionPhase(B,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const Y=await fe(this.state.conversation,{llmSummarizer:ze=>this.summarizeConversationWithLLM(ze),contextLimit:s});this.emitCompactionPhase(B,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${Y} \u6761\u6D88\u606F`);const me=Q(this.state.conversation),Be=X(this.state.conversation),qe=this.state.conversation.length;N=!0;const de=W.prunedCount+Y;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:B,sizeBeforeKB:p,sizeAfterKB:me,freedKB:Math.round((p-me)*10)/10,tokensBefore:z,tokensAfter:Be,messageCountBefore:ne,messageCountAfter:qe,strategy:Y>0?"summarize":"prune",freedTokens:W.freedTokens,prunedToolMessages:W.prunedCount,summarizedMessages:Y,trigger:"provider_overflow_error"}),de===0)throw E;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${de} older messages and rebuilt the request instead of retrying the same oversized payload`}),k=d(),_(k),T-=1;continue}if(!((A||T<M)&&!this.abortRequested&&!this.state.terminated&&Gt(E)))throw E;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${T}${A?"":`/${M}`} failed; retrying: ${E.message}`,nonFatal:!0});const O=Math.min(yt,gt*Math.pow(2,T-1)),D=Math.random()*1e3;await Mt(O+D)}finally{this.abortController===S&&(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 a=e.body.getReader(),i=new TextDecoder,u=new Map;let r="",c="",l;const g=b=>{for(const d of uo(b)){if(d==="[DONE]")continue;const $=JSON.parse(d);if(!v($))continue;const h=$.usage;h&&(l=h);const C=$.choices?.[0]?.delta,_=Zt(C);_&&this.emitAcodeEvent("thinking_delta",{text:_});const k=typeof C?.content=="string"?C.content:"";k&&(r+=k,this.emitAcodeEvent("assistant_delta",{text:k}));const A=Array.isArray(C?.tool_calls)?C.tool_calls:[];for(const M of A)co(u,M)}};let y=!0;for(;;){const b=y&&s?s:t,{done:d,value:$}=await x(a.read(),b,y?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(y=!1,d)break;c+=i.decode($,{stream:!0});const h=c.split(/\r?\n\r?\n/);c=h.pop()??"";for(const f of h)g(f)}return c+=i.decode(),c.trim()&&g(c),{choices:[{message:{content:r||null,tool_calls:lo(u)}}],...l?{usage:l}:{}}}async handleToolCalls(e,t,o=this.contextVersion){m(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=i=>ge(i.function.name)==="poll_message",a=[...e.filter(i=>!s(i)),...e.filter(i=>s(i))];e.length>1&&a.some((i,u)=>i!==e[u])&&m(`[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)){m("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const u=i.function.name;m(`[ACodeRuntime] \u{1F50D} Looking up tool: ${u}`);let r=this.state.exposedTools.find(c=>c.exposedName===u);if(r||(r=this.state.exposedTools.find(c=>c.toolName===u),r&&m(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${u} -> ${r.exposedName}`)),!r){console.error(`[ACodeRuntime] \u274C Tool not found: ${u}, 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: ${u}`});continue}m(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const _=Pe(i.function.arguments);m(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(_).slice(0,200)}`),le(r,this.state.permissions,t);const k=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:_});if(this.isTurnSuperseded(o))return;const A=se(k);if(A)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${A.message}`),new Error(A.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:_,argumentsPreview:Oe(_)});const M=Date.now(),N=Jt(r,_,this.state.provider.mcpToolTimeoutMs);m(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${N}ms, abortRequested: ${this.abortRequested})`),N<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${N})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const T=await x(r.execute(_,{onOutput:w=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:w.stream,text:w.text,sequence:w.sequence,cwd:w.cwd,commandLineCount:w.commandLineCount,...w.commandFilePath?{commandFilePath:w.commandFilePath}:{}})},toolCallId:i.id}),N,`ACode built-in tool ${r.toolName}`),S=Date.now()-M;if(m(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${S}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,result:P(T)}),this.isTurnSuperseded(o)))return;const R=P(T);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${R.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,result:R}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:R}),await this.appendSyntheticMultimodalUserMessage(R,i.id,o);continue}const c=this.state.mcpConnections.find(_=>_.serverName===r.serverName);if(!c){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(_=>_.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const l=Pe(i.function.arguments);m(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(l).slice(0,200)}`),le(r,this.state.permissions,t);const g=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:l});if(this.isTurnSuperseded(o))return;const y=se(g);if(y)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${y.message}`),new Error(y.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.serverName,tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:l,argumentsPreview:Oe(l)});const b=mt(r.toolName),d=b?this.state.provider.mcpPollingToolTimeoutMs:this.state.provider.mcpToolTimeoutMs,$=Date.now();m(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${d}ms, polling: ${b})`);const h=b&&ge(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(c,r,l,d):await this.callMcpToolWithTimeout(c,r,l,d,b),f=Date.now()-$;if(m(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${f}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:P(h)}),this.isTurnSuperseded(o)))return;const C=P(h);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${C.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,result:C}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:C}),await this.appendSyntheticMultimodalUserMessage(C,i.id,o)}catch(c){const l=c instanceof Error&&c.message.includes("timed out after"),g=c instanceof Error&&c.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${l}, isAbortError=${g}`,c instanceof Error?c.message:String(c)),this.isTurnSuperseded(o)){m("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw m(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,result:`[aborted] ${c instanceof Error?c.message:String(c)}`,failed:!0,aborted:!0}),c instanceof Error?c:new Error(String(c));m(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${l})`),this.appendToolFailureResult(i,r,c)}}m(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,s,a){const i=s>0?s:At,r=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const c=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await x(Promise.race([e.client.callTool({name:t.toolName,arguments:r},void 0,{timeout:i}),c.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(l){if(!a||s>0||!Yt(l))throw l;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{c.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
18
+ `+lt}]},i=new AbortController;this.abortController=i;let l=!1;try{return await E((async()=>{const r=await E(fetch(oe(o),{method:"POST",headers:s,body:JSON.stringify(a),signal:i.signal}),t.requestTimeoutMs,"ACode LLM summarization",()=>{l=!0,i.abort()});if(!r.ok){const g=await E(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{l=!0,i.abort()}),y=g.length>500?`${g.slice(0,500)}...(truncated, total ${g.length} chars)`:g;throw new Error(`ACode LLM summarization request failed: ${r.status} ${y}`)}const c=(await E(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{l=!0,i.abort()})).choices?.[0]?.message?.content;if(!c||c.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return c})(),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:s,maxOutput:a,inputLimit:i,threshold:l}=ae(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,u=X(this.state.conversation)+Ee(this.state.exposedTools),c=Math.max(r,u),g=c>=l;if(m(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${u}, effectiveUsed=${c}, contextLimit=${s}, inputLimit=${i??"n/a"}, maxOutput=${a}, triggerThreshold=${l}, shouldCompact=${g}`),g){const A=H(this.state.conversation),R=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:R,sizeKB:A,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(R,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${c} tokens, \u9608\u503C: ${l}, \u89E6\u53D1: ${r>=l?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const x=await he(this.state.conversation,s,a,{llmSummarizer:S=>this.summarizeConversationWithLLM(S),onPhase:S=>this.handleCompactionPhase(R,S),actualUsedTokens:c}),M=H(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:R,sizeBeforeKB:A,sizeAfterKB:M,freedKB:Math.round((A-M)*10)/10,strategy:x.strategy,freedTokens:x.freedTokens,tokensBefore:x.tokensBefore,tokensAfter:x.tokensAfter,prunedToolMessages:x.prunedToolMessages,summarizedMessages:x.summarizedMessages,messageCountBefore:x.messageCountBefore,messageCountAfter:x.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const y=await Yt(this.state.conversation,Re,s,a,A=>this.summarizeConversationWithLLM(A));y>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${y} older messages to fit within ${Re} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const w=this.state.exposedTools.filter(A=>Wt(A,this.state.permissions,e)),d=()=>{const A={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(A.reasoning_effort=t.effort),t.stream&&(A.stream_options={include_usage:!0}),w.length>0&&(A.tools=qe(w),A.tool_choice="auto"),A},b="POST",h=Jt(o),f=ro(t),C=ao(f),_=A=>{const R=JSON.stringify(A,null,2);m(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${h}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:h,requestMethod:b,requestUrl:h,requestHeaders:C,stream:t.stream,messageCount:this.state.conversation.length,toolCount:w.length,lastUserMessagePreview:Kt(this.state.conversation),estimatedContextTokens:xe(R),requestBody:R})};let k=d();_(k);const T=t.requestRetryCount===re,$=T?1/0:t.requestRetryCount+1;let N=!1;for(let A=1;T||A<=$;A+=1){this.state.terminated||(this.abortRequested=!1),A>1&&_(k);const R=new AbortController;this.abortController=R;let x=!1;try{return await E((async()=>{const M=await E(fetch(oe(o),{method:b,headers:f,body:JSON.stringify(k),signal:R.signal}),t.requestFirstByteTimeoutMs,"ACode provider request",()=>{x=!0,R.abort()});if(!M.ok){const O=await E(M.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{x=!0,R.abort()}),P=O.length>500?`${O.slice(0,500)}...(truncated, total ${O.length} chars)`:O;throw new Error(`ACode provider request failed: ${M.status} ${P}`)}const S=M.headers?.get?.("content-type")||"";if(t.stream&&S.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(M,t.requestStreamIdleTimeoutMs,R,t.requestFirstByteTimeoutMs);const L=await E(M.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{x=!0,R.abort()});return v(L)?L:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof L}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{R.abort()})}catch(M){let S;if(M instanceof Error&&M.name==="AbortError"?x?S=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?S=new Error("ACode provider request aborted by user"):S=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):S=M instanceof Error?M:new Error(String(M)),!N&&!this.abortRequested&&!this.state.terminated&&Oe(S)){const p=H(this.state.conversation),z=X(this.state.conversation),ne=this.state.conversation.length,q=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:q,sizeKB:p,estimatedTokens:z,messageCount:ne,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(q,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${ne}\u6761, \u5927\u5C0F: ${p}KB`),this.emitCompactionPhase(q,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const W=ut(this.state.conversation,s);this.emitCompactionPhase(q,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${W.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${W.freedTokens} tokens`),this.emitCompactionPhase(q,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const Y=await fe(this.state.conversation,{llmSummarizer:Fe=>this.summarizeConversationWithLLM(Fe),contextLimit:s});this.emitCompactionPhase(q,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${Y} \u6761\u6D88\u606F`);const me=H(this.state.conversation),Be=X(this.state.conversation),ze=this.state.conversation.length;N=!0;const de=W.prunedCount+Y;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:q,sizeBeforeKB:p,sizeAfterKB:me,freedKB:Math.round((p-me)*10)/10,tokensBefore:z,tokensAfter:Be,messageCountBefore:ne,messageCountAfter:ze,strategy:Y>0?"summarize":"prune",freedTokens:W.freedTokens,prunedToolMessages:W.prunedCount,summarizedMessages:Y,trigger:"provider_overflow_error"}),de===0)throw S;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${de} older messages and rebuilt the request instead of retrying the same oversized payload`}),k=d(),_(k),A-=1;continue}if(!((T||A<$)&&!this.abortRequested&&!this.state.terminated&&Vt(S)))throw S;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${A}${T?"":`/${$}`} failed; retrying: ${S.message}`,nonFatal:!0});const O=Math.min(At,Tt*Math.pow(2,A-1)),P=Math.random()*1e3;await Rt(O+P)}finally{this.abortController===R&&(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 a=e.body.getReader(),i=new TextDecoder,l=new Map;let r="",u="",c;const g=w=>{for(const d of co(w)){if(d==="[DONE]")continue;const b=JSON.parse(d);if(!v(b))continue;const h=b.usage;h&&(c=h);const C=b.choices?.[0]?.delta,_=to(C);_&&this.emitAcodeEvent("thinking_delta",{text:_});const k=typeof C?.content=="string"?C.content:"";k&&(r+=k,this.emitAcodeEvent("assistant_delta",{text:k}));const T=Array.isArray(C?.tool_calls)?C.tool_calls:[];for(const $ of T)mo(l,$)}};let y=!0;for(;;){const w=y&&s?s:t,{done:d,value:b}=await E(a.read(),w,y?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(y=!1,d)break;u+=i.decode(b,{stream:!0});const h=u.split(/\r?\n\r?\n/);u=h.pop()??"";for(const f of h)g(f)}return u+=i.decode(),u.trim()&&g(u),{choices:[{message:{content:r||null,tool_calls:po(l)}}],...c?{usage:c}:{}}}async handleToolCalls(e,t,o=this.contextVersion){m(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=i=>ge(i.function.name)==="poll_message",a=[...e.filter(i=>!s(i)),...e.filter(i=>s(i))];e.length>1&&a.some((i,l)=>i!==e[l])&&m(`[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)){m("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const l=i.function.name;m(`[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&&m(`[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}m(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const _=Le(i.function.arguments);m(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(_).slice(0,200)}`),ce(r,this.state.permissions,t);const k=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:_});if(this.isTurnSuperseded(o))return;const T=se(k);if(T)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${T.message}`),new Error(T.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:_,argumentsPreview:Ue(_)});const $=Date.now(),N=Ht(r,_,this.state.provider.mcpToolTimeoutMs);m(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${N}ms, abortRequested: ${this.abortRequested})`),N<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${N})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const A=this.beginToolSettle(r,_,i.id);try{const R=await E(r.execute(_,{onOutput:S=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:S.stream,text:S.text,sequence:S.sequence,cwd:S.cwd,commandLineCount:S.commandLineCount,...S.commandFilePath?{commandFilePath:S.commandFilePath}:{}})},toolCallId:i.id,...A.signal?{settleSignal:A.signal}:{}}),N,`ACode built-in tool ${r.toolName}`),x=Date.now()-$;if(m(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${x}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 M=D(R);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${M.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,result:M}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:M}),await this.appendSyntheticMultimodalUserMessage(M,i.id,o)}finally{this.clearToolSettle(A.seq)}continue}const u=this.state.mcpConnections.find(_=>_.serverName===r.serverName);if(!u){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(_=>_.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const c=Le(i.function.arguments);m(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(c).slice(0,200)}`),ce(r,this.state.permissions,t);const g=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:c});if(this.isTurnSuperseded(o))return;const y=se(g);if(y)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${y.message}`),new Error(y.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.serverName,tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:c,argumentsPreview:Ue(c)});const w=pt(r.toolName),d=w?this.state.provider.mcpPollingToolTimeoutMs:this.state.provider.mcpToolTimeoutMs,b=Date.now();m(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${d}ms, polling: ${w})`);const h=w&&ge(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(u,r,c,d):await this.callMcpToolWithTimeout(u,r,c,d,w),f=Date.now()-b;if(m(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${f}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:D(h)}),this.isTurnSuperseded(o)))return;const C=D(h);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${C.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,result:C}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:C}),await this.appendSyntheticMultimodalUserMessage(C,i.id,o)}catch(u){const c=u instanceof Error&&u.message.includes("timed out after"),g=u instanceof Error&&u.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${c}, isAbortError=${g}`,u instanceof Error?u.message:String(u)),this.isTurnSuperseded(o)){m("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw m(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,result:`[aborted] ${u instanceof Error?u.message:String(u)}`,failed:!0,aborted:!0}),u instanceof Error?u:new Error(String(u));m(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${c})`),this.appendToolFailureResult(i,r,u)}}m(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,s,a){const i=s>0?s:Ct,r=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const u=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await E(Promise.race([e.client.callTool({name:t.toolName,arguments:r},void 0,{timeout:i}),u.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(c){if(!a||s>0||!Xt(c))throw c;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{u.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
19
19
  Error: ${o.error}`:`Sub-agent ${o.subId} [${o.status}]: ${o.description}
20
- Output: ${o.output.length>500?o.output.slice(0,500)+"... (truncated)":o.output}`;return{msgId:`subagent-completion-${o.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:s,requireReply:!1,prompt:`Sub-agent ${o.subId} (${o.description}) has reached terminal state: ${o.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}});return{content:[{type:"text",text:JSON.stringify({directMessages:t,groupMessages:[],fromBuffer:!1,systemMessages:[]},null,2)}]}}static mergeSubAgentCompletionsIntoMcpResult(e,t){if(t.length===0)return e;const o=P(e);let s;try{s=JSON.parse(o)}catch{return e}const i=[...t.map(u=>{const r=u.error?`Sub-agent ${u.subId} [${u.status}]: ${u.description}
21
- Error: ${u.error}`:`Sub-agent ${u.subId} [${u.status}]: ${u.description}
22
- Output: ${u.output.length>500?u.output.slice(0,500)+"... (truncated)":u.output}`;return{msgId:`subagent-completion-${u.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:r,requireReply:!1,prompt:`Sub-agent ${u.subId} (${u.description}) has reached terminal state: ${u.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:i},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const a=this.state.mcpConnections.find(i=>i.serverName==="aws-client-agent-mcp");if(!a)return m("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(a,t):e==="memory_expiration"?await this.recheckMemoryExpiration(a,t):await this.recheckMemoryCleanup(a,t)}catch(i){return m(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${i instanceof Error?i.message:String(i)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${i instanceof Error?i.message:String(i)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await x(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=P(o),a=JSON.parse(s);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 m(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(a=>`- ${a}`).join(`
20
+ Output: ${o.output.length>500?o.output.slice(0,500)+"... (truncated)":o.output}`;return{msgId:`subagent-completion-${o.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:s,requireReply:!1,prompt:`Sub-agent ${o.subId} (${o.description}) has reached terminal state: ${o.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}});return{content:[{type:"text",text:JSON.stringify({directMessages:t,groupMessages:[],fromBuffer:!1,systemMessages:[]},null,2)}]}}static mergeSubAgentCompletionsIntoMcpResult(e,t){if(t.length===0)return e;const o=D(e);let s;try{s=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()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:i},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const a=this.state.mcpConnections.find(i=>i.serverName==="aws-client-agent-mcp");if(!a)return m("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(a,t):e==="memory_expiration"?await this.recheckMemoryExpiration(a,t):await this.recheckMemoryCleanup(a,t)}catch(i){return m(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${i instanceof Error?i.message:String(i)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${i instanceof Error?i.message:String(i)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await E(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=D(o),a=JSON.parse(s);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 m(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(a=>`- ${a}`).join(`
23
23
  `);return m(`[ACodeRuntime] recheck memory_file_change: ${o.length}/${t.length} URIs still updating`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
24
24
  ${s}
25
25
 
26
- \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async i=>{const u=await this.readMemoryViaMcp(e,i);if(!u)return;const r=u.expiresAt??u.expires_at,c=u.memory_status==="recalling",l=typeof r=="string"&&new Date(r).getTime()<s;(c||l)&&o.push(i)})),o.length===0)return m(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const a=o.map(i=>`- ${i}`).join(`
26
+ \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async i=>{const l=await this.readMemoryViaMcp(e,i);if(!l)return;const r=l.expiresAt??l.expires_at,u=l.memory_status==="recalling",c=typeof r=="string"&&new Date(r).getTime()<s;(u||c)&&o.push(i)})),o.length===0)return m(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const a=o.map(i=>`- ${i}`).join(`
27
27
  `);return m(`[ACodeRuntime] recheck memory_expiration: ${o.length}/${t.length} URIs still expired or recalling`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u5904\u7406\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
28
28
  ${a}
29
29
 
30
- \u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const u=await x(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),r=P(u);o=JSON.parse(r)}catch{return{done:!1,continueMessage:"get_memory_stats \u67E5\u8BE2\u5931\u8D25\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5BB9\u91CF\u662F\u5426\u5DF2\u8FBE\u6807\uFF0C\u8BF7\u91CD\u65B0\u9A8C\u8BC1\u540E\u518D\u7EE7\u7EED\u3002"}}const s=o.by_type??{},a=[];for(const u of t){const r=u.indexOf("/");if(r<0)continue;const c=u.slice(0,r),l=u.slice(r+1),y=s[c]?.by_domain?.[l];y?.exceeded&&a.push(`${c}/${l} (\u5F53\u524D ${y.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${y.limit??"?"})`)}if(a.length===0)return m(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const i=a.map(u=>`- ${u}`).join(`
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 s=o.by_type??{},a=[];for(const l of t){const r=l.indexOf("/");if(r<0)continue;const u=l.slice(0,r),c=l.slice(r+1),y=s[u]?.by_domain?.[c];y?.exceeded&&a.push(`${u}/${c} (\u5F53\u524D ${y.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${y.limit??"?"})`)}if(a.length===0)return m(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const i=a.map(l=>`- ${l}`).join(`
31
31
  `);return m(`[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
 
@@ -75,11 +75,11 @@ ${t}
75
75
  \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
76
76
 
77
77
  \u4EE5\u4E0B ${e.uris.length} \u4E2A\u6C38\u4E45\u8BB0\u5FC6\u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D1\u751F\u53D8\u66F4\uFF1A
78
- ${e.uris.map(o=>{const s=e.fileChanges?.find(r=>r.uri===o);if(!s)return`- ${o}`;const a={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},i=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],u=i.length>0?i.map(r=>{if(r.status==="no_change")return` \xB7 ${r.path}`;const c=a[r.status]??r.status,l=r.status==="content_changed"&&r.localMd5&&r.serverMd5?` \u672C\u5730: ${r.localMd5} Server: ${r.serverMd5}`:r.status==="not_found"&&r.serverMd5?` Server: ${r.serverMd5}`:"";return` \xB7 ${r.path}\uFF08${c}${l}\uFF09`}).join(`
78
+ ${e.uris.map(o=>{const s=e.fileChanges?.find(r=>r.uri===o);if(!s)return`- ${o}`;const a={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},i=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],l=i.length>0?i.map(r=>{if(r.status==="no_change")return` \xB7 ${r.path}`;const u=a[r.status]??r.status,c=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}${c}\uFF09`}).join(`
79
79
  `):s.boundFiles&&s.boundFiles.length>0?s.boundFiles.map(r=>` \xB7 ${r}`).join(`
80
80
  `):" \u65E0\uFF08\u8BF7\u901A\u8FC7 read_memory \u67E5\u770B bound_files\uFF09";return`- ${o}
81
81
  - \u7ED1\u5B9A\u6587\u4EF6:
82
- ${u}`}).join(`
82
+ ${l}`}).join(`
83
83
  `)}
84
84
 
85
85
  \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
@@ -97,5 +97,5 @@ ${u}`}).join(`
97
97
  - \u2705 \u82E5\u5168\u90E8 memory_status \u4E3A "normal"\uFF1A\u9759\u9ED8\u7ED3\u675F
98
98
 
99
99
  \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
100
- \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=P(e)}catch{return e}let s;try{s=JSON.parse(o)}catch{return e}const a=s.directMessages;if(!Array.isArray(a)||a.length===0)return e;const i=[];let u=0;for(const c of a){const l=c._acodeAutoDelegate;if(l&&(l.type==="memory_expiration"||l.type==="memory_file_change"||l.type==="memory_cleanup")){u++;const g=Date.now(),y=l.uris.filter(f=>this.pendingMemorySubAgents.has(f)).length,b=l.uris.filter(f=>{const C=this.memoryDelegateCooldownUntil.get(f);return C!==void 0&&g<C}).length,d=l.uris.filter(f=>{if(this.pendingMemorySubAgents.has(f))return!1;const C=this.memoryDelegateCooldownUntil.get(f);return!(C!==void 0&&g<C)});if(d.length===0){m(`[ACodeRuntime] Memory ${l.type} skipped: ${y} in-progress, ${b} in cooldown (total ${l.uris.length} URIs)`);continue}const $=Array.isArray(l.fileChanges)?l.fileChanges.filter(f=>d.includes(f.uri)):void 0,h=this.buildMemoryDelegatePrompt({type:l.type,uris:d,fileChanges:$});try{const f=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:"explore",description:`Memory ${l.type} auto-delegate (${d.length} items)`,prompt:h,workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const A of d)this.pendingMemorySubAgents.set(A,f);const C=new Set(d);t.subscribe(f,()=>{const A=t.getSubAgent(f);if(A&&(A.status==="completed"||A.status==="failed"||A.status==="cancelled")){const M=Date.now();for(const N of C)this.pendingMemorySubAgents.get(N)===f&&this.pendingMemorySubAgents.delete(N),this.memoryDelegateCooldownUntil.set(N,M+$e);for(const[N,T]of this.memoryDelegateCooldownUntil)T<=M&&this.memoryDelegateCooldownUntil.delete(N);m(`[ACodeRuntime] Memory delegate sub-agent ${f} finished (${A.status}), ${C.size} URI(s) entered ${$e}ms cooldown`)}});const _=l.type,k=async(A,M)=>this.recheckMemoryDelegate(_,d,A,M);await t.startWithRecheck(f,k,3),m(`[ACodeRuntime] Auto-delegated memory ${l.type} to sub-agent ${f} (${d.length} URIs, ${l.uris.length-d.length} already in progress)`)}catch(f){for(const C of d)this.pendingMemorySubAgents.delete(C);m(`[ACodeRuntime] Failed to auto-delegate memory ${l.type} (suppressed, will retry next poll): ${f instanceof Error?f.message:String(f)}`)}}else i.push(c)}if(u===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 a=this.config.subAgentManager;if(!a)return await this.callMcpToolWithTimeout(e,t,o,s,!0);const i=a.takeCompletedSubAgents();if(i.length>0)return m(`[ACodeRuntime] poll_message: ${i.length} sub-agent(s) already completed, returning synthetic result`),j.formatSubAgentCompletionAsPollResult(i);let u=!1;for(;;){const r=a.waitForAnyCompletion(),c=u?{...o,_aws_silent_poll:!0}:o,l=this.callMcpToolWithTimeout(e,t,c,s,!0);try{const g=await Promise.race([l.then(d=>({type:"mcp",result:d})),r.promise.then(d=>({type:"subagent",notif:d}))]);if(g.type==="subagent"){const d=a.takeCompletedSubAgents();return d.length===0&&d.push(g.notif),m(`[ACodeRuntime] poll_message: sub-agent ${g.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),j.formatSubAgentCompletionAsPollResult(d)}const y=a.takeCompletedSubAgents();if(y.length>0){m(`[ACodeRuntime] poll_message: MCP returned, merging ${y.length} sub-agent completion(s)`);const d=j.mergeSubAgentCompletionsIntoMcpResult(g.result,y),$=await this.processMemoryAutoDelegates(d);if($!==null&&this.pollResultHasMessages($))return $;await this.waitForDelegateRepoll(),u=!0;continue}const b=await this.processMemoryAutoDelegates(g.result);if(b!==null&&this.pollResultHasMessages(b))return b;await this.waitForDelegateRepoll(),u=!0}finally{r.cancel()}}}pollResultHasMessages(e){try{const t=P(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,a=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||a>0}catch{return!0}}async waitForDelegateRepoll(){m(`[ACodeRuntime] poll_message: all messages delegated, waiting ${be}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,be);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,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 s=ce(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 a=await Ne(s.content);if(this.isTurnSuperseded(o))return;this.state.conversation.push({role:"user",content:a});const i=this.state.conversation.find(u=>u.role==="tool"&&u.tool_call_id===t);if(i&&typeof i.content=="string"){let u;try{const r=JSON.parse(i.content);if(typeof r=="object"&&r!==null){const c={...r};"attachments"in c&&(delete c.attachments,u=JSON.stringify(c))}}catch{}if(u===void 0){const r=i.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();r!==i.content&&(u=r)}u!==void 0&&u.length>0?i.content=u:u!==void 0&&(i.content="[Tool result contained images; see user message above]")}}appendToolFailureResult(e,t,o){const s=Xt(t,o);m(`[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}: ${G(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){return e.map(t=>({...t,tools:t.tools.filter(o=>Ct.has(o.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[s,a]of Object.entries(e))try{const i=new We({name:"acode",version:"0.1.0"}),u=this.createMcpTransport(a);await x(i.connect(u),t,`ACode MCP server ${s} connect`);const{tools:r}=await x(i.listTools(),t,`ACode MCP server ${s} listTools`);o.push({serverName:s,client:i,transport:u,tools:r.map(c=>({serverName:s,toolName:c.name,kind:"mcp",exposedName:no(s,c.name),description:c.description,inputSchema:ye(c.inputSchema)?c.inputSchema:{type:"object",properties:{}}}))})}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${s}: ${i instanceof Error?i.message:String(i)}`})}return o}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");return new Ke({command:e.command,args:e.args,cwd:e.cwd||this.config.workingDirectory,env:{...this.config.env??{},...e.env??{}},stderr:"pipe"})}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 Je(new URL(e.url),{requestInit:t}):new Qe(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 x(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:ee}),ee,"ACode startup get_profile"),a=this.extractProfileFromToolResult(s);return oo(a)}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(!v(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(v(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(v(s))return s}catch{}}return v(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[];return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],await Promise.all(e.map(t=>H(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}j.SKILL_REFRESH_DEBOUNCE_MS=500;export{j as ACodeRuntime};
100
+ \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 s;try{s=JSON.parse(o)}catch{return e}const a=s.directMessages;if(!Array.isArray(a)||a.length===0)return e;const i=[];let l=0;for(const u of a){const c=u._acodeAutoDelegate;if(c&&(c.type==="memory_expiration"||c.type==="memory_file_change"||c.type==="memory_cleanup")){l++;const g=Date.now(),y=c.uris.filter(f=>this.pendingMemorySubAgents.has(f)).length,w=c.uris.filter(f=>{const C=this.memoryDelegateCooldownUntil.get(f);return C!==void 0&&g<C}).length,d=c.uris.filter(f=>{if(this.pendingMemorySubAgents.has(f))return!1;const C=this.memoryDelegateCooldownUntil.get(f);return!(C!==void 0&&g<C)});if(d.length===0){m(`[ACodeRuntime] Memory ${c.type} skipped: ${y} in-progress, ${w} in cooldown (total ${c.uris.length} URIs)`);continue}const b=Array.isArray(c.fileChanges)?c.fileChanges.filter(f=>d.includes(f.uri)):void 0,h=this.buildMemoryDelegatePrompt({type:c.type,uris:d,fileChanges:b});try{const f=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:"explore",description:`Memory ${c.type} auto-delegate (${d.length} items)`,prompt:h,workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const T of d)this.pendingMemorySubAgents.set(T,f);const C=new Set(d);t.subscribe(f,()=>{const T=t.getSubAgent(f);if(T&&(T.status==="completed"||T.status==="failed"||T.status==="cancelled")){const $=Date.now();for(const N of C)this.pendingMemorySubAgents.get(N)===f&&this.pendingMemorySubAgents.delete(N),this.memoryDelegateCooldownUntil.set(N,$+Se);for(const[N,A]of this.memoryDelegateCooldownUntil)A<=$&&this.memoryDelegateCooldownUntil.delete(N);m(`[ACodeRuntime] Memory delegate sub-agent ${f} finished (${T.status}), ${C.size} URI(s) entered ${Se}ms cooldown`)}});const _=c.type,k=async(T,$)=>this.recheckMemoryDelegate(_,d,T,$);await t.startWithRecheck(f,k,3),m(`[ACodeRuntime] Auto-delegated memory ${c.type} to sub-agent ${f} (${d.length} URIs, ${c.uris.length-d.length} already in progress)`)}catch(f){for(const C of d)this.pendingMemorySubAgents.delete(C);m(`[ACodeRuntime] Failed to auto-delegate memory ${c.type} (suppressed, will retry next poll): ${f instanceof Error?f.message:String(f)}`)}}else i.push(u)}if(l===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 a=this.config.subAgentManager;if(!a)return await this.callMcpToolWithTimeout(e,t,o,s,!0);const i=a.takeCompletedSubAgents();if(i.length>0)return m(`[ACodeRuntime] poll_message: ${i.length} sub-agent(s) already completed, returning synthetic result`),j.formatSubAgentCompletionAsPollResult(i);let l=!1;for(;;){const r=a.waitForAnyCompletion(),u=l?{...o,_aws_silent_poll:!0}:o,c=this.callMcpToolWithTimeout(e,t,u,s,!0);try{const g=await Promise.race([c.then(d=>({type:"mcp",result:d})),r.promise.then(d=>({type:"subagent",notif:d}))]);if(g.type==="subagent"){const d=a.takeCompletedSubAgents();return d.length===0&&d.push(g.notif),m(`[ACodeRuntime] poll_message: sub-agent ${g.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),j.formatSubAgentCompletionAsPollResult(d)}const y=a.takeCompletedSubAgents();if(y.length>0){m(`[ACodeRuntime] poll_message: MCP returned, merging ${y.length} sub-agent completion(s)`);const d=j.mergeSubAgentCompletionsIntoMcpResult(g.result,y),b=await this.processMemoryAutoDelegates(d);if(b!==null&&this.pollResultHasMessages(b))return b;await this.waitForDelegateRepoll(),l=!0;continue}const w=await this.processMemoryAutoDelegates(g.result);if(w!==null&&this.pollResultHasMessages(w))return w;await this.waitForDelegateRepoll(),l=!0}finally{r.cancel()}}}pollResultHasMessages(e){try{const t=D(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,a=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||a>0}catch{return!0}}async waitForDelegateRepoll(){m(`[ACodeRuntime] poll_message: all messages delegated, waiting ${$e}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,$e);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,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 s=ue(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 a=await Ie(s.content);if(this.isTurnSuperseded(o))return;this.state.conversation.push({role:"user",content:a});const i=this.state.conversation.find(l=>l.role==="tool"&&l.tool_call_id===t);if(i&&typeof i.content=="string"){let l;try{const r=JSON.parse(i.content);if(typeof r=="object"&&r!==null){const u={...r};"attachments"in u&&(delete u.attachments,l=JSON.stringify(u))}}catch{}if(l===void 0){const r=i.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();r!==i.content&&(l=r)}l!==void 0&&l.length>0?i.content=l:l!==void 0&&(i.content="[Tool result contained images; see user message above]")}}appendToolFailureResult(e,t,o){const s=eo(t,o);m(`[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}: ${G(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){return e.map(t=>({...t,tools:t.tools.filter(o=>_t.has(o.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[s,a]of Object.entries(e))try{const i=new Je({name:"acode",version:"0.1.0"}),l=this.createMcpTransport(a);await E(i.connect(l),t,`ACode MCP server ${s} connect`);const r={serverName:s,client:i,transport:l,tools:[]};i.setNotificationHandler(Ge,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:u}=await E(i.listTools(),t,`ACode MCP server ${s} listTools`);r.tools=Te(s,u),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}async refreshMcpConnectionTools(e,t){try{const{tools:s}=await E(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Te(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.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(s=>s.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(s=>({name:s.exposedName,source:s.kind==="mcp"?`${s.serverName}.${s.toolName}`:`builtin.${s.toolName}`,description:s.description||""}))})}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");return new He({command:e.command,args:e.args,cwd:e.cwd||this.config.workingDirectory,env:{...this.config.env??{},...e.env??{}},stderr:"pipe"})}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 Ke(new URL(e.url),{requestInit:t}):new Qe(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:ee}),ee,"ACode startup get_profile"),a=this.extractProfileFromToolResult(s);return so(a)}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(!v(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(v(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(v(s))return s}catch{}}return v(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1;return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1,await Promise.all(e.map(t=>Q(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}j.SKILL_REFRESH_DEBOUNCE_MS=500;export{j as ACodeRuntime};
101
101
 
@@ -131,7 +131,7 @@ aws-client-agent-mcp
131
131
  "groups": [
132
132
  {
133
133
  "id": "project:demo",
134
- "projectName": "demo",
134
+ "projectId": "demo",
135
135
  "roomType": "project",
136
136
  "scopeRefId": "demo",
137
137
  "name": "demo 公共群聊",
@@ -139,7 +139,7 @@ aws-client-agent-mcp
139
139
  },
140
140
  {
141
141
  "id": "inner_group:g-1",
142
- "projectName": "demo",
142
+ "projectId": "demo",
143
143
  "roomType": "inner_group",
144
144
  "scopeRefId": "g-1",
145
145
  "name": "后端小组",
@@ -1,8 +1,9 @@
1
1
 
2
2
  import type { MemoryStats } from "./memory-store.js";
3
3
  import { StatusReporter } from "./status-reporter.js";
4
- import type { AgentConfig, BrowserListenerEvent, DirectMessage, DmHistoryResponse, FetchUnreadMessagesOptions, FinishTaskRollbackArgs, GroupHistoryResponse, GroupRoomsResponse, HireBatchResult, HireColleagueArgs, HireColleaguesBatchArgs, HiredColleagueResult, MessageHandler, OnlineListResponse, ProfileInfo, RegisterResult, SendDmResult, SendMessageResult, StartTaskRollbackArgs, TaskInstanceCommentArgs, UnreadMessagesResult } from "./types.js";
4
+ import type { AgentConfig, BrowserListenerEvent, DirectMessage, DmHistoryResponse, FetchUnreadMessagesOptions, FinishTaskRollbackArgs, GroupHistoryResponse, GroupRoomsResponse, HireBatchResult, HireColleagueArgs, HireColleaguesBatchArgs, HiredColleagueResult, MessageHandler, OnlineListResponse, ProfileInfo, RegisterResult, ServerConfig, SendDmResult, SendMessageResult, StartTaskRollbackArgs, TaskInstanceCommentArgs, UnreadMessagesResult } from "./types.js";
5
5
  export type ProfileHandler = (profile: ProfileInfo) => void;
6
+ export type AgentConfigHandler = (data: Record<string, unknown>) => void;
6
7
  export declare class AgentClient {
7
8
  private wsClient;
8
9
  private httpClient;
@@ -10,11 +11,12 @@ export declare class AgentClient {
10
11
  private serverConfig;
11
12
  private agentId;
12
13
  private displayName;
13
- private projectName;
14
+ private projectId;
14
15
  private isRunning;
15
16
  private isDegradedMode;
16
17
  private messageHandler;
17
18
  private profileHandler;
19
+ private configHandler;
18
20
  private pollTimer;
19
21
  private statusReporter;
20
22
  private newCharacterHandler;
@@ -47,7 +49,7 @@ export declare class AgentClient {
47
49
 
48
50
  reportMemoryStats(memoryStats: MemoryStats): Promise<void>;
49
51
 
50
- sendGroupMessage(content: string, projectName?: string, roomId?: string): Promise<SendMessageResult>;
52
+ sendGroupMessage(content: string, projectId?: string, roomId?: string): Promise<SendMessageResult>;
51
53
 
52
54
  sendDirectMessage(targetId: string, content: string, waitReply?: boolean, replyToCallId?: string, timeoutMs?: number): Promise<SendDmResult>;
53
55
 
@@ -88,9 +90,16 @@ export declare class AgentClient {
88
90
 
89
91
  terminateTask(taskInstanceId: string, reason: string): Promise<unknown>;
90
92
 
93
+ getDebugLogConfig(): Promise<unknown>;
94
+
95
+ queryDebugLogs(args: Record<string, unknown>): Promise<unknown>;
96
+
97
+ queryFileChangesHistory(args: Record<string, unknown>): Promise<unknown>;
98
+
91
99
  start(handler: MessageHandler, options?: {
92
100
  pollMode?: boolean;
93
101
  profileHandler?: ProfileHandler;
102
+ configHandler?: AgentConfigHandler;
94
103
  }): void;
95
104
 
96
105
  stop(): void;
@@ -107,11 +116,12 @@ export declare class AgentClient {
107
116
  getState(): {
108
117
  agentId: string | null;
109
118
  displayName: string | null;
110
- projectName: string | null;
119
+ projectId: string | null;
111
120
  isConnected: boolean;
112
121
  isRunning: boolean;
113
122
  };
114
123
  getAgentConfig(): AgentConfig;
124
+ getServerConfig(): ServerConfig;
115
125
  reloadConfig(): void;
116
126
 
117
127
  enterDegradedMode(): void;