aws-runtime-bridge 1.9.171 → 1.9.172

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.
@@ -1,41 +1,44 @@
1
- import{EventEmitter as yt}from"node:events";import{randomUUID as Ct}from"node:crypto";import O from"node:fs";import Ne from"node:os";import F from"node:path";import{Client as _t}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as At}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as bt}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as wt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as kt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as St,DEFAULT_TOOL_PERMISSION_POLICY as Pe,getEditFailureSnapshot as Mt}from"./built-in-file-tools.js";import{ReadFileStateTracker as $t}from"./read-file-state.js";import{ASK_USER_QUESTION_TOOL_NAME as vt,createAskUserQuestionTool as xt}from"./ask-user-question-tool.js";import{createSkillTool as Et}from"./skill-tool.js";import{createTodoWriteTool as Rt,createTodoReadTool as It}from"./todo-tool.js";import{createSubAgentTools as Nt}from"./sub-agent-tools.js";import{createAwaitCompleteTool as Pt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as Ot}from"./builtins/commandArtifacts.js";import{buildRuntimeEnvironmentPrompt as Dt}from"./runtime-environment.js";import{resolveAcodeHome as Lt}from"./paths.js";import{backgroundCommandManager as ae}from"./background-command-manager.js";import{createTerminalTool as Bt}from"./terminal-tool.js";import{ToolGroupManager as Ut,createExpandToolsTool as qt,createCallToolTool as Ft,mcpGroupKeyOf as Oe,isPluginGroupKey as De,pluginGroupKeyOf as zt}from"./tool-group-manager.js";import{loadAcodeCommands as jt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as Le}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as Wt,COMPACTION_LLM_PROMPT_TEMPLATE as Gt,COMPACTION_PRUNE_CATEGORIES as Jt,conversationSizeBytes as Be,conversationSizeKB as Q,estimateConversationTokens as z,isCompactionSummaryMessage as Kt,isRuntimeResourcesMessage as Ht,performCompaction as be,previewCompaction as Yt,resolveReplayWindow as Qt,pruneToolOutputs as Vt,RUNTIME_RESOURCES_PREFIX as Xt,summarizeConversation as Ue}from"./compaction.js";import{isContextOverflowError as we,resolveFinishReasonOverflow as Zt}from"./context-overflow.js";import{loadAcodeConfig as eo,loadAcodeSkillGroup as to}from"./config.js";import{ACodeHookBus as oo,findDeniedHookResult as qe}from"./hooks/hookBus.js";import{isMcpPollingToolName as Fe,isMcpBlockingToolName as ke,isMcpBatchExcludedToolName as Se,isMcpIndefinitelyBlockingToolName as so,getSemanticToolName as Me}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as D}from"./meeting-debug-log.js";import{BackgroundOutputRingBuffer as no}from"./background-output-ringbuffer.js";import{buildToolCatalog as ze,matchesToolAllocation as je,mergeAllocatableTools as pe,PRESET_EXPLORE as io,rebindDefaultAgentId as We,resolveToolAllocation as ro,SUB_AGENT_ALLOWED_MCP_TOOLS as ao}from"./tool-allocation.js";import{ConcurrencyLimiter as Ge,getSharedResourceLock as lo,ToolConcurrencyScheduler as co,ToolTraceRecorder as Je}from"./tool-concurrency/index.js";function uo(n){if(typeof n!="object"||n===null)return!1;const e=n;return e.kind==="builtin"&&typeof e.toolName=="string"&&typeof e.exposedName=="string"&&typeof e.description=="string"&&typeof e.execute=="function"&&typeof e.inputSchema=="object"&&e.inputSchema!==null}function mo(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function po(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function ho(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(mo):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(po)),e}function le(n){return n.map(ho)}function fo(n,e){const t=j(n.prompt_cache_hit_tokens),o=j(n.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const s=j(n.cache_read_input_tokens),i=j(n.cache_creation_input_tokens);if(s!==void 0||i!==void 0){const u=s??0,c=i??0,m=j(n.input_tokens)??(e!==void 0?Math.max(0,e-u-c):0);return{cacheHitTokens:u,cacheMissTokens:c+m}}const a=j(n.cache_hit_tokens),r=j(n.cache_miss_tokens);if(a!==void 0||r!==void 0)return{cacheHitTokens:a??0,cacheMissTokens:r??0};const l=j(n.prompt_tokens_details?.cached_tokens);if(l!==void 0){const u=e!==void 0?Math.max(0,e-l):0;return{cacheHitTokens:l,cacheMissTokens:u}}}function j(n){const e=typeof n=="number"?n:typeof n=="string"&&n.trim()?Number(n):NaN;if(!(!Number.isFinite(e)||e<0))return e}function go(n,e){if(!n)return e;const t=o=>{const s=e[o],i=n[o];return o==="prompt_tokens_details"?{...i,...s}:s??i};return{prompt_tokens:t("prompt_tokens"),completion_tokens:t("completion_tokens"),input_tokens:t("input_tokens"),output_tokens:t("output_tokens"),prompt_cache_hit_tokens:t("prompt_cache_hit_tokens"),prompt_cache_miss_tokens:t("prompt_cache_miss_tokens"),cache_read_input_tokens:t("cache_read_input_tokens"),cache_creation_input_tokens:t("cache_creation_input_tokens"),cache_hit_tokens:t("cache_hit_tokens"),cache_miss_tokens:t("cache_miss_tokens"),prompt_tokens_details:t("prompt_tokens_details")}}function To(){return new Date().toISOString()}function k(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function he(n){return k(n)}function Ke(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:Ts(n,t.name),description:t.description,inputSchema:he(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}const fe="ACODE_TOOL_GROUPS_V1:";function yo(n){const e=String(n??"").trim();if(!e.startsWith(fe))return[];const t=e.slice(fe.length).trim();if(!t)return[];let o;try{o=JSON.parse(t)}catch{return[]}if(!he(o)||!Array.isArray(o.groups))return[];const s=[];for(const i of o.groups){if(!he(i))continue;const a=typeof i.key=="string"?i.key.trim():"";if(!a)continue;const r=Array.isArray(i.toolNames)?i.toolNames.filter(l=>typeof l=="string"&&l.length>0):[];s.push({key:a,label:typeof i.label=="string"&&i.label.trim()?i.label:a,toolNames:r})}return s}function Co(n){const e=String(n??"").trim();if(!e)return;if(!e.startsWith(fe))return e;const t=e.slice(fe.length).trim();return t.startsWith("{")?void 0:t||void 0}function N(n){return String(n??"").trim()||void 0}const He=6e4,Ye=30*6e4,Qe=6e4,Ve=6e4,$e=-1,Xe=0,_o=1e3,Ao=3e4,ge=6e4,Ze=0,bo=2147483647,wo=8,ko=10*6e4+2e3,So=1e4,Te=5e3,et=10*60*1e3,te=10*1024*1024,tt=800*1024,ot=32*1024*1024,Mo=4,$o=1.25;function st(){const n=Number.parseInt(String(process.env.ACODE_MAX_REQUEST_BODY_BYTES??"").trim(),10);return Number.isFinite(n)&&n>0?n:void 0}function vo(){return st()!==void 0}function xo(n){const e=st();if(e!==void 0)return e;if(!Number.isFinite(n)||n<=0)return tt;const t=Math.floor(n*Mo*$o);return Math.min(ot,Math.max(tt,t))}const ye=process.env.ACODE_COMPACTION_DEBUG==="1",nt=ye?F.join(Ne.tmpdir(),"acode-compaction-debug.log"):"";function p(...n){ye&&console.log(...n)}const Eo=process.env.ACODE_IMAGE_DIAG==="1",Ro=process.env.ACODE_IMAGE_DIAG_LOG||F.join(Ne.tmpdir(),"acode-image-inject.log");function Ce(n){if(!Eo)return;const e=`[${new Date().toISOString()}] ${JSON.stringify(n)}
2
- `;O.promises.appendFile(Ro,e).catch(()=>{})}const Io=process.env.ACODE_TOKEN_DEBUG==="1";function oe(...n){Io&&console.log("[TokenDebug][Runtime]",...n)}const No=64e3;function _e(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:No,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=Wt(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((i,a)=>{s=setTimeout(()=>{o?.(),a(new Error(`${t} timed out after ${e}ms`))},e),n.then(i,a)})}finally{s&&clearTimeout(s)}}function it(){return`toolbatch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}async function se(n,e,t,o=So){try{await x(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function ne(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===$e?$e:Number.isFinite(t)&&t>0?Math.floor(t):e}function ce(n,e){const t=ne(n,e);return t>0?t:e}const rt=3;function ve(n){return n?Math.ceil(n.length/rt):0}function Po(n,e){let t=n.length;for(const o of e){const s=(o.kind==="mcp",o.toolName);if(t+=s.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const i=o;i.inputSchema&&(t+=JSON.stringify(i.inputSchema).length)}}return Math.ceil(t/rt)}function ue(n){if(n.length===0)return 0;const e=JSON.stringify(ht(n));return ve(e)}async function Oo(n){await new Promise(e=>setTimeout(e,n))}function Do(n){return typeof n=="boolean"}function Lo(n,e,t){if(Do(t?.supportsImageInput))return t.supportsImageInput;const o=k(e)?e.models:void 0,s=k(o)?o[n]:void 0;if(!k(s))return!1;const i=s.modalities;return!k(i)||!Array.isArray(i.input)?!1:i.input.some(a=>String(a||"").trim().toLowerCase()==="image")}function xe(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(k(s)){const i=s[t];if(k(i)){const a=i[o];if(a!==void 0)return a}}return e[o]}function Bo(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",i=N(n.effort)||N(o?.effort)||N(t?.effort)||void 0;return{model:s,baseURL:N(o?.baseURL||o?.baseUrl),apiKey:N(o?.apiKey),effort:i,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:ce(o?.requestTimeoutMs??o?.timeoutMs,He),requestTotalTimeoutMs:ce(o?.requestTotalTimeoutMs,Ye),requestRetryCount:ne(o?.requestRetryCount,Xe),requestFirstByteTimeoutMs:ce(o?.requestFirstByteTimeoutMs,Qe),requestStreamIdleTimeoutMs:ce(o?.requestStreamIdleTimeoutMs,Ve),mcpToolTimeoutMs:ce(o?.mcpToolTimeoutMs,ge),mcpPollingToolTimeoutMs:ne(o?.mcpPollingToolTimeoutMs,Ze),supportsImageInput:Lo(s,t,o),contextLimit:ne(xe(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:ne(xe(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:ne(xe(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function H(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function Uo(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function qo(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function Fo(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 zo(n){const e=await n.arrayBuffer();if(e.byteLength>te)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${te} bytes`);return Buffer.from(e).toString("base64")}async function jo(n){const e=n.trim();if(qo(e)){if(e.slice(e.indexOf(",")+1).length*.75>te)throw new Error(`ACode inline image exceeds the ${te} byte size limit`);return e}Fo(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 zo(t)}`}function Wo(n){const e=N(n.base64Data??n.base64??n.data);return e?e.length*.75>te?void 0:Uo(N(n.mediaType??n.mimeType)||"image/png",e):N(n.url??n.serverUrl)}function at(n,e,t,o){return`[Attached file: ${[n?`name=${n}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(i=>!!i).join(", ")}]`}function Go(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,i=e.exec(n);for(;i!==null;){H(t,n.slice(s,i.index));const a=i[1],r=(i[2]||"").trim();if(a==="\u56FE\u7247"&&r)t.push({type:"image_url",image_url:{url:r}}),o=!0;else if(a==="\u6587\u4EF6"&&r){const[l="",u="",c="",m=""]=r.split("|").map(h=>h.trim());H(t,at(l,u,c,m))}else H(t,i[0]);s=i.index+i[0].length,i=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(H(t,n.slice(s)),{content:t,hasImages:o})}function Jo(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const i of s){if(!k(i))continue;const a=N(i.content);if(!a)continue;const r=N(i.senderName);H(n,r?`Message from ${r}:`:"Message:");const l=Ee(a);Array.isArray(l.content)?n.push(...l.content):H(n,l.content),t=t||l.hasImages}return t}function Ko(n){for(const e of["directMessages","groupMessages","messages"]){const t=n[e];if(Array.isArray(t))for(const o of t){if(!k(o))continue;const s=o.content;typeof s!="string"||!s.trim()||(o.content=Ho(s))}}}function Ho(n){let e;try{e=JSON.parse(n)}catch{return n.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim()||n}if(k(e)&&"attachments"in e){const t={...e};return t.attachments=[],JSON.stringify(t)}return n}function Yo(n){let e;try{e=JSON.parse(n)}catch{return}if(!k(e))return;const t=[];let o=Jo(t,e);const s=N(e.text)||"",i=Array.isArray(e.attachments)?e.attachments:[];H(t,s);for(const a of i){if(!k(a))continue;const r=a;if(String(r.type??r.kind??"").toLowerCase()==="image"){const c=Wo(r);c?(t.push({type:"image_url",image_url:{url:c}}),o=!0):N(r.base64Data??r.base64??r.data)&&H(t,`[Image attachment omitted: ${N(r.name)||"unnamed"} exceeds the ${te} byte inline limit]`);continue}const u=N(r.url??r.serverUrl)||"";H(t,at(N(r.name)||"",u,N(r.mediaType??r.mimeType)||"",N(r.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function Ee(n){return Yo(n)??Go(n)}async function lt(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 jo(t.image_url.url)}})}return e}function Qo(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function Vo(n,e){const t=n.permissions??e.permissions??{},o=n.permissions?[]:e.allowedTools??[],s=n.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(i=>i.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(i=>i.trim()).filter(Boolean)}}function Xo(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function Zo(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 ct(n,e){return Zo(e).some(t=>Xo(n,t))}function ut(n,e,t){if(e.length>0&&!e.some(o=>ct(o,n)))throw new Error(t)}function mt(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>ct(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);ut(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),ut(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function es(n,e,t){try{return mt(n,e,t),!0}catch{return!1}}function Ae(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function ts(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(Ae(e.toString()));return`${t.origin}${t.pathname}`}catch{return Ae(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function os(n){const e=[...n].reverse().find(o=>o.role==="user"),t=Qo(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function ss(n){try{const e=JSON.parse(n);return he(e)?e:{}}catch{return{}}}function ns(n,e,t){if(new Set([vt,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,i=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(i)||i<=0?Math.max(t,ko):Math.min(Math.floor(i),10*6e4)+2e3}function is(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 W(n){if(!k(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>k(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
3
- `)}return JSON.stringify(n)}function me(n){return n instanceof Error?n.message:String(n)}function rs(n){const e={orphanToolMessages:0,repairedToolCalls:0,downgradedAssistants:0,relocatedInterruptions:0,reorderedToolResults:0};if(n.length===0)return e;const t=(c,m)=>{const h=typeof c.content=="string"?c.content:JSON.stringify(c.content??"");c.role="user",delete c.tool_call_id,c.content=`[\u7CFB\u7EDF\u63D0\u793A] \u4EE5\u4E0B\u4E3A\u4E00\u6B21\u5DE5\u5177\u6267\u884C\u7684\u7ED3\u679C\uFF08tool_call_id=${m}\uFF09\uFF0C\u5176\u5BF9\u5E94\u7684\u5DE5\u5177\u8C03\u7528\u4E0A\u4E0B\u6587\u5DF2\u4E0D\u5728\u4F1A\u8BDD\u4E2D\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF1A
4
- ${h}`,e.orphanToolMessages+=1},o=c=>{const m=new Map;for(const y of n)if(y.role==="assistant"&&Array.isArray(y.tool_calls))for(const _ of y.tool_calls){const d=typeof _?.id=="string"?_.id:"";d&&!m.has(d)&&m.set(d,y)}const h=new Set;for(const y of n){if(y.role==="assistant"&&Array.isArray(y.tool_calls)){for(const f of y.tool_calls){const g=typeof f?.id=="string"?f.id:"";g&&h.add(g)}continue}if(y.role!=="tool")continue;const _=typeof y.tool_call_id=="string"?y.tool_call_id.trim():"";if(!_){t(y,"(\u7F3A\u5931)");continue}if(h.has(_))continue;const d=m.get(_);if(d){c.push({message:y,id:_,assistant:d});continue}t(y,_)}},s=c=>{if(c.length!==0){for(const m of c){const h=n.indexOf(m.message);h>=0&&n.splice(h,1)}for(const m of c){const h=n.indexOf(m.assistant);if(h<0){t(m.message,m.id);continue}let y=h+1;for(;y<n.length&&n[y].role==="tool";)y+=1;n.splice(y,0,m.message),e.reorderedToolResults+=1}}},i=[];o(i),s(i);const a=()=>{const c=new Set;for(const m of n)m.role==="tool"&&m.tool_call_id&&c.add(m.tool_call_id);return c};let r=a();const l="\uFF08\u8BE5\u5DE5\u5177\u8C03\u7528\u7ED3\u679C\u7F3A\u5931\uFF1A\u6240\u5C5E\u8F6E\u6B21\u88AB\u4E2D\u65AD\u6216\u4E0A\u4E0B\u6587\u538B\u7F29\u65F6\u5DF2\u79FB\u9664\uFF0C\u8BF7\u52FF\u57FA\u4E8E\u8BE5\u8C03\u7528\u7EE7\u7EED\u63A8\u65AD\uFF0C\u5FC5\u8981\u65F6\u91CD\u65B0\u8C03\u7528\u5DE5\u5177\u3002\uFF09";for(let c=0;c<n.length;c++){const m=n[c];if(m.role!=="assistant"||!Array.isArray(m.tool_calls))continue;const h=m.tool_calls.filter(f=>typeof f?.id=="string"&&f.id.trim().length>0);if(h.length!==m.tool_calls.length){if(e.downgradedAssistants+=1,h.length===0){delete m.tool_calls,(m.content===null||m.content===void 0)&&(m.content="");continue}m.tool_calls=h}const y=m.tool_calls.map(f=>f?.id).filter(f=>typeof f=="string"&&f.length>0&&!r.has(f));if(y.length===0)continue;let _=-1;for(let f=c+1;f<n.length;f++){if(n[f].role==="tool"){_=f+1;continue}break}if(_>c){const f=y.map(g=>({role:"tool",tool_call_id:g,content:l}));n.splice(_,0,...f),c+=f.length,e.repairedToolCalls+=y.length,r=a();continue}if(c===n.length-1){for(const f of y)n.push({role:"tool",tool_call_id:f,content:l});e.repairedToolCalls+=y.length,r=a();continue}const d=new Set(m.tool_calls.map(f=>f?.id).filter(f=>typeof f=="string"&&f.length>0));delete m.tool_calls,(m.content===null||m.content===void 0)&&(m.content="");for(const f of n)if(f.role==="tool"&&f.tool_call_id&&d.has(f.tool_call_id)){const g=typeof f.content=="string"?f.content:JSON.stringify(f.content??""),C=f.tool_call_id;f.role="user",delete f.tool_call_id,f.content=`[\u7CFB\u7EDF\u63D0\u793A] \u4EE5\u4E0B\u4E3A\u4E00\u6B21\u5DE5\u5177\u6267\u884C\u7684\u7ED3\u679C\uFF08tool_call_id=${C}\uFF09\uFF0C\u5176\u5BF9\u5E94\u7684\u5DE5\u5177\u8C03\u7528\u4E0A\u4E0B\u6587\u5DF2\u4E0D\u5728\u4F1A\u8BDD\u4E2D\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF1A
5
- ${g}`,e.orphanToolMessages+=1}r=a(),e.downgradedAssistants+=1}for(let c=0;c<n.length;c++){const m=n[c];if(m.role!=="assistant"||!Array.isArray(m.tool_calls))continue;const h=new Set(m.tool_calls.map(g=>g?.id).filter(g=>typeof g=="string"&&g.length>0));if(h.size===0)continue;const y=g=>g.role==="tool"&&typeof g.tool_call_id=="string"&&h.has(g.tool_call_id),_=[];for(let g=c+1;g<n.length;g++){const C=n[g];if(y(C))continue;if(C.role==="tool")break;let w=!1;for(let b=g+1;b<n.length;b++)if(y(n[b])){w=!0;break}if(!w)break;_.push(C)}if(_.length===0)continue;const d=n.filter(g=>!_.includes(g));let f=-1;for(let g=0;g<d.length;g++)y(d[g])&&(f=g);f<0||(d.splice(f+1,0,..._),n.length=0,n.push(...d),e.relocatedInterruptions+=_.length)}const u=[];return o(u),s(u),e}const dt={truncatedCount:0,strategy:"none",prunedToolMessages:0,summarizedMessages:0,freedTokens:0};async function as(n,e,t,o,s,i){if(Be(n)<=e)return dt;const r=await be(n,t,o,{llmSummarizer:s});if(r.strategy!=="none")return r.summarizedMessages>0&&i&&await i(),{truncatedCount:r.prunedToolMessages+r.summarizedMessages,strategy:r.strategy,prunedToolMessages:r.prunedToolMessages,summarizedMessages:r.summarizedMessages,freedTokens:r.freedTokens};const l=await Ue(n,{llmSummarizer:s,contextLimit:t});return l>0&&i&&await i(),{truncatedCount:l,strategy:l>0?"summarize":"none",prunedToolMessages:0,summarizedMessages:l,freedTokens:0}}function ls(n){return we(n)}function cs(n){const e=me(n).toLowerCase();return ls(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 us(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=me(n).toLowerCase();return e===-32001||t.includes("request timed out")}function ms(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 pt(n,e,t){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:ms(e),message:me(e)},...t?{file_snapshot:{path:t.path,bytes:t.bytes,content:t.content}}:{}})}function ds(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function ps(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(k(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function hs(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 fs(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
6
- `)}function gs(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,i=e.instanceName,a=e.projectId,r=e.workspacePath,l=e.runtimeMode,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 i=="string"&&i.trim()&&t.push(`Instance: ${i.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Project: ${a.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Workspace: ${r.trim()}`),typeof l=="string"&&l.trim()&&t.push(`Runtime Mode: ${l.trim()}`),typeof u=="string"&&u.trim()&&t.push(`Description: ${u.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
7
- `)}function ht(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function Ts(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function ys(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function Cs(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,_s(e)?As(t):t]))}function _s(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function As(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function bs(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function ft(n){if(!k(n))return null;const e=n.error;if(k(e)){const t=typeof e.message=="string"?e.message:"",o=e.code??e.status??e.type,s=o==null?"":String(o);return t||s?[s,t].filter(Boolean).join(" "):null}if(typeof e=="string"&&e)return e;if(n.type==="error"||n.object==="error"){const t=typeof n.message=="string"?n.message:"",o=n.code??n.status,s=o==null?"":String(o);if(t||s)return[s,t].filter(Boolean).join(" ")}return null}const ws=/role 'tool'|tool calls and tool results|tool_call_sequence|\b11148\b/i;let gt=0,de="";function Re(n,e,t){if(!ws.test(t))return null;try{const o=new Map,s=new Map;n.forEach((d,f)=>{if(d.role==="assistant"&&Array.isArray(d.tool_calls))for(const g of d.tool_calls){const C=typeof g?.id=="string"?g.id.trim():"";C&&!o.has(C)&&o.set(C,f)}else if(d.role==="tool"){const g=typeof d.tool_call_id=="string"?d.tool_call_id.trim():"";g&&!s.has(g)&&s.set(g,f)}});const i=[];n.forEach((d,f)=>{if(d.role==="tool"){const g=typeof d.tool_call_id=="string"?d.tool_call_id.trim():"",C=g?o.get(g):void 0;(g===""||C===void 0||C>f)&&i.push(f)}else if(d.role==="assistant"&&Array.isArray(d.tool_calls))for(const g of d.tool_calls){const C=typeof g?.id=="string"?g.id.trim():"";if(C===""||!s.has(C)){i.push(f);break}}});const a=d=>` [\u5DE5\u5177\u5E8F\u5217\u8BC1\u636E] \u53EF\u7591\u6D88\u606F ${i.length}/${n.length} \u6761\uFF08${d?`\u5DF2\u5199\u5165 ${d}`:"\u843D\u76D8\u5931\u8D25"}\uFF09`,r=Date.now();if(r-gt<1e4&&de)return a(de);gt=r;const l=d=>({role:d.role,tool_call_id:d.tool_call_id,tool_calls:Array.isArray(d.tool_calls)?d.tool_calls.map(f=>f?.id??null):void 0,contentPreview:typeof d.content=="string"?d.content.slice(0,300):d.content===null?null:JSON.stringify(d.content).slice(0,300)}),u=`acode-tool-seq-${new Date(r).toISOString().replace(/[:.]/g,"-")}.json`,c=String(process.env.AWS_TEST_HOME||"").trim()||String(process.env.AWS_RUNTIME_HOME_DIR||"").trim(),m=String(process.env.AWS_RUNTIME_ENV||"").trim().toLowerCase()==="development",h=c||(m?F.resolve(process.cwd(),"..",".dev-home"):F.dirname(Lt())),y=F.join(h,".aws-bridge","log"),_={timestamp:new Date(r).toISOString(),status:e,errorBody:t.slice(0,4e3),suspectIndexes:i,messages:n.map((d,f)=>({index:f,role:d.role,tool_call_id:d.tool_call_id,tool_calls:Array.isArray(d.tool_calls)?d.tool_calls.map(g=>g?.id??null):void 0})),suspectWindows:i.map(d=>{const f=Math.max(0,d-6),g=Math.min(n.length,d+7);return{center:d,range:[f,g],messages:n.slice(f,g).map((C,w)=>({index:f+w,...l(C)}))}})};return de=`.aws-bridge/log/${u}`,O.promises.mkdir(y,{recursive:!0}).then(()=>O.promises.writeFile(F.join(y,u),JSON.stringify(_,null,2),"utf-8")).then(()=>O.promises.readdir(y)).then(d=>{const f=d.filter(C=>C.startsWith("acode-tool-seq-")).sort(),g=f.length-20;return g<=0?null:Promise.all(f.slice(0,g).map(C=>O.promises.unlink(F.join(y,C)).catch(()=>{})))}).catch(()=>{de=""}),a(de)}catch{return null}}function Tt(n){const e=new Set,t=Date.now();return n.map((o,s)=>{const i=typeof o?.id=="string"?o.id.trim():"";if(i&&!e.has(i))return e.add(i),o;let a=`call-${t}-${s}`,r=1;for(;e.has(a);)a=`call-${t}-${s}-${r}`,r+=1;return e.add(a),{...o,id:a}})}function ks(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 Ss(n){return Tt([...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0))}function Ms(){const n=process.env.ACODE_ABORT_FORCE_SETTLE_GRACE_MS;if(n===void 0||n.trim()==="")return 6e4;const e=Number(n.trim());return Number.isFinite(e)&&e>=0?Math.floor(e):6e4}class Z extends yt{hasActiveBlockingToolCall(){return this.activeBlockingToolCalls>0}static isLongBlockingMcpToolName(e){return so(e)}constructor(e){super(),this.config=e,this.initialConversation=[],this.mcpStderrBuffers=new Map,this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:He,requestTotalTimeoutMs:Ye,requestRetryCount:Xe,requestFirstByteTimeoutMs:Qe,requestStreamIdleTimeoutMs:Ve,mcpToolTimeoutMs:ge,mcpPollingToolTimeoutMs:Ze,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new Le([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:{...Pe}},this.abortController=null,this.exposedToolsInitialized=!1,this.recoveredToolNames=new Set,this.readFileStateTracker=new $t,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.toolGroupManager=null,this.pluginGroupStates=new Map,this.submitQueue=Promise.resolve(),this.activeTurnToken=null,this.forceSettleWaiters=new Map,this.abortForceSettleTimer=null,this.activeTurn=!1,this.activeBlockingToolCalls=0,this.forceMessagePending=!1,this.compactRequested=null,this.turnPromptPushed=!1,this.abortRequested=!1,this.toolSettleSlots=new Map,this.toolSettleSeq=0,this.toolResourceLock=lo(),this.toolConcurrencyScheduler=new co,this.toolReadOnlyLimiter=null,this.toolBashLimiter=null,this.toolConcurrencyEnabled=!0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.permissionWaiters=new Map,this.hookBus=new oo({sessionId:e.sessionId,onError:(i,a)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${i.name}: ${a instanceof Error?a.message:String(a)}`})}});for(const i of e.hooks??[])this.hookBus.register(i);e.toolPermissionPolicy&&(this.state.toolPermissionPolicy={...Pe,...e.toolPermissionPolicy});const t=e.toolConcurrency;this.toolConcurrencyEnabled=t?.enabled!==!1;const o=t?.maxReadOnly??8;this.toolReadOnlyLimiter=new Ge(o);const s=t?.maxBash??0;this.toolBashLimiter=s>0?new Ge(s):null}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:To(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s,i){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s,...i?{trigger:i}:{}})}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 runCompactionPass(e){const{contextLimit:t,maxOutput:o,effectiveUsed:s,trigger:i,force:a,plan:r}=e,l=Q(this.state.conversation),u=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:u,sizeKB:l,estimatedTokens:s,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:this.state.provider.model,trigger:i}),this.emitCompactionPhase(u,"detect",e.detectLabel,e.detectDetail);const c=await be(this.state.conversation,t,o,{llmSummarizer:h=>this.summarizeConversationWithLLM(h),onPhase:h=>this.handleCompactionPhase(u,h),actualUsedTokens:s,force:a,plan:r}),m=Q(this.state.conversation);return this.emitAcodeEvent("context_compaction",{action:"end",compactionId:u,sizeBeforeKB:l,sizeAfterKB:m,freedKB:Math.round((l-m)*10)/10,strategy:c.strategy,freedTokens:c.freedTokens,tokensBefore:c.tokensBefore,tokensAfter:c.tokensAfter,prunedToolMessages:c.prunedToolMessages,summarizedMessages:c.summarizedMessages,messageCountBefore:c.messageCountBefore,messageCountAfter:c.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,c.summarizedMessages>0&&await this.rebuildRuntimeResourcesMessage(),c}compactContext(e){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");return this.compactRequested={pruneCategories:e?.pruneCategories??[...Jt],summarize:e?.summarize??!0},p(`[ACodeRuntime] \u{1F5DC}\uFE0F Manual compaction requested (\u5148\u884C\u538B\u7F29): plan=${JSON.stringify(this.compactRequested)}`),{requested:!0}}getCompactionPreview(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");return Yt(this.state.conversation)}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await eo(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),i=Bo(this.config,e);p(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${i.model}, baseURL=${i.baseURL??"(none)"}, apiKey=${i.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const a=Vo(this.config,e),r=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},i.mcpToolTimeoutMs),l=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const u=await this.fetchProfilePrompt(r),c=this.config.agentId||"unknown";Ot(c),ae.reconcileOrphans(c);const m=St(this.config.workingDirectory,c,this.config.onFileChange,{manager:ae,emitCompleted:T=>{this.emitAcodeEvent("background_command_completed",T)}},this.createToolPermissionController(),{tracker:this.readFileStateTracker,enabled:this.config.enableStaleFileGuard!==!1}),h=xt(this.buildAskUserQuestionDeps(),()=>this.contextVersion),y=Et(t);this.skillTool=y;const _=Rt(c),d=It(c),f=this.config.subAgentManager?Nt(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],g=Pt(this.buildAwaitCompleteDeps()),C=this.config.terminalManager?Bt(c,{terminalManager:this.config.terminalManager}):null,w=new Map;this.pluginGroupStates=w;const b=new Ut({stateOf:T=>De(T)?w.get(T)??"disabled":(this.config.capabilityState??(()=>"disabled"))(T)});b.register({key:"pencil",label:"\u8BBE\u8BA1\u753B\u5E03(pencil)",summary:"UI design editor",collapsible:!0}),b.register({key:"draw",label:"\u7ED8\u56FE",summary:"\u7ED8\u5236 draw.io \u6D41\u7A0B\u56FE/\u6CF3\u9053\u56FE",collapsible:!0}),b.register({key:"office",label:"Office \u6587\u4EF6",summary:"\u53EF\u8FDB\u884C\u67E5\u770B/\u521B\u5EFA\u548C\u590D\u6742\u7F16\u8F91 Word/PPT/Excel",collapsible:!0}),b.register({key:"launch",label:"\u542F\u52A8\u9879\u7BA1\u7406",summary:"\u7BA1\u7406\u9879\u76EE\u4E2D\u4E1A\u52A1\u7A0B\u5E8F\u7684\u8D77\u505C\uFF0C\u82E5\u540E\u9762\u9700\u8981\u542F\u52A8\u9879\u76EE\u5E94\u4F7F\u7528\u6B64\u5DE5\u5177",collapsible:!0}),b.register({key:"hire",label:"\u62DB\u8058\u5DE5\u5177",summary:"\u62DB\u8058\u65B0\u7684\u540C\u4E8B Agent",collapsible:!0}),b.register({key:"browser",label:"\u6D4F\u89C8\u5668\u64CD\u4F5C",summary:"\u542F\u52A8\u6D4F\u89C8\u5668\u4F1A\u8BDD\u3001\u5BFC\u822A\u3001\u622A\u56FE\u4E0E\u9875\u9762\u4EA4\u4E92",collapsible:!0}),b.register({key:"desktop",label:"\u684C\u9762\u64CD\u4F5C",summary:"\u622A\u5C4F\u3001\u9F20\u6807\u952E\u76D8\u63A7\u5236\u4E0E UI \u81EA\u52A8\u5316",collapsible:!1}),b.register({key:"task",label:"\u6D41\u7A0B\u4EFB\u52A1",summary:"\u5904\u7406\u6D41\u7A0B\u7EBF\u4EFB\u52A1\uFF1A\u67E5\u770B\u5F53\u524D\u4EFB\u52A1\u3001\u63D0\u4EA4\u6267\u884C\u7ED3\u679C\u3001\u56DE\u9000\u4EFB\u52A1\u3001\u7ED9\u6D41\u7A0B\u5B9E\u4F8B\u7559\u8A00",collapsible:!0,toolNames:["my_task","submit_task_result","start_task_rollback","finish_task_rollback","create_task_instance_comment"]}),b.register({key:"meeting",label:"\u4F1A\u8BAE",summary:"\u521B\u5EFA/\u52A0\u5165\u4F1A\u8BAE\u3001\u53D1\u8A00\u3001\u67E5\u770B\u4F1A\u8BAE\u4FE1\u606F\u3001\u79BB\u5F00/\u7ED3\u675F\u4F1A\u8BAE",collapsible:!0,toolNames:["create_meeting","leave_meeting","end_meeting","meeting_speak","get_meeting_info","my_meetings"]}),b.register({key:"debug",label:"\u8C03\u8BD5\u65E5\u5FD7",summary:"\u6309\u6761\u4EF6\u5206\u9875\u67E5\u8BE2 Debug \u65E5\u5FD7\u4E0E\u83B7\u53D6\u65E5\u5FD7\u4E0A\u62A5\u914D\u7F6E",collapsible:!0,toolNames:["get_debug_log_config","query_debug_logs"]}),b.register({key:"fileHistory",label:"\u6587\u4EF6\u53D8\u66F4\u5386\u53F2",summary:"\u6309\u89D2\u8272/\u5B9E\u4F8B/\u6587\u4EF6\u8DEF\u5F84\u8FC7\u6EE4\u67E5\u8BE2\u6587\u4EF6\u53D8\u66F4\u5386\u53F2",collapsible:!0,toolNames:["query_file_changes_history"]}),b.register({key:"email",label:"\u90AE\u7BB1",summary:"\u6536\u53D1\u89D2\u8272\u5B9E\u4F8B\u57DF\u540D\u90AE\u7BB1\uFF08xxxxx@\u57DF\u540D\uFF09\uFF1A\u53D1\u4FE1\u3001\u5217\u90AE\u4EF6\u3001\u8BFB\u6B63\u6587\u4E0E\u9644\u4EF6\u3001\u56DE\u4FE1\u4FDD\u6301\u7EBF\u7A0B\u3001\u786E\u8BA4\u4E1A\u52A1\u6D88\u8D39",collapsible:!0,toolNames:["send_email","list_emails","read_email","reply_email","ack_email"]}),this.toolGroupManager=b;for(const T of r){const I=T.spec??e.mcpServers?.[T.serverName];I&&this.registerMcpCollapsedGroup(T.serverName,I,T)}for(const T of r)this.registerToolGroupsFromMcp(T);if(this.config.pluginBridge)try{const T=await this.config.pluginBridge.listPlugins();this.applyPluginGroups(T,w,b)}catch(T){p(`[ACodeRuntime] \u63D2\u4EF6\u7EC4\u6CE8\u518C\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${T instanceof Error?T.message:String(T)}`)}const M=qt({toolGroupManager:b,getAllTools:()=>this.state.exposedTools,capabilityToolRelay:this.config.capabilityToolRelay,pluginBridge:this.config.pluginBridge}),$=Ft({toolGroupManager:b,pluginBridge:this.config.pluginBridge,capabilityToolRelay:this.config.capabilityToolRelay,findTool:T=>{const I=this.state.exposedTools.find(Ie=>Ie.exposedName===T||Ie.toolName===T);if(!I)return;const re=I.group??b.getGroupForExposedName(I.exposedName);return{kind:I.kind,group:re,toolName:I.toolName}},dispatchTool:(T,I,re)=>this.executeSingleToolByName(T,I,re)}),S=[...m,h,y,_,d,...f,g,...C?[C]:[],M,$,...r.flatMap(T=>T.tools),...We(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const T=We(this.config.subAgentSuiteTools??[],this.config.agentId??""),I=pe(S,T);S.length=0,S.push(...I)}let v=S;const E=this.config.subAgentAllowedTools;E&&E.length>0&&(v=v.filter(T=>je(T,E)));const G=this.resolveCommandDirs(e);let L=[...G,...this.discoverPluginCommandDirs()];if(this.config.pluginBridge?.getCommandDirs)try{const T=await this.config.pluginBridge.getCommandDirs();T.length>0&&(L=[...L,...T])}catch(T){p(`[ACodeRuntime] \u63D2\u4EF6\u547D\u4EE4\u76EE\u5F55\u83B7\u53D6\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${T instanceof Error?T.message:String(T)}`)}L=[...new Set(L)],this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const B=await jt(L),ie=new Le(B),ee=hs(t),A=fs(B),P=b.buildCapabilityPrompt(),Y=this.config.pluginBridge?["","## \u63D2\u4EF6\u7CFB\u7EDF","\u5DF2\u5B89\u88C5\u63D2\u4EF6\u4EE5\u6536\u7EB3\u7EC4\u5F62\u5F0F\u5217\u51FA\uFF08\u89C1\u4E0A\u65B9\u300C\u53EF\u7528\u80FD\u529B\u300D\u4E2D\u7684 plugin:{\u63D2\u4EF6\u540D} \u6761\u76EE\uFF09\u3002",'\u9700\u8981\u67D0\u63D2\u4EF6\u7684\u5DE5\u5177\u65F6\uFF0C\u5148 expand_tools({ group: "plugin:\u63D2\u4EF6\u540D" }) \u5C55\u5F00\uFF1B','\u5DE5\u5177\u5B9A\u4E49\uFF08\u542B\u53C2\u6570 schema\uFF09\u968F\u5C55\u5F00\u7ED3\u679C\u8FD4\u56DE\uFF0C\u518D\u7528 call_tool({ name: "\u63D2\u4EF6\u540D.\u5DE5\u5177\u540D", arguments: {...} }) \u8C03\u7528\u3002',"\u63D2\u4EF6\u4E8B\u4EF6\u4EE5 [plugin-event] \u6D88\u606F\u51FA\u73B0\uFF0C\u6D88\u606F\u6807\u660E\u6765\u6E90\u63D2\u4EF6\u4E0E\u4E8B\u4EF6\u540D\u5E76\u5E26 toolHints\uFF08\u5EFA\u8BAE\u8C03\u7528\u7684\u5DE5\u5177\uFF09\uFF0C\u6309\u63D0\u793A\u5C55\u5F00\u5E76\u5904\u7406\u3002","\u80FD\u529B\u7BA1\u7406\u5206\u5C5E\u4E24\u4E2A\u72EC\u7ACB\u6388\u6743\u7684\u5DE5\u5177\u7EC4\uFF1A","\u300C\u80FD\u529B\u5E02\u573A\u300D\u7EC4\u8D1F\u8D23\u5B89\u88C5/\u5378\u8F7D MCP / Skill / Plugin\uFF1Alist_ability_market \u6D4F\u89C8\uFF08\u8FD4\u56DE\u73AF\u5883\u53D8\u91CF\u5951\u7EA6 envSchema\uFF0CMCP \u9700\u636E\u6B64\u914D\u7F6E env\uFF0C\u654F\u611F\u503C\u5FC5\u987B\u7531\u7528\u6237\u63D0\u4F9B\uFF09\u3001install_ability_market_item \u5B89\u88C5\u3001uninstall_ability_market_item \u5378\u8F7D\uFF08kind=plugin \u5373\u5B89\u88C5/\u5378\u8F7D\u63D2\u4EF6\uFF09\u3002","\u300C\u80FD\u529B\u5F00\u53D1\u300D\u7EC4\u8D1F\u8D23\u81EA\u7814 MCP / \u63D2\u4EF6 / Skill \u5E76\u7BA1\u7406\u5DF2\u88C5\u63D2\u4EF6\uFF1A","\u7528 ability_dev_ide \u8BFB\u7F16\u5199\u89C4\u8303\uFF08action=guide\uFF0Ckind=plugin|mcp|skill\uFF09\u5E76\u5728\u81EA\u5DF1\u7684\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u5185\u7F16\u5199\uFF1B","MCP/\u63D2\u4EF6\u7528 ability_dev_ide \u4E34\u65F6\u6302\u8F7D\u8C03\u8BD5\uFF08action=mount/unmount/list/logs\uFF1B\u4E0D\u6301\u4E45\u5316\u3001\u91CD\u542F\u5373\u5931\u6548\uFF0C\u6539\u4EE3\u7801\u81EA\u52A8\u91CD\u8F7D\uFF09\uFF0C","mount \u540E\u5DE5\u5177\u540D\u5F62\u5982 <server>__<tool>\uFF08\u53CC\u4E0B\u5212\u7EBF\uFF09\uFF0C\u7528 call_tool \u8C03\u7528\uFF1B","action=list \u67E5\u770B\u6302\u8F7D\u9879\u4E0E\u66B4\u9732\u7684\u5DE5\u5177\u540D\uFF0Caction=logs \u6392\u67E5\u5B50\u8FDB\u7A0B\u62A5\u9519\uFF0Caction=unmount \u6458\u9664\uFF1B","\u8C03\u8BD5\u901A\u8FC7\u540E\u7528 formal_ability \u8F6C\u6B63\uFF08\u7F3A\u7701 scope=global \u4EC5\u767B\u8BB0\u5168\u5C40\u914D\u7F6E\u6A21\u677F\u4E14\u521D\u59CB\u5316\u5173\u95ED\uFF0C\u9700\u7528\u6237\u5728\u9762\u677F\u5F00\u542F\u540E\u751F\u6548\uFF1Bscope=instance \u624D\u7ACB\u5373\u751F\u6548\uFF09\uFF1BSkill \u65E0\u8C03\u8BD5\u6001\uFF0C\u540C\u6837\u53EF\u7ECF formal_ability \u6216\u80FD\u529B\u5E02\u573A\u5B89\u88C5\u3002","\u5DF2\u5B89\u88C5\u63D2\u4EF6\u7684\u542F\u505C/\u91CD\u8F7D\u7531\u7528\u6237\u5728\u9762\u677F\u64CD\u4F5C\uFF1B","\u67E5\u770B\u81EA\u8EAB\u5168\u90E8\u80FD\u529B\uFF08MCP/Skill/Plugin \u542F\u505C\u4E0E\u6765\u6E90\u3001\u5DE5\u5177\u5F00\u5173\u3001\u8C03\u8BD5\u6302\u8F7D\uFF09\u7528 list_my_abilities\u3002","\u672A\u7ECF\u7528\u6237\u660E\u786E\u8981\u6C42\u4E0D\u8981\u5B89\u88C5\u6216\u5378\u8F7D\u63D2\u4EF6\u3002"].join(`
8
- `):"",U=P+Y,R=[i.systemPrompt,ee,A,U].map(T=>T?.trim()).filter(T=>!!T).join(`
1
+ import{EventEmitter as kt}from"node:events";import{randomUUID as St}from"node:crypto";import D from"node:fs";import Oe from"node:os";import z from"node:path";import{Client as Mt}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as vt}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as $t}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Et}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as xt}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as Rt,DEFAULT_TOOL_PERMISSION_POLICY as Le,getEditFailureSnapshot as It}from"./built-in-file-tools.js";import{ReadFileStateTracker as Nt}from"./read-file-state.js";import{ASK_USER_QUESTION_TOOL_NAME as Pt,createAskUserQuestionTool as Ot}from"./ask-user-question-tool.js";import{createSkillTool as Lt}from"./skill-tool.js";import{createTodoWriteTool as Dt,createTodoReadTool as Bt}from"./todo-tool.js";import{createSubAgentTools as Ut}from"./sub-agent-tools.js";import{createAwaitCompleteTool as qt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as Ft}from"./builtins/commandArtifacts.js";import{buildRuntimeEnvironmentPrompt as zt}from"./runtime-environment.js";const De="[Runtime Instructions]";import{resolveAcodeHome as jt}from"./paths.js";import{backgroundCommandManager as le}from"./background-command-manager.js";import{createTerminalTool as Wt}from"./terminal-tool.js";import{ToolGroupManager as Gt,createExpandToolsTool as Jt,createCallToolTool as Kt,mcpGroupKeyOf as Be,isPluginGroupKey as Ue,pluginGroupKeyOf as Ht}from"./tool-group-manager.js";import{loadAcodeCommands as Qt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as qe}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as Yt,calculateCompactionBudget as Vt,COMPACTION_LLM_PROMPT_TEMPLATE as Xt,conversationSizeBytes as Fe,conversationSizeKB as Y,estimateConversationTokens as j,isCompactionSummaryMessage as Zt,isRuntimeResourcesMessage as eo,isRuntimeInstructionsMessage as to,performCompaction as pe,resolveReplayWindow as oo,pruneToolOutputs as so,RUNTIME_RESOURCES_PREFIX as no,summarizeConversation as ze,SummaryUnavailableError as io}from"./compaction.js";import{isContextOverflowError as we,resolveFinishReasonOverflow as ro}from"./context-overflow.js";import{loadAcodeConfig as ao,loadAcodeSkillGroup as lo}from"./config.js";import{ACodeHookBus as co,findDeniedHookResult as je}from"./hooks/hookBus.js";import{isMcpPollingToolName as We,isMcpBlockingToolName as ke,isMcpBatchExcludedToolName as Se,isMcpIndefinitelyBlockingToolName as uo,getSemanticToolName as Me}from"./mcpToolNames.js";import{runtimeMeetingDebugLog as B}from"./meeting-debug-log.js";import{BackgroundOutputRingBuffer as mo}from"./background-output-ringbuffer.js";import{buildToolCatalog as Ge,matchesToolAllocation as Je,mergeAllocatableTools as he,PRESET_EXPLORE as po,rebindDefaultAgentId as Ke,resolveToolAllocation as ho,SUB_AGENT_ALLOWED_MCP_TOOLS as fo}from"./tool-allocation.js";import{ConcurrencyLimiter as He,getSharedResourceLock as go,ToolConcurrencyScheduler as yo,ToolTraceRecorder as Qe}from"./tool-concurrency/index.js";function To(n){if(typeof n!="object"||n===null)return!1;const e=n;return e.kind==="builtin"&&typeof e.toolName=="string"&&typeof e.exposedName=="string"&&typeof e.description=="string"&&typeof e.execute=="function"&&typeof e.inputSchema=="object"&&e.inputSchema!==null}function Co(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function _o(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function Ao(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(Co):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(_o)),n.reasoning&&(e.reasoning=n.reasoning),e}function ce(n){return n.map(Ao)}function bo(n){return n.map(e=>{const{reasoning:t,...o}=e;return o})}function wo(n,e){const t=W(n.prompt_cache_hit_tokens),o=W(n.prompt_cache_miss_tokens);if(t!==void 0||o!==void 0)return{cacheHitTokens:t??0,cacheMissTokens:o??0};const s=W(n.cache_read_input_tokens),i=W(n.cache_creation_input_tokens);if(s!==void 0||i!==void 0){const u=s??0,c=i??0,d=W(n.input_tokens)??(e!==void 0?Math.max(0,e-u-c):0);return{cacheHitTokens:u,cacheMissTokens:c+d}}const r=W(n.cache_hit_tokens),a=W(n.cache_miss_tokens);if(r!==void 0||a!==void 0)return{cacheHitTokens:r??0,cacheMissTokens:a??0};const l=W(n.prompt_tokens_details?.cached_tokens);if(l!==void 0){const u=e!==void 0?Math.max(0,e-l):0;return{cacheHitTokens:l,cacheMissTokens:u}}}function W(n){const e=typeof n=="number"?n:typeof n=="string"&&n.trim()?Number(n):NaN;if(!(!Number.isFinite(e)||e<0))return e}function ko(n,e){if(!n)return e;const t=o=>{const s=e[o],i=n[o];return o==="prompt_tokens_details"?{...i,...s}:s??i};return{prompt_tokens:t("prompt_tokens"),completion_tokens:t("completion_tokens"),input_tokens:t("input_tokens"),output_tokens:t("output_tokens"),prompt_cache_hit_tokens:t("prompt_cache_hit_tokens"),prompt_cache_miss_tokens:t("prompt_cache_miss_tokens"),cache_read_input_tokens:t("cache_read_input_tokens"),cache_creation_input_tokens:t("cache_creation_input_tokens"),cache_hit_tokens:t("cache_hit_tokens"),cache_miss_tokens:t("cache_miss_tokens"),prompt_tokens_details:t("prompt_tokens_details")}}function So(){return new Date().toISOString()}function S(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function fe(n){return S(n)}function Ye(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:bs(n,t.name),description:t.description,inputSchema:fe(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}const ge="ACODE_TOOL_GROUPS_V1:";function Mo(n){const e=String(n??"").trim();if(!e.startsWith(ge))return[];const t=e.slice(ge.length).trim();if(!t)return[];let o;try{o=JSON.parse(t)}catch{return[]}if(!fe(o)||!Array.isArray(o.groups))return[];const s=[];for(const i of o.groups){if(!fe(i))continue;const r=typeof i.key=="string"?i.key.trim():"";if(!r)continue;const a=Array.isArray(i.toolNames)?i.toolNames.filter(l=>typeof l=="string"&&l.length>0):[];s.push({key:r,label:typeof i.label=="string"&&i.label.trim()?i.label:r,toolNames:a})}return s}function vo(n){const e=String(n??"").trim();if(!e)return;if(!e.startsWith(ge))return e;const t=e.slice(ge.length).trim();return t.startsWith("{")?void 0:t||void 0}function I(n){return String(n??"").trim()||void 0}const Ve=6e4,Xe=30*6e4,Ze=6e4,et=6e4,ve=-1,tt=0,$o=1e3,Eo=3e4,ye=6e4,ot=0,xo=2147483647,Ro=8,Io=10*6e4+2e3,No=1e4,Te=5e3,st=10*60*1e3,te=10*1024*1024,nt=800*1024,it=32*1024*1024,Po=4,Oo=1.25;function rt(){const n=Number.parseInt(String(process.env.ACODE_MAX_REQUEST_BODY_BYTES??"").trim(),10);return Number.isFinite(n)&&n>0?n:void 0}function Lo(){return rt()!==void 0}function Do(n){const e=rt();if(e!==void 0)return e;if(!Number.isFinite(n)||n<=0)return nt;const t=Math.floor(n*Po*Oo);return Math.min(it,Math.max(nt,t))}const Ce=process.env.ACODE_COMPACTION_DEBUG==="1",at=Ce?z.join(Oe.tmpdir(),"acode-compaction-debug.log"):"";function f(...n){Ce&&console.log(...n)}const Bo=process.env.ACODE_IMAGE_DIAG==="1",Uo=process.env.ACODE_IMAGE_DIAG_LOG||z.join(Oe.tmpdir(),"acode-image-inject.log");function _e(n){if(!Bo)return;const e=`[${new Date().toISOString()}] ${JSON.stringify(n)}
2
+ `;D.promises.appendFile(Uo,e).catch(()=>{})}const qo=process.env.ACODE_TOKEN_DEBUG==="1";function oe(...n){qo&&console.log("[TokenDebug][Runtime]",...n)}const Fo=64e3,$e=8e3;function Ae(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:Fo,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=Yt(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:s}}async function $(n,e,t,o){if(e<=0)return await n;let s;try{return await new Promise((i,r)=>{s=setTimeout(()=>{o?.(),r(new Error(`${t} timed out after ${e}ms`))},e),n.then(i,r)})}finally{s&&clearTimeout(s)}}function lt(){return`toolbatch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}async function se(n,e,t,o=No){try{await $(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function ne(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===ve?ve:Number.isFinite(t)&&t>0?Math.floor(t):e}function ue(n,e){const t=ne(n,e);return t>0?t:e}const ct=3;function Ee(n){return n?Math.ceil(n.length/ct):0}function zo(n,e){let t=n.length;for(const o of e){const s=(o.kind==="mcp",o.toolName);if(t+=s.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const i=o;i.inputSchema&&(t+=JSON.stringify(i.inputSchema).length)}}return Math.ceil(t/ct)}function ie(n){if(n.length===0)return 0;const e=JSON.stringify(_t(n));return Ee(e)}async function jo(n){await new Promise(e=>setTimeout(e,n))}function Wo(n){return typeof n=="boolean"}function Go(n,e,t){if(Wo(t?.supportsImageInput))return t.supportsImageInput;const o=S(e)?e.models:void 0,s=S(o)?o[n]:void 0;if(!S(s))return!1;const i=s.modalities;return!S(i)||!Array.isArray(i.input)?!1:i.input.some(r=>String(r||"").trim().toLowerCase()==="image")}function xe(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(S(s)){const i=s[t];if(S(i)){const r=i[o];if(r!==void 0)return r}}return e[o]}function Jo(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",i=I(n.effort)||I(o?.effort)||I(t?.effort)||void 0;return{model:s,baseURL:I(o?.baseURL||o?.baseUrl),apiKey:I(o?.apiKey),effort:i,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:ue(o?.requestTimeoutMs??o?.timeoutMs,Ve),requestTotalTimeoutMs:ue(o?.requestTotalTimeoutMs,Xe),requestRetryCount:ne(o?.requestRetryCount,tt),requestFirstByteTimeoutMs:ue(o?.requestFirstByteTimeoutMs,Ze),requestStreamIdleTimeoutMs:ue(o?.requestStreamIdleTimeoutMs,et),mcpToolTimeoutMs:ue(o?.mcpToolTimeoutMs,ye),mcpPollingToolTimeoutMs:ne(o?.mcpPollingToolTimeoutMs,ot),supportsImageInput:Go(s,t,o),contextLimit:ne(xe(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:ne(xe(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:ne(xe(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function H(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function Ko(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function Ho(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function Qo(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 Yo(n){const e=await n.arrayBuffer();if(e.byteLength>te)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${te} bytes`);return Buffer.from(e).toString("base64")}async function Vo(n){const e=n.trim();if(Ho(e)){if(e.slice(e.indexOf(",")+1).length*.75>te)throw new Error(`ACode inline image exceeds the ${te} byte size limit`);return e}Qo(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 Yo(t)}`}function Xo(n){const e=I(n.base64Data??n.base64??n.data);return e?e.length*.75>te?void 0:Ko(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function ut(n,e,t,o){return`[Attached file: ${[n?`name=${n}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(i=>!!i).join(", ")}]`}function Zo(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,i=e.exec(n);for(;i!==null;){H(t,n.slice(s,i.index));const r=i[1],a=(i[2]||"").trim();if(r==="\u56FE\u7247"&&a)t.push({type:"image_url",image_url:{url:a}}),o=!0;else if(r==="\u6587\u4EF6"&&a){const[l="",u="",c="",d=""]=a.split("|").map(p=>p.trim());H(t,ut(l,u,c,d))}else H(t,i[0]);s=i.index+i[0].length,i=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(H(t,n.slice(s)),{content:t,hasImages:o})}function es(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const i of s){if(!S(i))continue;const r=I(i.content);if(!r)continue;const a=I(i.senderName);H(n,a?`Message from ${a}:`:"Message:");const l=Re(r);Array.isArray(l.content)?n.push(...l.content):H(n,l.content),t=t||l.hasImages}return t}function ts(n){for(const e of["directMessages","groupMessages","messages"]){const t=n[e];if(Array.isArray(t))for(const o of t){if(!S(o))continue;const s=o.content;typeof s!="string"||!s.trim()||(o.content=os(s))}}}function os(n){let e;try{e=JSON.parse(n)}catch{return n.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim()||n}if(S(e)&&"attachments"in e){const t={...e};return t.attachments=[],JSON.stringify(t)}return n}function ss(n){let e;try{e=JSON.parse(n)}catch{return}if(!S(e))return;const t=[];let o=es(t,e);const s=I(e.text)||"",i=Array.isArray(e.attachments)?e.attachments:[];H(t,s);for(const r of i){if(!S(r))continue;const a=r;if(String(a.type??a.kind??"").toLowerCase()==="image"){const c=Xo(a);c?(t.push({type:"image_url",image_url:{url:c}}),o=!0):I(a.base64Data??a.base64??a.data)&&H(t,`[Image attachment omitted: ${I(a.name)||"unnamed"} exceeds the ${te} byte inline limit]`);continue}const u=I(a.url??a.serverUrl)||"";H(t,ut(I(a.name)||"",u,I(a.mediaType??a.mimeType)||"",I(a.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function Re(n){return ss(n)??Zo(n)}async function mt(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 Vo(t.image_url.url)}})}return e}function ns(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function is(n,e){const t=n.permissions??e.permissions??{},o=n.permissions?[]:e.allowedTools??[],s=n.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(i=>i.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(i=>i.trim()).filter(Boolean)}}function rs(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function as(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 dt(n,e){return as(e).some(t=>rs(n,t))}function pt(n,e,t){if(e.length>0&&!e.some(o=>dt(o,n)))throw new Error(t)}function ht(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>dt(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);pt(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),pt(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function ls(n,e,t){try{return ht(n,e,t),!0}catch{return!1}}function be(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function cs(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(be(e.toString()));return`${t.origin}${t.pathname}`}catch{return be(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function us(n){const e=[...n].reverse().find(o=>o.role==="user"),t=ns(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function ms(n){try{const e=JSON.parse(n);return fe(e)?e:{}}catch{return{}}}function ds(n,e,t){if(new Set([Pt,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,i=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(i)||i<=0?Math.max(t,Io):Math.min(Math.floor(i),10*6e4)+2e3}function ps(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 G(n){if(!S(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>S(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
3
+ `)}return JSON.stringify(n)}function me(n){return n instanceof Error?n.message:String(n)}function hs(n){const e={orphanToolMessages:0,repairedToolCalls:0,downgradedAssistants:0,relocatedInterruptions:0,reorderedToolResults:0};if(n.length===0)return e;const t=(c,d)=>{const p=typeof c.content=="string"?c.content:JSON.stringify(c.content??"");c.role="user",delete c.tool_call_id,c.content=`[\u7CFB\u7EDF\u63D0\u793A] \u4EE5\u4E0B\u4E3A\u4E00\u6B21\u5DE5\u5177\u6267\u884C\u7684\u7ED3\u679C\uFF08tool_call_id=${d}\uFF09\uFF0C\u5176\u5BF9\u5E94\u7684\u5DE5\u5177\u8C03\u7528\u4E0A\u4E0B\u6587\u5DF2\u4E0D\u5728\u4F1A\u8BDD\u4E2D\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF1A
4
+ ${p}`,e.orphanToolMessages+=1},o=c=>{const d=new Map;for(const T of n)if(T.role==="assistant"&&Array.isArray(T.tool_calls))for(const _ of T.tool_calls){const m=typeof _?.id=="string"?_.id:"";m&&!d.has(m)&&d.set(m,T)}const p=new Set;for(const T of n){if(T.role==="assistant"&&Array.isArray(T.tool_calls)){for(const h of T.tool_calls){const g=typeof h?.id=="string"?h.id:"";g&&p.add(g)}continue}if(T.role!=="tool")continue;const _=typeof T.tool_call_id=="string"?T.tool_call_id.trim():"";if(!_){t(T,"(\u7F3A\u5931)");continue}if(p.has(_))continue;const m=d.get(_);if(m){c.push({message:T,id:_,assistant:m});continue}t(T,_)}},s=c=>{if(c.length!==0){for(const d of c){const p=n.indexOf(d.message);p>=0&&n.splice(p,1)}for(const d of c){const p=n.indexOf(d.assistant);if(p<0){t(d.message,d.id);continue}let T=p+1;for(;T<n.length&&n[T].role==="tool";)T+=1;n.splice(T,0,d.message),e.reorderedToolResults+=1}}},i=[];o(i),s(i);const r=()=>{const c=new Set;for(const d of n)d.role==="tool"&&d.tool_call_id&&c.add(d.tool_call_id);return c};let a=r();const l="\uFF08\u8BE5\u5DE5\u5177\u8C03\u7528\u7ED3\u679C\u7F3A\u5931\uFF1A\u6240\u5C5E\u8F6E\u6B21\u88AB\u4E2D\u65AD\u6216\u4E0A\u4E0B\u6587\u538B\u7F29\u65F6\u5DF2\u79FB\u9664\uFF0C\u8BF7\u52FF\u57FA\u4E8E\u8BE5\u8C03\u7528\u7EE7\u7EED\u63A8\u65AD\uFF0C\u5FC5\u8981\u65F6\u91CD\u65B0\u8C03\u7528\u5DE5\u5177\u3002\uFF09";for(let c=0;c<n.length;c++){const d=n[c];if(d.role!=="assistant"||!Array.isArray(d.tool_calls))continue;const p=d.tool_calls.filter(h=>typeof h?.id=="string"&&h.id.trim().length>0);if(p.length!==d.tool_calls.length){if(e.downgradedAssistants+=1,p.length===0){delete d.tool_calls,(d.content===null||d.content===void 0)&&(d.content="");continue}d.tool_calls=p}const T=d.tool_calls.map(h=>h?.id).filter(h=>typeof h=="string"&&h.length>0&&!a.has(h));if(T.length===0)continue;let _=-1;for(let h=c+1;h<n.length;h++){if(n[h].role==="tool"){_=h+1;continue}break}if(_>c){const h=T.map(g=>({role:"tool",tool_call_id:g,content:l}));n.splice(_,0,...h),c+=h.length,e.repairedToolCalls+=T.length,a=r();continue}if(c===n.length-1){for(const h of T)n.push({role:"tool",tool_call_id:h,content:l});e.repairedToolCalls+=T.length,a=r();continue}const m=new Set(d.tool_calls.map(h=>h?.id).filter(h=>typeof h=="string"&&h.length>0));delete d.tool_calls,(d.content===null||d.content===void 0)&&(d.content="");for(const h of n)if(h.role==="tool"&&h.tool_call_id&&m.has(h.tool_call_id)){const g=typeof h.content=="string"?h.content:JSON.stringify(h.content??""),y=h.tool_call_id;h.role="user",delete h.tool_call_id,h.content=`[\u7CFB\u7EDF\u63D0\u793A] \u4EE5\u4E0B\u4E3A\u4E00\u6B21\u5DE5\u5177\u6267\u884C\u7684\u7ED3\u679C\uFF08tool_call_id=${y}\uFF09\uFF0C\u5176\u5BF9\u5E94\u7684\u5DE5\u5177\u8C03\u7528\u4E0A\u4E0B\u6587\u5DF2\u4E0D\u5728\u4F1A\u8BDD\u4E2D\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF1A
5
+ ${g}`,e.orphanToolMessages+=1}a=r(),e.downgradedAssistants+=1}for(let c=0;c<n.length;c++){const d=n[c];if(d.role!=="assistant"||!Array.isArray(d.tool_calls))continue;const p=new Set(d.tool_calls.map(g=>g?.id).filter(g=>typeof g=="string"&&g.length>0));if(p.size===0)continue;const T=g=>g.role==="tool"&&typeof g.tool_call_id=="string"&&p.has(g.tool_call_id),_=[];for(let g=c+1;g<n.length;g++){const y=n[g];if(T(y))continue;if(y.role==="tool")break;let w=!1;for(let A=g+1;A<n.length;A++)if(T(n[A])){w=!0;break}if(!w)break;_.push(y)}if(_.length===0)continue;const m=n.filter(g=>!_.includes(g));let h=-1;for(let g=0;g<m.length;g++)T(m[g])&&(h=g);h<0||(m.splice(h+1,0,..._),n.length=0,n.push(...m),e.relocatedInterruptions+=_.length)}const u=[];return o(u),s(u),e}const ft={truncatedCount:0,strategy:"none",prunedToolMessages:0,summarizedMessages:0,freedTokens:0};async function fs(n,e,t,o,s,i){if(Fe(n)<=e)return ft;const a=await pe(n,t,o,{llmSummarizer:s});if(a.strategy!=="none")return a.summarizedMessages>0&&i&&await i(),{truncatedCount:a.prunedToolMessages+a.summarizedMessages,strategy:a.strategy,prunedToolMessages:a.prunedToolMessages,summarizedMessages:a.summarizedMessages,freedTokens:a.freedTokens};const l=await ze(n,{llmSummarizer:s,contextLimit:t});return l>0&&i&&await i(),{truncatedCount:l,strategy:l>0?"summarize":"none",prunedToolMessages:0,summarizedMessages:l,freedTokens:0}}function gs(n){return we(n)}function ys(n){const e=me(n).toLowerCase();return gs(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 Ts(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=me(n).toLowerCase();return e===-32001||t.includes("request timed out")}function Cs(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 gt(n,e,t){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:Cs(e),message:me(e)},...t?{file_snapshot:{path:t.path,bytes:t.bytes,content:t.content}}:{}})}function _s(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function yt(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(S(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function Tt(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 Ct(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
6
+ `)}function As(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,i=e.instanceName,r=e.projectId,a=e.workspacePath,l=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 i=="string"&&i.trim()&&t.push(`Instance: ${i.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Project: ${r.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Workspace: ${a.trim()}`),typeof l=="string"&&l.trim()&&t.push(`Runtime Mode: ${l.trim()}`),typeof u=="string"&&u.trim()&&t.push(`Description: ${u.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
7
+ `)}function _t(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function bs(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function ws(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function ks(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Ss(e)?Ms(t):t]))}function Ss(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function Ms(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function At(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function Ie(n){if(!S(n))return null;const e=n.error;if(S(e)){const t=typeof e.message=="string"?e.message:"",o=e.code??e.status??e.type,s=o==null?"":String(o);return t||s?[s,t].filter(Boolean).join(" "):null}if(typeof e=="string"&&e)return e;if(n.type==="error"||n.object==="error"){const t=typeof n.message=="string"?n.message:"",o=n.code??n.status,s=o==null?"":String(o);if(t||s)return[s,t].filter(Boolean).join(" ")}return null}const vs=/role 'tool'|tool calls and tool results|tool_call_sequence|\b11148\b/i;let bt=0,de="";function Ne(n,e,t){if(!vs.test(t))return null;try{const o=new Map,s=new Map;n.forEach((m,h)=>{if(m.role==="assistant"&&Array.isArray(m.tool_calls))for(const g of m.tool_calls){const y=typeof g?.id=="string"?g.id.trim():"";y&&!o.has(y)&&o.set(y,h)}else if(m.role==="tool"){const g=typeof m.tool_call_id=="string"?m.tool_call_id.trim():"";g&&!s.has(g)&&s.set(g,h)}});const i=[];n.forEach((m,h)=>{if(m.role==="tool"){const g=typeof m.tool_call_id=="string"?m.tool_call_id.trim():"",y=g?o.get(g):void 0;(g===""||y===void 0||y>h)&&i.push(h)}else if(m.role==="assistant"&&Array.isArray(m.tool_calls))for(const g of m.tool_calls){const y=typeof g?.id=="string"?g.id.trim():"";if(y===""||!s.has(y)){i.push(h);break}}});const r=m=>` [\u5DE5\u5177\u5E8F\u5217\u8BC1\u636E] \u53EF\u7591\u6D88\u606F ${i.length}/${n.length} \u6761\uFF08${m?`\u5DF2\u5199\u5165 ${m}`:"\u843D\u76D8\u5931\u8D25"}\uFF09`,a=Date.now();if(a-bt<1e4&&de)return r(de);bt=a;const l=m=>({role:m.role,tool_call_id:m.tool_call_id,tool_calls:Array.isArray(m.tool_calls)?m.tool_calls.map(h=>h?.id??null):void 0,contentPreview:typeof m.content=="string"?m.content.slice(0,300):m.content===null?null:JSON.stringify(m.content).slice(0,300)}),u=`acode-tool-seq-${new Date(a).toISOString().replace(/[:.]/g,"-")}.json`,c=String(process.env.AWS_TEST_HOME||"").trim()||String(process.env.AWS_RUNTIME_HOME_DIR||"").trim(),d=String(process.env.AWS_RUNTIME_ENV||"").trim().toLowerCase()==="development",p=c||(d?z.resolve(process.cwd(),"..",".dev-home"):z.dirname(jt())),T=z.join(p,".aws-bridge","log"),_={timestamp:new Date(a).toISOString(),status:e,errorBody:t.slice(0,4e3),suspectIndexes:i,messages:n.map((m,h)=>({index:h,role:m.role,tool_call_id:m.tool_call_id,tool_calls:Array.isArray(m.tool_calls)?m.tool_calls.map(g=>g?.id??null):void 0})),suspectWindows:i.map(m=>{const h=Math.max(0,m-6),g=Math.min(n.length,m+7);return{center:m,range:[h,g],messages:n.slice(h,g).map((y,w)=>({index:h+w,...l(y)}))}})};return de=`.aws-bridge/log/${u}`,D.promises.mkdir(T,{recursive:!0}).then(()=>D.promises.writeFile(z.join(T,u),JSON.stringify(_,null,2),"utf-8")).then(()=>D.promises.readdir(T)).then(m=>{const h=m.filter(y=>y.startsWith("acode-tool-seq-")).sort(),g=h.length-20;return g<=0?null:Promise.all(h.slice(0,g).map(y=>D.promises.unlink(z.join(T,y)).catch(()=>{})))}).catch(()=>{de=""}),r(de)}catch{return null}}function wt(n){const e=new Set,t=Date.now();return n.map((o,s)=>{const i=typeof o?.id=="string"?o.id.trim():"";if(i&&!e.has(i))return e.add(i),o;let r=`call-${t}-${s}`,a=1;for(;e.has(r);)r=`call-${t}-${s}-${a}`,a+=1;return e.add(r),{...o,id:r}})}function $s(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 Es(n){return wt([...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0))}function xs(){const n=process.env.ACODE_ABORT_FORCE_SETTLE_GRACE_MS;if(n===void 0||n.trim()==="")return 6e4;const e=Number(n.trim());return Number.isFinite(e)&&e>=0?Math.floor(e):6e4}class Z extends kt{hasActiveBlockingToolCall(){return this.activeBlockingToolCalls>0}static isLongBlockingMcpToolName(e){return uo(e)}constructor(e){super(),this.config=e,this.initialConversation=[],this.mcpStderrBuffers=new Map,this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:Ve,requestTotalTimeoutMs:Xe,requestRetryCount:tt,requestFirstByteTimeoutMs:Ze,requestStreamIdleTimeoutMs:et,mcpToolTimeoutMs:ye,mcpPollingToolTimeoutMs:ot,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new qe([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:{...Le}},this.abortController=null,this.exposedToolsInitialized=!1,this.recoveredToolNames=new Set,this.readFileStateTracker=new Nt,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.toolGroupManager=null,this.pluginGroupStates=new Map,this.submitQueue=Promise.resolve(),this.activeTurnToken=null,this.forceSettleWaiters=new Map,this.abortForceSettleTimer=null,this.activeTurn=!1,this.activeBlockingToolCalls=0,this.forceMessagePending=!1,this.compactRequested=!1,this.instructionsDirty=!1,this.turnPromptPushed=!1,this.abortRequested=!1,this.toolSettleSlots=new Map,this.toolSettleSeq=0,this.toolResourceLock=go(),this.toolConcurrencyScheduler=new yo,this.toolReadOnlyLimiter=null,this.toolBashLimiter=null,this.toolConcurrencyEnabled=!0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.permissionWaiters=new Map,this.hookBus=new co({sessionId:e.sessionId,onError:(i,r)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${i.name}: ${r instanceof Error?r.message:String(r)}`})}});for(const i of e.hooks??[])this.hookBus.register(i);e.toolPermissionPolicy&&(this.state.toolPermissionPolicy={...Le,...e.toolPermissionPolicy});const t=e.toolConcurrency;this.toolConcurrencyEnabled=t?.enabled!==!1;const o=t?.maxReadOnly??8;this.toolReadOnlyLimiter=new He(o);const s=t?.maxBash??0;this.toolBashLimiter=s>0?new He(s):null}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:So(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s,i){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s,...i?{trigger:i}:{}})}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\uFF08\u4FDD\u771F\u7EA7\u522B L${t.level??1}\uFF09...`);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;case"degrade":this.emitCompactionPhase(e,`degrade_l${t.level??2}`,`\u964D\u7EA7\u5230 L${t.level??2}`,t.reason??"\u4FDD\u771F\u7EA7\u522B\u4E0B\u964D");break}}async runCompactionPass(e){const{contextLimit:t,maxOutput:o,effectiveUsed:s,trigger:i,force:r}=e,a=Y(this.state.conversation),l=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:l,sizeKB:a,estimatedTokens:s,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:this.state.provider.model,trigger:i}),this.emitCompactionPhase(l,"detect",e.detectLabel,e.detectDetail);const u=Vt({contextLimit:t,maxOutput:o,...this.state.provider.inputLimit?{inputLimit:this.state.provider.inputLimit}:{},toolsTokens:ie(this.state.exposedTools)});let c;try{c=await pe(this.state.conversation,t,o,{llmSummarizer:p=>this.summarizeConversationWithLLM(p),onPhase:p=>this.handleCompactionPhase(l,p),actualUsedTokens:s,force:r,budget:u,allowRuleFallback:!1,retryPolicy:{maxAttempts:Math.max(1,this.state.provider.requestRetryCount??3)}})}catch(p){if(!(p instanceof io))throw p;this.emitAcodeEvent("warning",{message:`LLM \u6458\u8981\u4E0D\u53EF\u7528\uFF0C\u5DF2\u4F7F\u7528\u89C4\u5219\u6458\u8981\u515C\u5E95\uFF1A${p.message}`}),c=await pe(this.state.conversation,t,o,{onPhase:T=>this.handleCompactionPhase(l,T),actualUsedTokens:s,force:r,budget:u})}const d=Y(this.state.conversation);return this.emitAcodeEvent("context_compaction",{action:"end",compactionId:l,sizeBeforeKB:a,sizeAfterKB:d,freedKB:Math.round((a-d)*10)/10,strategy:c.strategy,freedTokens:c.freedTokens,tokensBefore:c.tokensBefore,tokensAfter:c.tokensAfter,prunedToolMessages:c.prunedToolMessages,summarizedMessages:c.summarizedMessages,messageCountBefore:c.messageCountBefore,messageCountAfter:c.messageCountAfter,level:c.level,...c.levelLabel?{levelLabel:c.levelLabel}:{},...c.ladderStep?{ladderStep:c.ladderStep}:{},...c.summaryChunks?{summaryChunks:c.summaryChunks}:{},...c.downsampleCount!==void 0?{downsampleCount:c.downsampleCount}:{},...c.noSummary!==void 0?{noSummary:c.noSummary}:{},...c.reachedTarget!==void 0?{reachedTarget:c.reachedTarget}:{}}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,c.summarizedMessages>0&&await this.rebuildRuntimeResourcesMessage(),this.rebuildRuntimeInstructionsMessage(),c}compactContext(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");return this.compactRequested=!0,f("[ACodeRuntime] \u{1F5DC}\uFE0F Manual compaction requested (\u5148\u884C\u538B\u7F29): unified high-fidelity cascade"),{requested:!0}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await ao(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),i=Jo(this.config,e);f(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${i.model}, baseURL=${i.baseURL??"(none)"}, apiKey=${i.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const r=is(this.config,e),a=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},i.mcpToolTimeoutMs),l=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const u=await this.fetchProfilePrompt(a),c=this.config.agentId||"unknown";Ft(c),le.reconcileOrphans(c);const d=Rt(this.config.workingDirectory,c,this.config.onFileChange,{manager:le,emitCompleted:C=>{this.emitAcodeEvent("background_command_completed",C)}},this.createToolPermissionController(),{tracker:this.readFileStateTracker,enabled:this.config.enableStaleFileGuard!==!1}),p=Ot(this.buildAskUserQuestionDeps(),()=>this.contextVersion),T=Lt(t);this.skillTool=T;const _=Dt(c),m=Bt(c),h=this.config.subAgentManager?Ut(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],g=qt(this.buildAwaitCompleteDeps()),y=this.config.terminalManager?Wt(c,{terminalManager:this.config.terminalManager}):null,w=new Map;this.pluginGroupStates=w;const A=new Gt({stateOf:C=>Ue(C)?w.get(C)??"disabled":(this.config.capabilityState??(()=>"disabled"))(C)});A.register({key:"pencil",label:"\u8BBE\u8BA1\u753B\u5E03(pencil)",summary:"UI design editor",collapsible:!0}),A.register({key:"draw",label:"\u7ED8\u56FE",summary:"\u7ED8\u5236 draw.io \u6D41\u7A0B\u56FE/\u6CF3\u9053\u56FE",collapsible:!0}),A.register({key:"office",label:"Office \u6587\u4EF6",summary:"\u53EF\u8FDB\u884C\u67E5\u770B/\u521B\u5EFA\u548C\u590D\u6742\u7F16\u8F91 Word/PPT/Excel",collapsible:!0}),A.register({key:"launch",label:"\u542F\u52A8\u9879\u7BA1\u7406",summary:"\u7BA1\u7406\u9879\u76EE\u4E2D\u4E1A\u52A1\u7A0B\u5E8F\u7684\u8D77\u505C\uFF0C\u82E5\u540E\u9762\u9700\u8981\u542F\u52A8\u9879\u76EE\u5E94\u4F7F\u7528\u6B64\u5DE5\u5177",collapsible:!0}),A.register({key:"hire",label:"\u62DB\u8058\u5DE5\u5177",summary:"\u62DB\u8058\u65B0\u7684\u540C\u4E8B Agent",collapsible:!0}),A.register({key:"browser",label:"\u6D4F\u89C8\u5668\u64CD\u4F5C",summary:"\u542F\u52A8\u6D4F\u89C8\u5668\u4F1A\u8BDD\u3001\u5BFC\u822A\u3001\u622A\u56FE\u4E0E\u9875\u9762\u4EA4\u4E92",collapsible:!0}),A.register({key:"desktop",label:"\u684C\u9762\u64CD\u4F5C",summary:"\u622A\u5C4F\u3001\u9F20\u6807\u952E\u76D8\u63A7\u5236\u4E0E UI \u81EA\u52A8\u5316",collapsible:!1}),A.register({key:"task",label:"\u6D41\u7A0B\u4EFB\u52A1",summary:"\u5904\u7406\u6D41\u7A0B\u7EBF\u4EFB\u52A1\uFF1A\u67E5\u770B\u5F53\u524D\u4EFB\u52A1\u3001\u63D0\u4EA4\u6267\u884C\u7ED3\u679C\u3001\u56DE\u9000\u4EFB\u52A1\u3001\u7ED9\u6D41\u7A0B\u5B9E\u4F8B\u7559\u8A00",collapsible:!0,toolNames:["my_task","submit_task_result","start_task_rollback","finish_task_rollback","create_task_instance_comment"]}),A.register({key:"meeting",label:"\u4F1A\u8BAE",summary:"\u521B\u5EFA/\u52A0\u5165\u4F1A\u8BAE\u3001\u53D1\u8A00\u3001\u67E5\u770B\u4F1A\u8BAE\u4FE1\u606F\u3001\u79BB\u5F00/\u7ED3\u675F\u4F1A\u8BAE",collapsible:!0,toolNames:["create_meeting","leave_meeting","end_meeting","meeting_speak","get_meeting_info","my_meetings"]}),A.register({key:"debug",label:"\u8C03\u8BD5\u65E5\u5FD7",summary:"\u6309\u6761\u4EF6\u5206\u9875\u67E5\u8BE2 Debug \u65E5\u5FD7\u4E0E\u83B7\u53D6\u65E5\u5FD7\u4E0A\u62A5\u914D\u7F6E",collapsible:!0,toolNames:["get_debug_log_config","query_debug_logs"]}),A.register({key:"fileHistory",label:"\u6587\u4EF6\u53D8\u66F4\u5386\u53F2",summary:"\u6309\u89D2\u8272/\u5B9E\u4F8B/\u6587\u4EF6\u8DEF\u5F84\u8FC7\u6EE4\u67E5\u8BE2\u6587\u4EF6\u53D8\u66F4\u5386\u53F2",collapsible:!0,toolNames:["query_file_changes_history"]}),A.register({key:"email",label:"\u90AE\u7BB1",summary:"\u6536\u53D1\u89D2\u8272\u5B9E\u4F8B\u57DF\u540D\u90AE\u7BB1\uFF08xxxxx@\u57DF\u540D\uFF09\uFF1A\u53D1\u4FE1\u3001\u5217\u90AE\u4EF6\u3001\u8BFB\u6B63\u6587\u4E0E\u9644\u4EF6\u3001\u56DE\u4FE1\u4FDD\u6301\u7EBF\u7A0B\u3001\u786E\u8BA4\u4E1A\u52A1\u6D88\u8D39",collapsible:!0,toolNames:["send_email","list_emails","read_email","reply_email","ack_email"]}),this.toolGroupManager=A;for(const C of a){const R=C.spec??e.mcpServers?.[C.serverName];R&&this.registerMcpCollapsedGroup(C.serverName,R,C)}for(const C of a)this.registerToolGroupsFromMcp(C);if(this.config.pluginBridge)try{const C=await this.config.pluginBridge.listPlugins();this.applyPluginGroups(C,w,A)}catch(C){f(`[ACodeRuntime] \u63D2\u4EF6\u7EC4\u6CE8\u518C\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${C instanceof Error?C.message:String(C)}`)}const N=Jt({toolGroupManager:A,getAllTools:()=>this.state.exposedTools,capabilityToolRelay:this.config.capabilityToolRelay,pluginBridge:this.config.pluginBridge}),k=Kt({toolGroupManager:A,pluginBridge:this.config.pluginBridge,capabilityToolRelay:this.config.capabilityToolRelay,findTool:C=>{const R=this.state.exposedTools.find(Pe=>Pe.exposedName===C||Pe.toolName===C);if(!R)return;const ae=R.group??A.getGroupForExposedName(R.exposedName);return{kind:R.kind,group:ae,toolName:R.toolName}},dispatchTool:(C,R,ae)=>this.executeSingleToolByName(C,R,ae)}),v=[...d,p,T,_,m,...h,g,...y?[y]:[],N,k,...a.flatMap(C=>C.tools),...Ke(this.config.extraBuiltInTools??[],this.config.agentId??"")];if(this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0){const C=Ke(this.config.subAgentSuiteTools??[],this.config.agentId??""),R=he(v,C);v.length=0,v.push(...R)}let M=v;const L=this.config.subAgentAllowedTools;L&&L.length>0&&(M=M.filter(C=>Je(C,L)));const E=this.resolveCommandDirs(e);let O=[...E,...this.discoverPluginCommandDirs()];if(this.config.pluginBridge?.getCommandDirs)try{const C=await this.config.pluginBridge.getCommandDirs();C.length>0&&(O=[...O,...C])}catch(C){f(`[ACodeRuntime] \u63D2\u4EF6\u547D\u4EE4\u76EE\u5F55\u83B7\u53D6\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${C instanceof Error?C.message:String(C)}`)}O=[...new Set(O)],this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const U=await Qt(O),re=new qe(U),ee=Tt(t),b=Ct(U),P=A.buildCapabilityPrompt(),Q=this.config.pluginBridge?["","## \u63D2\u4EF6\u7CFB\u7EDF","\u5DF2\u5B89\u88C5\u63D2\u4EF6\u4EE5\u6536\u7EB3\u7EC4\u5F62\u5F0F\u5217\u51FA\uFF08\u89C1\u4E0A\u65B9\u300C\u53EF\u7528\u80FD\u529B\u300D\u4E2D\u7684 plugin:{\u63D2\u4EF6\u540D} \u6761\u76EE\uFF09\u3002",'\u9700\u8981\u67D0\u63D2\u4EF6\u7684\u5DE5\u5177\u65F6\uFF0C\u5148 expand_tools({ group: "plugin:\u63D2\u4EF6\u540D" }) \u5C55\u5F00\uFF1B','\u5DE5\u5177\u5B9A\u4E49\uFF08\u542B\u53C2\u6570 schema\uFF09\u968F\u5C55\u5F00\u7ED3\u679C\u8FD4\u56DE\uFF0C\u518D\u7528 call_tool({ name: "\u63D2\u4EF6\u540D.\u5DE5\u5177\u540D", arguments: {...} }) \u8C03\u7528\u3002',"\u63D2\u4EF6\u4E8B\u4EF6\u4EE5 [plugin-event] \u6D88\u606F\u51FA\u73B0\uFF0C\u6D88\u606F\u6807\u660E\u6765\u6E90\u63D2\u4EF6\u4E0E\u4E8B\u4EF6\u540D\u5E76\u5E26 toolHints\uFF08\u5EFA\u8BAE\u8C03\u7528\u7684\u5DE5\u5177\uFF09\uFF0C\u6309\u63D0\u793A\u5C55\u5F00\u5E76\u5904\u7406\u3002","\u80FD\u529B\u7BA1\u7406\u5206\u5C5E\u4E24\u4E2A\u72EC\u7ACB\u6388\u6743\u7684\u5DE5\u5177\u7EC4\uFF1A","\u300C\u80FD\u529B\u5E02\u573A\u300D\u7EC4\u8D1F\u8D23\u5B89\u88C5/\u5378\u8F7D MCP / Skill / Plugin\uFF1Alist_ability_market \u6D4F\u89C8\uFF08\u8FD4\u56DE\u73AF\u5883\u53D8\u91CF\u5951\u7EA6 envSchema\uFF0CMCP \u9700\u636E\u6B64\u914D\u7F6E env\uFF0C\u654F\u611F\u503C\u5FC5\u987B\u7531\u7528\u6237\u63D0\u4F9B\uFF09\u3001install_ability_market_item \u5B89\u88C5\u3001uninstall_ability_market_item \u5378\u8F7D\uFF08kind=plugin \u5373\u5B89\u88C5/\u5378\u8F7D\u63D2\u4EF6\uFF09\u3002","\u300C\u80FD\u529B\u5F00\u53D1\u300D\u7EC4\u8D1F\u8D23\u81EA\u7814 MCP / \u63D2\u4EF6 / Skill \u5E76\u7BA1\u7406\u5DF2\u88C5\u63D2\u4EF6\uFF1A","\u7528 ability_dev_ide \u8BFB\u7F16\u5199\u89C4\u8303\uFF08action=guide\uFF0Ckind=plugin|mcp|skill\uFF09\u5E76\u5728\u81EA\u5DF1\u7684\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u5185\u7F16\u5199\uFF1B","MCP/\u63D2\u4EF6\u7528 ability_dev_ide \u4E34\u65F6\u6302\u8F7D\u8C03\u8BD5\uFF08action=mount/unmount/list/logs\uFF1B\u4E0D\u6301\u4E45\u5316\u3001\u91CD\u542F\u5373\u5931\u6548\uFF0C\u6539\u4EE3\u7801\u81EA\u52A8\u91CD\u8F7D\uFF09\uFF0C","mount \u540E\u5DE5\u5177\u540D\u5F62\u5982 <server>__<tool>\uFF08\u53CC\u4E0B\u5212\u7EBF\uFF09\uFF0C\u7528 call_tool \u8C03\u7528\uFF1B","action=list \u67E5\u770B\u6302\u8F7D\u9879\u4E0E\u66B4\u9732\u7684\u5DE5\u5177\u540D\uFF0Caction=logs \u6392\u67E5\u5B50\u8FDB\u7A0B\u62A5\u9519\uFF0Caction=unmount \u6458\u9664\uFF1B","\u8C03\u8BD5\u901A\u8FC7\u540E\u7528 formal_ability \u8F6C\u6B63\uFF08\u7F3A\u7701 scope=global \u4EC5\u767B\u8BB0\u5168\u5C40\u914D\u7F6E\u6A21\u677F\u4E14\u521D\u59CB\u5316\u5173\u95ED\uFF0C\u9700\u7528\u6237\u5728\u9762\u677F\u5F00\u542F\u540E\u751F\u6548\uFF1Bscope=instance \u624D\u7ACB\u5373\u751F\u6548\uFF09\uFF1BSkill \u65E0\u8C03\u8BD5\u6001\uFF0C\u540C\u6837\u53EF\u7ECF formal_ability \u6216\u80FD\u529B\u5E02\u573A\u5B89\u88C5\u3002","\u5DF2\u5B89\u88C5\u63D2\u4EF6\u7684\u542F\u505C/\u91CD\u8F7D\u7531\u7528\u6237\u5728\u9762\u677F\u64CD\u4F5C\uFF1B","\u67E5\u770B\u81EA\u8EAB\u5168\u90E8\u80FD\u529B\uFF08MCP/Skill/Plugin \u542F\u505C\u4E0E\u6765\u6E90\u3001\u5DE5\u5177\u5F00\u5173\u3001\u8C03\u8BD5\u6302\u8F7D\uFF09\u7528 list_my_abilities\u3002","\u672A\u7ECF\u7528\u6237\u660E\u786E\u8981\u6C42\u4E0D\u8981\u5B89\u88C5\u6216\u5378\u8F7D\u63D2\u4EF6\u3002"].join(`
8
+ `):"",q=P+Q,x=[De,i.systemPrompt,ee,b,q].map(C=>C?.trim()).filter(C=>!!C).join(`
9
9
 
10
- `),J=T=>T?.trim()?[{role:"system",content:T.trim()}]:[],q=[this.config.rolePrompt,u].map(T=>T?.trim()).filter(T=>!!T).join(`
10
+ `),J=C=>C?.trim()?[{role:"system",content:C.trim()}]:[],F=[this.config.rolePrompt,u].map(C=>C?.trim()).filter(C=>!!C).join(`
11
11
 
12
- `),V=[...J(this.config.globalPrompt),...J(q),...J(this.config.memory),...J(this.config.resumeContext),...R?[{role:"system",content:R}]:[],...J(Dt())],X=V.map(T=>T.content).filter(Boolean).join(`
12
+ `),V=[...J(this.config.globalPrompt),...J(F),...J(this.config.memory),...J(this.config.resumeContext),...x?[{role:"system",content:x}]:[],...J(zt())],X=V.map(C=>C.content).filter(Boolean).join(`
13
13
 
14
- `);this.initialConversation=le(V),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:i,permissions:a,mcpConnections:r,ownsMcpConnections:l,exposedTools:v,commands:B,commandRegistry:ie,conversation:le(V),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:this.state.toolPermissionPolicy},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:i.model,commandCount:B.length});const K=_e(i);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:i.model,commandCount:B.length,estimatedContextTokens:Po(X,v),contextLimit:K.contextLimit,maxOutput:K.maxOutput,...K.inputLimit!==void 0?{inputLimit:K.inputLimit}:{},compactionThreshold:K.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:r.length,builtInToolCount:m.length,toolCount:v.length,permissionMode:a.mode,allowedToolRules:a.allow,deniedToolRules:a.deny,tools:v.map(T=>({name:T.exposedName,source:T.kind==="mcp"?`${T.serverName}.${T.toolName}`:`builtin.${T.toolName}`,description:T.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(T=>({name:T.name,description:T.description,directory:T.directory})),skillGroups:o.map(T=>({dir:T.dir,exists:T.exists,skills:T.skills.map(I=>({name:I.name,description:I.description,directory:I.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:B.length,commandDirs:G,commands:B.map(T=>({name:T.name,description:T.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=F.join(this.config.workingDirectory,".acode","skills"),o=F.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,i=[],a=[];for(const u of[e,t,o]){if(!u)continue;const c=F.resolve(u);if(!s.has(c)){s.add(c),i.push(await to(u));try{await O.promises.access(c),a.push(c)}catch{}}}const r=new Map;for(const u of i)for(const c of u.skills)r.set(c.name,c);return{skills:[...r.values()],skillGroups:i,watchedDirs:a}}startSkillWatchers(e){for(const t of e){let o=null;try{o=O.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=O.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()},Z.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}))}))}),p(`[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(!ye||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:i}=_e(e);this.compactionDebugTimer=setInterval(()=>{try{const a=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,r=z(this.state.conversation)+ue(this.state.exposedTools),l=Math.max(a,r),u=Q(this.state.conversation),c=this.state.started&&!this.state.terminated,m=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${u}KB`,`estimation=${r} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${a}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${i}`,`remainingToTrigger=${Math.max(0,i-a)}`,`isRunning=${c}`,`shouldCompact=${c?l>=i:!1}`,"---"].join(" | ");O.promises.appendFile(nt,m+`
15
- `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e,t){const o=this.contextVersion;p(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${o}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const s=this.submitQueue.then(()=>(p(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${o}`),this.executeSubmitGuarded(e,o,t)));return this.submitQueue=s.catch(()=>{p("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),p("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),s}executeSubmitGuarded(e,t,o){const s={};this.activeTurnToken=s;const i=this.executeSubmit(e,t,o),a=new Promise(r=>{this.forceSettleWaiters.set(s,r)});return i.finally(()=>{this.forceSettleWaiters.delete(s),this.activeTurnToken===s&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([i,a])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=Ms();this.abortForceSettleTimer=setTimeout(()=>{this.abortForceSettleTimer=null,this.activeTurn&&this.activeTurnToken===e&&this.forceSettleActiveTurn(`turn still unsettled ${t}ms after abort()`)},t),typeof this.abortForceSettleTimer.unref=="function"&&this.abortForceSettleTimer.unref()}forceSettleActiveTurn(e){const t=this.activeTurnToken;console.error(`[ACodeRuntime] \u{1F6A8} FORCE SETTLE: active turn ignored abort() (${e}). Force-settling to unblock submitQueue; late executeSubmit continuation will be superseded.`),this.contextVersion+=1,this.activeTurn=!1,this.abortRequested=!1,this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.emitAcodeEvent("error",{message:`ACode turn force-settled: ${e}`}),this.emitAcodeEvent("turn_complete",{failed:!0});const o=t?this.forceSettleWaiters.get(t):void 0;t&&this.forceSettleWaiters.delete(t),this.activeTurnToken=null,o?.()}notifyForceMessage(){this.forceMessagePending=!0,p("[ACodeRuntime] \u{1F514} Force message pending flag set")}exportConversation(){return le(this.state.conversation)}async importTranscript(e){if(!Array.isArray(e)||e.length===0)return console.log("[HIBERNATE-REPLAY][runtime] \u7A7A\u8F93\u5165\uFF0C\u8DF3\u8FC7\u91CD\u653E"),0;if(!this.state.started)return console.log(`[HIBERNATE-REPLAY][runtime] \u4F1A\u8BDD\u672A start()\uFF0C\u8DF3\u8FC7\u91CD\u653E\uFF08${e.length}\u6761\u88AB\u4E22\u5F03\uFF09`),0;const t=e.filter(u=>u.role!=="system");if(t.length===0)return 0;const{contextLimit:o,maxOutput:s,inputLimit:i}=_e(this.state.provider),a=Qt(o,i),r=z(this.state.conversation)+z(t)+ue(this.state.exposedTools);let l=t;if(console.log(`[HIBERNATE-REPLAY][runtime] \u9884\u68C0: \u53EF\u91CD\u653E=${t.length}\u6761 projectedTokens=${r} hardWindow=${a} \u9700\u8981\u9884\u538B\u7F29=${r>=a}`),r>=a){p(`[ACodeRuntime] \u{1F4E6} importTranscript pre-compaction: projected=${r} >= hardWindow=${a}`);try{const u=await be(t,o,s,{llmSummarizer:c=>this.summarizeConversationWithLLM(c)});if(u.strategy!=="none"){const c=z(t);p(`[ACodeRuntime] \u{1F4E6} importTranscript pre-compaction done: strategy=${u.strategy}, tokensBefore=${r}, tokensAfter=${c}`)}}catch(u){p(`[ACodeRuntime] \u26A0\uFE0F importTranscript pre-compaction failed, replaying raw: ${u instanceof Error?u.message:String(u)}`)}l=t}return this.state.conversation.push(...le(l)),console.log(`[HIBERNATE-REPLAY][runtime] \u91CD\u653E\u5B8C\u6210: \u62FC\u5165=${l.length}\u6761 conversation\u603B\u957F=${this.state.conversation.length}\u6761 \u603Btoken\u4F30\u7B97=${z(this.state.conversation)+ue(this.state.exposedTools)}`),this.emitAcodeEvent("context_compaction",{action:"end",compactionId:`transcript-replay-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,sizeKB:Q(this.state.conversation),estimatedTokens:z(this.state.conversation)+ue(this.state.exposedTools),actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,replayedMessageCount:l.length,model:this.state.provider.model,trigger:"hibernation_replay"}),l.length}addBuiltInTools(e){if(!this.state||!this.exposedToolsInitialized||!Array.isArray(e))return 0;const t=new Set(this.state.exposedTools.map(s=>s.exposedName)),o=[];for(const s of e)uo(s)&&(t.has(s.exposedName)||(t.add(s.exposedName),o.push(s)));return o.length===0?0:(this.state.exposedTools=[...this.state.exposedTools,...o],this.emitExposedToolsStatus(),o.length)}removeBuiltInToolsByPrefix(e){if(!this.state||!this.exposedToolsInitialized||!e)return 0;const t=this.state.exposedTools.length;this.state.exposedTools=this.state.exposedTools.filter(s=>!s.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}async addMcpServer(e,t){if(!this.state?.started||this.state.terminated)return{ok:!1,tools:0,error:"ACode runtime is not active"};const o=String(e??"").trim();if(!o)return{ok:!1,tools:0,error:"server name is required"};this.state.mcpConnections.find(u=>u.serverName===o)&&await this.removeMcpServer(o);const i=this.state.provider.mcpToolTimeoutMs;let a;const r=new Map;try{a=await this.connectMcpServers({[o]:t},i,r)}catch(u){return{ok:!1,tools:0,error:u instanceof Error?u.message:String(u)}}const l=a.find(u=>u.serverName===o);if(!l){const u=r.get(o);return{ok:!1,tools:0,error:u?`MCP server ${o} \u8FDE\u63A5\u5931\u8D25: ${u}`:`MCP server ${o} \u8FDE\u63A5\u5931\u8D25`}}return this.state.mcpConnections=[...this.state.mcpConnections,l],this.registerMcpCollapsedGroup(o,t,l),this.registerToolGroupsFromMcp(l),this.exposedToolsInitialized&&(this.state.exposedTools=[...this.state.exposedTools,...l.tools]),this.emitExposedToolsStatus(),{ok:!0,tools:l.tools.length,toolNames:l.tools.map(u=>u.exposedName)}}async removeMcpServer(e){const t=String(e??"").trim();if(!t)return{ok:!1,removed:!1};const o=this.state?.mcpConnections.find(s=>s.serverName===t);return o?(this.state.mcpConnections=this.state.mcpConnections.filter(s=>s.serverName!==t),this.state.exposedTools=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.serverName===t)),this.toolGroupManager?.unregister?.(Oe(t)),this.mcpStderrBuffers.delete(t),await se(`ACode MCP server ${t} close`,o.transport.close(),s=>{this.emitAcodeEvent("error",{message:s})},this.state.provider.mcpToolTimeoutMs),this.emitExposedToolsStatus(),{ok:!0,removed:!0}):{ok:!0,removed:!1}}addPluginCommands(e){if(!this.state||e.length===0)return;this.state.commandRegistry.addCommands(e);const t=new Set(this.state.commands.map(o=>o.name));this.state.commands=[...this.state.commands,...e.filter(o=>!t.has(o.name))]}applyPluginGroups(e,t,o){const s=new Map;for(const a of e)s.set(zt(a.name),{label:a.name,summary:a.description??"",state:a.enabled?"collapsed":"disabled"});let i=!1;for(const a of o.getAllGroups())De(a.key)&&(s.has(a.key)||(o.unregister(a.key),t.delete(a.key),i=!0));for(const[a,r]of s){const l=o.getRegistration(a);l?(l.label!==r.label||l.summary!==r.summary)&&o.register({...l,label:r.label,summary:r.summary,collapsible:!0,pluginName:r.label}):(o.register({key:a,label:r.label,summary:r.summary,collapsible:!0,pluginName:r.label}),i=!0);const u=t.get(a);u!==void 0&&u!==r.state&&(i=!0),t.set(a,r.state)}return i}async syncPluginGroups(){if(!this.config.pluginBridge||!this.toolGroupManager||!this.state)return;let e;try{e=await this.config.pluginBridge.listPlugins()}catch(o){p(`[ACodeRuntime] syncPluginGroups \u62C9\u53D6\u63D2\u4EF6\u6E05\u5355\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${o instanceof Error?o.message:String(o)}`);return}this.applyPluginGroups(e,this.pluginGroupStates,this.toolGroupManager)&&this.injectPluginChangeNotice()}injectPluginChangeNotice(){const e="[\u63D2\u4EF6\u80FD\u529B\u53D8\u66F4]",t=this.state.conversation;for(let s=t.length-1;s>=0;s--){const i=t[s];i.role==="system"&&typeof i.content=="string"&&i.content.startsWith(e)&&t.splice(s,1)}const o=[...this.pluginGroupStates.entries()].filter(([,s])=>s!=="disabled").map(([s])=>s.slice(7));t.push({role:"system",content:`${e}
16
- \u63D2\u4EF6\u80FD\u529B\u6E05\u5355\u5DF2\u66F4\u65B0\u3002\u5F53\u524D\u53EF\u7528\u63D2\u4EF6\uFF1A`+(o.length?o.map(s=>`plugin:${s}`).join("\u3001"):"\uFF08\u65E0\uFF09")+'\u3002\u9700\u8981\u67D0\u63D2\u4EF6\u7684\u5DE5\u5177\u65F6\uFF0C\u5148 expand_tools({ group:"plugin:\u63D2\u4EF6\u540D" }) \u5C55\u5F00\uFF0C\u518D\u7528 call_tool \u8C03\u7528\u3002'})}emitExposedToolsStatus(){this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(e=>e.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(e=>({name:e.exposedName,source:e.kind==="mcp"?`${e.serverName}.${e.toolName}`:`builtin.${e.toolName}`,description:e.description||""}))})}async injectForceMessage(){if(!this.forceMessagePending)return!1;this.forceMessagePending=!1;const e=this.state.mcpConnections.find(t=>t.tools.some(o=>o.toolName==="get_message"));if(!e)return p("[ACodeRuntime] injectForceMessage: no connection with get_message found"),!1;try{const t=await x(e.client.callTool({name:"get_message",arguments:{_aws_force_inject:!0}},void 0,{timeout:1e4}),1e4,"injectForceMessage get_message"),o=W(t);let s=[];try{const l=JSON.parse(o);Array.isArray(l?.directMessages)&&(s=l.directMessages.filter(u=>u?.force===!0))}catch{return!1}if(s.length===0)return!1;const i=JSON.stringify({directMessages:s,groupMessages:[]}),a=`forced_get_msg_${Date.now()}`,r=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:a,type:"function",function:{name:r,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:a,content:i}),p(`[ACodeRuntime] injectForceMessage: injected ${s.length} force message(s) into conversation`),!0}catch(t){return p(`[ACodeRuntime] injectForceMessage failed: ${t}`),!1}}async resetContext(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");this.contextVersion+=1,this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.state.conversation=le(this.initialConversation),this.turnPromptPushed=!1,this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t,o){const s=Date.now();if(p("[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"),p("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),p(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),p(`[ACodeRuntime] \u{1F522} Context version: ${t}`),p("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const i=this.activeTurnToken,a=e.trim();let r=!1;const l=o?.resume===!0&&this.turnPromptPushed;l||(this.turnPromptPushed=!1);try{let u;if(l)p("[ACodeRuntime] \u{1F501} resume turn: skip UserPromptSubmit hook (already ran in failed turn)"),u=[];else{p("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const C=Date.now();u=await this.hookBus.dispatch("UserPromptSubmit",{prompt:a});const w=Date.now()-C;p(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${w}ms, results: ${u.length}`)}if(this.isTurnSuperseded(t)){p("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const c=qe(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}),r=!0,p("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}p("[ACodeRuntime] \u{1F50D} Expanding command if any...");const m=this.state.commandRegistry.expand(a),h=m?.prompt.trim()||a,y=m?.command.allowedTools;if(m&&!l){p(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${m.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:m.command.name,arguments:m.argumentsText,sourcePath:m.command.sourcePath});const C=m.command.plugin;C&&p(`[ACodeRuntime] \u{1F4CB} Slash command belongs to plugin: ${C}`)}if(!this.state.provider.baseURL){p("[ACodeRuntime] \u26A0\uFE0F No provider baseURL configured, using fallback response");const C=is(h,this.state);this.emitAcodeEvent("assistant_delta",{text:C}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:h.length,outputTokens:C.length}}),r=!0,p("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}if(l){if(p("[ACodeRuntime] \u{1F501} resume turn: user message already in conversation, skipping push"),this.isTurnSuperseded(t)){p("[ACodeRuntime] \uFE0F Turn superseded before resume runModelTurn, aborting");return}}else{p("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const C=Ee(h);if(C.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.");p("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const w=await lt(C.content);if(this.isTurnSuperseded(t)){p("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}p("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:w}),this.turnPromptPushed=!0,p(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`)}p("[ACodeRuntime] Starting runModelTurn...");const _=Date.now(),d=await this.runModelTurn(y,t),f=Date.now()-_;if(p(`[ACodeRuntime] \u2705 runModelTurn completed in ${f}ms`),p(`[ACodeRuntime] \u{1F4DD} Result: text=${d.text?d.text.slice(0,80)+(d.text.length>80?"...":""):"(empty)"}, finishReason=${d.finishReason||"(none)"}`),this.isTurnSuperseded(t)){p("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}d.text&&!this.state.provider.stream&&(p("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:d.text})),p("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:d.usage??{inputTokens:h.length,outputTokens:d.totalOutputTextLength??d.text.length},...d.responseBody?{responseBody:d.responseBody}:{},...d.finishReason?{finishReason:d.finishReason}:{}}),oe(`turn_complete emitted: usage=${JSON.stringify(d.usage??{inputTokens:h.length,outputTokens:d.totalOutputTextLength??d.text.length})} (providerUsage=${d.usage?"real":"FALLBACK-text-length"}) textLength=${d.text.length} totalOutputTextLength=${d.totalOutputTextLength}`),p(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(d.usage?"":" (estimated, no provider usage)")),r=!0,this.turnPromptPushed=!1;const g=Date.now()-s;p("[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"),p(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${g}ms`),p("[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(u){const c=Date.now()-s;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${c}ms:`,u instanceof Error?u.message:String(u)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",u instanceof Error?u.stack:"(no stack)"),this.isTurnSuperseded(t)){p("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){p("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),r=!0;return}p("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:u instanceof Error?u.message:String(u)}),this.emitAcodeEvent("turn_complete",{failed:!0}),r=!0}finally{const u=Date.now()-s;p(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${u}ms`),p(`[ACodeRuntime] \u{1F50D} turnCompleted=${r}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===i&&(this.activeTurn=!1,this.abortRequested=!1),!r&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${u}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}),p("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(p(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.armAbortForceSettle()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,contextVersion:t})})}}async buildAllocatableToolList(){const e=this.state?.exposedTools??[],t=this.config.subAgentSuiteTools??[];let o=[];if(this.config.subAgentSuiteToolProvider)try{o=await this.config.subAgentSuiteToolProvider([])}catch{o=[]}return pe(e,pe(t,o))}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,s=this.config.workingDirectory,i=this.config;return{spawnSubAgent:async a=>{let r=this.config.subAgentSuiteTools;if(a.allowedTools&&a.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const u=await this.config.subAgentSuiteToolProvider(a.allowedTools);u.length>0&&(r=r?pe(r,u):u)}catch{}const l=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:a.subagentType,description:a.description,prompt:a.prompt,...a.allowedTools&&a.allowedTools.length>0?{allowedTools:a.allowedTools}:{},workingDirectory:s,parentConfig:{...i,sharedMcpConnections:this.state?.mcpConnections,...r&&r.length>0?{subAgentSuiteTools:r}:{}}});return await e.start(l),{subId:l}},listSubAgentToolCatalog:async()=>ze(await this.buildAllocatableToolList()),listSubAgents:async()=>{const a=e.listByParent(t),r=[],l=[];for(const u of a){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"?r.push(c):l.push(c)}return l.sort((u,c)=>(c.endedAt??0)-(u.endedAt??0)),{running:r,history:l}},getSubAgentStatus:async a=>{const r=e.getSubAgent(a);return r?{subId:r.subId,subagentType:r.subagentType,description:r.description,status:r.status,startedAt:r.startedAt,endedAt:r.endedAt,durationMs:r.durationMs,prompt:r.prompt,result:r.result,errorMessage:r.errorMessage,contextSnapshot:r.contextSnapshot}:null},awaitSubAgents:async(a,r)=>{const l=new Set;for(const u of a)this.pendingAwaitedSubIds.add(u),l.add(u);try{return await e.awaitCompletion(a,r)}finally{for(const u of l)this.pendingAwaitedSubIds.delete(u)}},abortSubAgent:a=>e.abort(a)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,s)=>{for(const i of o)this.pendingAwaitedSubIds.add(i);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const i of o)this.pendingAwaitedSubIds.delete(i)}}:null,awaitBgCommands:(o,s)=>{for(const i of o)this.pendingAwaitedBgTaskIds.add(i);try{return ae.awaitCompletion(e,o,s)}finally{for(const i of o)this.pendingAwaitedBgTaskIds.delete(i)}}}}submitQuestionAnswer(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}createToolPermissionController(){return{getLevel:e=>this.state.toolPermissionPolicy[e]??"allow",requestPermission:(e,t)=>this.requestToolPermission(e,t)}}requestToolPermission(e,t){const o=Ct();return new Promise(s=>{this.permissionWaiters.set(o,{capability:e,detail:t,resolve:s}),this.emitAcodeEvent("tool_permission_request",{requestId:o,capability:e,agentId:this.config.agentId,...t})})}submitToolPermissionDecision(e,t){const o=this.permissionWaiters.get(e);return o?(this.permissionWaiters.delete(e),o.resolve(t),!0):!1}rejectAllPermissionWaiters(e){if(this.permissionWaiters.size!==0){for(const[,t]of this.permissionWaiters)t.resolve(!1);this.permissionWaiters.clear(),D("tool-permission",`waiters rejected: ${e}`)}}setToolPermissionPolicy(e){this.state.toolPermissionPolicy={...this.state.toolPermissionPolicy,...e}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);p(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(s=>{p(`[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);p(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),ae.interruptAwaits(e,t)}detachCurrentToolExecution(e){const t=e?this.toolSettleSlots.get(e):this.pickSettleCandidate();return!t||!t.settlable||t.settled?!1:(t.settled=!0,t.resolveSettle?.(),p(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${t.toolName} (toolCallId=${t.toolCallId}) to background`),!0)}pickSettleCandidate(){let e=null;for(const t of this.toolSettleSlots.values())!t.settlable||t.settled||(e===null||t.order<e.order)&&(e=t);return e}beginToolSettle(e,t,o){const s=e.toolName==="Bash",i=++this.toolSettleSeq;let a;const r=s?new Promise(l=>{a=l}):void 0;return this.toolSettleSlots.set(o,{seq:i,toolName:e.toolName,toolCallId:o,settlable:s,settled:!1,resolveSettle:a??null,order:i}),{seq:i,signal:r}}clearToolSettle(e,t){if(t!==void 0){this.toolSettleSlots.get(t)?.seq===e&&this.toolSettleSlots.delete(t);return}for(const[o,s]of this.toolSettleSlots)if(s.seq===e){this.toolSettleSlots.delete(o);return}}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.armAbortForceSettle(),this.rejectAllQuestionWaiters("session terminated"),this.rejectAllPermissionWaiters("session terminated"),this.readFileStateTracker.clear(),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await se("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await se("ACode background commands shutdown",ae.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),se("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await se("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(),ye)try{O.promises.appendFile(nt,`[${new Date().toISOString()}] runtime stopped | ---
17
- `,"utf-8").catch(()=>{})}catch{}}discoverPluginCommandDirs(){const e=this.config.pluginsDir;if(!e)return[];let t;try{t=O.readdirSync(e)}catch{return[]}const o=[];for(const s of t){if(s.startsWith("."))continue;const i=F.join(e,s);let a;try{a=O.statSync(i)}catch{continue}if(!a.isDirectory())continue;const r=F.join(i,"commands");let l;try{O.existsSync(r)&&(l=O.statSync(r))}catch{l=void 0}l?.isDirectory()&&o.push(r)}return o}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",s,i,a,r="",l=0;this.lastIterationUsage=void 0,p(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const u=50;for(let c=0;c<u;c+=1){if(p(`[ACodeRuntime] \u{1F504} Iteration ${c+1} starting...`),this.isTurnSuperseded(t))return p(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${c+1}, aborting`),{text:"",totalOutputTextLength:r.length};await this.injectForceMessage();const m=Date.now(),h=await this.requestChatCompletion(e),y=Date.now()-m;if(p(`[ACodeRuntime] \u{1F916} AI request completed in ${y}ms, choices: ${h.choices?.length||0}`),this.isTurnSuperseded(t))return p(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${c+1}`),{text:"",totalOutputTextLength:r.length};if(this.state.terminated)throw p(`[ACodeRuntime] Runtime terminated at iteration ${c+1}`),new Error("ACode runtime was stopped during the active turn");const _=h.choices?.[0];i=JSON.stringify(h,null,2),a=typeof _?.finish_reason=="string"?_.finish_reason:void 0;const d=_?.message,f=typeof d?.content=="string"?d.content:"",g=Array.isArray(d?.tool_calls)?Tt(d.tool_calls):[];if(p(`[ACodeRuntime] AI response: content=${f?f.slice(0,100)+(f.length>100?"...":""):"(empty)"}, toolCalls=${g.length}, finishReason=${a||"(none)"}`),h.usage){const M=j(h.usage.prompt_tokens??h.usage.input_tokens),$=j(h.usage.completion_tokens??h.usage.output_tokens),S=M!==void 0,v=$!==void 0;if(oe(`provider usage parsed: raw=${JSON.stringify(h.usage)} input=${M} output=${$} hasInput=${S} hasOutput=${v} iteration=${c+1}`),S||v){const E=fo(h.usage,M),G=s?.outputTokens??r.length+f.length;this.state.accumulatedCacheHitTokens+=E?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=E?.cacheMissTokens??0,s={inputTokens:S?M:s?.inputTokens??0,outputTokens:v?$:G,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=s,this.emitAcodeEvent("iteration_usage",{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheHitTokens:s.cacheHitTokens,cacheMissTokens:s.cacheMissTokens}),l+=S?M:0,this.state.accumulatedInputTokens=S?M:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=v?$:this.state.accumulatedOutputTokens,oe(`finalUsage updated: ${JSON.stringify(s)} (cacheUsage=${JSON.stringify(E??null)})`),p(`[ACodeRuntime] \u{1F4B0} Token usage: input=${s.inputTokens}, output=${s.outputTokens} (turn accumulated cost: input=${l})`),p(E?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${E.cacheHitTokens}, miss=${E.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else oe(`provider response has NO usage field (fallback to text-length estimate), iteration=${c+1}`);if(this.state.conversation.push({role:"assistant",content:f||null,tool_calls:g.length>0?g:void 0}),f&&(o=f,r+=f,p(`[ACodeRuntime] \u2728 Captured assistant text: ${f.slice(0,80)}...`)),g.length===0)return p(`[ACodeRuntime] \u2705 No tool calls at iteration ${c+1}, completing turn`),{text:o,usage:s,responseBody:i,finishReason:a,totalOutputTextLength:r.length};const C=g.map(M=>M.function.name).join(", ");p(`[ACodeRuntime] \u{1F527} Executing ${g.length} tool(s) at iteration ${c+1}: ${C}`);const w=Date.now();await this.handleToolCalls(g,e,t);const b=Date.now()-w;if(p(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${b}ms at iteration ${c+1}`),this.isTurnSuperseded(t))return p(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${c+1}`),{text:"",totalOutputTextLength:r.length};p(`[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:i,finishReason:a||"safety_iteration_limit_reached",totalOutputTextLength:r.length}}async summarizeConversationWithLLM(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured for LLM summarization");const s={"Content-Type":"application/json"};t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`);const i={model:t.model,stream:!1,messages:[{role:"system",content:"You are a helpful AI assistant tasked with summarizing conversations. When asked to summarize, provide a detailed but concise summary of the conversation. Focus on information that would be helpful for continuing the conversation, especially what was in progress and what needs to happen next. Do not respond to any questions in the conversation, only output the summary."},{role:"user",content:`Below is an earlier conversation (${e.messageCount} messages) that needs to be summarized to free context space (current context limit: ${e.contextLimit} tokens).
14
+ `);this.initialConversation=ce(V),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:i,permissions:r,mcpConnections:a,ownsMcpConnections:l,exposedTools:M,commands:U,commandRegistry:re,conversation:ce(V),accumulatedInputTokens:0,accumulatedOutputTokens:0,accumulatedCacheHitTokens:0,accumulatedCacheMissTokens:0,toolPermissionPolicy:this.state.toolPermissionPolicy},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:i.model,commandCount:U.length});const K=Ae(i);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:i.model,commandCount:U.length,estimatedContextTokens:zo(X,M),contextLimit:K.contextLimit,maxOutput:K.maxOutput,...K.inputLimit!==void 0?{inputLimit:K.inputLimit}:{},compactionThreshold:K.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:a.length,builtInToolCount:d.length,toolCount:M.length,permissionMode:r.mode,allowedToolRules:r.allow,deniedToolRules:r.deny,tools:M.map(C=>({name:C.exposedName,source:C.kind==="mcp"?`${C.serverName}.${C.toolName}`:`builtin.${C.toolName}`,description:C.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(C=>({name:C.name,description:C.description,directory:C.directory})),skillGroups:o.map(C=>({dir:C.dir,exists:C.exists,skills:C.skills.map(R=>({name:R.name,description:R.description,directory:R.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:U.length,commandDirs:E,commands:U.map(C=>({name:C.name,description:C.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=z.join(this.config.workingDirectory,".acode","skills"),o=z.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,i=[],r=[];for(const u of[e,t,o]){if(!u)continue;const c=z.resolve(u);if(!s.has(c)){s.add(c),i.push(await lo(u));try{await D.promises.access(c),r.push(c)}catch{}}}const a=new Map;for(const u of i)for(const c of u.skills)a.set(c.name,c);return{skills:[...a.values()],skillGroups:i,watchedDirs:r}}startSkillWatchers(e){for(const t of e){let o=null;try{o=D.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=D.watch(t,()=>{this.scheduleSkillRefresh()})}catch{continue}}o&&(o.on("error",()=>{}),this.skillWatchers.push(o))}}scheduleSkillRefresh(){this.skillRefreshTimer&&clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=setTimeout(()=>{this.skillRefreshTimer=null,this.refreshSkills()},Z.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.instructionsDirty=!0,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}))}))}),f(`[skill-watch] Skills refreshed: ${e.length} skills (${e.map(o=>o.name).join(", ")||"none"})`,{sessionId:this.config.sessionId})}catch(e){console.error("[skill-watch] Failed to refresh skills:",e instanceof Error?e.message:e)}}stopSkillWatchers(){this.skillRefreshTimer&&(clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=null);for(const e of this.skillWatchers)try{e.close()}catch{}this.skillWatchers=[]}startCompactionDebugLog(){if(!Ce||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:i}=Ae(e);this.compactionDebugTimer=setInterval(()=>{try{const r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,a=j(this.state.conversation)+ie(this.state.exposedTools),l=Math.max(r,a),u=Y(this.state.conversation),c=this.state.started&&!this.state.terminated,d=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${u}KB`,`estimation=${a} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${r}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${i}`,`remainingToTrigger=${Math.max(0,i-r)}`,`isRunning=${c}`,`shouldCompact=${c?l>=i:!1}`,"---"].join(" | ");D.promises.appendFile(at,d+`
15
+ `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e,t){const o=this.contextVersion;f(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${o}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const s=this.submitQueue.then(()=>(f(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${o}`),this.executeSubmitGuarded(e,o,t)));return this.submitQueue=s.catch(()=>{f("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),f("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),s}executeSubmitGuarded(e,t,o){const s={};this.activeTurnToken=s;const i=this.executeSubmit(e,t,o),r=new Promise(a=>{this.forceSettleWaiters.set(s,a)});return i.finally(()=>{this.forceSettleWaiters.delete(s),this.activeTurnToken===s&&(this.abortForceSettleTimer&&(clearTimeout(this.abortForceSettleTimer),this.abortForceSettleTimer=null),this.activeTurnToken=null)}).catch(()=>{}),Promise.race([i,r])}armAbortForceSettle(){if(!this.activeTurn||!this.activeTurnToken)return;const e=this.activeTurnToken;this.abortForceSettleTimer&&clearTimeout(this.abortForceSettleTimer);const t=xs();this.abortForceSettleTimer=setTimeout(()=>{this.abortForceSettleTimer=null,this.activeTurn&&this.activeTurnToken===e&&this.forceSettleActiveTurn(`turn still unsettled ${t}ms after abort()`)},t),typeof this.abortForceSettleTimer.unref=="function"&&this.abortForceSettleTimer.unref()}forceSettleActiveTurn(e){const t=this.activeTurnToken;console.error(`[ACodeRuntime] \u{1F6A8} FORCE SETTLE: active turn ignored abort() (${e}). Force-settling to unblock submitQueue; late executeSubmit continuation will be superseded.`),this.contextVersion+=1,this.activeTurn=!1,this.abortRequested=!1,this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.emitAcodeEvent("error",{message:`ACode turn force-settled: ${e}`}),this.emitAcodeEvent("turn_complete",{failed:!0});const o=t?this.forceSettleWaiters.get(t):void 0;t&&this.forceSettleWaiters.delete(t),this.activeTurnToken=null,o?.()}notifyForceMessage(){this.forceMessagePending=!0,f("[ACodeRuntime] \u{1F514} Force message pending flag set")}exportConversation(){return ce(this.state.conversation)}async importTranscript(e){if(!Array.isArray(e)||e.length===0)return console.log("[HIBERNATE-REPLAY][runtime] \u7A7A\u8F93\u5165\uFF0C\u8DF3\u8FC7\u91CD\u653E"),0;if(!this.state.started)return console.log(`[HIBERNATE-REPLAY][runtime] \u4F1A\u8BDD\u672A start()\uFF0C\u8DF3\u8FC7\u91CD\u653E\uFF08${e.length}\u6761\u88AB\u4E22\u5F03\uFF09`),0;const t=e.filter(u=>u.role!=="system");if(t.length===0)return 0;const{contextLimit:o,maxOutput:s,inputLimit:i}=Ae(this.state.provider),r=oo(o,i),a=j(this.state.conversation)+j(t)+ie(this.state.exposedTools);let l=t;if(console.log(`[HIBERNATE-REPLAY][runtime] \u9884\u68C0: \u53EF\u91CD\u653E=${t.length}\u6761 projectedTokens=${a} hardWindow=${r} \u9700\u8981\u9884\u538B\u7F29=${a>=r}`),a>=r){f(`[ACodeRuntime] \u{1F4E6} importTranscript pre-compaction: projected=${a} >= hardWindow=${r}`);try{const u=await pe(t,o,s,{llmSummarizer:c=>this.summarizeConversationWithLLM(c)});if(u.strategy!=="none"){const c=j(t);f(`[ACodeRuntime] \u{1F4E6} importTranscript pre-compaction done: strategy=${u.strategy}, tokensBefore=${a}, tokensAfter=${c}`)}}catch(u){f(`[ACodeRuntime] \u26A0\uFE0F importTranscript pre-compaction failed, replaying raw: ${u instanceof Error?u.message:String(u)}`)}l=t}return this.state.conversation.push(...ce(l)),console.log(`[HIBERNATE-REPLAY][runtime] \u91CD\u653E\u5B8C\u6210: \u62FC\u5165=${l.length}\u6761 conversation\u603B\u957F=${this.state.conversation.length}\u6761 \u603Btoken\u4F30\u7B97=${j(this.state.conversation)+ie(this.state.exposedTools)}`),this.emitAcodeEvent("context_compaction",{action:"end",compactionId:`transcript-replay-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,sizeKB:Y(this.state.conversation),estimatedTokens:j(this.state.conversation)+ie(this.state.exposedTools),actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,replayedMessageCount:l.length,model:this.state.provider.model,trigger:"hibernation_replay"}),l.length}addBuiltInTools(e){if(!this.state||!this.exposedToolsInitialized||!Array.isArray(e))return 0;const t=new Set(this.state.exposedTools.map(s=>s.exposedName)),o=[];for(const s of e)To(s)&&(t.has(s.exposedName)||(t.add(s.exposedName),o.push(s)));return o.length===0?0:(this.state.exposedTools=[...this.state.exposedTools,...o],this.emitExposedToolsStatus(),o.length)}removeBuiltInToolsByPrefix(e){if(!this.state||!this.exposedToolsInitialized||!e)return 0;const t=this.state.exposedTools.length;this.state.exposedTools=this.state.exposedTools.filter(s=>!s.exposedName.startsWith(e));const o=t-this.state.exposedTools.length;return o>0&&this.emitExposedToolsStatus(),o}async addMcpServer(e,t){if(!this.state?.started||this.state.terminated)return{ok:!1,tools:0,error:"ACode runtime is not active"};const o=String(e??"").trim();if(!o)return{ok:!1,tools:0,error:"server name is required"};this.state.mcpConnections.find(u=>u.serverName===o)&&await this.removeMcpServer(o);const i=this.state.provider.mcpToolTimeoutMs;let r;const a=new Map;try{r=await this.connectMcpServers({[o]:t},i,a)}catch(u){return{ok:!1,tools:0,error:u instanceof Error?u.message:String(u)}}const l=r.find(u=>u.serverName===o);if(!l){const u=a.get(o);return{ok:!1,tools:0,error:u?`MCP server ${o} \u8FDE\u63A5\u5931\u8D25: ${u}`:`MCP server ${o} \u8FDE\u63A5\u5931\u8D25`}}return this.state.mcpConnections=[...this.state.mcpConnections,l],this.registerMcpCollapsedGroup(o,t,l),this.registerToolGroupsFromMcp(l),this.exposedToolsInitialized&&(this.state.exposedTools=[...this.state.exposedTools,...l.tools]),this.emitExposedToolsStatus(),{ok:!0,tools:l.tools.length,toolNames:l.tools.map(u=>u.exposedName)}}async removeMcpServer(e){const t=String(e??"").trim();if(!t)return{ok:!1,removed:!1};const o=this.state?.mcpConnections.find(s=>s.serverName===t);return o?(this.state.mcpConnections=this.state.mcpConnections.filter(s=>s.serverName!==t),this.state.exposedTools=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.serverName===t)),this.toolGroupManager?.unregister?.(Be(t)),this.mcpStderrBuffers.delete(t),await se(`ACode MCP server ${t} close`,o.transport.close(),s=>{this.emitAcodeEvent("error",{message:s})},this.state.provider.mcpToolTimeoutMs),this.emitExposedToolsStatus(),{ok:!0,removed:!0}):{ok:!0,removed:!1}}addPluginCommands(e){if(!this.state||e.length===0)return;this.state.commandRegistry.addCommands(e);const t=new Set(this.state.commands.map(o=>o.name));this.state.commands=[...this.state.commands,...e.filter(o=>!t.has(o.name))]}applyPluginGroups(e,t,o){const s=new Map;for(const r of e)s.set(Ht(r.name),{label:r.name,summary:r.description??"",state:r.enabled?"collapsed":"disabled"});let i=!1;for(const r of o.getAllGroups())Ue(r.key)&&(s.has(r.key)||(o.unregister(r.key),t.delete(r.key),i=!0));for(const[r,a]of s){const l=o.getRegistration(r);l?(l.label!==a.label||l.summary!==a.summary)&&o.register({...l,label:a.label,summary:a.summary,collapsible:!0,pluginName:a.label}):(o.register({key:r,label:a.label,summary:a.summary,collapsible:!0,pluginName:a.label}),i=!0);const u=t.get(r);u!==void 0&&u!==a.state&&(i=!0),t.set(r,a.state)}return i}async syncPluginGroups(){if(!this.config.pluginBridge||!this.toolGroupManager||!this.state)return;let e;try{e=await this.config.pluginBridge.listPlugins()}catch(o){f(`[ACodeRuntime] syncPluginGroups \u62C9\u53D6\u63D2\u4EF6\u6E05\u5355\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${o instanceof Error?o.message:String(o)}`);return}this.applyPluginGroups(e,this.pluginGroupStates,this.toolGroupManager)&&(this.injectPluginChangeNotice(),this.instructionsDirty=!0)}injectPluginChangeNotice(){const e="[\u63D2\u4EF6\u80FD\u529B\u53D8\u66F4]",t=this.state.conversation;for(let s=t.length-1;s>=0;s--){const i=t[s];i.role==="system"&&typeof i.content=="string"&&i.content.startsWith(e)&&t.splice(s,1)}const o=[...this.pluginGroupStates.entries()].filter(([,s])=>s!=="disabled").map(([s])=>s.slice(7));t.push({role:"system",content:`${e}
16
+ \u63D2\u4EF6\u80FD\u529B\u6E05\u5355\u5DF2\u66F4\u65B0\u3002\u5F53\u524D\u53EF\u7528\u63D2\u4EF6\uFF1A`+(o.length?o.map(s=>`plugin:${s}`).join("\u3001"):"\uFF08\u65E0\uFF09")+'\u3002\u9700\u8981\u67D0\u63D2\u4EF6\u7684\u5DE5\u5177\u65F6\uFF0C\u5148 expand_tools({ group:"plugin:\u63D2\u4EF6\u540D" }) \u5C55\u5F00\uFF0C\u518D\u7528 call_tool \u8C03\u7528\u3002'})}emitExposedToolsStatus(){this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(e=>e.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(e=>({name:e.exposedName,source:e.kind==="mcp"?`${e.serverName}.${e.toolName}`:`builtin.${e.toolName}`,description:e.description||""}))})}async injectForceMessage(){if(!this.forceMessagePending)return!1;this.forceMessagePending=!1;const e=this.state.mcpConnections.find(t=>t.tools.some(o=>o.toolName==="get_message"));if(!e)return f("[ACodeRuntime] injectForceMessage: no connection with get_message found"),!1;try{const t=await $(e.client.callTool({name:"get_message",arguments:{_aws_force_inject:!0}},void 0,{timeout:1e4}),1e4,"injectForceMessage get_message"),o=G(t);let s=[];try{const l=JSON.parse(o);Array.isArray(l?.directMessages)&&(s=l.directMessages.filter(u=>u?.force===!0))}catch{return!1}if(s.length===0)return!1;const i=JSON.stringify({directMessages:s,groupMessages:[]}),r=`forced_get_msg_${Date.now()}`,a=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:r,type:"function",function:{name:a,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:r,content:i}),f(`[ACodeRuntime] injectForceMessage: injected ${s.length} force message(s) into conversation`),!0}catch(t){return f(`[ACodeRuntime] injectForceMessage failed: ${t}`),!1}}async resetContext(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");this.contextVersion+=1,this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.state.conversation=ce(this.initialConversation),this.turnPromptPushed=!1,this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t,o){const s=Date.now();if(f("[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"),f("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),f(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),f(`[ACodeRuntime] \u{1F522} Context version: ${t}`),f("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const i=this.activeTurnToken,r=e.trim();let a=!1;const l=o?.resume===!0&&this.turnPromptPushed;l||(this.turnPromptPushed=!1);try{let u;if(l)f("[ACodeRuntime] \u{1F501} resume turn: skip UserPromptSubmit hook (already ran in failed turn)"),u=[];else{f("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const y=Date.now();u=await this.hookBus.dispatch("UserPromptSubmit",{prompt:r});const w=Date.now()-y;f(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${w}ms, results: ${u.length}`)}if(this.isTurnSuperseded(t)){f("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const c=je(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,f("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}f("[ACodeRuntime] \u{1F50D} Expanding command if any...");const d=this.state.commandRegistry.expand(r),p=d?.prompt.trim()||r,T=d?.command.allowedTools;if(d&&!l){f(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${d.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:d.command.name,arguments:d.argumentsText,sourcePath:d.command.sourcePath});const y=d.command.plugin;y&&f(`[ACodeRuntime] \u{1F4CB} Slash command belongs to plugin: ${y}`)}if(!this.state.provider.baseURL){f("[ACodeRuntime] \u26A0\uFE0F No provider baseURL configured, using fallback response");const y=ps(p,this.state);this.emitAcodeEvent("assistant_delta",{text:y}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:p.length,outputTokens:y.length},usageEstimated:!0}),a=!0,f("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}if(l){if(f("[ACodeRuntime] \u{1F501} resume turn: user message already in conversation, skipping push"),this.isTurnSuperseded(t)){f("[ACodeRuntime] \uFE0F Turn superseded before resume runModelTurn, aborting");return}}else{f("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const y=Re(p);if(y.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");f("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const w=await mt(y.content);if(this.isTurnSuperseded(t)){f("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}f("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:w}),this.turnPromptPushed=!0,f(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`)}f("[ACodeRuntime] Starting runModelTurn...");const _=Date.now(),m=await this.runModelTurn(T,t),h=Date.now()-_;if(f(`[ACodeRuntime] \u2705 runModelTurn completed in ${h}ms`),f(`[ACodeRuntime] \u{1F4DD} Result: text=${m.text?m.text.slice(0,80)+(m.text.length>80?"...":""):"(empty)"}, finishReason=${m.finishReason||"(none)"}`),this.isTurnSuperseded(t)){f("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}m.text&&!this.state.provider.stream&&(f("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:m.text})),f("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:m.usage??{inputTokens:p.length,outputTokens:m.totalOutputTextLength??m.text.length},usageEstimated:!m.usage,...m.responseBody?{responseBody:m.responseBody}:{},...m.finishReason?{finishReason:m.finishReason}:{}}),oe(`turn_complete emitted: usage=${JSON.stringify(m.usage??{inputTokens:p.length,outputTokens:m.totalOutputTextLength??m.text.length})} (providerUsage=${m.usage?"real":"FALLBACK-text-length"}) textLength=${m.text.length} totalOutputTextLength=${m.totalOutputTextLength}`),f(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(m.usage?"":" (estimated, no provider usage)")),a=!0,this.turnPromptPushed=!1;const g=Date.now()-s;f("[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"),f(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${g}ms`),f("[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(u){const c=Date.now()-s;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${c}ms:`,u instanceof Error?u.message:String(u)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",u instanceof Error?u.stack:"(no stack)"),this.isTurnSuperseded(t)){f("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){f("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),a=!0;return}f("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:u instanceof Error?u.message:String(u)}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0}finally{const u=Date.now()-s;f(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${u}ms`),f(`[ACodeRuntime] \u{1F50D} turnCompleted=${a}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurnToken===i&&(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: ${u}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}),f("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(f(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.rejectAllPermissionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop(),this.armAbortForceSettle()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,contextVersion:t})})}}async buildAllocatableToolList(){const e=this.state?.exposedTools??[],t=this.config.subAgentSuiteTools??[];let o=[];if(this.config.subAgentSuiteToolProvider)try{o=await this.config.subAgentSuiteToolProvider([])}catch{o=[]}return he(e,he(t,o))}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,s=this.config.workingDirectory,i=this.config;return{spawnSubAgent:async r=>{let a=this.config.subAgentSuiteTools;if(r.allowedTools&&r.allowedTools.length>0&&this.config.subAgentSuiteToolProvider)try{const u=await this.config.subAgentSuiteToolProvider(r.allowedTools);u.length>0&&(a=a?he(a,u):u)}catch{}const l=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:r.subagentType,description:r.description,prompt:r.prompt,...r.allowedTools&&r.allowedTools.length>0?{allowedTools:r.allowedTools}:{},workingDirectory:s,parentConfig:{...i,sharedMcpConnections:this.state?.mcpConnections,...a&&a.length>0?{subAgentSuiteTools:a}:{}}});return await e.start(l),{subId:l}},listSubAgentToolCatalog:async()=>Ge(await this.buildAllocatableToolList()),listSubAgents:async()=>{const r=e.listByParent(t),a=[],l=[];for(const u of r){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"?a.push(c):l.push(c)}return l.sort((u,c)=>(c.endedAt??0)-(u.endedAt??0)),{running:a,history:l}},getSubAgentStatus:async r=>{const a=e.getSubAgent(r);return a?{subId:a.subId,subagentType:a.subagentType,description:a.description,status:a.status,startedAt:a.startedAt,endedAt:a.endedAt,durationMs:a.durationMs,prompt:a.prompt,result:a.result,errorMessage:a.errorMessage,contextSnapshot:a.contextSnapshot}:null},awaitSubAgents:async(r,a)=>{const l=new Set;for(const u of r)this.pendingAwaitedSubIds.add(u),l.add(u);try{return await e.awaitCompletion(r,a)}finally{for(const u of l)this.pendingAwaitedSubIds.delete(u)}},abortSubAgent:r=>e.abort(r)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,s)=>{for(const i of o)this.pendingAwaitedSubIds.add(i);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const i of o)this.pendingAwaitedSubIds.delete(i)}}:null,awaitBgCommands:(o,s)=>{for(const i of o)this.pendingAwaitedBgTaskIds.add(i);try{return le.awaitCompletion(e,o,s)}finally{for(const i of o)this.pendingAwaitedBgTaskIds.delete(i)}}}}submitQuestionAnswer(e,t){return this.settleQuestionWaiter(e,{answers:t})}cancelQuestionAnswer(e,t){const o=String(t||"").trim();return this.settleQuestionWaiter(e,{cancelled:!0,...o?{reason:o}:{}})}settleQuestionWaiter(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}createToolPermissionController(){return{getLevel:e=>this.state.toolPermissionPolicy[e]??"allow",requestPermission:(e,t)=>this.requestToolPermission(e,t)}}requestToolPermission(e,t){const o=St();return new Promise(s=>{this.permissionWaiters.set(o,{capability:e,detail:t,resolve:s}),this.emitAcodeEvent("tool_permission_request",{requestId:o,capability:e,agentId:this.config.agentId,...t})})}submitToolPermissionDecision(e,t){const o=this.permissionWaiters.get(e);return o?(this.permissionWaiters.delete(e),o.resolve(t),!0):!1}rejectAllPermissionWaiters(e){if(this.permissionWaiters.size!==0){for(const[,t]of this.permissionWaiters)t.resolve(!1);this.permissionWaiters.clear(),B("tool-permission",`waiters rejected: ${e}`)}}setToolPermissionPolicy(e){this.state.toolPermissionPolicy={...this.state.toolPermissionPolicy,...e}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);f(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(s=>{f(`[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);f(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),le.interruptAwaits(e,t)}detachCurrentToolExecution(e){const t=e?this.toolSettleSlots.get(e):this.pickSettleCandidate();return!t||!t.settlable||t.settled?!1:(t.settled=!0,t.resolveSettle?.(),f(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${t.toolName} (toolCallId=${t.toolCallId}) to background`),!0)}pickSettleCandidate(){let e=null;for(const t of this.toolSettleSlots.values())!t.settlable||t.settled||(e===null||t.order<e.order)&&(e=t);return e}beginToolSettle(e,t,o){const s=e.toolName==="Bash",i=++this.toolSettleSeq;let r;const a=s?new Promise(l=>{r=l}):void 0;return this.toolSettleSlots.set(o,{seq:i,toolName:e.toolName,toolCallId:o,settlable:s,settled:!1,resolveSettle:r??null,order:i}),{seq:i,signal:a}}clearToolSettle(e,t){if(t!==void 0){this.toolSettleSlots.get(t)?.seq===e&&this.toolSettleSlots.delete(t);return}for(const[o,s]of this.toolSettleSlots)if(s.seq===e){this.toolSettleSlots.delete(o);return}}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.armAbortForceSettle(),this.rejectAllQuestionWaiters("session terminated"),this.rejectAllPermissionWaiters("session terminated"),this.readFileStateTracker.clear(),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await se("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await se("ACode background commands shutdown",le.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),se("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await se("ACode Stop hooks",this.hookBus.dispatch("Stop",{reason:"session_stop"}),t=>{this.emitAcodeEvent("error",{message:t})}),this.state.terminated=!0,this.sessionCompleteEmitted||(this.sessionCompleteEmitted=!0,this.emitAcodeEvent("session_complete",{exitCode:0})),this.stopCompactionDebugLog(),this.stopSkillWatchers(),Ce)try{D.promises.appendFile(at,`[${new Date().toISOString()}] runtime stopped | ---
17
+ `,"utf-8").catch(()=>{})}catch{}}discoverPluginCommandDirs(){const e=this.config.pluginsDir;if(!e)return[];let t;try{t=D.readdirSync(e)}catch{return[]}const o=[];for(const s of t){if(s.startsWith("."))continue;const i=z.join(e,s);let r;try{r=D.statSync(i)}catch{continue}if(!r.isDirectory())continue;const a=z.join(i,"commands");let l;try{D.existsSync(a)&&(l=D.statSync(a))}catch{l=void 0}l?.isDirectory()&&o.push(a)}return o}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",s,i,r,a="",l=0;this.lastIterationUsage=void 0,f(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const u=50;for(let c=0;c<u;c+=1){if(f(`[ACodeRuntime] \u{1F504} Iteration ${c+1} starting...`),this.isTurnSuperseded(t))return f(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${c+1}, aborting`),{text:"",totalOutputTextLength:a.length};await this.injectForceMessage();const d=Date.now(),p=await this.requestChatCompletion(e),T=Date.now()-d;if(f(`[ACodeRuntime] \u{1F916} AI request completed in ${T}ms, choices: ${p.choices?.length||0}`),this.isTurnSuperseded(t))return f(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${c+1}`),{text:"",totalOutputTextLength:a.length};if(this.state.terminated)throw f(`[ACodeRuntime] Runtime terminated at iteration ${c+1}`),new Error("ACode runtime was stopped during the active turn");const _=p.choices?.[0];i=JSON.stringify(p,null,2),r=typeof _?.finish_reason=="string"?_.finish_reason:void 0;const m=_?.message,h=typeof m?.content=="string"?m.content:"",g=yt(m),y=Array.isArray(m?.tool_calls)?wt(m.tool_calls):[];if(f(`[ACodeRuntime] AI response: content=${h?h.slice(0,100)+(h.length>100?"...":""):"(empty)"}, toolCalls=${y.length}, finishReason=${r||"(none)"}`),p.usage){const k=W(p.usage.prompt_tokens??p.usage.input_tokens),v=W(p.usage.completion_tokens??p.usage.output_tokens),M=k!==void 0,L=v!==void 0;if(oe(`provider usage parsed: raw=${JSON.stringify(p.usage)} input=${k} output=${v} hasInput=${M} hasOutput=${L} iteration=${c+1}`),M||L){const E=wo(p.usage,k),O=s?.outputTokens??a.length+h.length;this.state.accumulatedCacheHitTokens+=E?.cacheHitTokens??0,this.state.accumulatedCacheMissTokens+=E?.cacheMissTokens??0,s={inputTokens:M?k:s?.inputTokens??0,outputTokens:L?v:O,cacheHitTokens:this.state.accumulatedCacheHitTokens,cacheMissTokens:this.state.accumulatedCacheMissTokens},this.lastIterationUsage=s,this.emitAcodeEvent("iteration_usage",{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheHitTokens:s.cacheHitTokens,cacheMissTokens:s.cacheMissTokens}),l+=M?k:0,this.state.accumulatedInputTokens=M?k:this.state.accumulatedInputTokens,this.state.accumulatedOutputTokens=L?v:this.state.accumulatedOutputTokens,oe(`finalUsage updated: ${JSON.stringify(s)} (cacheUsage=${JSON.stringify(E??null)})`),f(`[ACodeRuntime] \u{1F4B0} Token usage: input=${s.inputTokens}, output=${s.outputTokens} (turn accumulated cost: input=${l})`),f(E?`[ACodeRuntime] \u{1F4B0} Cache usage (provider reported): hit=${E.cacheHitTokens}, miss=${E.cacheMissTokens}`:'[ACodeRuntime] \u{1F4B0} Cache usage: provider usage \u4E2D\u65E0\u7F13\u5B58\u5B57\u6BB5\uFF08\u9762\u677F\u5C06\u663E\u793A "-"\uFF09')}}else oe(`provider response has NO usage field (fallback to text-length estimate), iteration=${c+1}`);if(this.state.conversation.push({role:"assistant",content:h||null,tool_calls:y.length>0?y:void 0,...g?{reasoning:g.slice(0,$e)}:{}}),h&&(o=h,a+=h,f(`[ACodeRuntime] \u2728 Captured assistant text: ${h.slice(0,80)}...`)),y.length===0)return f(`[ACodeRuntime] \u2705 No tool calls at iteration ${c+1}, completing turn`),{text:o,usage:s,responseBody:i,finishReason:r,totalOutputTextLength:a.length};const w=y.map(k=>k.function.name).join(", ");f(`[ACodeRuntime] \u{1F527} Executing ${y.length} tool(s) at iteration ${c+1}: ${w}`);const A=Date.now();await this.handleToolCalls(y,e,t);const N=Date.now()-A;if(f(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${N}ms at iteration ${c+1}`),this.isTurnSuperseded(t))return f(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${c+1}`),{text:"",totalOutputTextLength:a.length};f(`[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:i,finishReason:r||"safety_iteration_limit_reached",totalOutputTextLength:a.length}}async summarizeConversationWithLLM(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured for LLM summarization");const s={"Content-Type":"application/json"};t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`);const i={model:t.model,stream:!0,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).
18
18
 
19
19
  --- Conversation Start ---
20
20
  ${e.conversationText}
21
21
  --- Conversation End ---
22
22
 
23
- `+Gt}]},a=new AbortController;this.abortController=a;let r=!1;try{return await x((async()=>{const l=await x(fetch(Ae(o),{method:"POST",headers:s,body:JSON.stringify(i),signal:a.signal}),t.requestTotalTimeoutMs,"ACode LLM summarization",()=>{r=!0,a.abort()});if(!l.ok){const m=await x(l.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{r=!0,a.abort()}),h=m.length>500?`${m.slice(0,500)}...(truncated, total ${m.length} chars)`:m;throw new Error(`ACode LLM summarization request failed: ${l.status} ${h}`)}const c=(await x(l.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{r=!0,a.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",()=>{a.abort()})}catch(l){throw l instanceof Error&&l.name==="AbortError"?r?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):l}finally{this.abortController===a&&(this.abortController=null)}}async requestChatCompletion(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured");const{contextLimit:s,maxOutput:i,inputLimit:a,threshold:r}=_e(t),l=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,u=z(this.state.conversation)+ue(this.state.exposedTools),c=Math.max(l,u),m=c>=r,h=this.compactRequested;this.compactRequested=null,p(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${l}, estimation=${u}, effectiveUsed=${c}, contextLimit=${s}, inputLimit=${a??"n/a"}, maxOutput=${i}, triggerThreshold=${r}, shouldCompact=${m}, manualCompact=${h}`),h?await this.runCompactionPass({contextLimit:s,maxOutput:i,effectiveUsed:c,trigger:"manual",force:!0,detectLabel:"\u624B\u52A8\u89E6\u53D1\u4E0A\u4E0B\u6587\u538B\u7F29",detectDetail:`\u7528\u6237\u8BF7\u6C42\u5148\u884C\u538B\u7F29\uFF0C\u5F53\u524D\u4F30\u7B97\u7528\u91CF: ${c} tokens`,plan:h}):m&&await this.runCompactionPass({contextLimit:s,maxOutput:i,effectiveUsed:c,trigger:l>=r?"actual_usage":"estimated_overflow",force:!1,detectLabel:"\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",detectDetail:`\u6709\u6548\u7528\u91CF: ${c} tokens, \u9608\u503C: ${r}, \u89E6\u53D1: ${l>=r?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`});const y=xo(s);let _=vo()||m;if(!_){const A=Be(this.state.conversation);A>ot?_=!0:A>y&&p(`[ACodeRuntime] \u23ED\uFE0F Byte-cap truncation skipped: body ${A}B > cap ${y}B, but effectiveUsed ${c} < threshold ${r} (aligned with frontend compression marker; rely on provider 413/overflow fallback)`)}let d=dt,f=0,g=0,C=0;if(_&&(f=Q(this.state.conversation),g=z(this.state.conversation),C=this.state.conversation.length,d=await as(this.state.conversation,y,s,i,A=>this.summarizeConversationWithLLM(A),()=>this.rebuildRuntimeResourcesMessage())),d.truncatedCount>0){const A=`compaction-bytes-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:A,sizeKB:f,estimatedTokens:g,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:C,model:t.model,trigger:"request_body_byte_limit"}),this.emitCompactionPhase(A,"byte_limit_detect","\u68C0\u6D4B\u5230\u8BF7\u6C42\u4F53\u8D85\u9650",`\u8BF7\u6C42\u4F53\u8D85\u8FC7 ${y} \u5B57\u8282\u4E0A\u9650\uFF0C\u5373\u5C06\u88C1\u526A\u5386\u53F2`,"request_body_byte_limit");const P=Q(this.state.conversation),Y=z(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:A,sizeBeforeKB:f,sizeAfterKB:P,freedKB:Math.round((f-P)*10)/10,strategy:d.strategy,freedTokens:d.freedTokens,tokensBefore:g,tokensAfter:Y,prunedToolMessages:d.prunedToolMessages,summarizedMessages:d.summarizedMessages,messageCountBefore:C,messageCountAfter:this.state.conversation.length,trigger:"request_body_byte_limit"}),this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${d.truncatedCount} older messages to fit within ${y} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const w=()=>{const A=rs(this.state.conversation);(A.orphanToolMessages>0||A.repairedToolCalls>0||A.downgradedAssistants>0||A.relocatedInterruptions>0||A.reorderedToolResults>0)&&(p(`[ACodeRuntime] \u{1FA79} sanitizeToolCallSequence: orphanTools=${A.orphanToolMessages} repairedCalls=${A.repairedToolCalls} downgradedAssistants=${A.downgradedAssistants} relocatedInterruptions=${A.relocatedInterruptions} reorderedToolResults=${A.reorderedToolResults}`),this.emitAcodeEvent("warning",{message:`\u68C0\u6D4B\u5230\u5DE5\u5177\u8C03\u7528\u5E8F\u5217\u4E0D\u5B8C\u6574\uFF0C\u5DF2\u81EA\u52A8\u4FEE\u590D\uFF08\u5B64\u513F\u5DE5\u5177\u7ED3\u679C ${A.orphanToolMessages} \u6761\u3001\u8865\u5360\u4F4D\u7ED3\u679C ${A.repairedToolCalls} \u4E2A\u3001\u964D\u7EA7 assistant \u6D88\u606F ${A.downgradedAssistants} \u6761\u3001\u56DE\u6B63\u7A7F\u63D2\u6D88\u606F ${A.relocatedInterruptions} \u6761\u3001\u56DE\u6B63\u9519\u5E8F\u7ED3\u679C ${A.reorderedToolResults} \u6761\uFF09\uFF0C\u907F\u514D provider 400 (tool_call_sequence_broken) \u6B7B\u5FAA\u73AF\u3002`}))};w();const b=this.state.exposedTools.filter(A=>this.toolGroupManager&&!this.toolGroupManager.shouldShowToLLMByName(A.exposedName)?!1:es(A,this.state.permissions,e)),M=()=>{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}),b.length>0&&(A.tools=ht(b),A.tool_choice="auto"),A},$="POST",S=ts(o),v=ys(t),E=Cs(v),G=A=>{const P=JSON.stringify(A,null,2);p(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${S}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:S,requestMethod:$,requestUrl:S,requestHeaders:E,stream:t.stream,messageCount:this.state.conversation.length,toolCount:b.length,lastUserMessagePreview:os(this.state.conversation),estimatedContextTokens:ve(P),...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),oe(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${b.length} estimatedContextTokens=${ve(P)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let L=M();G(L);const B=t.requestRetryCount===$e,ie=B?1/0:t.requestRetryCount+1;let ee=!1;for(let A=1;B||A<=ie;A+=1){this.state.terminated||(this.abortRequested=!1),A>1&&G(L);const P=new AbortController;this.abortController=P;let Y=!1;try{const U=await x((async()=>{const J=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,q=await x(fetch(Ae(o),{method:$,headers:v,body:JSON.stringify(L),signal:P.signal}),J,"ACode provider request",()=>{Y=!0,P.abort()});if(!q.ok){const T=await x(q.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{Y=!0,P.abort()}),I=T.length>500?`${T.slice(0,500)}...(truncated, total ${T.length} chars)`:T,re=Re(this.state.conversation,q.status,T)??"";throw new Error(`ACode provider request failed: ${q.status} ${I}${re}`)}const V=q.headers?.get?.("content-type")||"";if(t.stream&&V.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(q,t.requestStreamIdleTimeoutMs,P,t.requestFirstByteTimeoutMs);const X=await x(q.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{Y=!0,P.abort()});if(!k(X))return this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof X}); treating as empty response`}),{};const K=ft(X);if(K){const T=Re(this.state.conversation,q.status,K)??"";throw new Error(`ACode provider request failed: ${K}${T}`)}return X})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{P.abort()}),R=Zt({finishReason:U.choices?.[0]?.finish_reason,stopReason:U.choices?.[0]?.stop_reason});if(R.kind==="context_overflow"){if(!ee&&await this.compactForContextOverflow({contextLimit:s,trigger:"finish_reason_context_overflow",warningMessage:`ACode provider reported context overflow via ${R.source} (${R.marker}); summarized older messages and rebuilt the request instead of accepting the truncated payload`})>0){ee=!0,w(),L=M(),G(L),A-=1;continue}this.emitAcodeEvent("warning",{message:`ACode provider reported context overflow via ${R.source} (${R.marker}), but no further compaction was possible`})}return U}catch(U){let R;if(U instanceof Error&&U.name==="AbortError"?Y?R=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?R=new Error("ACode provider request aborted by user"):R=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):R=U instanceof Error?U:new Error(String(U)),!ee&&!this.abortRequested&&!this.state.terminated&&(we(U)||we(R))){if(await this.compactForContextOverflow({contextLimit:s,trigger:"provider_overflow_error",warningMessage:"ACode provider context limit exceeded; summarized older messages and rebuilt the request instead of retrying the same oversized payload"})===0)throw R;ee=!0,w(),L=M(),G(L),A-=1;continue}if(!((B||A<ie)&&!this.abortRequested&&!this.state.terminated&&cs(R)))throw R;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${A}${B?"":`/${ie}`} failed; retrying: ${R.message}`,nonFatal:!0});const q=Math.min(Ao,_o*Math.pow(2,A-1)),V=Math.random()*1e3;await Oo(q+V)}finally{this.abortController===P&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async compactForContextOverflow(e){const{contextLimit:t,trigger:o,warningMessage:s}=e,i=Q(this.state.conversation),a=z(this.state.conversation),r=this.state.conversation.length,l=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:l,sizeKB:i,estimatedTokens:a,messageCount:r,model:this.state.provider.model,trigger:o}),this.emitCompactionPhase(l,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${r}\u6761, \u5927\u5C0F: ${i}KB`),this.emitCompactionPhase(l,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const u=Vt(this.state.conversation,t);this.emitCompactionPhase(l,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${u.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${u.freedTokens} tokens`),this.emitCompactionPhase(l,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const c=await Ue(this.state.conversation,{llmSummarizer:d=>this.summarizeConversationWithLLM(d),contextLimit:t});this.emitCompactionPhase(l,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${c} \u6761\u6D88\u606F`);const m=Q(this.state.conversation),h=z(this.state.conversation),y=this.state.conversation.length,_=u.prunedCount+c;return this.emitAcodeEvent("context_compaction",{action:"end",compactionId:l,sizeBeforeKB:i,sizeAfterKB:m,freedKB:Math.round((i-m)*10)/10,tokensBefore:a,tokensAfter:h,messageCountBefore:r,messageCountAfter:y,strategy:c>0?"summarize":"prune",freedTokens:u.freedTokens,prunedToolMessages:u.prunedCount,summarizedMessages:c,trigger:o}),_===0?0:(this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,c>0&&await this.rebuildRuntimeResourcesMessage(),this.emitAcodeEvent("warning",{message:s}),_)}async rebuildRuntimeResourcesMessage(){const e=this.config.runtimeResourcesProvider;if(!e)return;const t=this.state.conversation;for(let l=t.length-1;l>=0;l--)Ht(t[l])&&t.splice(l,1);let o;try{o=await e()}catch(l){p(`[ACodeRuntime] runtime resources provider failed, snapshot skipped: ${me(l)}`);return}const s=typeof o=="string"?o.trim():"";if(!s)return;let i=0,a=-1;for(let l=0;l<t.length;l++){const u=t[l];if(u.role!=="system")break;Kt(u)&&(a=l),i=l+1}const r=a>=0?a+1:i;t.splice(r,0,{role:"system",content:`${Xt}
24
- ${s}`})}async readChatCompletionStream(e,t,o,s){if(!e.body)throw new Error("ACode provider stream response has no body");const i=e.body.getReader(),a=new TextDecoder,r=new Map;let l="",u="",c,m,h;const y=d=>{for(const f of bs(d)){if(f==="[DONE]")continue;const g=JSON.parse(f);if(!k(g))continue;const C=ft(g);if(C){o?.abort();const E=Re(this.state.conversation,200,C)??"";throw new Error(`ACode provider request failed: ${C}${E}`)}const w=g.usage;w&&(c=go(c,w),oe(`stream usage chunk received: ${JSON.stringify(w)} -> merged: ${JSON.stringify(c)}`));const b=g.choices?.[0];typeof b?.finish_reason=="string"&&b.finish_reason&&(m=b.finish_reason),typeof b?.stop_reason=="string"&&b.stop_reason&&(h=b.stop_reason);const M=b?.delta,$=ps(M);$&&this.emitAcodeEvent("thinking_delta",{text:$});const S=typeof M?.content=="string"?M.content:"";S&&(l+=S,this.emitAcodeEvent("assistant_delta",{text:S}));const v=Array.isArray(M?.tool_calls)?M.tool_calls:[];for(const E of v)ks(r,E)}};let _=!0;for(;;){const d=_&&s?s:t,{done:f,value:g}=await x(i.read(),d,_?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(_=!1,f)break;u+=a.decode(g,{stream:!0});const C=u.split(/\r?\n\r?\n/);u=C.pop()??"";for(const w of C)y(w)}return u+=a.decode(),u.trim()&&y(u),{choices:[{message:{content:l||null,tool_calls:Ss(r)},...m?{finish_reason:m}:{},...h?{stop_reason:h}:{}}],...c?{usage:c}:{}}}async handleToolCalls(e,t,o=this.contextVersion){p(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=e.filter(l=>!Se(l.function.name)),i=l=>!Se(l.function.name),a=this.toolConcurrencyEnabled&&s.length>1?{batchId:it(),toolCount:s.length}:void 0;a&&!this.isTurnSuperseded(o)&&this.emitToolBatchStart(a,s);const r=[];for(const l of e){if(this.isTurnSuperseded(o))break;r.push(await this.prepareToolCall(l,t,o,i(l)?a:void 0))}for(let l=r.length;l<e.length;l++){const u=e[l];r.push({toolCall:u,batchId:i(u)?a?.batchId:void 0,tool:void 0,arguments:{},mode:"blocking",scope:"unknown",access:"exclusive",claims:[],immediateError:void 0})}this.toolConcurrencyEnabled&&r.length>1?await this.executePreparedToolCallsConcurrently(r,o,a):await this.executePreparedToolCallsSerially(r,o),p(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}emitToolBatchStart(e,t){const o=t.map(s=>s.function.name);p(`[ACodeRuntime] \u{1F9E9} Tool batch ${e.batchId} started: tools=${e.toolCount} [${o.join(", ")}]`),this.emitAcodeEvent("mcp_status",{action:"tool_batch_start",server:"builtin",batchId:e.batchId,toolCount:e.toolCount,toolNames:o})}async executePreparedToolCallsConcurrently(e,t,o){const s=e.map(h=>({toolCallId:h.toolCall.id,toolName:h.tool?.exposedName??h.toolCall.function.name,mode:h.mode,scope:h.scope,claims:h.claims})),i=this.toolConcurrencyScheduler.schedule(s),a=o?.batchId??it(),r=new Je(a),l=new Set(e.filter(h=>!Se(h.toolCall.function.name)).map(h=>h.toolCall.id));for(const h of e)l.has(h.toolCall.id)&&r.register({toolCallId:h.toolCall.id,toolName:h.tool?.exposedName??h.toolCall.function.name,mode:h.mode,resourceKeys:(i.plans.get(h.toolCall.id)?.claims??[]).map(y=>y.key)});const u=new Map,c=new Map(e.map(h=>[h.toolCall.id,h]));for(const h of i.waves){if(this.isTurnSuperseded(t))break;const y=h.planIds.map(d=>c.get(d)).filter(d=>d!==void 0);if(y.length===0)continue;(await Promise.allSettled(y.map(d=>this.executeOnePreparedTool(d,r,t)))).forEach((d,f)=>{const g=y[f];u.set(g.toolCall.id,d.status==="fulfilled"?d.value:{toolCallId:g.toolCall.id,status:"failed",error:d.reason})})}if(await this.commitPreparedToolOutcomes(e,u,r,t),!o)return;const m=r.finalize();p(`[ACodeRuntime] \u26A1 Tool batch ${a}: tools=${m.toolCount} speedup=${m.speedup}x parallelism=${m.parallelism}x wall=${m.wallClockMs}ms contentions=${m.contentionCount} failures=${m.failureCount}`),this.emitAcodeEvent("mcp_status",{action:"tool_batch_metrics",server:"builtin",batchId:a,toolCount:m.toolCount,parallelism:m.parallelism,speedup:m.speedup,wallClockMs:m.wallClockMs,totalWaitMs:m.totalWaitMs,contentionCount:m.contentionCount,failureCount:m.failureCount,maxConcurrentObserved:m.maxConcurrentObserved,traces:m.traces.map(h=>({toolCallId:h.toolCallId,toolName:h.toolName,mode:h.mode,resourceKeys:h.resourceKeys,waitMs:h.waitDurationMs,runMs:h.executionDurationMs,status:h.status}))})}async executePreparedToolCallsSerially(e,t){const o=new Je(`toolbatch-serial-${Date.now().toString(36)}`),s=new Map;for(const i of e)o.register({toolCallId:i.toolCall.id,toolName:i.tool?.exposedName??i.toolCall.function.name,mode:i.mode,resourceKeys:i.claims.map(a=>a.key)}),!this.isTurnSuperseded(t)&&s.set(i.toolCall.id,await this.executeOnePreparedTool(i,o,t));await this.commitPreparedToolOutcomes(e,s,o,t)}async commitPreparedToolOutcomes(e,t,o,s){const i=[];for(const a of e){if(this.isTurnSuperseded(s)){this.commitSupersededToolResult(a),o.transition(a.toolCall.id,"superseded");continue}const r=t.get(a.toolCall.id);if(!r){await this.commitToolOutcome(a,{toolCallId:a.toolCall.id,status:"failed",error:a.immediateError??new Error("Tool was not executed")},s,i),o.transition(a.toolCall.id,"committed");continue}o.transition(a.toolCall.id,"committing"),await this.commitToolOutcome(a,r,s,i),o.transition(a.toolCall.id,"committed")}i.length>0&&this.state.conversation.push(...i)}async executeOnePreparedTool(e,t,o){if(e.immediateError!==void 0||!e.tool){t.transition(e.toolCall.id,"failed");const r=e.immediateError??new Error("Tool not found");return t.setError(e.toolCall.id,r instanceof Error?r.message:String(r)),{toolCallId:e.toolCall.id,status:"failed",error:r}}t.transition(e.toolCall.id,"waiting_resource");const s=await this.toolResourceLock.acquire(e.claims,e.access),i=this.resolveToolLimiter(e),a=i?await i.acquire():()=>{};try{if(this.isTurnSuperseded(o))return{toolCallId:e.toolCall.id,status:"superseded"};t.transition(e.toolCall.id,"running");const r=e.tool.kind==="builtin"?await this.runBuiltInToolCall(e,o):await this.runMcpToolCall(e,o);return t.transition(e.toolCall.id,r.status),r.error!==void 0&&t.setError(e.toolCall.id,r.error instanceof Error?r.error.message:String(r.error)),r}catch(r){const l=r instanceof Error?r.message:String(r);return p(`[ACodeRuntime] \u274C Tool ${e.tool.exposedName} threw unexpectedly: ${l}`),t.transition(e.toolCall.id,"failed"),t.setError(e.toolCall.id,l),{toolCallId:e.toolCall.id,status:"failed",error:r}}finally{a(),s()}}resolveToolLimiter(e){return e.tool?.kind!=="builtin"?null:e.mode==="read"?this.toolReadOnlyLimiter:e.tool.toolName==="Bash"?this.toolBashLimiter:null}async prepareToolCall(e,t,o,s){const i=e.function.name;let a=this.state.exposedTools.find(c=>c.exposedName===i);a||(a=this.state.exposedTools.find(c=>c.toolName===i),a&&p(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${i} -> ${a.exposedName}`));const r=ss(e.function.arguments),l={toolCall:e,batchId:s?.batchId,tool:a,arguments:r,mode:"exclusive",scope:"exact",access:"exclusive",claims:[],immediateError:void 0};if(a||await this.recoverHiddenMcpTool(i)&&(a=this.state.exposedTools.find(c=>c.exposedName===i)??this.state.exposedTools.find(c=>c.toolName===i),l.tool=a),!a){const c=this.state.exposedTools.map(h=>h.exposedName);console.error(`[ACodeRuntime] \u274C Tool not found: ${i}, available tools: ${c.join(", ")}`);const m=c.slice(0,40).join(", ")+(c.length>40?` \u2026(+${c.length-40} more)`:"");return l.immediateError=`ACode MCP tool not found: ${i}. Available tools: ${m}`,l}if(a.kind==="mcp"&&!this.state.mcpConnections.find(m=>m.serverName===a.serverName))return console.error(`[ACodeRuntime] \u274C MCP server not connected: ${a.serverName}, connected servers: ${this.state.mcpConnections.map(m=>m.serverName).join(", ")}`),l.immediateError=`ACode MCP server not connected: ${a.serverName}`,l;try{mt(a,this.state.permissions,t);const c=await this.hookBus.dispatch("PreToolUse",{source:a.kind==="mcp"?"mcp":"builtin",...a.kind==="mcp"?{serverName:a.serverName}:{},toolName:a.toolName,exposedName:a.exposedName,arguments:r}),m=qe(c);if(m)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${a.exposedName}: ${m.message}`),new Error(m.message||`ACode tool denied by hook: ${a.exposedName}`)}catch(c){return l.immediateError=c,l}if(this.isTurnSuperseded(o))return l;const u=this.resolveToolConcurrencyDeclaration(a,r);return l.mode=u.mode,l.scope=u.scope,l.access=u.access,l.claims=u.claims,this.emitAcodeEvent("mcp_status",{action:"call_tool",server:a.kind==="mcp"?a.serverName:"builtin",tool:a.toolName,exposedName:a.exposedName,toolUseId:e.id,arguments:r,argumentsPreview:ds(r),...l.batchId?{batchId:l.batchId}:{}}),l}resolveToolConcurrencyDeclaration(e,t){if(e.kind!=="builtin")return Me(e.toolName)==="poll_message"||ke(e.toolName)?{mode:"blocking",scope:"unknown",access:"exclusive",claims:[]}:{mode:"exclusive",scope:"unknown",access:"exclusive",claims:[]};const o=e.concurrencyMode,s=e.resourceScope??"exact";if(!o)return{mode:"exclusive",scope:s,access:"exclusive",claims:[]};if(o==="blocking")return{mode:"blocking",scope:s,access:"exclusive",claims:[]};const i=o;let a=[];if(e.resourceKeys)try{a=e.resourceKeys(t)??[]}catch(r){p(`[ACodeRuntime] \u26A0\uFE0F resourceKeys() threw for ${e.exposedName}, falling back to exclusive: ${r instanceof Error?r.message:String(r)}`),a=[]}return a.length===0&&s==="unknown"?{mode:"exclusive",scope:s,access:"exclusive",claims:[]}:{mode:o,scope:s,access:i,claims:a}}async runBuiltInToolCall(e,t){const o=e.tool;if(o.kind!=="builtin")return{toolCallId:e.toolCall.id,status:"failed",error:new Error("not builtin")};const s=e.arguments,i=ns(o,s,this.state.provider.mcpToolTimeoutMs);i<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${o.exposedName} has NO timeout (timeoutMs=${i})!`);const a=this.beginToolSettle(o,s,e.toolCall.id);try{const r=await x(o.execute(s,{onOutput:l=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:o.toolName,exposedName:o.exposedName,toolUseId:e.toolCall.id,stream:l.stream,text:l.text,sequence:l.sequence,cwd:l.cwd,commandLineCount:l.commandLineCount,...l.commandFilePath?{commandFilePath:l.commandFilePath}:{}})},toolCallId:e.toolCall.id,...a.signal?{settleSignal:a.signal}:{}}),i,`ACode built-in tool ${o.toolName}`);return{toolCallId:e.toolCall.id,status:"completed",resultText:W(r)}}catch(r){return this.classifyToolError(e,r)}finally{this.clearToolSettle(a.seq,e.toolCall.id)}}async runMcpToolCall(e,t){const o=e.tool;if(o.kind!=="mcp")return{toolCallId:e.toolCall.id,status:"failed",error:new Error("not mcp")};const s=this.state.mcpConnections.find(u=>u.serverName===o.serverName);if(!s)return{toolCallId:e.toolCall.id,status:"failed",error:new Error(`ACode MCP server not connected: ${o.serverName}`)};const i=e.arguments,a=Fe(o.toolName),r=ke(o.toolName),l=a?this.state.provider.mcpPollingToolTimeoutMs:r?0:this.state.provider.mcpToolTimeoutMs;try{const u=await this.withBlockingToolCallTracking(o.toolName,()=>a&&Me(o.toolName)==="poll_message"?this.callPollMessageWithSubAgentRace(s,o,i,l):this.callMcpToolWithTimeout(s,o,i,l,a));let c=W(u);return a&&(c=this.expandCommandsInPolledResult(c)),{toolCallId:e.toolCall.id,status:"completed",resultText:c}}catch(u){return this.classifyToolError(e,u)}}async withBlockingToolCallTracking(e,t){if(!Z.isLongBlockingMcpToolName(e))return await t();this.activeBlockingToolCalls+=1;try{return await t()}finally{this.activeBlockingToolCalls-=1}}classifyToolError(e,t){const s=(t instanceof Error?t.message:String(t)).includes("timed out after")?"timeout":t instanceof Error&&t.name==="AbortError"?"aborted":"failed";return{toolCallId:e.toolCall.id,status:s,error:t}}async commitToolOutcome(e,t,o,s=[]){const i=e.tool,a=i?.kind==="mcp"?i.serverName:"builtin",r=i?.toolName??e.toolCall.function.name;if(t.status==="completed"&&t.resultText!==void 0){const c=t.resultText;i&&await this.hookBus.dispatch("PostToolUse",{source:i.kind==="mcp"?"mcp":"builtin",...i.kind==="mcp"?{serverName:i.serverName}:{},toolName:i.toolName,exposedName:i.exposedName,result:c}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:a,tool:r,toolUseId:e.toolCall.id,result:c,...e.batchId?{batchId:e.batchId}:{}}),this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:c});const m=await this.appendSyntheticMultimodalUserMessage(c,e.toolCall.id,o);m&&s.push(m);return}if(t.status==="superseded"){this.commitSupersededToolResult(e);return}const l=t.error??new Error("Tool execution failed"),u=l instanceof Error?l.message:String(l);if(this.abortRequested||this.state.terminated){this.emitAcodeEvent("mcp_status",{action:"tool_result",server:a,tool:r,toolUseId:e.toolCall.id,result:`[aborted] ${u}`,failed:!0,aborted:!0,...e.batchId?{batchId:e.batchId}:{}}),this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:`[aborted] ${u}`});return}if(!i){this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:u}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:a,tool:r,toolUseId:e.toolCall.id,result:u,failed:!0,...e.batchId?{batchId:e.batchId}:{}});return}this.appendToolFailureResult(e.toolCall,i,l,e.batchId)}commitSupersededToolResult(e){const t=e.immediateError!==void 0?`[cancelled] ${e.immediateError instanceof Error?e.immediateError.message:String(e.immediateError)}`:"[cancelled] Tool execution was superseded by a newer turn.";this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:t}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:e.tool?.kind==="mcp"?e.tool.serverName:"builtin",tool:e.tool?.toolName??e.toolCall.function.name,toolUseId:e.toolCall.id,result:t,failed:!0,aborted:!0,...e.batchId?{batchId:e.batchId}:{}})}async executeSingleToolByName(e,t,o){let s=this.state.exposedTools.find(l=>l.exposedName===e);if(s||(s=this.state.exposedTools.find(l=>l.toolName===e)),!s)throw new Error(`Tool not found: ${e}`);if(s.kind==="builtin")return s.execute(t,{toolCallId:o?.toolCallId});const i=this.state.mcpConnections.find(l=>l.serverName===s.serverName);if(!i)throw new Error(`MCP server not found: ${s.serverName}`);const a=Fe(s.toolName),r=a?this.state.provider.mcpPollingToolTimeoutMs:ke(s.toolName)?0:this.state.provider.mcpToolTimeoutMs;if(a&&Me(s.toolName)==="poll_message"){const l=await this.withBlockingToolCallTracking(s.toolName,()=>this.callPollMessageWithSubAgentRace(i,s,t,r,{allowRepoll:!1}));return this.expandCommandsInPolledResult(W(l))}return this.withBlockingToolCallTracking(s.toolName,()=>this.callMcpToolWithTimeout(i,s,t,r,a))}async callMcpToolWithTimeout(e,t,o,s,i,a){const r=s>0?s:bo,u=!!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:u},void 0,{timeout:r,...a?{signal:a}:{}}),c.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(m){if(a?.aborted||!i||s>0||!us(m))throw m;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{c.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
23
+ `+Xt}]},r=new AbortController;this.abortController=r;let a=!1;try{return await $((async()=>{const l=await $(fetch(be(o),{method:"POST",headers:s,body:JSON.stringify(i),signal:r.signal}),t.requestTimeoutMs,"ACode LLM summarization",()=>{a=!0,r.abort()});if(!l.ok){const m=await $(l.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{a=!0,r.abort()}),h=m.length>500?`${m.slice(0,500)}...(truncated, total ${m.length} chars)`:m;throw new Error(`ACode LLM summarization request failed: ${l.status} ${h}`)}if(!l.body)throw new Error("ACode LLM summarization stream response has no body");const u=l.body.getReader(),c=new TextDecoder;let d="",p="";const T=m=>{for(const h of At(m)){if(h==="[DONE]")continue;let g;try{g=JSON.parse(h)}catch{continue}if(!S(g))continue;const y=Ie(g);if(y)throw new Error(`ACode LLM summarization failed: ${y}`);const w=g.choices?.[0]?.delta?.content,A=typeof w=="string"?w:"";A&&(d+=A,this.emitAcodeEvent("compaction_summary",{text:A}))}};for(;;){const{done:m,value:h}=await $(u.read(),t.requestTimeoutMs,"ACode LLM summarization idle",()=>r.abort());if(m)break;p+=c.decode(h,{stream:!0});const g=p.split(/\r?\n\r?\n/);p=g.pop()??"";for(const y of g)T(y)}p+=c.decode(),p.trim()&&T(p);const _=d;if(!_||_.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return _})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{r.abort()})}catch(l){throw l instanceof Error&&l.name==="AbortError"?a?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):l}finally{this.abortController===r&&(this.abortController=null)}}async requestChatCompletion(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured");this.instructionsDirty&&(this.instructionsDirty=!1,this.rebuildRuntimeInstructionsMessage());const{contextLimit:s,maxOutput:i,inputLimit:r,threshold:a}=Ae(t),l=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,u=j(this.state.conversation)+ie(this.state.exposedTools),c=Math.max(l,u),d=c>=a,p=this.compactRequested;this.compactRequested=!1,f(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${l}, estimation=${u}, effectiveUsed=${c}, contextLimit=${s}, inputLimit=${r??"n/a"}, maxOutput=${i}, triggerThreshold=${a}, shouldCompact=${d}, manualCompact=${p}`),p?await this.runCompactionPass({contextLimit:s,maxOutput:i,effectiveUsed:c,trigger:"manual",force:!0,detectLabel:"\u624B\u52A8\u89E6\u53D1\u4E0A\u4E0B\u6587\u538B\u7F29",detectDetail:`\u7528\u6237\u8BF7\u6C42\u5148\u884C\u538B\u7F29\uFF0C\u5F53\u524D\u4F30\u7B97\u7528\u91CF: ${c} tokens`}):d&&await this.runCompactionPass({contextLimit:s,maxOutput:i,effectiveUsed:c,trigger:l>=a?"actual_usage":"estimated_overflow",force:!1,detectLabel:"\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",detectDetail:`\u6709\u6548\u7528\u91CF: ${c} tokens, \u9608\u503C: ${a}, \u89E6\u53D1: ${l>=a?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`});const T=Do(s);let _=Lo()||d;if(!_){const b=Fe(this.state.conversation);b>it?_=!0:b>T&&f(`[ACodeRuntime] \u23ED\uFE0F Byte-cap truncation skipped: body ${b}B > cap ${T}B, but effectiveUsed ${c} < threshold ${a} (aligned with frontend compression marker; rely on provider 413/overflow fallback)`)}let m=ft,h=0,g=0,y=0;if(_&&(h=Y(this.state.conversation),g=j(this.state.conversation),y=this.state.conversation.length,m=await fs(this.state.conversation,T,s,i,b=>this.summarizeConversationWithLLM(b),()=>this.rebuildRuntimeResourcesMessage())),m.truncatedCount>0){const b=`compaction-bytes-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:b,sizeKB:h,estimatedTokens:g,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:y,model:t.model,trigger:"request_body_byte_limit"}),this.emitCompactionPhase(b,"byte_limit_detect","\u68C0\u6D4B\u5230\u8BF7\u6C42\u4F53\u8D85\u9650",`\u8BF7\u6C42\u4F53\u8D85\u8FC7 ${T} \u5B57\u8282\u4E0A\u9650\uFF0C\u5373\u5C06\u88C1\u526A\u5386\u53F2`,"request_body_byte_limit");const P=Y(this.state.conversation),Q=j(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:b,sizeBeforeKB:h,sizeAfterKB:P,freedKB:Math.round((h-P)*10)/10,strategy:m.strategy,freedTokens:m.freedTokens,tokensBefore:g,tokensAfter:Q,prunedToolMessages:m.prunedToolMessages,summarizedMessages:m.summarizedMessages,messageCountBefore:y,messageCountAfter:this.state.conversation.length,trigger:"request_body_byte_limit"}),this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${m.truncatedCount} older messages to fit within ${T} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const w=()=>{const b=hs(this.state.conversation);(b.orphanToolMessages>0||b.repairedToolCalls>0||b.downgradedAssistants>0||b.relocatedInterruptions>0||b.reorderedToolResults>0)&&(f(`[ACodeRuntime] \u{1FA79} sanitizeToolCallSequence: orphanTools=${b.orphanToolMessages} repairedCalls=${b.repairedToolCalls} downgradedAssistants=${b.downgradedAssistants} relocatedInterruptions=${b.relocatedInterruptions} reorderedToolResults=${b.reorderedToolResults}`),this.emitAcodeEvent("warning",{message:`\u68C0\u6D4B\u5230\u5DE5\u5177\u8C03\u7528\u5E8F\u5217\u4E0D\u5B8C\u6574\uFF0C\u5DF2\u81EA\u52A8\u4FEE\u590D\uFF08\u5B64\u513F\u5DE5\u5177\u7ED3\u679C ${b.orphanToolMessages} \u6761\u3001\u8865\u5360\u4F4D\u7ED3\u679C ${b.repairedToolCalls} \u4E2A\u3001\u964D\u7EA7 assistant \u6D88\u606F ${b.downgradedAssistants} \u6761\u3001\u56DE\u6B63\u7A7F\u63D2\u6D88\u606F ${b.relocatedInterruptions} \u6761\u3001\u56DE\u6B63\u9519\u5E8F\u7ED3\u679C ${b.reorderedToolResults} \u6761\uFF09\uFF0C\u907F\u514D provider 400 (tool_call_sequence_broken) \u6B7B\u5FAA\u73AF\u3002`}))};w();const A=this.state.exposedTools.filter(b=>this.toolGroupManager&&!this.toolGroupManager.shouldShowToLLMByName(b.exposedName)?!1:ls(b,this.state.permissions,e)),N=()=>{const b={model:t.model,messages:bo(this.state.conversation),stream:t.stream};return t.effort&&(b.reasoning_effort=t.effort),t.stream&&(b.stream_options={include_usage:!0}),A.length>0&&(b.tools=_t(A),b.tool_choice="auto"),b},k="POST",v=cs(o),M=ws(t),L=ks(M),E=b=>{const P=JSON.stringify(b,null,2);f(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${v}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:v,requestMethod:k,requestUrl:v,requestHeaders:L,stream:t.stream,messageCount:this.state.conversation.length,toolCount:A.length,lastUserMessagePreview:us(this.state.conversation),estimatedContextTokens:Ee(P),...this.lastIterationUsage?{lastUsage:this.lastIterationUsage}:{}}),oe(`ai_request emitted: model=${t.model} stream=${t.stream} messageCount=${this.state.conversation.length} toolCount=${A.length} estimatedContextTokens=${Ee(P)} lastUsage=${JSON.stringify(this.lastIterationUsage??null)}`)};let O=N();E(O);const U=t.requestRetryCount===ve,re=U?1/0:t.requestRetryCount+1;let ee=!1;for(let b=1;U||b<=re;b+=1){this.state.terminated||(this.abortRequested=!1),b>1&&E(O);const P=new AbortController;this.abortController=P;let Q=!1;try{const q=await $((async()=>{const J=t.stream?t.requestFirstByteTimeoutMs:t.requestTotalTimeoutMs,F=await $(fetch(be(o),{method:k,headers:M,body:JSON.stringify(O),signal:P.signal}),J,"ACode provider request",()=>{Q=!0,P.abort()});if(!F.ok){const C=await $(F.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{Q=!0,P.abort()}),R=C.length>500?`${C.slice(0,500)}...(truncated, total ${C.length} chars)`:C,ae=Ne(this.state.conversation,F.status,C)??"";throw new Error(`ACode provider request failed: ${F.status} ${R}${ae}`)}const V=F.headers?.get?.("content-type")||"";if(t.stream&&V.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(F,t.requestStreamIdleTimeoutMs,P,t.requestFirstByteTimeoutMs);const X=await $(F.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{Q=!0,P.abort()});if(!S(X))return this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof X}); treating as empty response`}),{};const K=Ie(X);if(K){const C=Ne(this.state.conversation,F.status,K)??"";throw new Error(`ACode provider request failed: ${K}${C}`)}return X})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{P.abort()}),x=ro({finishReason:q.choices?.[0]?.finish_reason,stopReason:q.choices?.[0]?.stop_reason});if(x.kind==="context_overflow"){if(!ee&&await this.compactForContextOverflow({contextLimit:s,trigger:"finish_reason_context_overflow",warningMessage:`ACode provider reported context overflow via ${x.source} (${x.marker}); summarized older messages and rebuilt the request instead of accepting the truncated payload`})>0){ee=!0,w(),O=N(),E(O),b-=1;continue}this.emitAcodeEvent("warning",{message:`ACode provider reported context overflow via ${x.source} (${x.marker}), but no further compaction was possible`})}return q}catch(q){let x;if(q instanceof Error&&q.name==="AbortError"?Q?x=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?x=new Error("ACode provider request aborted by user"):x=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):x=q instanceof Error?q:new Error(String(q)),!ee&&!this.abortRequested&&!this.state.terminated&&(we(q)||we(x))){if(await this.compactForContextOverflow({contextLimit:s,trigger:"provider_overflow_error",warningMessage:"ACode provider context limit exceeded; summarized older messages and rebuilt the request instead of retrying the same oversized payload"})===0)throw x;ee=!0,w(),O=N(),E(O),b-=1;continue}if(!((U||b<re)&&!this.abortRequested&&!this.state.terminated&&ys(x)))throw x;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${b}${U?"":`/${re}`} failed; retrying: ${x.message}`,nonFatal:!0});const F=Math.min(Eo,$o*Math.pow(2,b-1)),V=Math.random()*1e3;await jo(F+V)}finally{this.abortController===P&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async compactForContextOverflow(e){const{contextLimit:t,trigger:o,warningMessage:s}=e,i=Y(this.state.conversation),r=j(this.state.conversation),a=this.state.conversation.length,l=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:l,sizeKB:i,estimatedTokens:r,messageCount:a,model:this.state.provider.model,trigger:o}),this.emitCompactionPhase(l,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${a}\u6761, \u5927\u5C0F: ${i}KB`),this.emitCompactionPhase(l,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const u=so(this.state.conversation,t);this.emitCompactionPhase(l,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${u.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${u.freedTokens} tokens`),this.emitCompactionPhase(l,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const c=await ze(this.state.conversation,{llmSummarizer:m=>this.summarizeConversationWithLLM(m),contextLimit:t});this.emitCompactionPhase(l,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${c} \u6761\u6D88\u606F`);const d=Y(this.state.conversation),p=j(this.state.conversation),T=this.state.conversation.length,_=u.prunedCount+c;return this.emitAcodeEvent("context_compaction",{action:"end",compactionId:l,sizeBeforeKB:i,sizeAfterKB:d,freedKB:Math.round((i-d)*10)/10,tokensBefore:r,tokensAfter:p,messageCountBefore:a,messageCountAfter:T,strategy:c>0?"summarize":"prune",freedTokens:u.freedTokens,prunedToolMessages:u.prunedCount,summarizedMessages:c,trigger:o}),_===0?0:(this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,c>0&&await this.rebuildRuntimeResourcesMessage(),this.rebuildRuntimeInstructionsMessage(),this.emitAcodeEvent("warning",{message:s}),_)}async rebuildRuntimeResourcesMessage(){const e=this.config.runtimeResourcesProvider;if(!e)return;const t=this.state.conversation;for(let l=t.length-1;l>=0;l--)eo(t[l])&&t.splice(l,1);let o;try{o=await e()}catch(l){f(`[ACodeRuntime] runtime resources provider failed, snapshot skipped: ${me(l)}`);return}const s=typeof o=="string"?o.trim():"";if(!s)return;let i=0,r=-1;for(let l=0;l<t.length;l++){const u=t[l];if(u.role!=="system")break;Zt(u)&&(r=l),i=l+1}const a=r>=0?r+1:i;t.splice(a,0,{role:"system",content:`${no}
24
+ ${s}`})}rebuildRuntimeInstructionsMessage(){if(!this.state?.started||this.state.terminated)return;const e=this.state.conversation;for(let i=e.length-1;i>=0;i--)to(e[i])&&e.splice(i,1);const t=this.buildRuntimeInstructionsContent();if(!t)return;const o=(()=>{for(let i=0;i<e.length;i++)if(e[i].role!=="system")return i;return e.length})();let s=o;for(let i=0;i<o;i++){const r=e[i];if(r.role==="system"&&typeof r.content=="string"&&r.content.startsWith("[Runtime Environment]")){s=i;break}}e.splice(s,0,{role:"system",content:t})}buildRuntimeInstructionsContent(){const e=this.state.provider,t=this.state.skills??[],o=this.state.commands??[],s=Tt(t),i=Ct(o),r=this.toolGroupManager?.buildCapabilityPrompt()??"",a=this.config.pluginBridge?["","## \u63D2\u4EF6\u7CFB\u7EDF","\u5DF2\u5B89\u88C5\u63D2\u4EF6\u4EE5\u6536\u7EB3\u7EC4\u5F62\u5F0F\u5217\u51FA\uFF08\u89C1\u4E0A\u65B9\u300C\u53EF\u7528\u80FD\u529B\u300D\u4E2D\u7684 plugin:{\u63D2\u4EF6\u540D} \u6761\u76EE\uFF09\u3002",'\u9700\u8981\u67D0\u63D2\u4EF6\u7684\u5DE5\u5177\u65F6\uFF0C\u5148 expand_tools({ group: "plugin:\u63D2\u4EF6\u540D" }) \u5C55\u5F00\uFF1B','\u5DE5\u5177\u5B9A\u4E49\uFF08\u542B\u53C2\u6570 schema\uFF09\u968F\u5C55\u5F00\u7ED3\u679C\u8FD4\u56DE\uFF0C\u518D\u7528 call_tool({ name: "\u63D2\u4EF6\u540D.\u5DE5\u5177\u540D", arguments: {...} }) \u8C03\u7528\u3002'].join(`
25
+ `):"";return[De,e.systemPrompt,s,i,r+a].map(l=>l?.trim()).filter(l=>!!l).join(`
26
+
27
+ `)}async readChatCompletionStream(e,t,o,s){if(!e.body)throw new Error("ACode provider stream response has no body");const i=e.body.getReader(),r=new TextDecoder,a=new Map;let l="",u="",c="",d,p,T;const _=h=>{for(const g of At(h)){if(g==="[DONE]")continue;const y=JSON.parse(g);if(!S(y))continue;const w=Ie(y);if(w){o?.abort();const E=Ne(this.state.conversation,200,w)??"";throw new Error(`ACode provider request failed: ${w}${E}`)}const A=y.usage;A&&(d=ko(d,A),oe(`stream usage chunk received: ${JSON.stringify(A)} -> merged: ${JSON.stringify(d)}`));const N=y.choices?.[0];typeof N?.finish_reason=="string"&&N.finish_reason&&(p=N.finish_reason),typeof N?.stop_reason=="string"&&N.stop_reason&&(T=N.stop_reason);const k=N?.delta,v=yt(k);v&&(u.length<$e&&(u+=v.slice(0,$e-u.length)),this.emitAcodeEvent("thinking_delta",{text:v}));const M=typeof k?.content=="string"?k.content:"";M&&(l+=M,this.emitAcodeEvent("assistant_delta",{text:M}));const L=Array.isArray(k?.tool_calls)?k.tool_calls:[];for(const E of L)$s(a,E)}};let m=!0;for(;;){const h=m&&s?s:t,{done:g,value:y}=await $(i.read(),h,m?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(m=!1,g)break;c+=r.decode(y,{stream:!0});const w=c.split(/\r?\n\r?\n/);c=w.pop()??"";for(const A of w)_(A)}return c+=r.decode(),c.trim()&&_(c),{choices:[{message:{content:l||null,tool_calls:Es(a),...u?{reasoning:u}:{}},...p?{finish_reason:p}:{},...T?{stop_reason:T}:{}}],...d?{usage:d}:{}}}async handleToolCalls(e,t,o=this.contextVersion){f(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=e.filter(l=>!Se(l.function.name)),i=l=>!Se(l.function.name),r=this.toolConcurrencyEnabled&&s.length>1?{batchId:lt(),toolCount:s.length}:void 0;r&&!this.isTurnSuperseded(o)&&this.emitToolBatchStart(r,s);const a=[];for(const l of e){if(this.isTurnSuperseded(o))break;a.push(await this.prepareToolCall(l,t,o,i(l)?r:void 0))}for(let l=a.length;l<e.length;l++){const u=e[l];a.push({toolCall:u,batchId:i(u)?r?.batchId:void 0,tool:void 0,arguments:{},mode:"blocking",scope:"unknown",access:"exclusive",claims:[],immediateError:void 0})}this.toolConcurrencyEnabled&&a.length>1?await this.executePreparedToolCallsConcurrently(a,o,r):await this.executePreparedToolCallsSerially(a,o),f(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}emitToolBatchStart(e,t){const o=t.map(s=>s.function.name);f(`[ACodeRuntime] \u{1F9E9} Tool batch ${e.batchId} started: tools=${e.toolCount} [${o.join(", ")}]`),this.emitAcodeEvent("mcp_status",{action:"tool_batch_start",server:"builtin",batchId:e.batchId,toolCount:e.toolCount,toolNames:o})}async executePreparedToolCallsConcurrently(e,t,o){const s=e.map(p=>({toolCallId:p.toolCall.id,toolName:p.tool?.exposedName??p.toolCall.function.name,mode:p.mode,scope:p.scope,claims:p.claims})),i=this.toolConcurrencyScheduler.schedule(s),r=o?.batchId??lt(),a=new Qe(r),l=new Set(e.filter(p=>!Se(p.toolCall.function.name)).map(p=>p.toolCall.id));for(const p of e)l.has(p.toolCall.id)&&a.register({toolCallId:p.toolCall.id,toolName:p.tool?.exposedName??p.toolCall.function.name,mode:p.mode,resourceKeys:(i.plans.get(p.toolCall.id)?.claims??[]).map(T=>T.key)});const u=new Map,c=new Map(e.map(p=>[p.toolCall.id,p]));for(const p of i.waves){if(this.isTurnSuperseded(t))break;const T=p.planIds.map(m=>c.get(m)).filter(m=>m!==void 0);if(T.length===0)continue;(await Promise.allSettled(T.map(m=>this.executeOnePreparedTool(m,a,t)))).forEach((m,h)=>{const g=T[h];u.set(g.toolCall.id,m.status==="fulfilled"?m.value:{toolCallId:g.toolCall.id,status:"failed",error:m.reason})})}if(await this.commitPreparedToolOutcomes(e,u,a,t),!o)return;const d=a.finalize();f(`[ACodeRuntime] \u26A1 Tool batch ${r}: tools=${d.toolCount} speedup=${d.speedup}x parallelism=${d.parallelism}x wall=${d.wallClockMs}ms contentions=${d.contentionCount} failures=${d.failureCount}`),this.emitAcodeEvent("mcp_status",{action:"tool_batch_metrics",server:"builtin",batchId:r,toolCount:d.toolCount,parallelism:d.parallelism,speedup:d.speedup,wallClockMs:d.wallClockMs,totalWaitMs:d.totalWaitMs,contentionCount:d.contentionCount,failureCount:d.failureCount,maxConcurrentObserved:d.maxConcurrentObserved,traces:d.traces.map(p=>({toolCallId:p.toolCallId,toolName:p.toolName,mode:p.mode,resourceKeys:p.resourceKeys,waitMs:p.waitDurationMs,runMs:p.executionDurationMs,status:p.status}))})}async executePreparedToolCallsSerially(e,t){const o=new Qe(`toolbatch-serial-${Date.now().toString(36)}`),s=new Map;for(const i of e)o.register({toolCallId:i.toolCall.id,toolName:i.tool?.exposedName??i.toolCall.function.name,mode:i.mode,resourceKeys:i.claims.map(r=>r.key)}),!this.isTurnSuperseded(t)&&s.set(i.toolCall.id,await this.executeOnePreparedTool(i,o,t));await this.commitPreparedToolOutcomes(e,s,o,t)}async commitPreparedToolOutcomes(e,t,o,s){const i=[];for(const r of e){if(this.isTurnSuperseded(s)){this.commitSupersededToolResult(r),o.transition(r.toolCall.id,"superseded");continue}const a=t.get(r.toolCall.id);if(!a){await this.commitToolOutcome(r,{toolCallId:r.toolCall.id,status:"failed",error:r.immediateError??new Error("Tool was not executed")},s,i),o.transition(r.toolCall.id,"committed");continue}o.transition(r.toolCall.id,"committing"),await this.commitToolOutcome(r,a,s,i),o.transition(r.toolCall.id,"committed")}i.length>0&&this.state.conversation.push(...i)}async executeOnePreparedTool(e,t,o){if(e.immediateError!==void 0||!e.tool){t.transition(e.toolCall.id,"failed");const a=e.immediateError??new Error("Tool not found");return t.setError(e.toolCall.id,a instanceof Error?a.message:String(a)),{toolCallId:e.toolCall.id,status:"failed",error:a}}t.transition(e.toolCall.id,"waiting_resource");const s=await this.toolResourceLock.acquire(e.claims,e.access),i=this.resolveToolLimiter(e),r=i?await i.acquire():()=>{};try{if(this.isTurnSuperseded(o))return{toolCallId:e.toolCall.id,status:"superseded"};t.transition(e.toolCall.id,"running");const a=e.tool.kind==="builtin"?await this.runBuiltInToolCall(e,o):await this.runMcpToolCall(e,o);return t.transition(e.toolCall.id,a.status),a.error!==void 0&&t.setError(e.toolCall.id,a.error instanceof Error?a.error.message:String(a.error)),a}catch(a){const l=a instanceof Error?a.message:String(a);return f(`[ACodeRuntime] \u274C Tool ${e.tool.exposedName} threw unexpectedly: ${l}`),t.transition(e.toolCall.id,"failed"),t.setError(e.toolCall.id,l),{toolCallId:e.toolCall.id,status:"failed",error:a}}finally{r(),s()}}resolveToolLimiter(e){return e.tool?.kind!=="builtin"?null:e.mode==="read"?this.toolReadOnlyLimiter:e.tool.toolName==="Bash"?this.toolBashLimiter:null}async prepareToolCall(e,t,o,s){const i=e.function.name;let r=this.state.exposedTools.find(c=>c.exposedName===i);r||(r=this.state.exposedTools.find(c=>c.toolName===i),r&&f(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${i} -> ${r.exposedName}`));const a=ms(e.function.arguments),l={toolCall:e,batchId:s?.batchId,tool:r,arguments:a,mode:"exclusive",scope:"exact",access:"exclusive",claims:[],immediateError:void 0};if(r||await this.recoverHiddenMcpTool(i)&&(r=this.state.exposedTools.find(c=>c.exposedName===i)??this.state.exposedTools.find(c=>c.toolName===i),l.tool=r),!r){const c=this.state.exposedTools.map(p=>p.exposedName);console.error(`[ACodeRuntime] \u274C Tool not found: ${i}, available tools: ${c.join(", ")}`);const d=c.slice(0,40).join(", ")+(c.length>40?` \u2026(+${c.length-40} more)`:"");return l.immediateError=`ACode MCP tool not found: ${i}. Available tools: ${d}`,l}if(r.kind==="mcp"&&!this.state.mcpConnections.find(d=>d.serverName===r.serverName))return console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(d=>d.serverName).join(", ")}`),l.immediateError=`ACode MCP server not connected: ${r.serverName}`,l;try{ht(r,this.state.permissions,t);const c=await this.hookBus.dispatch("PreToolUse",{source:r.kind==="mcp"?"mcp":"builtin",...r.kind==="mcp"?{serverName:r.serverName}:{},toolName:r.toolName,exposedName:r.exposedName,arguments:a}),d=je(c);if(d)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${d.message}`),new Error(d.message||`ACode tool denied by hook: ${r.exposedName}`)}catch(c){return l.immediateError=c,l}if(this.isTurnSuperseded(o))return l;const u=this.resolveToolConcurrencyDeclaration(r,a);return l.mode=u.mode,l.scope=u.scope,l.access=u.access,l.claims=u.claims,this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:e.id,arguments:a,argumentsPreview:_s(a),...l.batchId?{batchId:l.batchId}:{}}),l}resolveToolConcurrencyDeclaration(e,t){if(e.kind!=="builtin")return Me(e.toolName)==="poll_message"||ke(e.toolName)?{mode:"blocking",scope:"unknown",access:"exclusive",claims:[]}:{mode:"exclusive",scope:"unknown",access:"exclusive",claims:[]};const o=e.concurrencyMode,s=e.resourceScope??"exact";if(!o)return{mode:"exclusive",scope:s,access:"exclusive",claims:[]};if(o==="blocking")return{mode:"blocking",scope:s,access:"exclusive",claims:[]};const i=o;let r=[];if(e.resourceKeys)try{r=e.resourceKeys(t)??[]}catch(a){f(`[ACodeRuntime] \u26A0\uFE0F resourceKeys() threw for ${e.exposedName}, falling back to exclusive: ${a instanceof Error?a.message:String(a)}`),r=[]}return r.length===0&&s==="unknown"?{mode:"exclusive",scope:s,access:"exclusive",claims:[]}:{mode:o,scope:s,access:i,claims:r}}async runBuiltInToolCall(e,t){const o=e.tool;if(o.kind!=="builtin")return{toolCallId:e.toolCall.id,status:"failed",error:new Error("not builtin")};const s=e.arguments,i=ds(o,s,this.state.provider.mcpToolTimeoutMs);i<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${o.exposedName} has NO timeout (timeoutMs=${i})!`);const r=this.beginToolSettle(o,s,e.toolCall.id);try{const a=await $(o.execute(s,{onOutput:l=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:o.toolName,exposedName:o.exposedName,toolUseId:e.toolCall.id,stream:l.stream,text:l.text,sequence:l.sequence,cwd:l.cwd,commandLineCount:l.commandLineCount,...l.commandFilePath?{commandFilePath:l.commandFilePath}:{}})},toolCallId:e.toolCall.id,...r.signal?{settleSignal:r.signal}:{}}),i,`ACode built-in tool ${o.toolName}`);return{toolCallId:e.toolCall.id,status:"completed",resultText:G(a)}}catch(a){return this.classifyToolError(e,a)}finally{this.clearToolSettle(r.seq,e.toolCall.id)}}async runMcpToolCall(e,t){const o=e.tool;if(o.kind!=="mcp")return{toolCallId:e.toolCall.id,status:"failed",error:new Error("not mcp")};const s=this.state.mcpConnections.find(u=>u.serverName===o.serverName);if(!s)return{toolCallId:e.toolCall.id,status:"failed",error:new Error(`ACode MCP server not connected: ${o.serverName}`)};const i=e.arguments,r=We(o.toolName),a=ke(o.toolName),l=r?this.state.provider.mcpPollingToolTimeoutMs:a?0:this.state.provider.mcpToolTimeoutMs;try{const u=await this.withBlockingToolCallTracking(o.toolName,()=>r&&Me(o.toolName)==="poll_message"?this.callPollMessageWithSubAgentRace(s,o,i,l):this.callMcpToolWithTimeout(s,o,i,l,r));let c=G(u);return r&&(c=this.expandCommandsInPolledResult(c)),{toolCallId:e.toolCall.id,status:"completed",resultText:c}}catch(u){return this.classifyToolError(e,u)}}async withBlockingToolCallTracking(e,t){if(!Z.isLongBlockingMcpToolName(e))return await t();this.activeBlockingToolCalls+=1;try{return await t()}finally{this.activeBlockingToolCalls-=1}}classifyToolError(e,t){const s=(t instanceof Error?t.message:String(t)).includes("timed out after")?"timeout":t instanceof Error&&t.name==="AbortError"?"aborted":"failed";return{toolCallId:e.toolCall.id,status:s,error:t}}async commitToolOutcome(e,t,o,s=[]){const i=e.tool,r=i?.kind==="mcp"?i.serverName:"builtin",a=i?.toolName??e.toolCall.function.name;if(t.status==="completed"&&t.resultText!==void 0){const c=t.resultText;i&&await this.hookBus.dispatch("PostToolUse",{source:i.kind==="mcp"?"mcp":"builtin",...i.kind==="mcp"?{serverName:i.serverName}:{},toolName:i.toolName,exposedName:i.exposedName,result:c}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r,tool:a,toolUseId:e.toolCall.id,result:c,...e.batchId?{batchId:e.batchId}:{}}),this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:c});const d=await this.appendSyntheticMultimodalUserMessage(c,e.toolCall.id,o);d&&s.push(d);return}if(t.status==="superseded"){this.commitSupersededToolResult(e);return}const l=t.error??new Error("Tool execution failed"),u=l instanceof Error?l.message:String(l);if(this.abortRequested||this.state.terminated){this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r,tool:a,toolUseId:e.toolCall.id,result:`[aborted] ${u}`,failed:!0,aborted:!0,...e.batchId?{batchId:e.batchId}:{}}),this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:`[aborted] ${u}`});return}if(!i){this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:u}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r,tool:a,toolUseId:e.toolCall.id,result:u,failed:!0,...e.batchId?{batchId:e.batchId}:{}});return}this.appendToolFailureResult(e.toolCall,i,l,e.batchId)}commitSupersededToolResult(e){const t=e.immediateError!==void 0?`[cancelled] ${e.immediateError instanceof Error?e.immediateError.message:String(e.immediateError)}`:"[cancelled] Tool execution was superseded by a newer turn.";this.state.conversation.push({role:"tool",tool_call_id:e.toolCall.id,content:t}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:e.tool?.kind==="mcp"?e.tool.serverName:"builtin",tool:e.tool?.toolName??e.toolCall.function.name,toolUseId:e.toolCall.id,result:t,failed:!0,aborted:!0,...e.batchId?{batchId:e.batchId}:{}})}async executeSingleToolByName(e,t,o){let s=this.state.exposedTools.find(l=>l.exposedName===e);if(s||(s=this.state.exposedTools.find(l=>l.toolName===e)),!s)throw new Error(`Tool not found: ${e}`);if(s.kind==="builtin")return s.execute(t,{toolCallId:o?.toolCallId});const i=this.state.mcpConnections.find(l=>l.serverName===s.serverName);if(!i)throw new Error(`MCP server not found: ${s.serverName}`);const r=We(s.toolName),a=r?this.state.provider.mcpPollingToolTimeoutMs:ke(s.toolName)?0:this.state.provider.mcpToolTimeoutMs;if(r&&Me(s.toolName)==="poll_message"){const l=await this.withBlockingToolCallTracking(s.toolName,()=>this.callPollMessageWithSubAgentRace(i,s,t,a,{allowRepoll:!1}));return this.expandCommandsInPolledResult(G(l))}return this.withBlockingToolCallTracking(s.toolName,()=>this.callMcpToolWithTimeout(i,s,t,a,r))}async callMcpToolWithTimeout(e,t,o,s,i,r){const a=s>0?s:xo,u=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const c=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await $(Promise.race([e.client.callTool({name:t.toolName,arguments:u},void 0,{timeout:a,...r?{signal:r}:{}}),c.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(d){if(r?.aborted||!i||s>0||!Ts(d))throw d;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}
25
28
  Error: ${o.error}`:`Sub-agent ${o.subId} [${o.status}]: ${o.description}
26
- 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=W(e);let s;try{s=JSON.parse(o)}catch{return e}const a=[...t.map(r=>{const l=r.error?`Sub-agent ${r.subId} [${r.status}]: ${r.description}
27
- Error: ${r.error}`:`Sub-agent ${r.subId} [${r.status}]: ${r.description}
28
- Output: ${r.output.length>500?r.output.slice(0,500)+"... (truncated)":r.output}`;return{msgId:`subagent-completion-${r.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:l,requireReply:!1,prompt:`Sub-agent ${r.subId} (${r.description}) has reached terminal state: ${r.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:a},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const i=this.state.mcpConnections.find(a=>a.serverName==="aws-client-agent-mcp");if(!i)return p("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(i,t):e==="memory_expiration"?await this.recheckMemoryExpiration(i,t):await this.recheckMemoryCleanup(i,t)}catch(a){return p(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${a instanceof Error?a.message:String(a)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${a instanceof Error?a.message:String(a)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await x(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=W(o),i=JSON.parse(s);return i==null||typeof i!="object"||Array.isArray(i)?null:i}catch(o){throw o}}async recheckMemoryFileChange(e,t){const o=[];if(await Promise.all(t.map(async i=>{const a=await this.readMemoryViaMcp(e,i);a&&a.memory_status==="updating"&&o.push(i)})),o.length===0)return p(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(i=>`- ${i}`).join(`
29
- `);return p(`[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
29
+ 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=G(e);let s;try{s=JSON.parse(o)}catch{return e}const r=[...t.map(a=>{const l=a.error?`Sub-agent ${a.subId} [${a.status}]: ${a.description}
30
+ Error: ${a.error}`:`Sub-agent ${a.subId} [${a.status}]: ${a.description}
31
+ Output: ${a.output.length>500?a.output.slice(0,500)+"... (truncated)":a.output}`;return{msgId:`subagent-completion-${a.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:l,requireReply:!1,prompt:`Sub-agent ${a.subId} (${a.description}) has reached terminal state: ${a.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:r},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const i=this.state.mcpConnections.find(r=>r.serverName==="aws-client-agent-mcp");if(!i)return f("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(i,t):e==="memory_expiration"?await this.recheckMemoryExpiration(i,t):await this.recheckMemoryCleanup(i,t)}catch(r){return f(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${r instanceof Error?r.message:String(r)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${r instanceof Error?r.message:String(r)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await $(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=G(o),i=JSON.parse(s);return i==null||typeof i!="object"||Array.isArray(i)?null:i}catch(o){throw o}}async recheckMemoryFileChange(e,t){const o=[];if(await Promise.all(t.map(async i=>{const r=await this.readMemoryViaMcp(e,i);r&&r.memory_status==="updating"&&o.push(i)})),o.length===0)return f(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(i=>`- ${i}`).join(`
32
+ `);return f(`[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
30
33
  ${s}
31
34
 
32
- \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async a=>{const r=await this.readMemoryViaMcp(e,a);if(!r)return;const l=r.expiresAt??r.expires_at,u=r.memory_status==="recalling",c=typeof l=="string"&&new Date(l).getTime()<s;(u||c)&&o.push(a)})),o.length===0)return p(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const i=o.map(a=>`- ${a}`).join(`
33
- `);return p(`[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
35
+ \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async r=>{const a=await this.readMemoryViaMcp(e,r);if(!a)return;const l=a.expiresAt??a.expires_at,u=a.memory_status==="recalling",c=typeof l=="string"&&new Date(l).getTime()<s;(u||c)&&o.push(r)})),o.length===0)return f(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const i=o.map(r=>`- ${r}`).join(`
36
+ `);return f(`[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
34
37
  ${i}
35
38
 
36
- \u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const r=await x(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),l=W(r);o=JSON.parse(l)}catch{return{done:!1,continueMessage:"get_memory_stats \u67E5\u8BE2\u5931\u8D25\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5BB9\u91CF\u662F\u5426\u5DF2\u8FBE\u6807\uFF0C\u8BF7\u91CD\u65B0\u9A8C\u8BC1\u540E\u518D\u7EE7\u7EED\u3002"}}const s=o.by_type??{},i=[];for(const r of t){const l=r.indexOf("/");if(l<0)continue;const u=r.slice(0,l),c=r.slice(l+1),h=s[u]?.by_domain?.[c];h?.exceeded&&i.push(`${u}/${c} (\u5F53\u524D ${h.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${h.limit??"?"})`)}if(i.length===0)return p(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const a=i.map(r=>`- ${r}`).join(`
37
- `);return p(`[ACodeRuntime] recheck memory_cleanup: ${i.length}/${t.length} type/domain pairs still exceeded`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
38
- ${a}
39
+ \u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const a=await $(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),l=G(a);o=JSON.parse(l)}catch{return{done:!1,continueMessage:"get_memory_stats \u67E5\u8BE2\u5931\u8D25\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5BB9\u91CF\u662F\u5426\u5DF2\u8FBE\u6807\uFF0C\u8BF7\u91CD\u65B0\u9A8C\u8BC1\u540E\u518D\u7EE7\u7EED\u3002"}}const s=o.by_type??{},i=[];for(const a of t){const l=a.indexOf("/");if(l<0)continue;const u=a.slice(0,l),c=a.slice(l+1),p=s[u]?.by_domain?.[c];p?.exceeded&&i.push(`${u}/${c} (\u5F53\u524D ${p.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${p.limit??"?"})`)}if(i.length===0)return f(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const r=i.map(a=>`- ${a}`).join(`
40
+ `);return f(`[ACodeRuntime] recheck memory_cleanup: ${i.length}/${t.length} type/domain pairs still exceeded`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
41
+ ${r}
39
42
 
40
43
  \u8BF7\u8C03\u7528 list_memories \u67E5\u770B\u8D85\u9650\u8BB0\u5FC6\uFF0C\u5220\u9664\u4E0D\u518D\u9700\u8981\u7684 instance_memory \u6216\u5BF9 instance_long_memory \u8C03\u7528 update_memory \u7EED\u671F\u3002`}}buildMemoryDelegatePrompt(e){const t=e.uris.map(o=>`- ${o}`).join(`
41
44
  `);return e.type==="memory_expiration"?`\u4F60\u662F\u4E00\u6761\u4E13\u95E8\u5904\u7406 memory \u8FC7\u671F\u6574\u7406\u7684\u5B50 agent\u3002
@@ -89,11 +92,11 @@ ${t}
89
92
  \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\u9879\u76EE\u8BB0\u5FC6\u6587\u4EF6\u53D8\u66F4\u66F4\u65B0\u7684\u5B50 agent\u3002
90
93
 
91
94
  \u4EE5\u4E0B ${e.uris.length} \u4E2A\u9879\u76EE\u8BB0\u5FC6\u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D1\u751F\u53D8\u66F4\uFF1A
92
- ${e.uris.map(o=>{const s=e.fileChanges?.find(l=>l.uri===o);if(!s)return`- ${o}`;const i={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},a=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],r=a.length>0?a.map(l=>{if(l.status==="no_change")return` \xB7 ${l.path}`;const u=i[l.status]??l.status,c=l.status==="content_changed"&&l.localMd5&&l.serverMd5?` \u672C\u5730: ${l.localMd5} Server: ${l.serverMd5}`:l.status==="not_found"&&l.serverMd5?` Server: ${l.serverMd5}`:"";return` \xB7 ${l.path}\uFF08${u}${c}\uFF09`}).join(`
95
+ ${e.uris.map(o=>{const s=e.fileChanges?.find(l=>l.uri===o);if(!s)return`- ${o}`;const i={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},r=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],a=r.length>0?r.map(l=>{if(l.status==="no_change")return` \xB7 ${l.path}`;const u=i[l.status]??l.status,c=l.status==="content_changed"&&l.localMd5&&l.serverMd5?` \u672C\u5730: ${l.localMd5} Server: ${l.serverMd5}`:l.status==="not_found"&&l.serverMd5?` Server: ${l.serverMd5}`:"";return` \xB7 ${l.path}\uFF08${u}${c}\uFF09`}).join(`
93
96
  `):s.boundFiles&&s.boundFiles.length>0?s.boundFiles.map(l=>` \xB7 ${l}`).join(`
94
97
  `):" \u65E0\uFF08\u8BF7\u901A\u8FC7 read_memory \u67E5\u770B bound_files\uFF09";return`- ${o}
95
98
  - \u7ED1\u5B9A\u6587\u4EF6:
96
- ${r}`}).join(`
99
+ ${a}`}).join(`
97
100
  `)}
98
101
 
99
102
  \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
@@ -111,5 +114,5 @@ ${r}`}).join(`
111
114
  - \u2705 \u82E5\u5168\u90E8 memory_status \u4E3A "normal"\uFF1A\u9759\u9ED8\u7ED3\u675F
112
115
 
113
116
  \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
114
- \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=W(e)}catch{return e}let s;try{s=JSON.parse(o)}catch{return e}const i=s.directMessages;if(!Array.isArray(i)||i.length===0)return e;const a=[];let r=0;for(const u of i){const c=u._acodeAutoDelegate;if(c&&(c.type==="memory_expiration"||c.type==="memory_file_change"||c.type==="memory_cleanup")){r++;const m=Date.now(),h=c.uris.filter(g=>this.pendingMemorySubAgents.has(g)).length,y=c.uris.filter(g=>{const C=this.memoryDelegateCooldownUntil.get(g);return C!==void 0&&m<C}).length,_=c.uris.filter(g=>{if(this.pendingMemorySubAgents.has(g))return!1;const C=this.memoryDelegateCooldownUntil.get(g);return!(C!==void 0&&m<C)});if(_.length===0){p(`[ACodeRuntime] Memory ${c.type} skipped: ${h} in-progress, ${y} in cooldown (total ${c.uris.length} URIs)`);continue}const d=Array.isArray(c.fileChanges)?c.fileChanges.filter(g=>_.includes(g.uri)):void 0,f=this.buildMemoryDelegatePrompt({type:c.type,uris:_,fileChanges:d});try{const g=ro("explore",[],ze(await this.buildAllocatableToolList())).patterns,C=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:io,description:`Memory ${c.type} auto-delegate (${_.length} items)`,prompt:f,...g.length>0?{allowedTools:g}:{},workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const $ of _)this.pendingMemorySubAgents.set($,C);const w=new Set(_);t.subscribe(C,()=>{const $=t.getSubAgent(C);if($&&($.status==="completed"||$.status==="failed"||$.status==="cancelled")){const S=Date.now();for(const v of w)this.pendingMemorySubAgents.get(v)===C&&this.pendingMemorySubAgents.delete(v),this.memoryDelegateCooldownUntil.set(v,S+et);for(const[v,E]of this.memoryDelegateCooldownUntil)E<=S&&this.memoryDelegateCooldownUntil.delete(v);p(`[ACodeRuntime] Memory delegate sub-agent ${C} finished (${$.status}), ${w.size} URI(s) entered ${et}ms cooldown`)}});const b=c.type,M=async($,S)=>this.recheckMemoryDelegate(b,_,$,S);await t.startWithRecheck(C,M,3),p(`[ACodeRuntime] Auto-delegated memory ${c.type} to sub-agent ${C} (${_.length} URIs, ${c.uris.length-_.length} already in progress)`)}catch(g){for(const C of _)this.pendingMemorySubAgents.delete(C);p(`[ACodeRuntime] Failed to auto-delegate memory ${c.type} (suppressed, will retry next poll): ${g instanceof Error?g.message:String(g)}`)}}else a.push(u)}if(r===0)return e;if(a.length===0)return null;const l={...s,directMessages:a};return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,s,i={}){const a=this.config.subAgentManager;if(!a)return D("runtime.poll.no-subagent-manager","\u65E0 SubAgentManager\uFF0C\u76F4\u63A5\u8D70\u666E\u901A MCP \u8C03\u7528"),await this.callMcpToolWithTimeout(e,t,o,s,!0);const r=i.allowRepoll!==!1,l=a.takeCompletedSubAgents();if(l.length>0)return p(`[ACodeRuntime] poll_message: ${l.length} sub-agent(s) already completed, returning synthetic result`),D("runtime.poll.subagent-synthetic",`${l.length} \u4E2A\u5B50 agent \u5DF2\u5B8C\u6210\uFF0C\u76F4\u63A5\u8FD4\u56DE\u5408\u6210\u7ED3\u679C\uFF08\u4E0D\u8C03 MCP\uFF09`),Z.formatSubAgentCompletionAsPollResult(l);let u=!1,c=0;for(;;){c++,D("runtime.poll.round-start",`\u7B2C ${c} \u8F6E race \u5F00\u59CB: timeoutMs=${s} silent=${u}`);const m=new AbortController,h=a.waitForAnyCompletion(),y=u?{...o,_aws_silent_poll:!0}:o,_=Date.now(),d=this.callMcpToolWithTimeout(e,t,y,s,!0,m.signal);try{const f=await Promise.race([d.then(w=>({type:"mcp",result:w})),h.promise.then(w=>({type:"subagent",notif:w}))]);if(f.type==="subagent"){D("runtime.poll.race-winner-subagent",`\u5B50 agent \u5148\u5B8C\u6210\uFF0Cabort MCP \u8C03\u7528\uFF08\u5DF2\u7B49\u5F85 ${Date.now()-_}ms\uFF09\u540E\u8FD4\u56DE\u5408\u6210\u7ED3\u679C`),m.abort(),d.catch(()=>{});const w=a.takeCompletedSubAgents();return w.length===0&&w.push(f.notif),p(`[ACodeRuntime] poll_message: sub-agent ${f.notif.subId} completed during race, returning synthetic result (${w.length} notification(s))`),Z.formatSubAgentCompletionAsPollResult(w)}D("runtime.poll.mcp-returned",`MCP \u5148\u8FD4\u56DE\uFF08\u8017\u65F6 ${Date.now()-_}ms\uFF09\uFF0C\u68C0\u67E5\u5F85\u5408\u5E76\u7684\u5B50 agent \u5B8C\u6210`);const g=a.takeCompletedSubAgents();if(g.length>0){p(`[ACodeRuntime] poll_message: MCP returned, merging ${g.length} sub-agent completion(s)`);const w=Z.mergeSubAgentCompletionsIntoMcpResult(f.result,g),b=await this.processMemoryAutoDelegates(w);if(D("runtime.poll.delegate-check",`\u5408\u5E76 ${g.length} \u4E2A\u5B50 agent \u5B8C\u6210\u540E\u59D4\u6258\u68C0\u67E5: processed=${b===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),b!==null){if(this.pollResultHasMessages(b))return D("runtime.poll.final-return",`\u7B2C ${c} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),b;D("runtime.poll.empty-repoll",`\u7B2C ${c} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${Te}ms \u540E\u91CD\u65B0 poll`)}if(!r)return b;await this.waitForDelegateRepoll(),u=!0;continue}const C=await this.processMemoryAutoDelegates(f.result);if(D("runtime.poll.delegate-check",`\u59D4\u6258\u68C0\u67E5: processed=${C===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),C!==null){if(this.pollResultHasMessages(C)){const w=this.summarizePollResultForDebug(C);return D("runtime.poll.final-return",`\u7B2C ${c} \u8F6E\uFF1A\u8FD4\u56DE poll \u7ED3\u679C\u7ED9 LLM: ${w}`),C}D("runtime.poll.empty-repoll",`\u7B2C ${c} \u8F6E\uFF1Apoll \u7ED3\u679C\u65E0\u5B9E\u9645\u6D88\u606F\uFF08directMessages/groupMessages \u5747\u7A7A\uFF09\uFF0C\u7B49\u5F85 ${Te}ms \u540E\u91CD\u65B0 poll`)}if(!r)return D("runtime.poll.delegate-return-no-repoll","\u975E\u9876\u5C42\u8F6E\u8BE2\u5165\u53E3\uFF1A\u59D4\u6258\u5DF2\u5B8C\u6210\uFF0C\u8FD4\u56DE\u539F\u59CB poll \u7ED3\u679C\uFF08\u4E0D\u91CD\u65B0 poll\uFF09"),f.result;await this.waitForDelegateRepoll(),u=!0}catch(f){throw D("runtime.poll.error",`\u7B2C ${c} \u8F6E MCP \u8C03\u7528\u5F02\u5E38: ${f instanceof Error?f.message:String(f)}`),f}finally{h.cancel()}}}summarizePollResultForDebug(e){try{const t=W(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages:[],i=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${s.length}${s.length>0?JSON.stringify(s.map(a=>({id:a.msgId,ch:a.channel}))):""} gm=${i.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=W(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,i=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||i>0}catch{return!0}}async waitForDelegateRepoll(){p(`[ACodeRuntime] poll_message: all messages delegated, waiting ${Te}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,Te);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((s,i)=>{t=()=>{i(new Error(`${e} interrupted because ACode runtime stopped`))}});return t?(this.stopWaiters.add(t),{promise:o,cancel:()=>{t&&this.stopWaiters.delete(t)}}):{promise:o,cancel:()=>{}}}notifyRuntimeStop(){const e=[...this.stopWaiters];this.stopWaiters.clear();for(const t of e)t()}async appendSyntheticMultimodalUserMessage(e,t,o=this.contextVersion){const s=Ee(e);{const a=e.slice(0,200);let r="unknown";try{const l=JSON.parse(e);l&&typeof l=="object"&&!Array.isArray(l)?r=`keys=[${Object.keys(l).join(",")}]`:Array.isArray(l)?r="array":r=typeof l}catch{r="non-json"}Ce({stage:"entry",toolCallId:t.slice(0,12),contentLen:e.length,topLevelShape:r,prefix:a})}if(!s.hasImages){let a=null;try{const r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r)){const l=[r.directMessages,r.groupMessages];a=[];for(const u of l)if(Array.isArray(u))for(const c of u){if(!c||typeof c!="object")continue;const m=c,h=typeof m.content=="string"?m.content:"",y={senderName:typeof m.senderName=="string"?m.senderName:"",msgId:typeof m.msgId=="string"?m.msgId:"",contentLen:h.length};let _=null;try{const d=JSON.parse(h);d&&typeof d=="object"&&!Array.isArray(d)&&(_=d)}catch{}_?(y.contentKind="json",y.hasAttachmentsField=Array.isArray(_.attachments),y.attachmentCount=Array.isArray(_.attachments)?_.attachments.length:0,y.attachmentKinds=Array.isArray(_.attachments)?_.attachments.map(d=>String(d.type??d.kind??"").toLowerCase()||"(empty)"):[],y.attachmentBase64Lens=Array.isArray(_.attachments)?_.attachments.map(d=>(typeof d.base64Data=="string"?d.base64Data:typeof d.base64=="string"?d.base64:typeof d.data=="string"?d.data:"").length):[]):(y.contentKind="non-json",y.contentPrefix=h.slice(0,60)),a.push(y)}}}catch{}return Ce({stage:"hasImages_false",toolCallId:t.slice(0,12),contentLen:e.length,parsedContentKind:Array.isArray(s.content)?"parts":typeof s.content,partsCount:Array.isArray(s.content)?s.content.length:null,dmProbe:a}),null}if(!this.state.provider.supportsImageInput)return this.emitAcodeEvent("error",{message:"ACode skipped image content from tool result because the provider/model is not configured for image input."}),Ce({stage:"supportsImageInput_false",toolCallId:t.slice(0,12),providerSupportsImageInput:this.state.provider.supportsImageInput,partsCount:Array.isArray(s.content)?s.content.length:null}),this.cleanToolMessageAttachments(t,"[Tool result contained images; skipped because the current model does not support image input]"),null;let i;try{i=await lt(s.content)}catch(a){const r=a instanceof Error?a.message:String(a),l=Array.isArray(s.content)?s.content.filter(u=>u.type==="image_url").map(u=>{const c=u.image_url.url,m=c.indexOf(",");return{urlHead:c.slice(0,Math.min(30,c.length)),base64Len:m>=0?c.length-m-1:null,isDataUrl:/^data:image\//i.test(c)}}):null;Ce({stage:"materialize_threw",toolCallId:t.slice(0,12),errMessage:r,imagePartsCount:l?l.length:0,imageParts:l}),this.emitAcodeEvent("error",{message:`ACode skipped image content from tool result: ${r}`}),i=Array.isArray(s.content)?s.content.map(u=>u.type==="text"?u:{type:"text",text:`[Image omitted: ${r}]`}):s.content}return this.isTurnSuperseded(o)?null:(this.cleanToolMessageAttachments(t,"[Tool result contained images; see user message above]"),{role:"user",content:i})}expandCommandsInPolledResult(e){const t=this.state.commandRegistry;if(!t||t.list().length===0)return e;let o;try{o=JSON.parse(e)}catch{return e}if(!k(o))return e;let s=!1;for(const i of["directMessages","groupMessages"]){const a=o[i];if(Array.isArray(a))for(const r of a){if(!k(r))continue;const l=N(r.content);if(!l)continue;const u=t.expand(l);u&&(r.content=u.prompt,s=!0)}}return s?JSON.stringify(o):e}cleanToolMessageAttachments(e,t){const o=this.state.conversation.find(i=>i.role==="tool"&&i.tool_call_id===e);if(!o||typeof o.content!="string")return;let s;try{const i=JSON.parse(o.content);if(typeof i=="object"&&i!==null){const a={...i};"attachments"in a&&delete a.attachments,Ko(a),s=JSON.stringify(a)}}catch{}if(s===void 0){const i=o.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();i!==o.content&&(s=i)}s!==void 0&&(o.content=s.length>0?s:t)}appendToolFailureResult(e,t,o,s){const i=pt(t,o),a=Mt(o),r=a?pt(t,o,a):i;p(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${i.length} chars`+(a?`, conversation snapshot: ${a.bytes} bytes`:"")),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${me(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,toolUseId:e.id,result:i,failed:!0,...s?{batchId:s}:{}}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:r})}filterSharedMcpConnectionsForSubAgent(e){const t=this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0?this.config.subAgentAllowedTools:null;return e.map(o=>({...o,tools:o.tools.filter(s=>t?je(s,t):ao.has(s.toolName))}))}async connectMcpServers(e,t,o){const s=[];for(const[i,a]of Object.entries(e))try{const r=new _t({name:"acode",version:"0.1.0"}),l=this.createMcpTransport(i,a);await x(r.connect(l),t,`ACode MCP server ${i} connect`);const u={serverName:i,client:r,transport:l,tools:[]};r.setNotificationHandler(kt,()=>{this.refreshMcpConnectionTools(u,t)});const{tools:c}=await x(r.listTools(),t,`ACode MCP server ${i} listTools`);u.tools=Ke(i,c);try{u.instructions=r.getInstructions()}catch{}u.spec=a,s.push(u)}catch(r){const l=r instanceof Error?r.message:String(r);o?.set(i,l),this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${i}: ${l}`})}return s}registerMcpCollapsedGroup(e,t,o){if(!this.toolGroupManager||t.collapsed!==!0||o.tools.length===0)return;const s=Oe(e),i=this.toolGroupManager.getRegistration(s),a=t.description?.trim()||Co(o.instructions)||`MCP \u5DE5\u5177\u96C6\uFF1A${e}`,r=this.toolGroupManager.claimedToolNamesBySubGroups(),l=o.tools.map(u=>u.toolName).filter(u=>!r.has(u));l.length!==0&&(this.toolGroupManager.register({key:s,label:t.description?.trim()||e,summary:a,collapsible:!0,toolNames:l,serverName:e}),this.emitAcodeEvent("mcp_status",{serverName:e,status:"collapsed_group_registered",toolCount:l.length,updated:!!i}))}registerToolGroupsFromMcp(e){if(!this.toolGroupManager)return!1;const t=yo(e.instructions);if(t.length===0)return!1;let o=0;for(const s of t)this.toolGroupManager.getRegistration(s.key)||(this.toolGroupManager.register({key:s.key,label:s.label,summary:"",collapsible:!0,toolNames:s.toolNames}),o+=1);return this.emitAcodeEvent("mcp_status",{serverName:e.serverName,status:"tool_groups_registered",declared:t.length,registered:o}),!0}requestMcpToolsRefresh(e){const t=this.state.mcpConnections.filter(o=>!e||o.serverName===e);for(const o of t)this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs)}async recoverHiddenMcpTool(e){if(this.recoveredToolNames.has(e)||this.recoveredToolNames.size>=wo)return!1;this.recoveredToolNames.add(e);const t=this.state.mcpConnections.filter(o=>o.tools.some(s=>s.toolName==="expand_tools"||s.exposedName==="expand_tools"||s.exposedName.endsWith("__expand_tools")));if(t.length===0)return!1;for(const o of t)await this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs);return this.state.exposedTools.some(o=>o.toolName===e||o.exposedName===e)}async refreshMcpConnectionTools(e,t){try{const{tools:s}=await x(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Ke(e.serverName,s)}catch(s){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${s instanceof Error?s.message:String(s)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitExposedToolsStatus()}createMcpTransport(e,t){if(t.type==="stdio"||t.command){if(!t.command)throw new Error("stdio MCP server requires command");const s=new bt({command:t.command,args:t.args,cwd:t.cwd||this.config.workingDirectory,env:{...this.config.env??{},...t.env??{}},stderr:"pipe"}),i=t.debugStderr===!0?this.ensureMcpStderrBuffer(e):null;return s.stderr?.on("data",a=>{i&&i.push(String(a))}),s}if(!t.url)throw new Error("remote MCP server requires url");const o=t.headers?{headers:t.headers}:void 0;return t.type==="sse"?new At(new URL(t.url),{requestInit:o}):new wt(new URL(t.url),{requestInit:o})}ensureMcpStderrBuffer(e){let t=this.mcpStderrBuffers.get(e);return t||(t=new no,this.mcpStderrBuffers.set(e,t)),t}getMcpServerStderr(e,t=100){const o=this.mcpStderrBuffers.get(e);if(!o)return[];const s=Math.max(1,Math.min(Math.floor(t)||100,500));return o.tail(s)}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:ge}),ge,"ACode startup get_profile"),i=this.extractProfileFromToolResult(s);return gs(i)}catch(s){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${s instanceof Error?s.message:String(s)}`}),""}return""}extractProfileFromToolResult(e){if(!k(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(k(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(k(s))return s}catch{}}return k(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=>se(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}Z.SKILL_REFRESH_DEBOUNCE_MS=500;export{Z as ACodeRuntime,fe as TOOL_GROUP_MANIFEST_PREFIX,vo as hasExplicitRequestBodyByteCap,Co as humanReadableInstructions,yo as parseToolGroupManifest,xo as resolveMaxRequestBodyBytes,pt as toToolErrorResultText};
117
+ \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=G(e)}catch{return e}let s;try{s=JSON.parse(o)}catch{return e}const i=s.directMessages;if(!Array.isArray(i)||i.length===0)return e;const r=[];let a=0;for(const u of i){const c=u._acodeAutoDelegate;if(c&&(c.type==="memory_expiration"||c.type==="memory_file_change"||c.type==="memory_cleanup")){a++;const d=Date.now(),p=c.uris.filter(g=>this.pendingMemorySubAgents.has(g)).length,T=c.uris.filter(g=>{const y=this.memoryDelegateCooldownUntil.get(g);return y!==void 0&&d<y}).length,_=c.uris.filter(g=>{if(this.pendingMemorySubAgents.has(g))return!1;const y=this.memoryDelegateCooldownUntil.get(g);return!(y!==void 0&&d<y)});if(_.length===0){f(`[ACodeRuntime] Memory ${c.type} skipped: ${p} in-progress, ${T} in cooldown (total ${c.uris.length} URIs)`);continue}const m=Array.isArray(c.fileChanges)?c.fileChanges.filter(g=>_.includes(g.uri)):void 0,h=this.buildMemoryDelegatePrompt({type:c.type,uris:_,fileChanges:m});try{const g=ho("explore",[],Ge(await this.buildAllocatableToolList())).patterns,y=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:po,description:`Memory ${c.type} auto-delegate (${_.length} items)`,prompt:h,...g.length>0?{allowedTools:g}:{},workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const k of _)this.pendingMemorySubAgents.set(k,y);const w=new Set(_);t.subscribe(y,()=>{const k=t.getSubAgent(y);if(k&&(k.status==="completed"||k.status==="failed"||k.status==="cancelled")){const v=Date.now();for(const M of w)this.pendingMemorySubAgents.get(M)===y&&this.pendingMemorySubAgents.delete(M),this.memoryDelegateCooldownUntil.set(M,v+st);for(const[M,L]of this.memoryDelegateCooldownUntil)L<=v&&this.memoryDelegateCooldownUntil.delete(M);f(`[ACodeRuntime] Memory delegate sub-agent ${y} finished (${k.status}), ${w.size} URI(s) entered ${st}ms cooldown`)}});const A=c.type,N=async(k,v)=>this.recheckMemoryDelegate(A,_,k,v);await t.startWithRecheck(y,N,3),f(`[ACodeRuntime] Auto-delegated memory ${c.type} to sub-agent ${y} (${_.length} URIs, ${c.uris.length-_.length} already in progress)`)}catch(g){for(const y of _)this.pendingMemorySubAgents.delete(y);f(`[ACodeRuntime] Failed to auto-delegate memory ${c.type} (suppressed, will retry next poll): ${g instanceof Error?g.message:String(g)}`)}}else r.push(u)}if(a===0)return e;if(r.length===0)return null;const l={...s,directMessages:r};return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,s,i={}){const r=this.config.subAgentManager;if(!r)return B("runtime.poll.no-subagent-manager","\u65E0 SubAgentManager\uFF0C\u76F4\u63A5\u8D70\u666E\u901A MCP \u8C03\u7528"),await this.callMcpToolWithTimeout(e,t,o,s,!0);const a=i.allowRepoll!==!1,l=r.takeCompletedSubAgents();if(l.length>0)return f(`[ACodeRuntime] poll_message: ${l.length} sub-agent(s) already completed, returning synthetic result`),B("runtime.poll.subagent-synthetic",`${l.length} \u4E2A\u5B50 agent \u5DF2\u5B8C\u6210\uFF0C\u76F4\u63A5\u8FD4\u56DE\u5408\u6210\u7ED3\u679C\uFF08\u4E0D\u8C03 MCP\uFF09`),Z.formatSubAgentCompletionAsPollResult(l);let u=!1,c=0;for(;;){c++,B("runtime.poll.round-start",`\u7B2C ${c} \u8F6E race \u5F00\u59CB: timeoutMs=${s} silent=${u}`);const d=new AbortController,p=r.waitForAnyCompletion(),T=u?{...o,_aws_silent_poll:!0}:o,_=Date.now(),m=this.callMcpToolWithTimeout(e,t,T,s,!0,d.signal);try{const h=await Promise.race([m.then(w=>({type:"mcp",result:w})),p.promise.then(w=>({type:"subagent",notif:w}))]);if(h.type==="subagent"){B("runtime.poll.race-winner-subagent",`\u5B50 agent \u5148\u5B8C\u6210\uFF0Cabort MCP \u8C03\u7528\uFF08\u5DF2\u7B49\u5F85 ${Date.now()-_}ms\uFF09\u540E\u8FD4\u56DE\u5408\u6210\u7ED3\u679C`),d.abort(),m.catch(()=>{});const w=r.takeCompletedSubAgents();return w.length===0&&w.push(h.notif),f(`[ACodeRuntime] poll_message: sub-agent ${h.notif.subId} completed during race, returning synthetic result (${w.length} notification(s))`),Z.formatSubAgentCompletionAsPollResult(w)}B("runtime.poll.mcp-returned",`MCP \u5148\u8FD4\u56DE\uFF08\u8017\u65F6 ${Date.now()-_}ms\uFF09\uFF0C\u68C0\u67E5\u5F85\u5408\u5E76\u7684\u5B50 agent \u5B8C\u6210`);const g=r.takeCompletedSubAgents();if(g.length>0){f(`[ACodeRuntime] poll_message: MCP returned, merging ${g.length} sub-agent completion(s)`);const w=Z.mergeSubAgentCompletionsIntoMcpResult(h.result,g),A=await this.processMemoryAutoDelegates(w);if(B("runtime.poll.delegate-check",`\u5408\u5E76 ${g.length} \u4E2A\u5B50 agent \u5B8C\u6210\u540E\u59D4\u6258\u68C0\u67E5: processed=${A===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),A!==null){if(this.pollResultHasMessages(A))return B("runtime.poll.final-return",`\u7B2C ${c} \u8F6E\uFF1A\u8FD4\u56DE\uFF08MCP+\u5B50agent\u5408\u5E76\u7ED3\u679C\uFF09`),A;B("runtime.poll.empty-repoll",`\u7B2C ${c} \u8F6E\uFF1A\u5408\u5E76\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u7B49\u5F85 ${Te}ms \u540E\u91CD\u65B0 poll`)}if(!a)return A;await this.waitForDelegateRepoll(),u=!0;continue}const y=await this.processMemoryAutoDelegates(h.result);if(B("runtime.poll.delegate-check",`\u59D4\u6258\u68C0\u67E5: processed=${y===null?"\u5168\u90E8\u88AB\u59D4\u6258(null)":"\u6709\u53EF\u4EA4\u4ED8"}`),y!==null){if(this.pollResultHasMessages(y)){const w=this.summarizePollResultForDebug(y);return B("runtime.poll.final-return",`\u7B2C ${c} \u8F6E\uFF1A\u8FD4\u56DE poll \u7ED3\u679C\u7ED9 LLM: ${w}`),y}B("runtime.poll.empty-repoll",`\u7B2C ${c} \u8F6E\uFF1Apoll \u7ED3\u679C\u65E0\u5B9E\u9645\u6D88\u606F\uFF08directMessages/groupMessages \u5747\u7A7A\uFF09\uFF0C\u7B49\u5F85 ${Te}ms \u540E\u91CD\u65B0 poll`)}if(!a)return B("runtime.poll.delegate-return-no-repoll","\u975E\u9876\u5C42\u8F6E\u8BE2\u5165\u53E3\uFF1A\u59D4\u6258\u5DF2\u5B8C\u6210\uFF0C\u8FD4\u56DE\u539F\u59CB poll \u7ED3\u679C\uFF08\u4E0D\u91CD\u65B0 poll\uFF09"),h.result;await this.waitForDelegateRepoll(),u=!0}catch(h){throw B("runtime.poll.error",`\u7B2C ${c} \u8F6E MCP \u8C03\u7528\u5F02\u5E38: ${h instanceof Error?h.message:String(h)}`),h}finally{p.cancel()}}}summarizePollResultForDebug(e){try{const t=G(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages:[],i=Array.isArray(o.groupMessages)?o.groupMessages:[];return`dm=${s.length}${s.length>0?JSON.stringify(s.map(r=>({id:r.msgId,ch:r.channel}))):""} gm=${i.length}`}catch{return"(\u65E0\u6CD5\u89E3\u6790\u4E3A JSON)"}}pollResultHasMessages(e){try{const t=G(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,i=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||i>0}catch{return!0}}async waitForDelegateRepoll(){f(`[ACodeRuntime] poll_message: all messages delegated, waiting ${Te}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,Te);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((s,i)=>{t=()=>{i(new Error(`${e} interrupted because ACode runtime stopped`))}});return t?(this.stopWaiters.add(t),{promise:o,cancel:()=>{t&&this.stopWaiters.delete(t)}}):{promise:o,cancel:()=>{}}}notifyRuntimeStop(){const e=[...this.stopWaiters];this.stopWaiters.clear();for(const t of e)t()}async appendSyntheticMultimodalUserMessage(e,t,o=this.contextVersion){const s=Re(e);{const r=e.slice(0,200);let a="unknown";try{const l=JSON.parse(e);l&&typeof l=="object"&&!Array.isArray(l)?a=`keys=[${Object.keys(l).join(",")}]`:Array.isArray(l)?a="array":a=typeof l}catch{a="non-json"}_e({stage:"entry",toolCallId:t.slice(0,12),contentLen:e.length,topLevelShape:a,prefix:r})}if(!s.hasImages){let r=null;try{const a=JSON.parse(e);if(a&&typeof a=="object"&&!Array.isArray(a)){const l=[a.directMessages,a.groupMessages];r=[];for(const u of l)if(Array.isArray(u))for(const c of u){if(!c||typeof c!="object")continue;const d=c,p=typeof d.content=="string"?d.content:"",T={senderName:typeof d.senderName=="string"?d.senderName:"",msgId:typeof d.msgId=="string"?d.msgId:"",contentLen:p.length};let _=null;try{const m=JSON.parse(p);m&&typeof m=="object"&&!Array.isArray(m)&&(_=m)}catch{}_?(T.contentKind="json",T.hasAttachmentsField=Array.isArray(_.attachments),T.attachmentCount=Array.isArray(_.attachments)?_.attachments.length:0,T.attachmentKinds=Array.isArray(_.attachments)?_.attachments.map(m=>String(m.type??m.kind??"").toLowerCase()||"(empty)"):[],T.attachmentBase64Lens=Array.isArray(_.attachments)?_.attachments.map(m=>(typeof m.base64Data=="string"?m.base64Data:typeof m.base64=="string"?m.base64:typeof m.data=="string"?m.data:"").length):[]):(T.contentKind="non-json",T.contentPrefix=p.slice(0,60)),r.push(T)}}}catch{}return _e({stage:"hasImages_false",toolCallId:t.slice(0,12),contentLen:e.length,parsedContentKind:Array.isArray(s.content)?"parts":typeof s.content,partsCount:Array.isArray(s.content)?s.content.length:null,dmProbe:r}),null}if(!this.state.provider.supportsImageInput)return this.emitAcodeEvent("error",{message:"ACode skipped image content from tool result because the provider/model is not configured for image input."}),_e({stage:"supportsImageInput_false",toolCallId:t.slice(0,12),providerSupportsImageInput:this.state.provider.supportsImageInput,partsCount:Array.isArray(s.content)?s.content.length:null}),this.cleanToolMessageAttachments(t,"[Tool result contained images; skipped because the current model does not support image input]"),null;let i;try{i=await mt(s.content)}catch(r){const a=r instanceof Error?r.message:String(r),l=Array.isArray(s.content)?s.content.filter(u=>u.type==="image_url").map(u=>{const c=u.image_url.url,d=c.indexOf(",");return{urlHead:c.slice(0,Math.min(30,c.length)),base64Len:d>=0?c.length-d-1:null,isDataUrl:/^data:image\//i.test(c)}}):null;_e({stage:"materialize_threw",toolCallId:t.slice(0,12),errMessage:a,imagePartsCount:l?l.length:0,imageParts:l}),this.emitAcodeEvent("error",{message:`ACode skipped image content from tool result: ${a}`}),i=Array.isArray(s.content)?s.content.map(u=>u.type==="text"?u:{type:"text",text:`[Image omitted: ${a}]`}):s.content}return this.isTurnSuperseded(o)?null:(this.cleanToolMessageAttachments(t,"[Tool result contained images; see user message above]"),{role:"user",content:i})}expandCommandsInPolledResult(e){const t=this.state.commandRegistry;if(!t||t.list().length===0)return e;let o;try{o=JSON.parse(e)}catch{return e}if(!S(o))return e;let s=!1;for(const i of["directMessages","groupMessages"]){const r=o[i];if(Array.isArray(r))for(const a of r){if(!S(a))continue;const l=I(a.content);if(!l)continue;const u=t.expand(l);u&&(a.content=u.prompt,s=!0)}}return s?JSON.stringify(o):e}cleanToolMessageAttachments(e,t){const o=this.state.conversation.find(i=>i.role==="tool"&&i.tool_call_id===e);if(!o||typeof o.content!="string")return;let s;try{const i=JSON.parse(o.content);if(typeof i=="object"&&i!==null){const r={...i};"attachments"in r&&delete r.attachments,ts(r),s=JSON.stringify(r)}}catch{}if(s===void 0){const i=o.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();i!==o.content&&(s=i)}s!==void 0&&(o.content=s.length>0?s:t)}appendToolFailureResult(e,t,o,s){const i=gt(t,o),r=It(o),a=r?gt(t,o,r):i;f(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${i.length} chars`+(r?`, conversation snapshot: ${r.bytes} bytes`:"")),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${me(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,toolUseId:e.id,result:i,failed:!0,...s?{batchId:s}:{}}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:a})}filterSharedMcpConnectionsForSubAgent(e){const t=this.config.subAgentAllowedTools&&this.config.subAgentAllowedTools.length>0?this.config.subAgentAllowedTools:null;return e.map(o=>({...o,tools:o.tools.filter(s=>t?Je(s,t):fo.has(s.toolName))}))}async connectMcpServers(e,t,o){const s=[];for(const[i,r]of Object.entries(e))try{const a=new Mt({name:"acode",version:"0.1.0"}),l=this.createMcpTransport(i,r);await $(a.connect(l),t,`ACode MCP server ${i} connect`);const u={serverName:i,client:a,transport:l,tools:[]};a.setNotificationHandler(xt,()=>{this.refreshMcpConnectionTools(u,t)});const{tools:c}=await $(a.listTools(),t,`ACode MCP server ${i} listTools`);u.tools=Ye(i,c);try{u.instructions=a.getInstructions()}catch{}u.spec=r,s.push(u)}catch(a){const l=a instanceof Error?a.message:String(a);o?.set(i,l),this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${i}: ${l}`})}return s}registerMcpCollapsedGroup(e,t,o){if(!this.toolGroupManager||t.collapsed!==!0||o.tools.length===0)return;const s=Be(e),i=this.toolGroupManager.getRegistration(s),r=t.description?.trim()||vo(o.instructions)||`MCP \u5DE5\u5177\u96C6\uFF1A${e}`,a=this.toolGroupManager.claimedToolNamesBySubGroups(),l=o.tools.map(u=>u.toolName).filter(u=>!a.has(u));l.length!==0&&(this.toolGroupManager.register({key:s,label:t.description?.trim()||e,summary:r,collapsible:!0,toolNames:l,serverName:e}),this.emitAcodeEvent("mcp_status",{serverName:e,status:"collapsed_group_registered",toolCount:l.length,updated:!!i}))}registerToolGroupsFromMcp(e){if(!this.toolGroupManager)return!1;const t=Mo(e.instructions);if(t.length===0)return!1;let o=0;for(const s of t)this.toolGroupManager.getRegistration(s.key)||(this.toolGroupManager.register({key:s.key,label:s.label,summary:"",collapsible:!0,toolNames:s.toolNames}),o+=1);return this.emitAcodeEvent("mcp_status",{serverName:e.serverName,status:"tool_groups_registered",declared:t.length,registered:o}),!0}requestMcpToolsRefresh(e){const t=this.state.mcpConnections.filter(o=>!e||o.serverName===e);for(const o of t)this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs)}async recoverHiddenMcpTool(e){if(this.recoveredToolNames.has(e)||this.recoveredToolNames.size>=Ro)return!1;this.recoveredToolNames.add(e);const t=this.state.mcpConnections.filter(o=>o.tools.some(s=>s.toolName==="expand_tools"||s.exposedName==="expand_tools"||s.exposedName.endsWith("__expand_tools")));if(t.length===0)return!1;for(const o of t)await this.refreshMcpConnectionTools(o,this.state.provider.mcpToolTimeoutMs);return this.state.exposedTools.some(o=>o.toolName===e||o.exposedName===e)}async refreshMcpConnectionTools(e,t){try{const{tools:s}=await $(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Ye(e.serverName,s)}catch(s){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${s instanceof Error?s.message:String(s)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitExposedToolsStatus()}createMcpTransport(e,t){if(t.type==="stdio"||t.command){if(!t.command)throw new Error("stdio MCP server requires command");const s=new $t({command:t.command,args:t.args,cwd:t.cwd||this.config.workingDirectory,env:{...this.config.env??{},...t.env??{}},stderr:"pipe"}),i=t.debugStderr===!0?this.ensureMcpStderrBuffer(e):null;return s.stderr?.on("data",r=>{i&&i.push(String(r))}),s}if(!t.url)throw new Error("remote MCP server requires url");const o=t.headers?{headers:t.headers}:void 0;return t.type==="sse"?new vt(new URL(t.url),{requestInit:o}):new Et(new URL(t.url),{requestInit:o})}ensureMcpStderrBuffer(e){let t=this.mcpStderrBuffers.get(e);return t||(t=new mo,this.mcpStderrBuffers.set(e,t)),t}getMcpServerStderr(e,t=100){const o=this.mcpStderrBuffers.get(e);if(!o)return[];const s=Math.max(1,Math.min(Math.floor(t)||100,500));return o.tail(s)}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(s=>s.toolName==="get_profile"))try{const s=await $(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:ye}),ye,"ACode startup get_profile"),i=this.extractProfileFromToolResult(s);return As(i)}catch(s){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${s instanceof Error?s.message:String(s)}`}),""}return""}extractProfileFromToolResult(e){if(!S(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(S(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(S(s))return s}catch{}}return S(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=>se(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}Z.SKILL_REFRESH_DEBOUNCE_MS=500;export{Z as ACodeRuntime,ge as TOOL_GROUP_MANIFEST_PREFIX,Lo as hasExplicitRequestBodyByteCap,vo as humanReadableInstructions,Mo as parseToolGroupManifest,Do as resolveMaxRequestBodyBytes,gt as toToolErrorResultText};
115
118