aws-runtime-bridge 1.9.108 → 1.9.110

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,34 +1,34 @@
1
- import{EventEmitter as je}from"node:events";import J from"node:fs";import We from"node:os";import V from"node:path";import{Client as Je}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Ke}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as He}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Qe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as Ge}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as Ye}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as Ve,createAskUserQuestionTool as Xe}from"./ask-user-question-tool.js";import{createSkillTool as Ze}from"./skill-tool.js";import{createTodoWriteTool as et,createTodoReadTool as tt}from"./todo-tool.js";import{createSubAgentTools as ot}from"./sub-agent-tools.js";import{createAwaitCompleteTool as nt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as st}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as K}from"./background-command-manager.js";import{createTerminalTool as it}from"./terminal-tool.js";import{loadAcodeCommands as rt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as pe}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as at,COMPACTION_LLM_PROMPT_TEMPLATE as lt,conversationSizeKB as H,estimateConversationTokens as X,performCompaction as he,pruneToolOutputs as ut,summarizeConversation as fe}from"./compaction.js";import{loadAcodeConfig as ct,loadAcodeSkillGroup as mt}from"./config.js";import{ACodeHookBus as dt,findDeniedHookResult as se}from"./hooks/hookBus.js";import{isMcpPollingToolName as pt,getSemanticToolName as ge}from"./mcpToolNames.js";function ht(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function ft(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function gt(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(ht):n.content};return n.tool_call_id&&(e.tool_call_id=n.tool_call_id),n.tool_calls&&(e.tool_calls=n.tool_calls.map(ft)),e}function ie(n){return n.map(gt)}function yt(){return new Date().toISOString()}function v(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function ye(n){return v(n)}function Te(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:io(n,t.name),description:t.description,inputSchema:ye(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function I(n){return String(n??"").trim()||void 0}const Z=6e4,Ae=10*6e4,Ce=2e4,_e=3e4,we=3,re=-1,Tt=1e3,At=3e4,ee=6e4,be=0,Ct=2147483647,_t=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),wt=new Set(["write_file","edit_file","delete_file"]),bt=10*6e4+2e3,$t=1e4,$e=5e3,Se=10*60*1e3,Me=10*1024*1024,Re=800*1024,te=process.env.ACODE_COMPACTION_DEBUG==="1",ke=te?V.join(We.tmpdir(),"acode-compaction-debug.log"):"";function m(...n){te&&console.log(...n)}const St=64e3;function ae(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:St,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=at(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:s}}async function E(n,e,t,o){if(e<=0)return await n;let s;try{return await new Promise((a,i)=>{s=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),n.then(a,i)})}finally{s&&clearTimeout(s)}}async function Q(n,e,t,o=$t){try{await E(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function F(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===re?re:Number.isFinite(t)&&t>0?Math.floor(t):e}function B(n,e){const t=F(n,e);return t>0?t:e}const ve=3;function xe(n){return n?Math.ceil(n.length/ve):0}function Mt(n,e){let t=n.length;for(const o of e){const s=(o.kind==="mcp",o.toolName);if(t+=s.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const a=o;a.inputSchema&&(t+=JSON.stringify(a.inputSchema).length)}}return Math.ceil(t/ve)}function Ee(n){if(n.length===0)return 0;const e=JSON.stringify(qe(n));return xe(e)}async function Rt(n){await new Promise(e=>setTimeout(e,n))}function kt(n){return typeof n=="boolean"}function vt(n,e,t){if(kt(t?.supportsImageInput))return t.supportsImageInput;const o=v(e)?e.models:void 0,s=v(o)?o[n]:void 0;if(!v(s))return!1;const a=s.modalities;return!v(a)||!Array.isArray(a.input)?!1:a.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function le(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(v(s)){const a=s[t];if(v(a)){const i=a[o];if(i!==void 0)return i}}return e[o]}function xt(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",a=I(n.effort)||I(o?.effort)||I(t?.effort)||void 0;return{model:s,baseURL:I(o?.baseURL||o?.baseUrl),apiKey:I(o?.apiKey),effort:a,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:B(o?.requestTimeoutMs??o?.timeoutMs,Z),requestTotalTimeoutMs:B(o?.requestTotalTimeoutMs,Ae),requestRetryCount:F(o?.requestRetryCount,we),requestFirstByteTimeoutMs:Math.min(B(o?.requestFirstByteTimeoutMs,Ce),B(o?.requestTimeoutMs??o?.timeoutMs,Z)),requestStreamIdleTimeoutMs:Math.min(B(o?.requestStreamIdleTimeoutMs,_e),B(o?.requestTimeoutMs??o?.timeoutMs,Z)),mcpToolTimeoutMs:B(o?.mcpToolTimeoutMs,ee),mcpPollingToolTimeoutMs:F(o?.mcpPollingToolTimeoutMs,be),supportsImageInput:vt(s,t,o),contextLimit:F(le(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:F(le(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:F(le(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function U(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function Et(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function Nt(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function It(n){let e;try{e=new URL(n)}catch{throw new Error(`ACode image URL is invalid: ${n}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`ACode image URL protocol is not supported: ${e.protocol}`)}async function Pt(n){const e=await n.arrayBuffer();if(e.byteLength>Me)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${Me} bytes`);return Buffer.from(e).toString("base64")}async function Dt(n){const e=n.trim();if(Nt(e))return e;It(e);const t=await fetch(e);if(!t.ok)throw new Error(`ACode image fetch failed: ${t.status} ${await t.text()}`);const o=t.headers.get("content-type")||"",s=o.split(";")[0]?.trim().toLowerCase()||"";if(!s.startsWith("image/"))throw new Error(`ACode image URL did not return an image content type: ${o||"unknown"}`);return`data:${s};base64,${await Pt(t)}`}function Lt(n){const e=I(n.base64Data??n.base64??n.data);return e?Et(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function Ne(n,e,t,o){return`[Attached file: ${[n?`name=${n}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(a=>!!a).join(", ")}]`}function Ot(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,a=e.exec(n);for(;a!==null;){U(t,n.slice(s,a.index));const i=a[1],l=(a[2]||"").trim();if(i==="\u56FE\u7247"&&l)t.push({type:"image_url",image_url:{url:l}}),o=!0;else if(i==="\u6587\u4EF6"&&l){const[r="",u="",c="",g=""]=l.split("|").map(y=>y.trim());U(t,Ne(r,u,c,g))}else U(t,a[0]);s=a.index+a[0].length,a=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(U(t,n.slice(s)),{content:t,hasImages:o})}function Ut(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const a of s){if(!v(a))continue;const i=I(a.content);if(!i)continue;const l=I(a.senderName);U(n,l?`Message from ${l}:`:"Message:");const r=ue(i);Array.isArray(r.content)?n.push(...r.content):U(n,r.content),t=t||r.hasImages}return t}function qt(n){let e;try{e=JSON.parse(n)}catch{return}if(!v(e))return;const t=[];let o=Ut(t,e);const s=I(e.text)||"",a=Array.isArray(e.attachments)?e.attachments:[];U(t,s);for(const i of a){if(!v(i))continue;const l=i;if(String(l.type??l.kind??"").toLowerCase()==="image"){const c=Lt(l);c&&(t.push({type:"image_url",image_url:{url:c}}),o=!0);continue}const u=I(l.url??l.serverUrl)||"";U(t,Ne(I(l.name)||"",u,I(l.mediaType??l.mimeType)||"",I(l.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function ue(n){return qt(n)??Ot(n)}async function Ie(n){if(!Array.isArray(n))return n;const e=[];for(const t of n){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await Dt(t.image_url.url)}})}return e}function Bt(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function zt(n,e){const t=n.permissions??e.permissions??{},o=n.permissions?[]:e.allowedTools??[],s=n.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(a=>a.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(a=>a.trim()).filter(Boolean)}}function Ft(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function jt(n){return n.kind==="builtin"?[n.exposedName,n.toolName,`builtin.${n.toolName}`]:[n.exposedName,n.toolName,`${n.serverName}.${n.toolName}`,`mcp.${n.serverName}.${n.toolName}`]}function Pe(n,e){return jt(e).some(t=>Ft(n,t))}function De(n,e,t){if(e.length>0&&!e.some(o=>Pe(o,n)))throw new Error(t)}function ce(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>Pe(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);De(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),De(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function Wt(n,e,t){try{return ce(n,e,t),!0}catch{return!1}}function oe(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function Jt(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(oe(e.toString()));return`${t.origin}${t.pathname}`}catch{return oe(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function Kt(n){const e=[...n].reverse().find(o=>o.role==="user"),t=Bt(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function Le(n){try{const e=JSON.parse(n);return ye(e)?e:{}}catch{return{}}}function Ht(n,e,t){if(new Set([Ve,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(a)||a<=0?Math.max(t,bt):Math.min(Math.floor(a),10*6e4)+2e3}function Qt(n,e){const t=n.trim();return`ACode \u5DF2\u63A5\u6536\u4EFB\u52A1\u3002\u5F53\u524D\u5DF2\u52A0\u8F7D ${e.configMcpCount} \u4E2A MCP \u914D\u7F6E\u3001${e.exposedTools.length} \u4E2A MCP Tool \u4E0E ${e.skills.length} \u4E2A Skill\u3002${t?`\u8F93\u5165\u6458\u8981\uFF1A${t.slice(0,200)}`:""}`}function D(n){if(!v(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>v(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
- `)}return JSON.stringify(n)}function G(n){return n instanceof Error?n.message:String(n)}function Gt(n){let e=16;if(typeof n.content=="string")e+=n.content.length*2;else if(Array.isArray(n.content))for(const t of n.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return n.tool_calls&&(e+=JSON.stringify(n.tool_calls).length),n.tool_call_id&&(e+=n.tool_call_id.length),e}async function Yt(n,e,t,o,s){let a=0;for(const l of n)a+=Gt(l);if(a<=e)return 0;const i=await he(n,t,o,{llmSummarizer:s});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:fe(n,{llmSummarizer:s,contextLimit:t})}function Oe(n){const e=G(n).toLowerCase();return e.includes("context_length_exceeded")||e.includes("context length")||e.includes("maximum context")||e.includes("max context")||e.includes("token limit")||e.includes("tokens exceed")||e.includes("too many tokens")||e.includes("input is too long")||e.includes("prompt is too long")||e.includes("request too large")||e.includes("413")}function Vt(n){const e=G(n).toLowerCase();return Oe(n)?!1:e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||/\b(408|429|500|502|503|504|520|521|522|523|524)\b/.test(e)}function Xt(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=G(n).toLowerCase();return e===-32001||t.includes("request timed out")}function Zt(n){if(typeof n=="object"&&n!==null){const e=Reflect.get(n,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(n,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function eo(n,e){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:Zt(e),message:G(e)}})}function Ue(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function to(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(v(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function oo(n){return n.length===0?"":["Skills are available for this session.","Use the `skill` tool to load specialized skill instructions when a user task matches one of the available skills listed in the tool description.","Do not attempt to follow skill instructions from memory \u2014 always invoke the `skill` tool first to load the full content."].join(" ")}function no(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
3
- `)}function so(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,a=e.instanceName,i=e.projectId,l=e.workspacePath,r=e.runtimeMode,u=e.describe;return typeof o=="string"&&o.trim()&&t.push(`Display Name: ${o.trim()}`),typeof s=="string"&&s.trim()&&t.push(`Role: ${s.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Instance: ${a.trim()}`),typeof i=="string"&&i.trim()&&t.push(`Project: ${i.trim()}`),typeof l=="string"&&l.trim()&&t.push(`Workspace: ${l.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Runtime Mode: ${r.trim()}`),typeof u=="string"&&u.trim()&&t.push(`Description: ${u.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
4
- `)}function qe(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function io(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function ro(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function ao(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,lo(e)?uo(t):t]))}function lo(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function uo(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function co(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function mo(n,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=n.get(t)??{id:e.id||`call-${t}`,type:"function",function:{name:"",arguments:""}};e.id&&(o.id=e.id),e.function?.name&&(o.function.name+=e.function.name),e.function?.arguments&&(o.function.arguments+=e.function.arguments),n.set(t,o)}function po(n){return[...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}class j extends je{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:Z,requestTotalTimeoutMs:Ae,requestRetryCount:we,requestFirstByteTimeoutMs:Ce,requestStreamIdleTimeoutMs:_e,mcpToolTimeoutMs:ee,mcpPollingToolTimeoutMs:be,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new pe([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0},this.abortController=null,this.exposedToolsInitialized=!1,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.submitQueue=Promise.resolve(),this.activeTurn=!1,this.abortRequested=!1,this.toolSettleSlot=null,this.toolSettleSeq=0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.hookBus=new dt({sessionId:e.sessionId,onError:(t,o)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${t.name}: ${o instanceof Error?o.message:String(o)}`})}});for(const t of e.hooks??[])this.hookBus.register(t)}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:yt(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s})}handleCompactionPhase(e,t){switch(t.phase){case"prune_start":this.emitCompactionPhase(e,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u6B63\u5728\u88C1\u526A ${t.messageCount??0} \u6761\u6D88\u606F\u4E2D\u7684\u5DE5\u5177\u8F93\u51FA...`);break;case"prune_end":this.emitCompactionPhase(e,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${t.prunedCount??0} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${t.freedTokens??0} tokens`);break;case"summarize_start":this.emitCompactionPhase(e,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6B63\u5728\u6458\u8981 ${t.messageCount??0} \u6761\u65E9\u671F\u5BF9\u8BDD...`);break;case"summarize_end":this.emitCompactionPhase(e,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${t.summarizedCount??0} \u6761\u6D88\u606F${t.usedLLM?" (LLM \u6458\u8981)":" (\u89C4\u5219\u6458\u8981)"}`);break}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await ct(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),a=xt(this.config,e);m(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${a.model}, baseURL=${a.baseURL??"(none)"}, apiKey=${a.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const i=zt(this.config,e),l=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},a.mcpToolTimeoutMs),r=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const u=await this.fetchProfilePrompt(l),c=this.config.agentId||"unknown";st(c),K.reconcileOrphans(c);const g=Ye(this.config.workingDirectory,c,this.config.onFileChange,{manager:K,emitCompleted:p=>{this.emitAcodeEvent("background_command_completed",p)}}),y=Xe(this.buildAskUserQuestionDeps(),()=>this.contextVersion),w=Ze(t);this.skillTool=w;const d=et(c),b=tt(c),h=this.config.subAgentManager?ot(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],f=nt(this.buildAwaitCompleteDeps()),C=this.config.terminalManager?it(c,{terminalManager:this.config.terminalManager}):null,_=[...g,y,w,d,b,...h,f,...C?[C]:[],...l.flatMap(p=>p.tools),...this.config.extraBuiltInTools??[]],k=this.config.subagentType==="explore"?_.filter(p=>!wt.has(p.exposedName)):_,T=this.resolveCommandDirs(e);this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const $=await rt(T),N=new pe($),A=oo(t),R=no($),x=[a.systemPrompt,A,R].map(p=>p?.trim()).filter(p=>!!p).join(`
1
+ import{EventEmitter as je}from"node:events";import J from"node:fs";import We from"node:os";import V from"node:path";import{Client as Je}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Ke}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as He}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Qe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as Ge}from"@modelcontextprotocol/sdk/types.js";import{createBuiltInFileTools as Ye}from"./built-in-file-tools.js";import{ASK_USER_QUESTION_TOOL_NAME as Ve,createAskUserQuestionTool as Xe}from"./ask-user-question-tool.js";import{createSkillTool as Ze}from"./skill-tool.js";import{createTodoWriteTool as et,createTodoReadTool as tt}from"./todo-tool.js";import{createSubAgentTools as ot}from"./sub-agent-tools.js";import{createAwaitCompleteTool as nt}from"./await-complete-tool.js";import{cleanupAcodeCmdDist as st}from"./builtins/commandArtifacts.js";import{backgroundCommandManager as K}from"./background-command-manager.js";import{createTerminalTool as it}from"./terminal-tool.js";import{loadAcodeCommands as rt}from"./commands/commandLoader.js";import{ACodeCommandRegistry as pe}from"./commands/commandRegistry.js";import{calculateCompactionThreshold as at,COMPACTION_LLM_PROMPT_TEMPLATE as ct,conversationSizeKB as H,estimateConversationTokens as X,performCompaction as he,pruneToolOutputs as lt,summarizeConversation as fe}from"./compaction.js";import{loadAcodeConfig as ut,loadAcodeSkillGroup as mt}from"./config.js";import{ACodeHookBus as dt,findDeniedHookResult as se}from"./hooks/hookBus.js";import{isMcpPollingToolName as pt,getSemanticToolName as ge}from"./mcpToolNames.js";function ht(n){return n.type==="text"?{type:"text",text:n.text}:{type:"image_url",image_url:{url:n.image_url.url}}}function ft(n){return{id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}}function gt(n){const e={role:n.role,content:Array.isArray(n.content)?n.content.map(ht):n.content};return n.tool_call_id&&(e.tool_call_id=n.tool_call_id),n.tool_calls&&(e.tool_calls=n.tool_calls.map(ft)),e}function ie(n){return n.map(gt)}function yt(){return new Date().toISOString()}function v(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function ye(n){return v(n)}function Ae(n,e){return e.map(t=>({serverName:n,toolName:t.name,kind:"mcp",exposedName:io(n,t.name),description:t.description,inputSchema:ye(t.inputSchema)?t.inputSchema:{type:"object",properties:{}}}))}function I(n){return String(n??"").trim()||void 0}const Z=6e4,Te=10*6e4,Ce=2e4,_e=3e4,we=3,re=-1,At=1e3,Tt=3e4,ee=6e4,be=0,Ct=2147483647,_t=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),wt=new Set(["write_file","edit_file","delete_file"]),bt=10*6e4+2e3,$t=1e4,$e=5e3,Me=10*60*1e3,Se=10*1024*1024,Re=800*1024,te=process.env.ACODE_COMPACTION_DEBUG==="1",ke=te?V.join(We.tmpdir(),"acode-compaction-debug.log"):"";function l(...n){te&&console.log(...n)}const Mt=64e3;function ae(n){const e=n.contextLimit&&n.contextLimit>0?n.contextLimit:Mt,t=n.maxOutput&&n.maxOutput>0?n.maxOutput:8192,o=n.inputLimit&&n.inputLimit>0?n.inputLimit:void 0,s=at(e,t,o);return{contextLimit:e,maxOutput:t,inputLimit:o,threshold:s}}async function x(n,e,t,o){if(e<=0)return await n;let s;try{return await new Promise((a,i)=>{s=setTimeout(()=>{o?.(),i(new Error(`${t} timed out after ${e}ms`))},e),n.then(a,i)})}finally{s&&clearTimeout(s)}}async function Q(n,e,t,o=$t){try{await x(e,o,n)}catch(s){t(s instanceof Error?s.message:String(s))}}function F(n,e){if(n===0||n==="0")return 0;const t=typeof n=="number"?n:Number(n);return t===re?re:Number.isFinite(t)&&t>0?Math.floor(t):e}function B(n,e){const t=F(n,e);return t>0?t:e}const ve=3;function xe(n){return n?Math.ceil(n.length/ve):0}function St(n,e){let t=n.length;for(const o of e){const s=(o.kind==="mcp",o.toolName);if(t+=s.length,o.kind==="mcp")o.description&&(t+=o.description.length),t+=JSON.stringify(o.inputSchema).length;else{const a=o;a.inputSchema&&(t+=JSON.stringify(a.inputSchema).length)}}return Math.ceil(t/ve)}function Ee(n){if(n.length===0)return 0;const e=JSON.stringify(qe(n));return xe(e)}async function Rt(n){await new Promise(e=>setTimeout(e,n))}function kt(n){return typeof n=="boolean"}function vt(n,e,t){if(kt(t?.supportsImageInput))return t.supportsImageInput;const o=v(e)?e.models:void 0,s=v(o)?o[n]:void 0;if(!v(s))return!1;const a=s.modalities;return!v(a)||!Array.isArray(a.input)?!1:a.input.some(i=>String(i||"").trim().toLowerCase()==="image")}function ce(n,e,t,o){if(n!==void 0)return n;if(!e)return;const s=e.models;if(v(s)){const a=s[t];if(v(a)){const i=a[o];if(i!==void 0)return i}}return e[o]}function xt(n,e){const t=e.provider?.default,o=t?.options,s=n.model||t?.model||e.model||"acode-default",a=I(n.effort)||I(o?.effort)||I(t?.effort)||void 0;return{model:s,baseURL:I(o?.baseURL||o?.baseUrl),apiKey:I(o?.apiKey),effort:a,systemPrompt:n.systemPrompt||e.systemPrompt,stream:o?.stream!==!1,requestTimeoutMs:B(o?.requestTimeoutMs??o?.timeoutMs,Z),requestTotalTimeoutMs:B(o?.requestTotalTimeoutMs,Te),requestRetryCount:F(o?.requestRetryCount,we),requestFirstByteTimeoutMs:Math.min(B(o?.requestFirstByteTimeoutMs,Ce),B(o?.requestTimeoutMs??o?.timeoutMs,Z)),requestStreamIdleTimeoutMs:Math.min(B(o?.requestStreamIdleTimeoutMs,_e),B(o?.requestTimeoutMs??o?.timeoutMs,Z)),mcpToolTimeoutMs:B(o?.mcpToolTimeoutMs,ee),mcpPollingToolTimeoutMs:F(o?.mcpPollingToolTimeoutMs,be),supportsImageInput:vt(s,t,o),contextLimit:F(ce(o?.contextLimit,t,s,"contextLimit"),0)||void 0,inputLimit:F(ce(o?.inputLimit,t,s,"inputLimit"),0)||void 0,maxOutput:F(ce(o?.maxOutput,t,s,"maxOutput"),0)||void 0}}function U(n,e){const t=e.replace(/\s+/g," ").trim();t&&n.push({type:"text",text:t})}function Et(n,e){const t=e.trim();return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t)?t:`data:${n||"image/png"};base64,${t}`}function Nt(n){return/^data:image\/[a-z0-9.+-]+;base64,/i.test(n.trim())}function It(n){let e;try{e=new URL(n)}catch{throw new Error(`ACode image URL is invalid: ${n}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`ACode image URL protocol is not supported: ${e.protocol}`)}async function Pt(n){const e=await n.arrayBuffer();if(e.byteLength>Se)throw new Error(`ACode image is too large to inline: ${e.byteLength} bytes exceeds ${Se} bytes`);return Buffer.from(e).toString("base64")}async function Dt(n){const e=n.trim();if(Nt(e))return e;It(e);const t=await fetch(e);if(!t.ok)throw new Error(`ACode image fetch failed: ${t.status} ${await t.text()}`);const o=t.headers.get("content-type")||"",s=o.split(";")[0]?.trim().toLowerCase()||"";if(!s.startsWith("image/"))throw new Error(`ACode image URL did not return an image content type: ${o||"unknown"}`);return`data:${s};base64,${await Pt(t)}`}function Lt(n){const e=I(n.base64Data??n.base64??n.data);return e?Et(I(n.mediaType??n.mimeType)||"image/png",e):I(n.url??n.serverUrl)}function Ne(n,e,t,o){return`[Attached file: ${[n?`name=${n}`:void 0,e?`url=${e}`:void 0,t?`mediaType=${t}`:void 0,o?`size=${o}`:void 0].filter(a=>!!a).join(", ")}]`}function Ot(n){const e=/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,t=[];let o=!1,s=0,a=e.exec(n);for(;a!==null;){U(t,n.slice(s,a.index));const i=a[1],c=(a[2]||"").trim();if(i==="\u56FE\u7247"&&c)t.push({type:"image_url",image_url:{url:c}}),o=!0;else if(i==="\u6587\u4EF6"&&c){const[r="",u="",m="",g=""]=c.split("|").map(y=>y.trim());U(t,Ne(r,u,m,g))}else U(t,a[0]);s=a.index+a[0].length,a=e.exec(n)}return t.length===0?{content:n,hasImages:!1}:(U(t,n.slice(s)),{content:t,hasImages:o})}function Ut(n,e){let t=!1;const o=[e.directMessages,e.groupMessages];for(const s of o)if(Array.isArray(s))for(const a of s){if(!v(a))continue;const i=I(a.content);if(!i)continue;const c=I(a.senderName);U(n,c?`Message from ${c}:`:"Message:");const r=le(i);Array.isArray(r.content)?n.push(...r.content):U(n,r.content),t=t||r.hasImages}return t}function qt(n){let e;try{e=JSON.parse(n)}catch{return}if(!v(e))return;const t=[];let o=Ut(t,e);const s=I(e.text)||"",a=Array.isArray(e.attachments)?e.attachments:[];U(t,s);for(const i of a){if(!v(i))continue;const c=i;if(String(c.type??c.kind??"").toLowerCase()==="image"){const m=Lt(c);m&&(t.push({type:"image_url",image_url:{url:m}}),o=!0);continue}const u=I(c.url??c.serverUrl)||"";U(t,Ne(I(c.name)||"",u,I(c.mediaType??c.mimeType)||"",I(c.size)||""))}return t.length===0?{content:n,hasImages:!1}:{content:t,hasImages:o}}function le(n){return qt(n)??Ot(n)}async function Ie(n){if(!Array.isArray(n))return n;const e=[];for(const t of n){if(t.type==="text"){e.push(t);continue}e.push({type:"image_url",image_url:{url:await Dt(t.image_url.url)}})}return e}function Bt(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e.type==="text"?e.text:"[Image]").join(" ").trim():""}function zt(n,e){const t=n.permissions??e.permissions??{},o=n.permissions?[]:e.allowedTools??[],s=n.permissions?[]:e.deniedTools??[];return{mode:t.mode??"default",allow:[...t.allow??[],...o].map(a=>a.trim()).filter(Boolean),deny:[...t.deny??[],...s].map(a=>a.trim()).filter(Boolean)}}function Ft(n,e){return n==="*"?!0:n.endsWith("*")?e.startsWith(n.slice(0,-1)):n===e}function jt(n){return n.kind==="builtin"?[n.exposedName,n.toolName,`builtin.${n.toolName}`]:[n.exposedName,n.toolName,`${n.serverName}.${n.toolName}`,`mcp.${n.serverName}.${n.toolName}`]}function Pe(n,e){return jt(e).some(t=>Ft(n,t))}function De(n,e,t){if(e.length>0&&!e.some(o=>Pe(o,n)))throw new Error(t)}function ue(n,e,t){if(e.mode!=="bypassPermissions"){if(e.deny.some(o=>Pe(o,n)))throw new Error(`ACode tool denied by permission rule: ${n.exposedName}`);De(n,e.allow,`ACode tool is not in allowed permission rules: ${n.exposedName}`),De(n,t??[],`ACode slash command does not allow tool: ${n.exposedName}`)}}function Wt(n,e,t){try{return ue(n,e,t),!0}catch{return!1}}function oe(n){const e=n.replace(/\/+$/g,"");return/\/chat\/completions$/i.test(e)?e:`${e}/chat/completions`}function Jt(n){try{const e=new URL(n);e.search="",e.hash="";const t=new URL(oe(e.toString()));return`${t.origin}${t.pathname}`}catch{return oe(n).replace(/([?&](?:api[_-]?key|token|authorization)=)[^&]+/gi,"$1[redacted]")}}function Kt(n){const e=[...n].reverse().find(o=>o.role==="user"),t=Bt(e?.content??null).trim();if(t)return t.length>300?`${t.slice(0,300)}...`:t}function Le(n){try{const e=JSON.parse(n);return ye(e)?e:{}}catch{return{}}}function Ht(n,e,t){if(new Set([Ve,"await_complete"]).has(n.toolName))return 0;if(n.toolName!=="Bash")return t;const s=e.timeout_ms??e.timeoutMs,a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;return!Number.isFinite(a)||a<=0?Math.max(t,bt):Math.min(Math.floor(a),10*6e4)+2e3}function Qt(n,e){const t=n.trim();return`ACode \u5DF2\u63A5\u6536\u4EFB\u52A1\u3002\u5F53\u524D\u5DF2\u52A0\u8F7D ${e.configMcpCount} \u4E2A MCP \u914D\u7F6E\u3001${e.exposedTools.length} \u4E2A MCP Tool \u4E0E ${e.skills.length} \u4E2A Skill\u3002${t?`\u8F93\u5165\u6458\u8981\uFF1A${t.slice(0,200)}`:""}`}function P(n){if(!v(n))return String(n??"");const e=n.content;if(Array.isArray(e)){const t=e.map(o=>v(o)?typeof o.text=="string"?o.text:JSON.stringify(o):"").filter(Boolean);if(t.length>0)return t.join(`
2
+ `)}return JSON.stringify(n)}function G(n){return n instanceof Error?n.message:String(n)}function Gt(n){let e=16;if(typeof n.content=="string")e+=n.content.length*2;else if(Array.isArray(n.content))for(const t of n.content)typeof t=="object"&&t!==null&&(e+=JSON.stringify(t).length);return n.tool_calls&&(e+=JSON.stringify(n.tool_calls).length),n.tool_call_id&&(e+=n.tool_call_id.length),e}async function Yt(n,e,t,o,s){let a=0;for(const c of n)a+=Gt(c);if(a<=e)return 0;const i=await he(n,t,o,{llmSummarizer:s});return i.strategy!=="none"?i.prunedToolMessages+i.summarizedMessages:fe(n,{llmSummarizer:s,contextLimit:t})}function Oe(n){const e=G(n).toLowerCase();return e.includes("context_length_exceeded")||e.includes("context length")||e.includes("maximum context")||e.includes("max context")||e.includes("token limit")||e.includes("tokens exceed")||e.includes("too many tokens")||e.includes("input is too long")||e.includes("prompt is too long")||e.includes("request too large")||e.includes("413")}function Vt(n){const e=G(n).toLowerCase();return Oe(n)?!1:e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||/\b(408|429|500|502|503|504|520|521|522|523|524)\b/.test(e)}function Xt(n){if(typeof n!="object"||n===null)return!1;const e=Reflect.get(n,"code"),t=G(n).toLowerCase();return e===-32001||t.includes("request timed out")}function Zt(n){if(typeof n=="object"&&n!==null){const e=Reflect.get(n,"code");if(typeof e=="string"&&e)return e;const t=Reflect.get(n,"name");if(typeof t=="string"&&t)return t}return"tool_error"}function eo(n,e){return JSON.stringify({ok:!1,tool:n.exposedName,error:{type:Zt(e),message:G(e)}})}function Ue(n){const e=JSON.stringify(n);return e.length>500?`${e.slice(0,500)}\u2026`:e}function to(n){const e=[n?.reasoning_content,n?.reasoning_text,n?.reasoning];for(const t of e){if(typeof t=="string"&&t)return t;if(v(t)){const o=t.text??t.content;if(typeof o=="string"&&o)return o}}return""}function oo(n){return n.length===0?"":["Skills are available for this session.","Use the `skill` tool to load specialized skill instructions when a user task matches one of the available skills listed in the tool description.","Do not attempt to follow skill instructions from memory \u2014 always invoke the `skill` tool first to load the full content."].join(" ")}function no(n){return n.length===0?"":["Available slash commands:",...n.map(e=>`- /${e.name}${e.description?`: ${e.description}`:""}`),"When the user invokes a slash command, ACode expands it before model execution."].join(`
3
+ `)}function so(n){if(!n||typeof n!="object")return"";const e=n,t=[],o=e.displayName,s=e.roleName,a=e.instanceName,i=e.projectId,c=e.workspacePath,r=e.runtimeMode,u=e.describe;return typeof o=="string"&&o.trim()&&t.push(`Display Name: ${o.trim()}`),typeof s=="string"&&s.trim()&&t.push(`Role: ${s.trim()}`),typeof a=="string"&&a.trim()&&t.push(`Instance: ${a.trim()}`),typeof i=="string"&&i.trim()&&t.push(`Project: ${i.trim()}`),typeof c=="string"&&c.trim()&&t.push(`Workspace: ${c.trim()}`),typeof r=="string"&&r.trim()&&t.push(`Runtime Mode: ${r.trim()}`),typeof u=="string"&&u.trim()&&t.push(`Description: ${u.trim()}`),t.length===0?"":["[User Profile]",...t].join(`
4
+ `)}function qe(n){return n.map(e=>({type:"function",function:{name:e.exposedName,description:e.description||e.toolName,parameters:e.inputSchema}}))}function io(n,e){return`${n}__${e}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"mcp_tool"}function ro(n){const e={"Content-Type":"application/json"};return n.apiKey&&(e.Authorization=`Bearer ${n.apiKey}`),e}function ao(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,co(e)?lo(t):t]))}function co(n){const e=n.trim().toLowerCase();return e==="authorization"||e==="api-key"||e==="x-api-key"||e==="openai-api-key"}function lo(n){return n.trim().toLowerCase().startsWith("bearer ")?"Bearer ***":"***"}function uo(n){return n.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim()).filter(Boolean)}function mo(n,e){const t=Number.isFinite(e.index)?Number(e.index):0,o=n.get(t)??{id:e.id||`call-${t}`,type:"function",function:{name:"",arguments:""}};e.id&&(o.id=e.id),e.function?.name&&(o.function.name+=e.function.name),e.function?.arguments&&(o.function.arguments+=e.function.arguments),n.set(t,o)}function po(n){return[...n.entries()].sort(([e],[t])=>e-t).map(([,e])=>e).filter(e=>e.function.name.trim().length>0)}class j extends je{constructor(e){super(),this.config=e,this.initialConversation=[],this.state={started:!1,terminated:!1,configMcpCount:0,skills:[],provider:{model:"acode-default",stream:!1,requestTimeoutMs:Z,requestTotalTimeoutMs:Te,requestRetryCount:we,requestFirstByteTimeoutMs:Ce,requestStreamIdleTimeoutMs:_e,mcpToolTimeoutMs:ee,mcpPollingToolTimeoutMs:be,supportsImageInput:!1},permissions:{mode:"default",allow:[],deny:[]},mcpConnections:[],ownsMcpConnections:!0,exposedTools:[],commands:[],commandRegistry:new pe([]),conversation:[],accumulatedInputTokens:0,accumulatedOutputTokens:0},this.abortController=null,this.exposedToolsInitialized=!1,this.pendingMemorySubAgents=new Map,this.memoryDelegateCooldownUntil=new Map,this.submitQueue=Promise.resolve(),this.activeTurn=!1,this.forceMessagePending=!1,this.abortRequested=!1,this.toolSettleSlot=null,this.toolSettleSeq=0,this.pendingAwaitedSubIds=new Set,this.pendingAwaitedBgTaskIds=new Set,this.sessionCompleteEmitted=!1,this.contextVersion=0,this.stopWaiters=new Set,this.compactionDebugTimer=null,this.skillTool=null,this.skillWatchers=[],this.skillRefreshTimer=null,this.questionWaiters=new Map,this.hookBus=new dt({sessionId:e.sessionId,onError:(t,o)=>{this.emitAcodeEvent("error",{message:`ACode hook failed: ${t.name}: ${o instanceof Error?o.message:String(o)}`})}});for(const t of e.hooks??[])this.hookBus.register(t)}getAvailableTools(){return this.state.exposedTools.map(e=>e.exposedName)}emitAcodeEvent(e,t){const o={type:e,sessionId:this.config.sessionId,timestamp:yt(),data:t};this.emit("event",o)}emitCompactionPhase(e,t,o,s){this.emitAcodeEvent("context_compaction",{action:"phase",compactionId:e,parentId:e,phase:t,phaseLabel:o,phaseDetail:s})}handleCompactionPhase(e,t){switch(t.phase){case"prune_start":this.emitCompactionPhase(e,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u6B63\u5728\u88C1\u526A ${t.messageCount??0} \u6761\u6D88\u606F\u4E2D\u7684\u5DE5\u5177\u8F93\u51FA...`);break;case"prune_end":this.emitCompactionPhase(e,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${t.prunedCount??0} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${t.freedTokens??0} tokens`);break;case"summarize_start":this.emitCompactionPhase(e,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6B63\u5728\u6458\u8981 ${t.messageCount??0} \u6761\u65E9\u671F\u5BF9\u8BDD...`);break;case"summarize_end":this.emitCompactionPhase(e,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${t.summarizedCount??0} \u6761\u6D88\u606F${t.usedLLM?" (LLM \u6458\u8981)":" (\u89C4\u5219\u6458\u8981)"}`);break}}async start(){this.emitAcodeEvent("startup_phase",{phase:"loading_config"});const e=await ut(this.config.configPath);this.emitAcodeEvent("startup_phase",{phase:"loading_skills"});const{skills:t,skillGroups:o,watchedDirs:s}=await this.loadAllSkills(),a=xt(this.config,e);l(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 resolveProviderConfig \u7ED3\u679C: config.model=${this.config.model??"(undefined)"}, resolvedModel=${a.model}, baseURL=${a.baseURL??"(none)"}, apiKey=${a.apiKey?"[set]":"(none)"}, configPath=${this.config.configPath??"(none)"}`);const i=zt(this.config,e),c=this.config.sharedMcpConnections?this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections):await this.connectMcpServers(e.mcpServers??{},a.mcpToolTimeoutMs),r=!this.config.sharedMcpConnections;this.emitAcodeEvent("startup_phase",{phase:"fetching_profile"});const u=await this.fetchProfilePrompt(c),m=this.config.agentId||"unknown";st(m),K.reconcileOrphans(m);const g=Ye(this.config.workingDirectory,m,this.config.onFileChange,{manager:K,emitCompleted:p=>{this.emitAcodeEvent("background_command_completed",p)}}),y=Xe(this.buildAskUserQuestionDeps(),()=>this.contextVersion),w=Ze(t);this.skillTool=w;const d=et(m),b=tt(m),h=this.config.subAgentManager?ot(this.buildSubAgentToolDeps(this.config.subAgentManager)):[],f=nt(this.buildAwaitCompleteDeps()),C=this.config.terminalManager?it(m,{terminalManager:this.config.terminalManager}):null,_=[...g,y,w,d,b,...h,f,...C?[C]:[],...c.flatMap(p=>p.tools),...this.config.extraBuiltInTools??[]],k=this.config.subagentType==="explore"?_.filter(p=>!wt.has(p.exposedName)):_,A=this.resolveCommandDirs(e);this.emitAcodeEvent("startup_phase",{phase:"loading_commands"});const $=await rt(A),N=new pe($),T=oo(t),R=no($),E=[a.systemPrompt,T,R].map(p=>p?.trim()).filter(p=>!!p).join(`
5
5
 
6
- `),M=p=>p?.trim()?[{role:"system",content:p.trim()}]:[],S=[this.config.rolePrompt,u].map(p=>p?.trim()).filter(p=>!!p).join(`
6
+ `),S=p=>p?.trim()?[{role:"system",content:p.trim()}]:[],M=[this.config.rolePrompt,u].map(p=>p?.trim()).filter(p=>!!p).join(`
7
7
 
8
- `),L=[...M(this.config.globalPrompt),...M(S),...M(this.config.memory),...x?[{role:"system",content:x}]:[]],O=L.map(p=>p.content).filter(Boolean).join(`
8
+ `),L=[...S(this.config.globalPrompt),...S(M),...S(this.config.memory),...E?[{role:"system",content:E}]:[]],O=L.map(p=>p.content).filter(Boolean).join(`
9
9
 
10
- `);this.initialConversation=ie(L),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:a,permissions:i,mcpConnections:l,ownsMcpConnections:r,exposedTools:k,commands:$,commandRegistry:N,conversation:ie(L),accumulatedInputTokens:0,accumulatedOutputTokens:0},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:$.length});const P=ae(a);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:$.length,estimatedContextTokens:Mt(O,k),contextLimit:P.contextLimit,maxOutput:P.maxOutput,...P.inputLimit!==void 0?{inputLimit:P.inputLimit}:{},compactionThreshold:P.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:l.length,builtInToolCount:g.length,toolCount:k.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:k.map(p=>({name:p.exposedName,source:p.kind==="mcp"?`${p.serverName}.${p.toolName}`:`builtin.${p.toolName}`,description:p.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(p=>({name:p.name,description:p.description,directory:p.directory})),skillGroups:o.map(p=>({dir:p.dir,exists:p.exists,skills:p.skills.map(z=>({name:z.name,description:z.description,directory:z.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:$.length,commandDirs:T,commands:$.map(p=>({name:p.name,description:p.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=V.join(this.config.workingDirectory,".acode","skills"),o=V.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,a=[],i=[];for(const u of[e,t,o]){if(!u)continue;const c=V.resolve(u);if(!s.has(c)){s.add(c),a.push(await mt(u));try{await J.promises.access(c),i.push(c)}catch{}}}const l=new Map;for(const u of a)for(const c of u.skills)l.set(c.name,c);return{skills:[...l.values()],skillGroups:a,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=J.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=J.watch(t,()=>{this.scheduleSkillRefresh()})}catch{continue}}o&&(o.on("error",()=>{}),this.skillWatchers.push(o))}}scheduleSkillRefresh(){this.skillRefreshTimer&&clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=setTimeout(()=>{this.skillRefreshTimer=null,this.refreshSkills()},j.SKILL_REFRESH_DEBOUNCE_MS)}async refreshSkills(){if(!(!this.state.started||this.state.terminated))try{const{skills:e,skillGroups:t}=await this.loadAllSkills();this.skillTool&&this.skillTool.refresh(e),this.state.skills=e,this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:e.length,skills:e.map(o=>({name:o.name,description:o.description,directory:o.directory})),skillGroups:t.map(o=>({dir:o.dir,exists:o.exists,skills:o.skills.map(s=>({name:s.name,description:s.description,directory:s.directory}))}))}),m(`[skill-watch] Skills refreshed: ${e.length} skills (${e.map(o=>o.name).join(", ")||"none"})`,{sessionId:this.config.sessionId})}catch(e){console.error("[skill-watch] Failed to refresh skills:",e instanceof Error?e.message:e)}}stopSkillWatchers(){this.skillRefreshTimer&&(clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=null);for(const e of this.skillWatchers)try{e.close()}catch{}this.skillWatchers=[]}startCompactionDebugLog(){if(!te||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:a}=ae(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,l=X(this.state.conversation)+Ee(this.state.exposedTools),r=Math.max(i,l),u=H(this.state.conversation),c=this.state.started&&!this.state.terminated,g=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${u}KB`,`estimation=${l} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${a}`,`remainingToTrigger=${Math.max(0,a-i)}`,`isRunning=${c}`,`shouldCompact=${c?r>=a:!1}`,"---"].join(" | ");J.promises.appendFile(ke,g+`
11
- `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;m(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${t}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const o=this.submitQueue.then(()=>(m(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmit(e,t)));return this.submitQueue=o.catch(()=>{m("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),m("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}async resetContext(){if(!this.state.started||this.state.terminated)throw new Error("ACode runtime is not active");this.contextVersion+=1,this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.state.conversation=ie(this.initialConversation),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t){const o=Date.now();if(m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),m("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),m(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),m(`[ACodeRuntime] \u{1F522} Context version: ${t}`),m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const s=e.trim();let a=!1;try{m("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const i=Date.now(),l=await this.hookBus.dispatch("UserPromptSubmit",{prompt:s}),r=Date.now()-i;if(m(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${r}ms, results: ${l.length}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const u=se(l);if(u){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${u.message}`),this.emitAcodeEvent("error",{message:u.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}m("[ACodeRuntime] \u{1F50D} Expanding command if any...");const c=this.state.commandRegistry.expand(s),g=c?.prompt.trim()||s,y=c?.command.allowedTools;if(c&&(m(`[ACodeRuntime] \u{1F4CB} Slash command detected: ${c.command.name}`),this.emitAcodeEvent("command_status",{action:"slash_command",command:c.command.name,arguments:c.argumentsText,sourcePath:c.command.sourcePath})),!this.state.provider.baseURL||!this.state.provider.apiKey){m("[ACodeRuntime] \u26A0\uFE0F No provider configured, using fallback response");const _=Qt(g,this.state);this.emitAcodeEvent("assistant_delta",{text:_}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:_.length}}),a=!0,m("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}m("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const w=ue(g);if(w.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");m("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const d=await Ie(w.content);if(this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}m("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:d}),m(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),m("[ACodeRuntime] Starting runModelTurn...");const b=Date.now(),h=await this.runModelTurn(y,t),f=Date.now()-b;if(m(`[ACodeRuntime] \u2705 runModelTurn completed in ${f}ms`),m(`[ACodeRuntime] \u{1F4DD} Result: text=${h.text?h.text.slice(0,80)+(h.text.length>80?"...":""):"(empty)"}, finishReason=${h.finishReason||"(none)"}`),this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}h.text&&!this.state.provider.stream&&(m("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:h.text})),m("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:h.usage??{inputTokens:g.length,outputTokens:h.totalOutputTextLength??h.text.length},...h.responseBody?{responseBody:h.responseBody}:{},...h.finishReason?{finishReason:h.finishReason}:{}}),m(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(h.usage?"":" (estimated, no provider usage)")),a=!0;const C=Date.now()-o;m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),m(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${C}ms`),m("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(i){const l=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${l}ms:`,i instanceof Error?i.message:String(i)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",i instanceof Error?i.stack:"(no stack)"),this.isTurnSuperseded(t)){m("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){m("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),a=!0;return}m("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:i instanceof Error?i.message:String(i)}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0}finally{const i=Date.now()-o;m(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${i}ms`),m(`[ACodeRuntime] \u{1F50D} turnCompleted=${a}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurn=!1,this.abortRequested=!1,!a&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${i}ms. This indicates a code path that should have emitted turn_complete but didn't. Forcing failed turn_complete to prevent state stuck.`),this.emitAcodeEvent("error",{message:"ACode turn completed without proper completion event (internal error)"}),this.emitAcodeEvent("turn_complete",{failed:!0}),m("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(m(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,contextVersion:t})})}}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,s=this.config.workingDirectory,a=this.config;return{spawnSubAgent:async i=>{const l=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,workingDirectory:s,parentConfig:{...a,sharedMcpConnections:this.state?.mcpConnections}});return await e.start(l),{subId:l}},listSubAgents:async()=>{const i=e.listByParent(t),l=[],r=[];for(const u of i){const c={subId:u.subId,subagentType:u.subagentType,description:u.description,status:u.status,startedAt:u.startedAt,endedAt:u.endedAt,durationMs:u.durationMs};u.status==="pending"||u.status==="running"?l.push(c):r.push(c)}return r.sort((u,c)=>(c.endedAt??0)-(u.endedAt??0)),{running:l,history:r}},getSubAgentStatus:async i=>{const l=e.getSubAgent(i);return l?{subId:l.subId,subagentType:l.subagentType,description:l.description,status:l.status,startedAt:l.startedAt,endedAt:l.endedAt,durationMs:l.durationMs,prompt:l.prompt,result:l.result,errorMessage:l.errorMessage,contextSnapshot:l.contextSnapshot}:null},awaitSubAgents:async(i,l)=>{const r=new Set;for(const u of i)this.pendingAwaitedSubIds.add(u),r.add(u);try{return await e.awaitCompletion(i,l)}finally{for(const u of r)this.pendingAwaitedSubIds.delete(u)}},abortSubAgent:i=>e.abort(i)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,s)=>{for(const a of o)this.pendingAwaitedSubIds.add(a);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const a of o)this.pendingAwaitedSubIds.delete(a)}}:null,awaitBgCommands:(o,s)=>{for(const a of o)this.pendingAwaitedBgTaskIds.add(a);try{return K.awaitCompletion(e,o,s)}finally{for(const a of o)this.pendingAwaitedBgTaskIds.delete(a)}}}}submitQuestionAnswer(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(s=>{m(`[ACodeRuntime] \u26A0\uFE0F manager.abort(${o}) threw: ${s instanceof Error?s.message:String(s)}`)})}cancelPendingAwaitedBgTasks(){if(this.pendingAwaitedBgTaskIds.size===0)return;const e=this.config.agentId??"unknown",t=Array.from(this.pendingAwaitedBgTaskIds);m(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),K.interruptAwaits(e,t)}detachCurrentToolExecution(){const e=this.toolSettleSlot;return!e||!e.settlable||e.settled?!1:(e.settled=!0,e.resolveSettle?.(),m(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${e.toolName} (toolCallId=${e.toolCallId}) to background`),!0)}beginToolSettle(e,t,o){const s=e.toolName==="Bash"&&typeof t.wait_seconds=="number"&&t.wait_seconds>0,a=++this.toolSettleSeq;let i;const l=s?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:a,toolName:e.toolName,toolCallId:o,settlable:s,settled:!1,resolveSettle:i??null},{seq:a,signal:l}}clearToolSettle(e){this.toolSettleSlot?.seq===e&&(this.toolSettleSlot=null)}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.rejectAllQuestionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await Q("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await Q("ACode background commands shutdown",K.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),Q("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await Q("ACode Stop hooks",this.hookBus.dispatch("Stop",{reason:"session_stop"}),t=>{this.emitAcodeEvent("error",{message:t})}),this.state.terminated=!0,this.sessionCompleteEmitted||(this.sessionCompleteEmitted=!0,this.emitAcodeEvent("session_complete",{exitCode:0})),this.stopCompactionDebugLog(),this.stopSkillWatchers(),te)try{J.promises.appendFile(ke,`[${new Date().toISOString()}] runtime stopped | ---
12
- `,"utf-8").catch(()=>{})}catch{}}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",s,a,i,l="",r=0;m(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const u=50;for(let c=0;c<u;c+=1){if(m(`[ACodeRuntime] \u{1F504} Iteration ${c+1} starting...`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${c+1}, aborting`),{text:"",totalOutputTextLength:l.length};const g=Date.now(),y=await this.requestChatCompletion(e),w=Date.now()-g;if(m(`[ACodeRuntime] \u{1F916} AI request completed in ${w}ms, choices: ${y.choices?.length||0}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${c+1}`),{text:"",totalOutputTextLength:l.length};if(this.state.terminated)throw m(`[ACodeRuntime] Runtime terminated at iteration ${c+1}`),new Error("ACode runtime was stopped during the active turn");const d=y.choices?.[0];a=JSON.stringify(y,null,2),i=typeof d?.finish_reason=="string"?d.finish_reason:void 0;const b=d?.message,h=typeof b?.content=="string"?b.content:"",f=Array.isArray(b?.tool_calls)?b.tool_calls:[];if(m(`[ACodeRuntime] AI response: content=${h?h.slice(0,100)+(h.length>100?"...":""):"(empty)"}, toolCalls=${f.length}, finishReason=${i||"(none)"}`),y.usage){const T=y.usage.prompt_tokens??y.usage.input_tokens,$=y.usage.completion_tokens??y.usage.output_tokens;typeof T=="number"&&typeof $=="number"&&(s={inputTokens:T,outputTokens:$},r+=T,this.state.accumulatedInputTokens=T,this.state.accumulatedOutputTokens=$,m(`[ACodeRuntime] \u{1F4B0} Token usage: input=${T}, output=${$} (turn accumulated cost: input=${r})`))}if(this.state.conversation.push({role:"assistant",content:h||null,tool_calls:f.length>0?f:void 0}),h&&(o=h,l+=h,m(`[ACodeRuntime] \u2728 Captured assistant text: ${h.slice(0,80)}...`)),f.length===0)return m(`[ACodeRuntime] \u2705 No tool calls at iteration ${c+1}, completing turn`),{text:o,usage:s,responseBody:a,finishReason:i,totalOutputTextLength:l.length};const C=f.map(T=>T.function.name).join(", ");m(`[ACodeRuntime] \u{1F527} Executing ${f.length} tool(s) at iteration ${c+1}: ${C}`);const _=Date.now();await this.handleToolCalls(f,e,t);const k=Date.now()-_;if(m(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${k}ms at iteration ${c+1}`),this.isTurnSuperseded(t))return m(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${c+1}`),{text:"",totalOutputTextLength:l.length};m(`[ACodeRuntime] \u{1F504} Preparing iteration ${c+2}...`)}return console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: Reached safety limit of ${u} iterations! This indicates a potential infinite loop. Forcing turn completion.`),{text:o||`ACode \u5DF2\u8FBE\u5230\u5B89\u5168\u8FED\u4EE3\u4E0A\u9650\uFF08${u}\u6B21\uFF09\uFF0C\u5F3A\u5236\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD\u3002`,usage:s,responseBody:a,finishReason:i||"safety_iteration_limit_reached",totalOutputTextLength:l.length}}async summarizeConversationWithLLM(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured for LLM summarization");const s={"Content-Type":"application/json"};t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`);const a={model:t.model,stream:!1,messages:[{role:"system",content:"You are a helpful AI assistant tasked with summarizing conversations. When asked to summarize, provide a detailed but concise summary of the conversation. Focus on information that would be helpful for continuing the conversation, especially what was in progress and what needs to happen next. Do not respond to any questions in the conversation, only output the summary."},{role:"user",content:`Below is an earlier conversation (${e.messageCount} messages) that needs to be summarized to free context space (current context limit: ${e.contextLimit} tokens).
10
+ `);this.initialConversation=ie(L),this.state={started:!0,terminated:!1,configMcpCount:Object.keys(e.mcpServers??{}).length,skills:t,provider:a,permissions:i,mcpConnections:c,ownsMcpConnections:r,exposedTools:k,commands:$,commandRegistry:N,conversation:ie(L),accumulatedInputTokens:0,accumulatedOutputTokens:0},this.exposedToolsInitialized=!0,this.emitAcodeEvent("startup_phase",{phase:"session_start_hook"}),await this.hookBus.dispatch("SessionStart",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:$.length});const D=ae(a);this.emitAcodeEvent("session_started",{workingDirectory:this.config.workingDirectory,model:a.model,commandCount:$.length,estimatedContextTokens:St(O,k),contextLimit:D.contextLimit,maxOutput:D.maxOutput,...D.inputLimit!==void 0?{inputLimit:D.inputLimit}:{},compactionThreshold:D.threshold}),this.emitAcodeEvent("mcp_status",{configPath:this.config.configPath,installedCount:this.state.configMcpCount,servers:Object.keys(e.mcpServers??{}),connectedCount:c.length,builtInToolCount:g.length,toolCount:k.length,permissionMode:i.mode,allowedToolRules:i.allow,deniedToolRules:i.deny,tools:k.map(p=>({name:p.exposedName,source:p.kind==="mcp"?`${p.serverName}.${p.toolName}`:`builtin.${p.toolName}`,description:p.description||""}))}),this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:t.length,skills:t.map(p=>({name:p.name,description:p.description,directory:p.directory})),skillGroups:o.map(p=>({dir:p.dir,exists:p.exists,skills:p.skills.map(z=>({name:z.name,description:z.description,directory:z.directory}))}))}),this.emitAcodeEvent("command_status",{action:"commands_loaded",installedCommandCount:$.length,commandDirs:A,commands:$.map(p=>({name:p.name,description:p.description}))}),this.config.initialPrompt&&await this.submit(this.config.initialPrompt),this.startCompactionDebugLog(),this.startSkillWatchers(s)}async loadAllSkills(){const e=this.config.skillsDir??"",t=V.join(this.config.workingDirectory,".acode","skills"),o=V.join(this.config.workingDirectory,".agentswork","skills"),s=new Set,a=[],i=[];for(const u of[e,t,o]){if(!u)continue;const m=V.resolve(u);if(!s.has(m)){s.add(m),a.push(await mt(u));try{await J.promises.access(m),i.push(m)}catch{}}}const c=new Map;for(const u of a)for(const m of u.skills)c.set(m.name,m);return{skills:[...c.values()],skillGroups:a,watchedDirs:i}}startSkillWatchers(e){for(const t of e){let o=null;try{o=J.watch(t,{recursive:!0},()=>{this.scheduleSkillRefresh()})}catch{try{o=J.watch(t,()=>{this.scheduleSkillRefresh()})}catch{continue}}o&&(o.on("error",()=>{}),this.skillWatchers.push(o))}}scheduleSkillRefresh(){this.skillRefreshTimer&&clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=setTimeout(()=>{this.skillRefreshTimer=null,this.refreshSkills()},j.SKILL_REFRESH_DEBOUNCE_MS)}async refreshSkills(){if(!(!this.state.started||this.state.terminated))try{const{skills:e,skillGroups:t}=await this.loadAllSkills();this.skillTool&&this.skillTool.refresh(e),this.state.skills=e,this.emitAcodeEvent("skill_status",{skillsDir:this.config.skillsDir,installedCount:e.length,skills:e.map(o=>({name:o.name,description:o.description,directory:o.directory})),skillGroups:t.map(o=>({dir:o.dir,exists:o.exists,skills:o.skills.map(s=>({name:s.name,description:s.description,directory:s.directory}))}))}),l(`[skill-watch] Skills refreshed: ${e.length} skills (${e.map(o=>o.name).join(", ")||"none"})`,{sessionId:this.config.sessionId})}catch(e){console.error("[skill-watch] Failed to refresh skills:",e instanceof Error?e.message:e)}}stopSkillWatchers(){this.skillRefreshTimer&&(clearTimeout(this.skillRefreshTimer),this.skillRefreshTimer=null);for(const e of this.skillWatchers)try{e.close()}catch{}this.skillWatchers=[]}startCompactionDebugLog(){if(!te||this.compactionDebugTimer)return;const e=this.state.provider,{contextLimit:t,maxOutput:o,inputLimit:s,threshold:a}=ae(e);this.compactionDebugTimer=setInterval(()=>{try{const i=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,c=X(this.state.conversation)+Ee(this.state.exposedTools),r=Math.max(i,c),u=H(this.state.conversation),m=this.state.started&&!this.state.terminated,g=[`[${new Date().toISOString()}]`,`started=${this.state.started}`,`terminated=${this.state.terminated}`,`activeTurn=${this.activeTurn}`,`conversationSize=${this.state.conversation.length}msgs`,`sizeKB=${u}KB`,`estimation=${c} tokens`,`actualInput=${this.state.accumulatedInputTokens}`,`actualOutput=${this.state.accumulatedOutputTokens}`,`actualUsed=${i}`,`contextLimit=${t}`,`inputLimit=${s??"n/a"}`,`maxOutput=${o}`,`triggerThreshold=${a}`,`remainingToTrigger=${Math.max(0,a-i)}`,`isRunning=${m}`,`shouldCompact=${m?r>=a:!1}`,"---"].join(" | ");J.promises.appendFile(ke,g+`
11
+ `,"utf-8").catch(()=>{})}catch{}},5e3)}stopCompactionDebugLog(){this.compactionDebugTimer&&(clearInterval(this.compactionDebugTimer),this.compactionDebugTimer=null)}async submit(e){const t=this.contextVersion;l(`[ACodeRuntime] \u{1F4EC} submit() queued: contextVersion=${t}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, terminated=${this.state.terminated}, message.length=${e.length}`);const o=this.submitQueue.then(()=>(l(`[ACodeRuntime] \u25B6\uFE0F executeSubmit dequeued: contextVersion=${t}`),this.executeSubmit(e,t)));return this.submitQueue=o.catch(()=>{l("[ACodeRuntime] \u{1F4EC} submit() queued item rejected (catch swallowed)")}),l("[ACodeRuntime] \u{1F4EC} submit() returning queued promise"),o}notifyForceMessage(){this.forceMessagePending=!0,l("[ACodeRuntime] \u{1F514} Force message pending flag set")}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 l("[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=P(t);let s=[];try{const r=JSON.parse(o);Array.isArray(r?.directMessages)&&(s=r.directMessages.filter(u=>u?.force===!0))}catch{return!1}if(s.length===0)return!1;const a=JSON.stringify({directMessages:s,groupMessages:[]}),i=`forced_get_msg_${Date.now()}`,c=`${e.serverName}__get_message`;return this.state.conversation.push({role:"assistant",content:null,tool_calls:[{id:i,type:"function",function:{name:c,arguments:"{}"}}]}),this.state.conversation.push({role:"tool",tool_call_id:i,content:a}),l(`[ACodeRuntime] injectForceMessage: injected ${s.length} force message(s) into conversation`),!0}catch(t){return l(`[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=ie(this.initialConversation),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}isTurnSuperseded(e){return e!==this.contextVersion}async executeSubmit(e,t){const o=Date.now();if(l("[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"),l("[ACodeRuntime] \u25B6\uFE0F executeSubmit STARTED"),l(`[ACodeRuntime] Message: <redacted, length=${e.length}>`),l(`[ACodeRuntime] \u{1F522} Context version: ${t}`),l("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),!this.state.started||this.state.terminated)throw console.error(`[ACodeRuntime] \u274C Runtime not active (started: ${this.state.started}, terminated: ${this.state.terminated})`),new Error("ACode runtime is not active");this.activeTurn=!0,this.abortRequested=!1;const s=e.trim();let a=!1;try{l("[ACodeRuntime] \u{1F50D} Dispatching UserPromptSubmit hook...");const i=Date.now(),c=await this.hookBus.dispatch("UserPromptSubmit",{prompt:s}),r=Date.now()-i;if(l(`[ACodeRuntime] \u2705 UserPromptSubmit hook completed in ${r}ms, results: ${c.length}`),this.isTurnSuperseded(t)){l("[ACodeRuntime] \u26A0\uFE0F Turn superseded after hook, aborting");return}const u=se(c);if(u){console.error(`[ACodeRuntime] \u274C Prompt denied by hook: ${u.message}`),this.emitAcodeEvent("error",{message:u.message||"ACode prompt was denied by hook"}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0,l("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (failed=true) due to hook deny");return}l("[ACodeRuntime] \u{1F50D} Expanding command if any...");const m=this.state.commandRegistry.expand(s),g=m?.prompt.trim()||s,y=m?.command.allowedTools;if(m&&(l(`[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})),!this.state.provider.baseURL||!this.state.provider.apiKey){l("[ACodeRuntime] \u26A0\uFE0F No provider configured, using fallback response");const _=Qt(g,this.state);this.emitAcodeEvent("assistant_delta",{text:_}),this.emitAcodeEvent("turn_complete",{usage:{inputTokens:g.length,outputTokens:_.length}}),a=!0,l("[ACodeRuntime] \u{1F4E4} Emitted turn_complete (fallback mode)");return}l("[ACodeRuntime] \u{1F4CE} Parsing attachment message...");const w=le(g);if(w.hasImages&&!this.state.provider.supportsImageInput)throw console.error("[ACodeRuntime] \u274C Image input not supported by current provider"),new Error("ACode provider/model is not configured for image input. Enable provider.default.models[model].modalities.input including 'image' or options.supportsImageInput=true.");l("[ACodeRuntime] \u{1F5BC}\uFE0F Materializing image content if any...");const d=await Ie(w.content);if(this.isTurnSuperseded(t)){l("[ACodeRuntime] \uFE0F Turn superseded after materializing content, aborting");return}l("[ACodeRuntime] \u{1F4AC} Adding user message to conversation"),this.state.conversation.push({role:"user",content:d}),l(`[ACodeRuntime] Conversation size: ${this.state.conversation.length} messages`),l("[ACodeRuntime] Starting runModelTurn...");const b=Date.now(),h=await this.runModelTurn(y,t),f=Date.now()-b;if(l(`[ACodeRuntime] \u2705 runModelTurn completed in ${f}ms`),l(`[ACodeRuntime] \u{1F4DD} Result: text=${h.text?h.text.slice(0,80)+(h.text.length>80?"...":""):"(empty)"}, finishReason=${h.finishReason||"(none)"}`),this.isTurnSuperseded(t)){l("[ACodeRuntime] \uFE0F Turn superseded after runModelTurn, aborting");return}h.text&&!this.state.provider.stream&&(l("[ACodeRuntime] \u{1F4E4} Emitting assistant_delta (non-streaming mode)"),this.emitAcodeEvent("assistant_delta",{text:h.text})),l("[ACodeRuntime] \u{1F4E4} Emitting turn_complete..."),this.emitAcodeEvent("turn_complete",{usage:h.usage??{inputTokens:g.length,outputTokens:h.totalOutputTextLength??h.text.length},...h.responseBody?{responseBody:h.responseBody}:{},...h.finishReason?{finishReason:h.finishReason}:{}}),l(`[ACodeRuntime] \u{1F4B0} Current context usage: input=${this.state.accumulatedInputTokens}, output=${this.state.accumulatedOutputTokens}`+(h.usage?"":" (estimated, no provider usage)")),a=!0;const C=Date.now()-o;l("[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"),l(`[ACodeRuntime] \u2705 executeSubmit COMPLETED in ${C}ms`),l("[ACodeRuntime] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(i){const c=Date.now()-o;if(console.error(`[ACodeRuntime] \u274C executeSubmit FAILED after ${c}ms:`,i instanceof Error?i.message:String(i)),console.error("[ACodeRuntime] \u{1F50D} Error stack:",i instanceof Error?i.stack:"(no stack)"),this.isTurnSuperseded(t)){l("[ACodeRuntime] \uFE0F Turn superseded in error handler, skipping recovery");return}if(this.abortRequested){l("[ACodeRuntime] \u26A0\uFE0F Abort requested, emitting aborted turn_complete"),this.emitAcodeEvent("turn_complete",{aborted:!0}),a=!0;return}l("[ACodeRuntime] Emitting error and failed turn_complete..."),this.emitAcodeEvent("error",{message:i instanceof Error?i.message:String(i)}),this.emitAcodeEvent("turn_complete",{failed:!0}),a=!0}finally{const i=Date.now()-o;l(`[ACodeRuntime] \u{1F51A} executeSubmit finally block entered after ${i}ms`),l(`[ACodeRuntime] \u{1F50D} turnCompleted=${a}, activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, contextVersion=${t}, currentContextVersion=${this.contextVersion}`),this.activeTurn=!1,this.abortRequested=!1,!a&&!this.isTurnSuperseded(t)&&(console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: executeSubmit finally block reached without turn_complete event! Duration: ${i}ms. This indicates a code path that should have emitted turn_complete but didn't. Forcing failed turn_complete to prevent state stuck.`),this.emitAcodeEvent("error",{message:"ACode turn completed without proper completion event (internal error)"}),this.emitAcodeEvent("turn_complete",{failed:!0}),l("[ACodeRuntime] Emergency turn_complete (failed=true) emitted"))}}async abort(){const e=this.abortController!==null,t=this.activeTurn;this.abortRequested=this.activeTurn,this.abortController?(l(`[ACodeRuntime] \u26D4 abort() calling abortController.abort() (activeTurn=${t})`),this.abortController.abort()):console.warn(`[ACodeRuntime] \u26D4 abort() called but abortController is null! activeTurn=${t}, abortRequested will be set to ${t}. This means abort() CANNOT cancel any running fetch/stream \u2014 if a built-in tool is executing, it will NOT be interrupted.`),this.abortController=null,this.rejectAllQuestionWaiters("aborted"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),this.notifyRuntimeStop()}buildAskUserQuestionDeps(){return{onQuestion:(e,t)=>{this.emitAcodeEvent("question_request",{toolCallId:e,questions:t})},waitForAnswer:(e,t)=>new Promise((o,s)=>{this.questionWaiters.set(e,{resolve:o,reject:s,contextVersion:t})})}}buildSubAgentToolDeps(e){const t=this.config.agentId??"unknown",o=this.config.sessionId,s=this.config.workingDirectory,a=this.config;return{spawnSubAgent:async i=>{const c=await e.spawn({parentAgentId:t,parentSessionId:o,subagentType:i.subagentType,description:i.description,prompt:i.prompt,workingDirectory:s,parentConfig:{...a,sharedMcpConnections:this.state?.mcpConnections}});return await e.start(c),{subId:c}},listSubAgents:async()=>{const i=e.listByParent(t),c=[],r=[];for(const u of i){const m={subId:u.subId,subagentType:u.subagentType,description:u.description,status:u.status,startedAt:u.startedAt,endedAt:u.endedAt,durationMs:u.durationMs};u.status==="pending"||u.status==="running"?c.push(m):r.push(m)}return r.sort((u,m)=>(m.endedAt??0)-(u.endedAt??0)),{running:c,history:r}},getSubAgentStatus:async i=>{const c=e.getSubAgent(i);return c?{subId:c.subId,subagentType:c.subagentType,description:c.description,status:c.status,startedAt:c.startedAt,endedAt:c.endedAt,durationMs:c.durationMs,prompt:c.prompt,result:c.result,errorMessage:c.errorMessage,contextSnapshot:c.contextSnapshot}:null},awaitSubAgents:async(i,c)=>{const r=new Set;for(const u of i)this.pendingAwaitedSubIds.add(u),r.add(u);try{return await e.awaitCompletion(i,c)}finally{for(const u of r)this.pendingAwaitedSubIds.delete(u)}},abortSubAgent:i=>e.abort(i)}}buildAwaitCompleteDeps(){const e=this.config.agentId??"unknown",t=this.config.subAgentManager;return{agentId:e,awaitSubAgents:t?(o,s)=>{for(const a of o)this.pendingAwaitedSubIds.add(a);try{return this.buildSubAgentToolDeps(t).awaitSubAgents(o,s)}finally{for(const a of o)this.pendingAwaitedSubIds.delete(a)}}:null,awaitBgCommands:(o,s)=>{for(const a of o)this.pendingAwaitedBgTaskIds.add(a);try{return K.awaitCompletion(e,o,s)}finally{for(const a of o)this.pendingAwaitedBgTaskIds.delete(a)}}}}submitQuestionAnswer(e,t){const o=this.questionWaiters.get(e);return o?(this.questionWaiters.delete(e),this.isTurnSuperseded(o.contextVersion)?(o.reject(new Error("turn superseded before user answered")),!1):(o.resolve(t),!0)):!1}rejectAllQuestionWaiters(e){if(this.questionWaiters.size!==0){for(const[,t]of this.questionWaiters)t.reject(new Error(`ask_user_question ${e}`));this.questionWaiters.clear()}}cancelPendingAwaitedSubAgents(){if(this.pendingAwaitedSubIds.size===0)return;const e=this.config.subAgentManager;if(!e)return;const t=Array.from(this.pendingAwaitedSubIds);l(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited sub-agent(s): ${t.join(", ")}`);for(const o of t)e.abort(o).catch(s=>{l(`[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);l(`[ACodeRuntime] \u26D4 Cancelling ${t.length} pending awaited background command(s): ${t.join(", ")}`),K.interruptAwaits(e,t)}detachCurrentToolExecution(){const e=this.toolSettleSlot;return!e||!e.settlable||e.settled?!1:(e.settled=!0,e.resolveSettle?.(),l(`[ACodeRuntime] \u{1F680} detachCurrentToolExecution: settling tool ${e.toolName} (toolCallId=${e.toolCallId}) to background`),!0)}beginToolSettle(e,t,o){const s=e.toolName==="Bash"&&typeof t.wait_seconds=="number"&&t.wait_seconds>0,a=++this.toolSettleSeq;let i;const c=s?new Promise(r=>{i=r}):void 0;return this.toolSettleSlot={seq:a,toolName:e.toolName,toolCallId:o,settlable:s,settled:!1,resolveSettle:i??null},{seq:a,signal:c}}clearToolSettle(e){this.toolSettleSlot?.seq===e&&(this.toolSettleSlot=null)}async stop(){if(this.state.terminated)return;this.state.terminated=!0,this.notifyRuntimeStop(),this.abortRequested=this.activeTurn,this.abortController?.abort(),this.abortController=null,this.rejectAllQuestionWaiters("session terminated"),this.cancelPendingAwaitedSubAgents(),this.cancelPendingAwaitedBgTasks(),await Q("ACode active turn shutdown",this.submitQueue,t=>{this.emitAcodeEvent("error",{message:t})}),await this.disconnectMcpServers();const e=this.config.agentId||"unknown";if(await Q("ACode background commands shutdown",K.disposeAgent(e),t=>{this.emitAcodeEvent("error",{message:t})}),Q("ACode agent PTY sessions shutdown",Promise.resolve(this.config.terminalManager?.killByAgent?.(e)),t=>{this.emitAcodeEvent("error",{message:t})}),await Q("ACode Stop hooks",this.hookBus.dispatch("Stop",{reason:"session_stop"}),t=>{this.emitAcodeEvent("error",{message:t})}),this.state.terminated=!0,this.sessionCompleteEmitted||(this.sessionCompleteEmitted=!0,this.emitAcodeEvent("session_complete",{exitCode:0})),this.stopCompactionDebugLog(),this.stopSkillWatchers(),te)try{J.promises.appendFile(ke,`[${new Date().toISOString()}] runtime stopped | ---
12
+ `,"utf-8").catch(()=>{})}catch{}}resolveCommandDirs(e){const t=[...this.config.commandDirs??[],...e.commandDirs??[],...e.commands?.directories??[]];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}async runModelTurn(e,t=this.contextVersion){let o="",s,a,i,c="",r=0;l(`[ACodeRuntime] \u25B6\uFE0F runModelTurn started (contextVersion: ${t})`);const u=50;for(let m=0;m<u;m+=1){if(l(`[ACodeRuntime] \u{1F504} Iteration ${m+1} starting...`),this.isTurnSuperseded(t))return l(`[ACodeRuntime] \u26A0\uFE0F Turn superseded at iteration ${m+1}, aborting`),{text:"",totalOutputTextLength:c.length};await this.injectForceMessage();const g=Date.now(),y=await this.requestChatCompletion(e),w=Date.now()-g;if(l(`[ACodeRuntime] \u{1F916} AI request completed in ${w}ms, choices: ${y.choices?.length||0}`),this.isTurnSuperseded(t))return l(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after AI response at iteration ${m+1}`),{text:"",totalOutputTextLength:c.length};if(this.state.terminated)throw l(`[ACodeRuntime] Runtime terminated at iteration ${m+1}`),new Error("ACode runtime was stopped during the active turn");const d=y.choices?.[0];a=JSON.stringify(y,null,2),i=typeof d?.finish_reason=="string"?d.finish_reason:void 0;const b=d?.message,h=typeof b?.content=="string"?b.content:"",f=Array.isArray(b?.tool_calls)?b.tool_calls:[];if(l(`[ACodeRuntime] AI response: content=${h?h.slice(0,100)+(h.length>100?"...":""):"(empty)"}, toolCalls=${f.length}, finishReason=${i||"(none)"}`),y.usage){const A=y.usage.prompt_tokens??y.usage.input_tokens,$=y.usage.completion_tokens??y.usage.output_tokens;typeof A=="number"&&typeof $=="number"&&(s={inputTokens:A,outputTokens:$},r+=A,this.state.accumulatedInputTokens=A,this.state.accumulatedOutputTokens=$,l(`[ACodeRuntime] \u{1F4B0} Token usage: input=${A}, output=${$} (turn accumulated cost: input=${r})`))}if(this.state.conversation.push({role:"assistant",content:h||null,tool_calls:f.length>0?f:void 0}),h&&(o=h,c+=h,l(`[ACodeRuntime] \u2728 Captured assistant text: ${h.slice(0,80)}...`)),f.length===0)return l(`[ACodeRuntime] \u2705 No tool calls at iteration ${m+1}, completing turn`),{text:o,usage:s,responseBody:a,finishReason:i,totalOutputTextLength:c.length};const C=f.map(A=>A.function.name).join(", ");l(`[ACodeRuntime] \u{1F527} Executing ${f.length} tool(s) at iteration ${m+1}: ${C}`);const _=Date.now();await this.handleToolCalls(f,e,t);const k=Date.now()-_;if(l(`[ACodeRuntime] \u2699\uFE0F Tool execution completed in ${k}ms at iteration ${m+1}`),this.isTurnSuperseded(t))return l(`[ACodeRuntime] \u26A0\uFE0F Turn superseded after tool execution at iteration ${m+1}`),{text:"",totalOutputTextLength:c.length};l(`[ACodeRuntime] \u{1F504} Preparing iteration ${m+2}...`)}return console.error(`[ACodeRuntime] \u{1F6A8} CRITICAL: Reached safety limit of ${u} iterations! This indicates a potential infinite loop. Forcing turn completion.`),{text:o||`ACode \u5DF2\u8FBE\u5230\u5B89\u5168\u8FED\u4EE3\u4E0A\u9650\uFF08${u}\u6B21\uFF09\uFF0C\u5F3A\u5236\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD\u3002`,usage:s,responseBody:a,finishReason:i||"safety_iteration_limit_reached",totalOutputTextLength:c.length}}async summarizeConversationWithLLM(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured for LLM summarization");const s={"Content-Type":"application/json"};t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`);const a={model:t.model,stream:!1,messages:[{role:"system",content:"You are a helpful AI assistant tasked with summarizing conversations. When asked to summarize, provide a detailed but concise summary of the conversation. Focus on information that would be helpful for continuing the conversation, especially what was in progress and what needs to happen next. Do not respond to any questions in the conversation, only output the summary."},{role:"user",content:`Below is an earlier conversation (${e.messageCount} messages) that needs to be summarized to free context space (current context limit: ${e.contextLimit} tokens).
13
13
 
14
14
  --- Conversation Start ---
15
15
  ${e.conversationText}
16
16
  --- Conversation End ---
17
17
 
18
- `+lt}]},i=new AbortController;this.abortController=i;let l=!1;try{return await E((async()=>{const r=await E(fetch(oe(o),{method:"POST",headers:s,body:JSON.stringify(a),signal:i.signal}),t.requestTimeoutMs,"ACode LLM summarization",()=>{l=!0,i.abort()});if(!r.ok){const g=await E(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{l=!0,i.abort()}),y=g.length>500?`${g.slice(0,500)}...(truncated, total ${g.length} chars)`:g;throw new Error(`ACode LLM summarization request failed: ${r.status} ${y}`)}const c=(await E(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{l=!0,i.abort()})).choices?.[0]?.message?.content;if(!c||c.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return c})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{i.abort()})}catch(r){throw r instanceof Error&&r.name==="AbortError"?l?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):r}finally{this.abortController===i&&(this.abortController=null)}}async requestChatCompletion(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured");const{contextLimit:s,maxOutput:a,inputLimit:i,threshold:l}=ae(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,u=X(this.state.conversation)+Ee(this.state.exposedTools),c=Math.max(r,u),g=c>=l;if(m(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${u}, effectiveUsed=${c}, contextLimit=${s}, inputLimit=${i??"n/a"}, maxOutput=${a}, triggerThreshold=${l}, shouldCompact=${g}`),g){const A=H(this.state.conversation),R=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:R,sizeKB:A,estimatedTokens:u,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:r>=l?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(R,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${c} tokens, \u9608\u503C: ${l}, \u89E6\u53D1: ${r>=l?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const x=await he(this.state.conversation,s,a,{llmSummarizer:S=>this.summarizeConversationWithLLM(S),onPhase:S=>this.handleCompactionPhase(R,S),actualUsedTokens:c}),M=H(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:R,sizeBeforeKB:A,sizeAfterKB:M,freedKB:Math.round((A-M)*10)/10,strategy:x.strategy,freedTokens:x.freedTokens,tokensBefore:x.tokensBefore,tokensAfter:x.tokensAfter,prunedToolMessages:x.prunedToolMessages,summarizedMessages:x.summarizedMessages,messageCountBefore:x.messageCountBefore,messageCountAfter:x.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const y=await Yt(this.state.conversation,Re,s,a,A=>this.summarizeConversationWithLLM(A));y>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${y} older messages to fit within ${Re} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const w=this.state.exposedTools.filter(A=>Wt(A,this.state.permissions,e)),d=()=>{const A={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(A.reasoning_effort=t.effort),t.stream&&(A.stream_options={include_usage:!0}),w.length>0&&(A.tools=qe(w),A.tool_choice="auto"),A},b="POST",h=Jt(o),f=ro(t),C=ao(f),_=A=>{const R=JSON.stringify(A,null,2);m(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${h}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:h,requestMethod:b,requestUrl:h,requestHeaders:C,stream:t.stream,messageCount:this.state.conversation.length,toolCount:w.length,lastUserMessagePreview:Kt(this.state.conversation),estimatedContextTokens:xe(R),requestBody:R})};let k=d();_(k);const T=t.requestRetryCount===re,$=T?1/0:t.requestRetryCount+1;let N=!1;for(let A=1;T||A<=$;A+=1){this.state.terminated||(this.abortRequested=!1),A>1&&_(k);const R=new AbortController;this.abortController=R;let x=!1;try{return await E((async()=>{const M=await E(fetch(oe(o),{method:b,headers:f,body:JSON.stringify(k),signal:R.signal}),t.requestFirstByteTimeoutMs,"ACode provider request",()=>{x=!0,R.abort()});if(!M.ok){const O=await E(M.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{x=!0,R.abort()}),P=O.length>500?`${O.slice(0,500)}...(truncated, total ${O.length} chars)`:O;throw new Error(`ACode provider request failed: ${M.status} ${P}`)}const S=M.headers?.get?.("content-type")||"";if(t.stream&&S.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(M,t.requestStreamIdleTimeoutMs,R,t.requestFirstByteTimeoutMs);const L=await E(M.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{x=!0,R.abort()});return v(L)?L:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof L}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{R.abort()})}catch(M){let S;if(M instanceof Error&&M.name==="AbortError"?x?S=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?S=new Error("ACode provider request aborted by user"):S=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):S=M instanceof Error?M:new Error(String(M)),!N&&!this.abortRequested&&!this.state.terminated&&Oe(S)){const p=H(this.state.conversation),z=X(this.state.conversation),ne=this.state.conversation.length,q=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:q,sizeKB:p,estimatedTokens:z,messageCount:ne,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(q,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${ne}\u6761, \u5927\u5C0F: ${p}KB`),this.emitCompactionPhase(q,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const W=ut(this.state.conversation,s);this.emitCompactionPhase(q,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${W.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${W.freedTokens} tokens`),this.emitCompactionPhase(q,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const Y=await fe(this.state.conversation,{llmSummarizer:Fe=>this.summarizeConversationWithLLM(Fe),contextLimit:s});this.emitCompactionPhase(q,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${Y} \u6761\u6D88\u606F`);const me=H(this.state.conversation),Be=X(this.state.conversation),ze=this.state.conversation.length;N=!0;const de=W.prunedCount+Y;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:q,sizeBeforeKB:p,sizeAfterKB:me,freedKB:Math.round((p-me)*10)/10,tokensBefore:z,tokensAfter:Be,messageCountBefore:ne,messageCountAfter:ze,strategy:Y>0?"summarize":"prune",freedTokens:W.freedTokens,prunedToolMessages:W.prunedCount,summarizedMessages:Y,trigger:"provider_overflow_error"}),de===0)throw S;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${de} older messages and rebuilt the request instead of retrying the same oversized payload`}),k=d(),_(k),A-=1;continue}if(!((T||A<$)&&!this.abortRequested&&!this.state.terminated&&Vt(S)))throw S;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${A}${T?"":`/${$}`} failed; retrying: ${S.message}`,nonFatal:!0});const O=Math.min(At,Tt*Math.pow(2,A-1)),P=Math.random()*1e3;await Rt(O+P)}finally{this.abortController===R&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,s){if(!e.body)throw new Error("ACode provider stream response has no body");const a=e.body.getReader(),i=new TextDecoder,l=new Map;let r="",u="",c;const g=w=>{for(const d of co(w)){if(d==="[DONE]")continue;const b=JSON.parse(d);if(!v(b))continue;const h=b.usage;h&&(c=h);const C=b.choices?.[0]?.delta,_=to(C);_&&this.emitAcodeEvent("thinking_delta",{text:_});const k=typeof C?.content=="string"?C.content:"";k&&(r+=k,this.emitAcodeEvent("assistant_delta",{text:k}));const T=Array.isArray(C?.tool_calls)?C.tool_calls:[];for(const $ of T)mo(l,$)}};let y=!0;for(;;){const w=y&&s?s:t,{done:d,value:b}=await E(a.read(),w,y?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(y=!1,d)break;u+=i.decode(b,{stream:!0});const h=u.split(/\r?\n\r?\n/);u=h.pop()??"";for(const f of h)g(f)}return u+=i.decode(),u.trim()&&g(u),{choices:[{message:{content:r||null,tool_calls:po(l)}}],...c?{usage:c}:{}}}async handleToolCalls(e,t,o=this.contextVersion){m(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=i=>ge(i.function.name)==="poll_message",a=[...e.filter(i=>!s(i)),...e.filter(i=>s(i))];e.length>1&&a.some((i,l)=>i!==e[l])&&m(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${a.map(i=>i.function.name).join(", ")}`);for(const i of a){if(this.isTurnSuperseded(o)){m("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const l=i.function.name;m(`[ACodeRuntime] \u{1F50D} Looking up tool: ${l}`);let r=this.state.exposedTools.find(u=>u.exposedName===l);if(r||(r=this.state.exposedTools.find(u=>u.toolName===l),r&&m(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${l} -> ${r.exposedName}`)),!r){console.error(`[ACodeRuntime] \u274C Tool not found: ${l}, available tools: ${this.state.exposedTools.map(u=>u.exposedName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP tool not found: ${l}`});continue}m(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const _=Le(i.function.arguments);m(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(_).slice(0,200)}`),ce(r,this.state.permissions,t);const k=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:_});if(this.isTurnSuperseded(o))return;const T=se(k);if(T)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${T.message}`),new Error(T.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:_,argumentsPreview:Ue(_)});const $=Date.now(),N=Ht(r,_,this.state.provider.mcpToolTimeoutMs);m(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${N}ms, abortRequested: ${this.abortRequested})`),N<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${N})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const A=this.beginToolSettle(r,_,i.id);try{const R=await E(r.execute(_,{onOutput:S=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:S.stream,text:S.text,sequence:S.sequence,cwd:S.cwd,commandLineCount:S.commandLineCount,...S.commandFilePath?{commandFilePath:S.commandFilePath}:{}})},toolCallId:i.id,...A.signal?{settleSignal:A.signal}:{}}),N,`ACode built-in tool ${r.toolName}`),x=Date.now()-$;if(m(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${x}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,result:D(R)}),this.isTurnSuperseded(o)))return;const M=D(R);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${M.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,result:M}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:M}),await this.appendSyntheticMultimodalUserMessage(M,i.id,o)}finally{this.clearToolSettle(A.seq)}continue}const u=this.state.mcpConnections.find(_=>_.serverName===r.serverName);if(!u){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(_=>_.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const c=Le(i.function.arguments);m(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(c).slice(0,200)}`),ce(r,this.state.permissions,t);const g=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:c});if(this.isTurnSuperseded(o))return;const y=se(g);if(y)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${y.message}`),new Error(y.message||`ACode tool denied by hook: ${r.exposedName}`);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.serverName,tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:c,argumentsPreview:Ue(c)});const w=pt(r.toolName),d=w?this.state.provider.mcpPollingToolTimeoutMs:this.state.provider.mcpToolTimeoutMs,b=Date.now();m(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${d}ms, polling: ${w})`);const h=w&&ge(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(u,r,c,d):await this.callMcpToolWithTimeout(u,r,c,d,w),f=Date.now()-b;if(m(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${f}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:D(h)}),this.isTurnSuperseded(o)))return;const C=D(h);m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${C.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,result:C}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:C}),await this.appendSyntheticMultimodalUserMessage(C,i.id,o)}catch(u){const c=u instanceof Error&&u.message.includes("timed out after"),g=u instanceof Error&&u.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${c}, isAbortError=${g}`,u instanceof Error?u.message:String(u)),this.isTurnSuperseded(o)){m("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw m(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),m(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,result:`[aborted] ${u instanceof Error?u.message:String(u)}`,failed:!0,aborted:!0}),u instanceof Error?u:new Error(String(u));m(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${c})`),this.appendToolFailureResult(i,r,u)}}m(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,s,a){const i=s>0?s:Ct,r=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const u=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await E(Promise.race([e.client.callTool({name:t.toolName,arguments:r},void 0,{timeout:i}),u.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(c){if(!a||s>0||!Xt(c))throw c;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{u.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
18
+ `+ct}]},i=new AbortController;this.abortController=i;let c=!1;try{return await x((async()=>{const r=await x(fetch(oe(o),{method:"POST",headers:s,body:JSON.stringify(a),signal:i.signal}),t.requestTimeoutMs,"ACode LLM summarization",()=>{c=!0,i.abort()});if(!r.ok){const g=await x(r.text(),t.requestTimeoutMs,"ACode LLM summarization error response body",()=>{c=!0,i.abort()}),y=g.length>500?`${g.slice(0,500)}...(truncated, total ${g.length} chars)`:g;throw new Error(`ACode LLM summarization request failed: ${r.status} ${y}`)}const m=(await x(r.json(),t.requestTimeoutMs,"ACode LLM summarization response body",()=>{c=!0,i.abort()})).choices?.[0]?.message?.content;if(!m||m.trim().length===0)throw new Error("ACode LLM summarization returned empty content");return m})(),t.requestTotalTimeoutMs,"ACode LLM summarization total",()=>{i.abort()})}catch(r){throw r instanceof Error&&r.name==="AbortError"?c?new Error(`ACode LLM summarization timed out after ${t.requestTimeoutMs}ms`):new Error("ACode LLM summarization aborted"):r}finally{this.abortController===i&&(this.abortController=null)}}async requestChatCompletion(e){const t=this.state.provider,o=t.baseURL;if(!o)throw new Error("ACode provider baseURL is not configured");const{contextLimit:s,maxOutput:a,inputLimit:i,threshold:c}=ae(t),r=this.state.accumulatedInputTokens+this.state.accumulatedOutputTokens,u=X(this.state.conversation)+Ee(this.state.exposedTools),m=Math.max(r,u),g=m>=c;if(l(`[ACodeRuntime] \u{1F50D} Compaction check: actualUsed=${r}, estimation=${u}, effectiveUsed=${m}, contextLimit=${s}, inputLimit=${i??"n/a"}, maxOutput=${a}, triggerThreshold=${c}, shouldCompact=${g}`),g){const T=H(this.state.conversation),R=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:R,sizeKB:T,estimatedTokens:u,actualInputTokens:this.state.accumulatedInputTokens,actualOutputTokens:this.state.accumulatedOutputTokens,messageCount:this.state.conversation.length,model:t.model,trigger:r>=c?"actual_usage":"estimated_overflow"}),this.emitCompactionPhase(R,"detect","\u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6709\u6548\u7528\u91CF: ${m} tokens, \u9608\u503C: ${c}, \u89E6\u53D1: ${r>=c?"\u5B9E\u9645\u7528\u91CF":"\u4F30\u7B97\u6EA2\u51FA"}`);const E=await he(this.state.conversation,s,a,{llmSummarizer:M=>this.summarizeConversationWithLLM(M),onPhase:M=>this.handleCompactionPhase(R,M),actualUsedTokens:m}),S=H(this.state.conversation);this.emitAcodeEvent("context_compaction",{action:"end",compactionId:R,sizeBeforeKB:T,sizeAfterKB:S,freedKB:Math.round((T-S)*10)/10,strategy:E.strategy,freedTokens:E.freedTokens,tokensBefore:E.tokensBefore,tokensAfter:E.tokensAfter,prunedToolMessages:E.prunedToolMessages,summarizedMessages:E.summarizedMessages,messageCountBefore:E.messageCountBefore,messageCountAfter:E.messageCountAfter}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0}const y=await Yt(this.state.conversation,Re,s,a,T=>this.summarizeConversationWithLLM(T));y>0&&(this.emitAcodeEvent("warning",{message:`Conversation truncated: removed ${y} older messages to fit within ${Re} byte request size limit`}),this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0);const w=this.state.exposedTools.filter(T=>Wt(T,this.state.permissions,e)),d=()=>{const T={model:t.model,messages:this.state.conversation,stream:t.stream};return t.effort&&(T.reasoning_effort=t.effort),t.stream&&(T.stream_options={include_usage:!0}),w.length>0&&(T.tools=qe(w),T.tool_choice="auto"),T},b="POST",h=Jt(o),f=ro(t),C=ao(f),_=T=>{const R=JSON.stringify(T,null,2);l(`[ACodeRuntime] \u2605\u2605\u2605 DEBUG \u2605\u2605\u2605 emitAiRequest: \u53D1\u9001\u8BF7\u6C42 model=${t.model}, endpoint=${h}, messageCount=${this.state.conversation.length}`),this.emitAcodeEvent("ai_request",{model:t.model,endpoint:h,requestMethod:b,requestUrl:h,requestHeaders:C,stream:t.stream,messageCount:this.state.conversation.length,toolCount:w.length,lastUserMessagePreview:Kt(this.state.conversation),estimatedContextTokens:xe(R),requestBody:R})};let k=d();_(k);const A=t.requestRetryCount===re,$=A?1/0:t.requestRetryCount+1;let N=!1;for(let T=1;A||T<=$;T+=1){this.state.terminated||(this.abortRequested=!1),T>1&&_(k);const R=new AbortController;this.abortController=R;let E=!1;try{return await x((async()=>{const S=await x(fetch(oe(o),{method:b,headers:f,body:JSON.stringify(k),signal:R.signal}),t.requestFirstByteTimeoutMs,"ACode provider request",()=>{E=!0,R.abort()});if(!S.ok){const O=await x(S.text(),t.requestStreamIdleTimeoutMs,"ACode provider error response body",()=>{E=!0,R.abort()}),D=O.length>500?`${O.slice(0,500)}...(truncated, total ${O.length} chars)`:O;throw new Error(`ACode provider request failed: ${S.status} ${D}`)}const M=S.headers?.get?.("content-type")||"";if(t.stream&&M.toLowerCase().includes("text/event-stream"))return await this.readChatCompletionStream(S,t.requestStreamIdleTimeoutMs,R,t.requestFirstByteTimeoutMs);const L=await x(S.json(),t.requestStreamIdleTimeoutMs,"ACode provider response body",()=>{E=!0,R.abort()});return v(L)?L:(this.emitAcodeEvent("warning",{message:`ACode provider returned invalid response format (expected object, got ${typeof L}); treating as empty response`}),{})})(),t.requestTotalTimeoutMs,"ACode provider request total",()=>{R.abort()})}catch(S){let M;if(S instanceof Error&&S.name==="AbortError"?E?M=new Error(`ACode provider request timed out (firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):this.state.terminated?M=new Error("ACode provider request aborted by user"):M=new Error(`ACode provider request timed out (watchdog abort, firstByte=${t.requestFirstByteTimeoutMs}ms, idle=${t.requestStreamIdleTimeoutMs}ms)`):M=S instanceof Error?S:new Error(String(S)),!N&&!this.abortRequested&&!this.state.terminated&&Oe(M)){const p=H(this.state.conversation),z=X(this.state.conversation),ne=this.state.conversation.length,q=`compaction-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.emitAcodeEvent("context_compaction",{action:"start",compactionId:q,sizeKB:p,estimatedTokens:z,messageCount:ne,model:t.model,trigger:"provider_overflow_error"}),this.emitCompactionPhase(q,"detect","Provider \u8FD4\u56DE\u4E0A\u4E0B\u6587\u6EA2\u51FA",`\u6D88\u606F: ${ne}\u6761, \u5927\u5C0F: ${p}KB`),this.emitCompactionPhase(q,"prune","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA","\u6B63\u5728\u88C1\u526A...");const W=lt(this.state.conversation,s);this.emitCompactionPhase(q,"prune_done","\u9636\u6BB51: \u88C1\u526A\u5DE5\u5177\u8F93\u51FA",`\u88C1\u526A\u4E86 ${W.prunedCount} \u6761\u5DE5\u5177\u8F93\u51FA, \u91CA\u653E ${W.freedTokens} tokens`),this.emitCompactionPhase(q,"summarize","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD","\u6B63\u5728\u6458\u8981...");const Y=await fe(this.state.conversation,{llmSummarizer:Fe=>this.summarizeConversationWithLLM(Fe),contextLimit:s});this.emitCompactionPhase(q,"summarize_done","\u9636\u6BB52: \u6458\u8981\u5316\u5BF9\u8BDD",`\u6458\u8981\u5316\u4E86 ${Y} \u6761\u6D88\u606F`);const me=H(this.state.conversation),Be=X(this.state.conversation),ze=this.state.conversation.length;N=!0;const de=W.prunedCount+Y;if(this.emitAcodeEvent("context_compaction",{action:"end",compactionId:q,sizeBeforeKB:p,sizeAfterKB:me,freedKB:Math.round((p-me)*10)/10,tokensBefore:z,tokensAfter:Be,messageCountBefore:ne,messageCountAfter:ze,strategy:Y>0?"summarize":"prune",freedTokens:W.freedTokens,prunedToolMessages:W.prunedCount,summarizedMessages:Y,trigger:"provider_overflow_error"}),de===0)throw M;this.state.accumulatedInputTokens=0,this.state.accumulatedOutputTokens=0,this.emitAcodeEvent("warning",{message:`ACode provider context limit exceeded; summarized ${de} older messages and rebuilt the request instead of retrying the same oversized payload`}),k=d(),_(k),T-=1;continue}if(!((A||T<$)&&!this.abortRequested&&!this.state.terminated&&Vt(M)))throw M;this.emitAcodeEvent("error",{message:`ACode provider request attempt ${T}${A?"":`/${$}`} failed; retrying: ${M.message}`,nonFatal:!0});const O=Math.min(Tt,At*Math.pow(2,T-1)),D=Math.random()*1e3;await Rt(O+D)}finally{this.abortController===R&&(this.abortController=null)}}throw new Error("ACode provider request failed after all retries")}async readChatCompletionStream(e,t,o,s){if(!e.body)throw new Error("ACode provider stream response has no body");const a=e.body.getReader(),i=new TextDecoder,c=new Map;let r="",u="",m;const g=w=>{for(const d of uo(w)){if(d==="[DONE]")continue;const b=JSON.parse(d);if(!v(b))continue;const h=b.usage;h&&(m=h);const C=b.choices?.[0]?.delta,_=to(C);_&&this.emitAcodeEvent("thinking_delta",{text:_});const k=typeof C?.content=="string"?C.content:"";k&&(r+=k,this.emitAcodeEvent("assistant_delta",{text:k}));const A=Array.isArray(C?.tool_calls)?C.tool_calls:[];for(const $ of A)mo(c,$)}};let y=!0;for(;;){const w=y&&s?s:t,{done:d,value:b}=await x(a.read(),w,y?"ACode provider stream first byte":"ACode provider stream idle",()=>o?.abort());if(y=!1,d)break;u+=i.decode(b,{stream:!0});const h=u.split(/\r?\n\r?\n/);u=h.pop()??"";for(const f of h)g(f)}return u+=i.decode(),u.trim()&&g(u),{choices:[{message:{content:r||null,tool_calls:po(c)}}],...m?{usage:m}:{}}}async handleToolCalls(e,t,o=this.contextVersion){l(`[ACodeRuntime] handleToolCalls started with ${e.length} tool(s)`);const s=i=>ge(i.function.name)==="poll_message",a=[...e.filter(i=>!s(i)),...e.filter(i=>s(i))];e.length>1&&a.some((i,c)=>i!==e[c])&&l(`[ACodeRuntime] \u2195\uFE0F Reordered tool calls (poll_message \u2192 end): ${a.map(i=>i.function.name).join(", ")}`);for(const i of a){if(this.isTurnSuperseded(o)){l("[ACodeRuntime] \uFE0F Turn superseded, skipping remaining tools");return}const c=i.function.name;l(`[ACodeRuntime] \u{1F50D} Looking up tool: ${c}`);let r=this.state.exposedTools.find(u=>u.exposedName===c);if(r||(r=this.state.exposedTools.find(u=>u.toolName===c),r&&l(`[ACodeRuntime] \u21A9\uFE0F \u88F8\u540D\u56DE\u9000\u5339\u914D: ${c} -> ${r.exposedName}`)),!r){console.error(`[ACodeRuntime] \u274C Tool not found: ${c}, available tools: ${this.state.exposedTools.map(u=>u.exposedName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP tool not found: ${c}`});continue}l(`[ACodeRuntime] Found tool: ${r.toolName} (kind: ${r.kind}, source: ${r.kind==="mcp"?r.serverName:"builtin"})`);try{if(r.kind==="builtin"){const _=Le(i.function.arguments);l(`[ACodeRuntime] Built-in tool arguments: ${JSON.stringify(_).slice(0,200)}`),ue(r,this.state.permissions,t);const k=await this.hookBus.dispatch("PreToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,arguments:_});if(this.isTurnSuperseded(o))return;const A=se(k);if(A)throw console.error(`[ACodeRuntime] \u274C Tool denied by hook: ${r.exposedName}: ${A.message}`),new Error(A.message||`ACode tool denied by hook: ${r.exposedName}`);l(`[ACodeRuntime] Emitting mcp_status call_tool for ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:_,argumentsPreview:Ue(_)});const $=Date.now(),N=Ht(r,_,this.state.provider.mcpToolTimeoutMs);l(`[ACodeRuntime] \u25B6\uFE0F Executing built-in tool: ${r.exposedName} (timeout: ${N}ms, abortRequested: ${this.abortRequested})`),N<=0&&console.warn(`[ACodeRuntime] \u26A0\uFE0F Built-in tool ${r.exposedName} has NO timeout (timeoutMs=${N})! If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);const T=this.beginToolSettle(r,_,i.id);try{const R=await x(r.execute(_,{onOutput:M=>{this.emitAcodeEvent("command_output",{server:"builtin",tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,stream:M.stream,text:M.text,sequence:M.sequence,cwd:M.cwd,commandLineCount:M.commandLineCount,...M.commandFilePath?{commandFilePath:M.commandFilePath}:{}})},toolCallId:i.id,...T.signal?{settleSignal:T.signal}:{}}),N,`ACode built-in tool ${r.toolName}`),E=Date.now()-$;if(l(`[ACodeRuntime] \u2705 Built-in tool ${r.exposedName} completed in ${E}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"builtin",toolName:r.toolName,exposedName:r.exposedName,result:P(R)}),this.isTurnSuperseded(o)))return;const S=P(R);l(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for ${r.exposedName}, result length: ${S.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:"builtin",tool:r.toolName,result:S}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:S}),await this.appendSyntheticMultimodalUserMessage(S,i.id,o)}finally{this.clearToolSettle(T.seq)}continue}const u=this.state.mcpConnections.find(_=>_.serverName===r.serverName);if(!u){console.error(`[ACodeRuntime] \u274C MCP server not connected: ${r.serverName}, connected servers: ${this.state.mcpConnections.map(_=>_.serverName).join(", ")}`),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:`ACode MCP server not connected: ${r.serverName}`});continue}const m=Le(i.function.arguments);l(`[ACodeRuntime] MCP tool arguments: ${JSON.stringify(m).slice(0,200)}`),ue(r,this.state.permissions,t);const g=await this.hookBus.dispatch("PreToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,arguments:m});if(this.isTurnSuperseded(o))return;const y=se(g);if(y)throw console.error(`[ACodeRuntime] \u274C MCP tool denied by hook: ${r.exposedName}: ${y.message}`),new Error(y.message||`ACode tool denied by hook: ${r.exposedName}`);l(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status call_tool for MCP ${r.exposedName}`),this.emitAcodeEvent("mcp_status",{action:"call_tool",server:r.serverName,tool:r.toolName,exposedName:r.exposedName,toolUseId:i.id,arguments:m,argumentsPreview:Ue(m)});const w=pt(r.toolName),d=w?this.state.provider.mcpPollingToolTimeoutMs:this.state.provider.mcpToolTimeoutMs,b=Date.now();l(`[ACodeRuntime] \u25B6\uFE0F Executing MCP tool: ${r.exposedName} (timeout: ${d}ms, polling: ${w})`);const h=w&&ge(r.toolName)==="poll_message"?await this.callPollMessageWithSubAgentRace(u,r,m,d):await this.callMcpToolWithTimeout(u,r,m,d,w),f=Date.now()-b;if(l(`[ACodeRuntime] \u2705 MCP tool ${r.exposedName} completed in ${f}ms`),this.isTurnSuperseded(o)||(await this.hookBus.dispatch("PostToolUse",{source:"mcp",serverName:r.serverName,toolName:r.toolName,exposedName:r.exposedName,result:P(h)}),this.isTurnSuperseded(o)))return;const C=P(h);l(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result for MCP ${r.exposedName}, result length: ${C.length} chars`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.serverName,tool:r.toolName,result:C}),this.state.conversation.push({role:"tool",tool_call_id:i.id,content:C}),await this.appendSyntheticMultimodalUserMessage(C,i.id,o)}catch(u){const m=u instanceof Error&&u.message.includes("timed out after"),g=u instanceof Error&&u.name==="AbortError";if(console.error(`[ACodeRuntime] \u274C Tool execution failed: ${i.function.name}`,`isTimeout=${m}, isAbortError=${g}`,u instanceof Error?u.message:String(u)),this.isTurnSuperseded(o)){l("[ACodeRuntime] \uFE0F Turn superseded after tool error, skipping");return}if(this.abortRequested||this.state.terminated)throw l(`[ACodeRuntime] \u26A0\uFE0F Rethrowing error due to abort/termination (abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`),l(`[ACodeRuntime] \u{1F4E4} Emitting mcp_status tool_result (failed, aborted) for ${r.exposedName} before rethrow to close timeline entry`),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:r.kind==="mcp"?r.serverName:"builtin",tool:r.toolName,result:`[aborted] ${u instanceof Error?u.message:String(u)}`,failed:!0,aborted:!0}),u instanceof Error?u:new Error(String(u));l(`[ACodeRuntime] Calling appendToolFailureResult for ${r.exposedName} (isTimeout=${m})`),this.appendToolFailureResult(i,r,u)}}l(`[ACodeRuntime] handleToolCalls completed for all ${e.length} tool(s)`)}async callMcpToolWithTimeout(e,t,o,s,a){const i=s>0?s:Ct,r=!!this.config.sharedMcpConnections?{...o,_aws_sub_agent:!0}:o;for(;;){const u=this.createRuntimeStopWaiter(`ACode MCP tool ${t.serverName}/${t.toolName}`);try{return await x(Promise.race([e.client.callTool({name:t.toolName,arguments:r},void 0,{timeout:i}),u.promise]),s,`ACode MCP tool ${t.serverName}/${t.toolName}`)}catch(m){if(!a||s>0||!Xt(m))throw m;this.emitAcodeEvent("warning",{message:`ACode MCP polling tool ${t.serverName}/${t.toolName} reached the MCP SDK timeout window and will continue polling.`})}finally{u.cancel()}}}static formatSubAgentCompletionAsPollResult(e){const t=e.map(o=>{const s=o.error?`Sub-agent ${o.subId} [${o.status}]: ${o.description}
19
19
  Error: ${o.error}`:`Sub-agent ${o.subId} [${o.status}]: ${o.description}
20
- Output: ${o.output.length>500?o.output.slice(0,500)+"... (truncated)":o.output}`;return{msgId:`subagent-completion-${o.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:s,requireReply:!1,prompt:`Sub-agent ${o.subId} (${o.description}) has reached terminal state: ${o.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}});return{content:[{type:"text",text:JSON.stringify({directMessages:t,groupMessages:[],fromBuffer:!1,systemMessages:[]},null,2)}]}}static mergeSubAgentCompletionsIntoMcpResult(e,t){if(t.length===0)return e;const o=D(e);let s;try{s=JSON.parse(o)}catch{return e}const i=[...t.map(l=>{const r=l.error?`Sub-agent ${l.subId} [${l.status}]: ${l.description}
21
- Error: ${l.error}`:`Sub-agent ${l.subId} [${l.status}]: ${l.description}
22
- Output: ${l.output.length>500?l.output.slice(0,500)+"... (truncated)":l.output}`;return{msgId:`subagent-completion-${l.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:r,requireReply:!1,prompt:`Sub-agent ${l.subId} (${l.description}) has reached terminal state: ${l.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:i},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const a=this.state.mcpConnections.find(i=>i.serverName==="aws-client-agent-mcp");if(!a)return m("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(a,t):e==="memory_expiration"?await this.recheckMemoryExpiration(a,t):await this.recheckMemoryCleanup(a,t)}catch(i){return m(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${i instanceof Error?i.message:String(i)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${i instanceof Error?i.message:String(i)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await E(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=D(o),a=JSON.parse(s);return a==null||typeof a!="object"||Array.isArray(a)?null:a}catch(o){throw o}}async recheckMemoryFileChange(e,t){const o=[];if(await Promise.all(t.map(async a=>{const i=await this.readMemoryViaMcp(e,a);i&&i.memory_status==="updating"&&o.push(a)})),o.length===0)return m(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(a=>`- ${a}`).join(`
23
- `);return m(`[ACodeRuntime] recheck memory_file_change: ${o.length}/${t.length} URIs still updating`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
20
+ Output: ${o.output.length>500?o.output.slice(0,500)+"... (truncated)":o.output}`;return{msgId:`subagent-completion-${o.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:s,requireReply:!1,prompt:`Sub-agent ${o.subId} (${o.description}) has reached terminal state: ${o.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}});return{content:[{type:"text",text:JSON.stringify({directMessages:t,groupMessages:[],fromBuffer:!1,systemMessages:[]},null,2)}]}}static mergeSubAgentCompletionsIntoMcpResult(e,t){if(t.length===0)return e;const o=P(e);let s;try{s=JSON.parse(o)}catch{return e}const i=[...t.map(c=>{const r=c.error?`Sub-agent ${c.subId} [${c.status}]: ${c.description}
21
+ Error: ${c.error}`:`Sub-agent ${c.subId} [${c.status}]: ${c.description}
22
+ Output: ${c.output.length>500?c.output.slice(0,500)+"... (truncated)":c.output}`;return{msgId:`subagent-completion-${c.subId}-${Date.now()}`,senderId:"ACode-Runtime",senderName:"\u7CFB\u7EDF",content:r,requireReply:!1,prompt:`Sub-agent ${c.subId} (${c.description}) has reached terminal state: ${c.status}. Review its output and decide next steps.`,timestamp:new Date().toISOString()}}),...s.directMessages??[]];return{content:[{type:"text",text:JSON.stringify({...s,directMessages:i},null,2)}]}}async recheckMemoryDelegate(e,t,o,s){const a=this.state.mcpConnections.find(i=>i.serverName==="aws-client-agent-mcp");if(!a)return l("[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done"),{done:!0};try{return e==="memory_file_change"?await this.recheckMemoryFileChange(a,t):e==="memory_expiration"?await this.recheckMemoryExpiration(a,t):await this.recheckMemoryCleanup(a,t)}catch(i){return l(`[ACodeRuntime] recheckMemoryDelegate failed (type=${e}, turn=${s}): ${i instanceof Error?i.message:String(i)}, treating as NOT done (retry via recheck loop)`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u65E0\u6CD5\u786E\u8BA4\u4EE5\u4E0B memory \u662F\u5426\u5DF2\u5904\u7406\uFF08\u6821\u9A8C\u5F02\u5E38\uFF1A${i instanceof Error?i.message:String(i)}\uFF09\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u9A8C\u8BC1\u6B65\u9AA4\uFF08read_memory / get_memory_stats\uFF09\u786E\u8BA4\u771F\u5B9E\u72B6\u6001\u540E\u518D\u7EE7\u7EED\u3002`}}}async readMemoryViaMcp(e,t){try{const o=await x(e.client.callTool({name:"read_memory",arguments:{uri:t,_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,`recheck read_memory ${t}`),s=P(o),a=JSON.parse(s);return a==null||typeof a!="object"||Array.isArray(a)?null:a}catch(o){throw o}}async recheckMemoryFileChange(e,t){const o=[];if(await Promise.all(t.map(async a=>{const i=await this.readMemoryViaMcp(e,a);i&&i.memory_status==="updating"&&o.push(a)})),o.length===0)return l(`[ACodeRuntime] recheck memory_file_change: all ${t.length} URIs done (memory_status=normal or deleted)`),{done:!0};const s=o.map(a=>`- ${a}`).join(`
23
+ `);return l(`[ACodeRuntime] recheck memory_file_change: ${o.length}/${t.length} URIs still updating`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
24
24
  ${s}
25
25
 
26
- \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async i=>{const l=await this.readMemoryViaMcp(e,i);if(!l)return;const r=l.expiresAt??l.expires_at,u=l.memory_status==="recalling",c=typeof r=="string"&&new Date(r).getTime()<s;(u||c)&&o.push(i)})),o.length===0)return m(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const a=o.map(i=>`- ${i}`).join(`
27
- `);return m(`[ACodeRuntime] recheck memory_expiration: ${o.length}/${t.length} URIs still expired or recalling`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u5904\u7406\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
26
+ \u8FD9\u4E9B memory \u7684 memory_status \u4ECD\u4E3A "updating"\u3002\u8BF7\u91CD\u65B0 read_memory \u67E5\u770B\u5185\u5BB9\uFF0C\u67E5\u770B\u7ED1\u5B9A\u6587\u4EF6\u6700\u65B0\u5185\u5BB9\uFF0C\u5E76\u8C03\u7528 update_memory \u5B8C\u6210\u66F4\u65B0\u3002`}}async recheckMemoryExpiration(e,t){const o=[],s=Date.now();if(await Promise.all(t.map(async i=>{const c=await this.readMemoryViaMcp(e,i);if(!c)return;const r=c.expiresAt??c.expires_at,u=c.memory_status==="recalling",m=typeof r=="string"&&new Date(r).getTime()<s;(u||m)&&o.push(i)})),o.length===0)return l(`[ACodeRuntime] recheck memory_expiration: all ${t.length} URIs done (renewed, cleaned, or no longer expired)`),{done:!0};const a=o.map(i=>`- ${i}`).join(`
27
+ `);return l(`[ACodeRuntime] recheck memory_expiration: ${o.length}/${t.length} URIs still expired or recalling`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u5904\u7406\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
28
28
  ${a}
29
29
 
30
- \u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const l=await E(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),r=D(l);o=JSON.parse(r)}catch{return{done:!1,continueMessage:"get_memory_stats \u67E5\u8BE2\u5931\u8D25\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5BB9\u91CF\u662F\u5426\u5DF2\u8FBE\u6807\uFF0C\u8BF7\u91CD\u65B0\u9A8C\u8BC1\u540E\u518D\u7EE7\u7EED\u3002"}}const s=o.by_type??{},a=[];for(const l of t){const r=l.indexOf("/");if(r<0)continue;const u=l.slice(0,r),c=l.slice(r+1),y=s[u]?.by_domain?.[c];y?.exceeded&&a.push(`${u}/${c} (\u5F53\u524D ${y.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${y.limit??"?"})`)}if(a.length===0)return m(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const i=a.map(l=>`- ${l}`).join(`
31
- `);return m(`[ACodeRuntime] recheck memory_cleanup: ${a.length}/${t.length} type/domain pairs still exceeded`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
30
+ \u8FD9\u4E9B memory \u4ECD\u5904\u4E8E\u8FC7\u671F\u6216\u56DE\u5FC6\u4E2D\u72B6\u6001\u3002\u8BF7\u8C03\u7528 memory_recurrence \u83B7\u53D6\u5185\u5BB9\uFF0C\u5BF9\u9700\u8981\u4FDD\u7559\u7684\u8C03\u7528 update_memory \u7EED\u671F\uFF0C\u5BF9\u65E0\u4EF7\u503C\u7684\u8C03\u7528 memory_recurrence_complete \u6E05\u7406\u3002`}}async recheckMemoryCleanup(e,t){let o;try{const c=await x(e.client.callTool({name:"get_memory_stats",arguments:{_aws_sub_agent:!0}},void 0,{timeout:3e4}),3e4,"recheck get_memory_stats"),r=P(c);o=JSON.parse(r)}catch{return{done:!1,continueMessage:"get_memory_stats \u67E5\u8BE2\u5931\u8D25\uFF0C\u65E0\u6CD5\u786E\u8BA4\u5BB9\u91CF\u662F\u5426\u5DF2\u8FBE\u6807\uFF0C\u8BF7\u91CD\u65B0\u9A8C\u8BC1\u540E\u518D\u7EE7\u7EED\u3002"}}const s=o.by_type??{},a=[];for(const c of t){const r=c.indexOf("/");if(r<0)continue;const u=c.slice(0,r),m=c.slice(r+1),y=s[u]?.by_domain?.[m];y?.exceeded&&a.push(`${u}/${m} (\u5F53\u524D ${y.count??"?"} \u6761\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${y.limit??"?"})`)}if(a.length===0)return l(`[ACodeRuntime] recheck memory_cleanup: all ${t.length} type/domain pairs within limits`),{done:!0};const i=a.map(c=>`- ${c}`).join(`
31
+ `);return l(`[ACodeRuntime] recheck memory_cleanup: ${a.length}/${t.length} type/domain pairs still exceeded`),{done:!1,continueMessage:`\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED\uFF1A
32
32
  ${i}
33
33
 
34
34
  \u8BF7\u8C03\u7528 list_memories \u67E5\u770B\u8D85\u9650\u8BB0\u5FC6\uFF0C\u5220\u9664\u4E0D\u518D\u9700\u8981\u7684 recently_memory \u6216\u5BF9 agent_memory \u8C03\u7528 update_memory \u7EED\u671F\u3002`}}buildMemoryDelegatePrompt(e){const t=e.uris.map(o=>`- ${o}`).join(`
@@ -75,11 +75,11 @@ ${t}
75
75
  \u5B8C\u6210\u540E\u7CFB\u7EDF\u4F1A\u901A\u8FC7\u67E5\u8BE2\u670D\u52A1\u7AEF\u771F\u5B9E\u72B6\u6001\u8FDB\u884C\u4E8C\u6B21\u9A8C\u8BC1\uFF08\u4E0D\u4F9D\u8D56\u4F60\u7684\u81EA\u62A5\u7ED3\u679C\uFF09\u3002\u82E5\u9A8C\u8BC1\u53D1\u73B0\u4ECD\u6709\u7C7B\u578B/\u57DF\u8D85\u8FC7\u5BB9\u91CF\u4E0A\u9650\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u4EE5\u4E0B\u7C7B\u578B/\u57DF\u5C1A\u672A\u6574\u7406\u5B8C\u6210\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`:`\u4F60\u662F\u4E00\u6761\u4E13\u95E8\u5904\u7406\u6C38\u4E45\u8BB0\u5FC6\u6587\u4EF6\u53D8\u66F4\u66F4\u65B0\u7684\u5B50 agent\u3002
76
76
 
77
77
  \u4EE5\u4E0B ${e.uris.length} \u4E2A\u6C38\u4E45\u8BB0\u5FC6\u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D1\u751F\u53D8\u66F4\uFF1A
78
- ${e.uris.map(o=>{const s=e.fileChanges?.find(r=>r.uri===o);if(!s)return`- ${o}`;const a={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},i=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],l=i.length>0?i.map(r=>{if(r.status==="no_change")return` \xB7 ${r.path}`;const u=a[r.status]??r.status,c=r.status==="content_changed"&&r.localMd5&&r.serverMd5?` \u672C\u5730: ${r.localMd5} Server: ${r.serverMd5}`:r.status==="not_found"&&r.serverMd5?` Server: ${r.serverMd5}`:"";return` \xB7 ${r.path}\uFF08${u}${c}\uFF09`}).join(`
78
+ ${e.uris.map(o=>{const s=e.fileChanges?.find(r=>r.uri===o);if(!s)return`- ${o}`;const a={no_change:"\u65E0\u53D8\u66F4",content_changed:"\u5185\u5BB9\u53D8\u66F4",not_found:"\u6587\u4EF6\u627E\u4E0D\u5230"},i=s.fileStatuses&&s.fileStatuses.length>0?s.fileStatuses:[],c=i.length>0?i.map(r=>{if(r.status==="no_change")return` \xB7 ${r.path}`;const u=a[r.status]??r.status,m=r.status==="content_changed"&&r.localMd5&&r.serverMd5?` \u672C\u5730: ${r.localMd5} Server: ${r.serverMd5}`:r.status==="not_found"&&r.serverMd5?` Server: ${r.serverMd5}`:"";return` \xB7 ${r.path}\uFF08${u}${m}\uFF09`}).join(`
79
79
  `):s.boundFiles&&s.boundFiles.length>0?s.boundFiles.map(r=>` \xB7 ${r}`).join(`
80
80
  `):" \u65E0\uFF08\u8BF7\u901A\u8FC7 read_memory \u67E5\u770B bound_files\uFF09";return`- ${o}
81
81
  - \u7ED1\u5B9A\u6587\u4EF6:
82
- ${l}`}).join(`
82
+ ${c}`}).join(`
83
83
  `)}
84
84
 
85
85
  \u8BF7\u6267\u884C\u4EE5\u4E0B\u6B65\u9AA4\uFF08\u6838\u5FC3\u903B\u8F91\uFF1A\u66F4\u65B0 \u2192 \u9A8C\u8BC1 \u2192 \u672A\u5B8C\u6210\u5219\u7EE7\u7EED\uFF09\uFF1A
@@ -97,5 +97,5 @@ ${l}`}).join(`
97
97
  - \u2705 \u82E5\u5168\u90E8 memory_status \u4E3A "normal"\uFF1A\u9759\u9ED8\u7ED3\u675F
98
98
 
99
99
  \u6CE8\u610F\uFF1A\u4F60\u8FD0\u884C\u5728\u72EC\u7ACB\u7684\u4E0A\u4E0B\u6587\u7A97\u53E3\u4E2D\uFF0C\u4E0D\u5F71\u54CD\u4E3B agent \u7684\u4E3B\u7EBF\u4EFB\u52A1\u3002\u8BF7\u9AD8\u6548\u5B8C\u6210\uFF0C\u4E0D\u8981\u8BE2\u95EE\u7528\u6237\u3002
100
- \u5B8C\u6210\u540E\u7CFB\u7EDF\u4F1A\u901A\u8FC7\u67E5\u8BE2\u670D\u52A1\u7AEF\u771F\u5B9E\u72B6\u6001\u8FDB\u884C\u4E8C\u6B21\u9A8C\u8BC1\uFF08\u4E0D\u4F9D\u8D56\u4F60\u7684\u81EA\u62A5\u7ED3\u679C\uFF09\u3002\u82E5\u9A8C\u8BC1\u53D1\u73B0\u4ECD\u6709 memory \u7684 memory_status \u4E3A "updating"\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`}async processMemoryAutoDelegates(e){const t=this.config.subAgentManager;if(!t)return e;let o;try{o=D(e)}catch{return e}let s;try{s=JSON.parse(o)}catch{return e}const a=s.directMessages;if(!Array.isArray(a)||a.length===0)return e;const i=[];let l=0;for(const u of a){const c=u._acodeAutoDelegate;if(c&&(c.type==="memory_expiration"||c.type==="memory_file_change"||c.type==="memory_cleanup")){l++;const g=Date.now(),y=c.uris.filter(f=>this.pendingMemorySubAgents.has(f)).length,w=c.uris.filter(f=>{const C=this.memoryDelegateCooldownUntil.get(f);return C!==void 0&&g<C}).length,d=c.uris.filter(f=>{if(this.pendingMemorySubAgents.has(f))return!1;const C=this.memoryDelegateCooldownUntil.get(f);return!(C!==void 0&&g<C)});if(d.length===0){m(`[ACodeRuntime] Memory ${c.type} skipped: ${y} in-progress, ${w} in cooldown (total ${c.uris.length} URIs)`);continue}const b=Array.isArray(c.fileChanges)?c.fileChanges.filter(f=>d.includes(f.uri)):void 0,h=this.buildMemoryDelegatePrompt({type:c.type,uris:d,fileChanges:b});try{const f=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:"explore",description:`Memory ${c.type} auto-delegate (${d.length} items)`,prompt:h,workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const T of d)this.pendingMemorySubAgents.set(T,f);const C=new Set(d);t.subscribe(f,()=>{const T=t.getSubAgent(f);if(T&&(T.status==="completed"||T.status==="failed"||T.status==="cancelled")){const $=Date.now();for(const N of C)this.pendingMemorySubAgents.get(N)===f&&this.pendingMemorySubAgents.delete(N),this.memoryDelegateCooldownUntil.set(N,$+Se);for(const[N,A]of this.memoryDelegateCooldownUntil)A<=$&&this.memoryDelegateCooldownUntil.delete(N);m(`[ACodeRuntime] Memory delegate sub-agent ${f} finished (${T.status}), ${C.size} URI(s) entered ${Se}ms cooldown`)}});const _=c.type,k=async(T,$)=>this.recheckMemoryDelegate(_,d,T,$);await t.startWithRecheck(f,k,3),m(`[ACodeRuntime] Auto-delegated memory ${c.type} to sub-agent ${f} (${d.length} URIs, ${c.uris.length-d.length} already in progress)`)}catch(f){for(const C of d)this.pendingMemorySubAgents.delete(C);m(`[ACodeRuntime] Failed to auto-delegate memory ${c.type} (suppressed, will retry next poll): ${f instanceof Error?f.message:String(f)}`)}}else i.push(u)}if(l===0)return e;if(i.length===0)return null;const r={...s,directMessages:i};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,s){const a=this.config.subAgentManager;if(!a)return await this.callMcpToolWithTimeout(e,t,o,s,!0);const i=a.takeCompletedSubAgents();if(i.length>0)return m(`[ACodeRuntime] poll_message: ${i.length} sub-agent(s) already completed, returning synthetic result`),j.formatSubAgentCompletionAsPollResult(i);let l=!1;for(;;){const r=a.waitForAnyCompletion(),u=l?{...o,_aws_silent_poll:!0}:o,c=this.callMcpToolWithTimeout(e,t,u,s,!0);try{const g=await Promise.race([c.then(d=>({type:"mcp",result:d})),r.promise.then(d=>({type:"subagent",notif:d}))]);if(g.type==="subagent"){const d=a.takeCompletedSubAgents();return d.length===0&&d.push(g.notif),m(`[ACodeRuntime] poll_message: sub-agent ${g.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),j.formatSubAgentCompletionAsPollResult(d)}const y=a.takeCompletedSubAgents();if(y.length>0){m(`[ACodeRuntime] poll_message: MCP returned, merging ${y.length} sub-agent completion(s)`);const d=j.mergeSubAgentCompletionsIntoMcpResult(g.result,y),b=await this.processMemoryAutoDelegates(d);if(b!==null&&this.pollResultHasMessages(b))return b;await this.waitForDelegateRepoll(),l=!0;continue}const w=await this.processMemoryAutoDelegates(g.result);if(w!==null&&this.pollResultHasMessages(w))return w;await this.waitForDelegateRepoll(),l=!0}finally{r.cancel()}}}pollResultHasMessages(e){try{const t=D(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,a=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||a>0}catch{return!0}}async waitForDelegateRepoll(){m(`[ACodeRuntime] poll_message: all messages delegated, waiting ${$e}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,$e);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((s,a)=>{t=()=>{a(new Error(`${e} interrupted because ACode runtime stopped`))}});return t?(this.stopWaiters.add(t),{promise:o,cancel:()=>{t&&this.stopWaiters.delete(t)}}):{promise:o,cancel:()=>{}}}notifyRuntimeStop(){const e=[...this.stopWaiters];this.stopWaiters.clear();for(const t of e)t()}async appendSyntheticMultimodalUserMessage(e,t,o=this.contextVersion){const s=ue(e);if(!s.hasImages)return;if(!this.state.provider.supportsImageInput){this.emitAcodeEvent("error",{message:"ACode skipped image content from tool result because the provider/model is not configured for image input."});return}const a=await Ie(s.content);if(this.isTurnSuperseded(o))return;this.state.conversation.push({role:"user",content:a});const i=this.state.conversation.find(l=>l.role==="tool"&&l.tool_call_id===t);if(i&&typeof i.content=="string"){let l;try{const r=JSON.parse(i.content);if(typeof r=="object"&&r!==null){const u={...r};"attachments"in u&&(delete u.attachments,l=JSON.stringify(u))}}catch{}if(l===void 0){const r=i.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();r!==i.content&&(l=r)}l!==void 0&&l.length>0?i.content=l:l!==void 0&&(i.content="[Tool result contained images; see user message above]")}}appendToolFailureResult(e,t,o){const s=eo(t,o);m(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${s.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${G(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,result:s,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:s})}filterSharedMcpConnectionsForSubAgent(e){return e.map(t=>({...t,tools:t.tools.filter(o=>_t.has(o.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[s,a]of Object.entries(e))try{const i=new Je({name:"acode",version:"0.1.0"}),l=this.createMcpTransport(a);await E(i.connect(l),t,`ACode MCP server ${s} connect`);const r={serverName:s,client:i,transport:l,tools:[]};i.setNotificationHandler(Ge,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:u}=await E(i.listTools(),t,`ACode MCP server ${s} listTools`);r.tools=Te(s,u),o.push(r)}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${s}: ${i instanceof Error?i.message:String(i)}`})}return o}async refreshMcpConnectionTools(e,t){try{const{tools:s}=await E(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Te(e.serverName,s)}catch(s){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${s instanceof Error?s.message:String(s)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(s=>s.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(s=>({name:s.exposedName,source:s.kind==="mcp"?`${s.serverName}.${s.toolName}`:`builtin.${s.toolName}`,description:s.description||""}))})}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");return new He({command:e.command,args:e.args,cwd:e.cwd||this.config.workingDirectory,env:{...this.config.env??{},...e.env??{}},stderr:"pipe"})}if(!e.url)throw new Error("remote MCP server requires url");const t=e.headers?{headers:e.headers}:void 0;return e.type==="sse"?new Ke(new URL(e.url),{requestInit:t}):new Qe(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(s=>s.toolName==="get_profile"))try{const s=await E(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:ee}),ee,"ACode startup get_profile"),a=this.extractProfileFromToolResult(s);return so(a)}catch(s){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${s instanceof Error?s.message:String(s)}`}),""}return""}extractProfileFromToolResult(e){if(!v(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(v(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(v(s))return s}catch{}}return v(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1;return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1,await Promise.all(e.map(t=>Q(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}j.SKILL_REFRESH_DEBOUNCE_MS=500;export{j as ACodeRuntime};
100
+ \u5B8C\u6210\u540E\u7CFB\u7EDF\u4F1A\u901A\u8FC7\u67E5\u8BE2\u670D\u52A1\u7AEF\u771F\u5B9E\u72B6\u6001\u8FDB\u884C\u4E8C\u6B21\u9A8C\u8BC1\uFF08\u4E0D\u4F9D\u8D56\u4F60\u7684\u81EA\u62A5\u7ED3\u679C\uFF09\u3002\u82E5\u9A8C\u8BC1\u53D1\u73B0\u4ECD\u6709 memory \u7684 memory_status \u4E3A "updating"\uFF0C\u4F1A\u53D1\u9001 "\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5BF9\u4EE5\u4E0B memory \u7684\u66F4\u65B0\uFF0C\u8BF7\u7EE7\u7EED" \u6D88\u606F\u8BA9\u4F60\u7EE7\u7EED\u5904\u7406\u3002`}async processMemoryAutoDelegates(e){const t=this.config.subAgentManager;if(!t)return e;let o;try{o=P(e)}catch{return e}let s;try{s=JSON.parse(o)}catch{return e}const a=s.directMessages;if(!Array.isArray(a)||a.length===0)return e;const i=[];let c=0;for(const u of a){const m=u._acodeAutoDelegate;if(m&&(m.type==="memory_expiration"||m.type==="memory_file_change"||m.type==="memory_cleanup")){c++;const g=Date.now(),y=m.uris.filter(f=>this.pendingMemorySubAgents.has(f)).length,w=m.uris.filter(f=>{const C=this.memoryDelegateCooldownUntil.get(f);return C!==void 0&&g<C}).length,d=m.uris.filter(f=>{if(this.pendingMemorySubAgents.has(f))return!1;const C=this.memoryDelegateCooldownUntil.get(f);return!(C!==void 0&&g<C)});if(d.length===0){l(`[ACodeRuntime] Memory ${m.type} skipped: ${y} in-progress, ${w} in cooldown (total ${m.uris.length} URIs)`);continue}const b=Array.isArray(m.fileChanges)?m.fileChanges.filter(f=>d.includes(f.uri)):void 0,h=this.buildMemoryDelegatePrompt({type:m.type,uris:d,fileChanges:b});try{const f=await t.spawn({parentAgentId:this.config.agentId||"unknown",parentSessionId:this.config.sessionId,subagentType:"explore",description:`Memory ${m.type} auto-delegate (${d.length} items)`,prompt:h,workingDirectory:this.config.workingDirectory,parentConfig:{...this.config,sharedMcpConnections:this.state?.mcpConnections},silent:!0});for(const A of d)this.pendingMemorySubAgents.set(A,f);const C=new Set(d);t.subscribe(f,()=>{const A=t.getSubAgent(f);if(A&&(A.status==="completed"||A.status==="failed"||A.status==="cancelled")){const $=Date.now();for(const N of C)this.pendingMemorySubAgents.get(N)===f&&this.pendingMemorySubAgents.delete(N),this.memoryDelegateCooldownUntil.set(N,$+Me);for(const[N,T]of this.memoryDelegateCooldownUntil)T<=$&&this.memoryDelegateCooldownUntil.delete(N);l(`[ACodeRuntime] Memory delegate sub-agent ${f} finished (${A.status}), ${C.size} URI(s) entered ${Me}ms cooldown`)}});const _=m.type,k=async(A,$)=>this.recheckMemoryDelegate(_,d,A,$);await t.startWithRecheck(f,k,3),l(`[ACodeRuntime] Auto-delegated memory ${m.type} to sub-agent ${f} (${d.length} URIs, ${m.uris.length-d.length} already in progress)`)}catch(f){for(const C of d)this.pendingMemorySubAgents.delete(C);l(`[ACodeRuntime] Failed to auto-delegate memory ${m.type} (suppressed, will retry next poll): ${f instanceof Error?f.message:String(f)}`)}}else i.push(u)}if(c===0)return e;if(i.length===0)return null;const r={...s,directMessages:i};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async callPollMessageWithSubAgentRace(e,t,o,s){const a=this.config.subAgentManager;if(!a)return await this.callMcpToolWithTimeout(e,t,o,s,!0);const i=a.takeCompletedSubAgents();if(i.length>0)return l(`[ACodeRuntime] poll_message: ${i.length} sub-agent(s) already completed, returning synthetic result`),j.formatSubAgentCompletionAsPollResult(i);let c=!1;for(;;){const r=a.waitForAnyCompletion(),u=c?{...o,_aws_silent_poll:!0}:o,m=this.callMcpToolWithTimeout(e,t,u,s,!0);try{const g=await Promise.race([m.then(d=>({type:"mcp",result:d})),r.promise.then(d=>({type:"subagent",notif:d}))]);if(g.type==="subagent"){const d=a.takeCompletedSubAgents();return d.length===0&&d.push(g.notif),l(`[ACodeRuntime] poll_message: sub-agent ${g.notif.subId} completed during race, returning synthetic result (${d.length} notification(s))`),j.formatSubAgentCompletionAsPollResult(d)}const y=a.takeCompletedSubAgents();if(y.length>0){l(`[ACodeRuntime] poll_message: MCP returned, merging ${y.length} sub-agent completion(s)`);const d=j.mergeSubAgentCompletionsIntoMcpResult(g.result,y),b=await this.processMemoryAutoDelegates(d);if(b!==null&&this.pollResultHasMessages(b))return b;await this.waitForDelegateRepoll(),c=!0;continue}const w=await this.processMemoryAutoDelegates(g.result);if(w!==null&&this.pollResultHasMessages(w))return w;await this.waitForDelegateRepoll(),c=!0}finally{r.cancel()}}}pollResultHasMessages(e){try{const t=P(e),o=JSON.parse(t),s=Array.isArray(o.directMessages)?o.directMessages.length:0,a=Array.isArray(o.groupMessages)?o.groupMessages.length:0;return s>0||a>0}catch{return!0}}async waitForDelegateRepoll(){l(`[ACodeRuntime] poll_message: all messages delegated, waiting ${$e}ms before re-poll`);const e=this.createRuntimeStopWaiter("delegate re-poll delay");try{await Promise.race([new Promise(t=>{const o=setTimeout(t,$e);o.unref&&o.unref()}),e.promise])}finally{e.cancel()}}createRuntimeStopWaiter(e){if(this.state.terminated)return{promise:Promise.reject(new Error(`${e} interrupted because ACode runtime stopped`)),cancel:()=>{}};let t;const o=new Promise((s,a)=>{t=()=>{a(new Error(`${e} interrupted because ACode runtime stopped`))}});return t?(this.stopWaiters.add(t),{promise:o,cancel:()=>{t&&this.stopWaiters.delete(t)}}):{promise:o,cancel:()=>{}}}notifyRuntimeStop(){const e=[...this.stopWaiters];this.stopWaiters.clear();for(const t of e)t()}async appendSyntheticMultimodalUserMessage(e,t,o=this.contextVersion){const s=le(e);if(!s.hasImages)return;if(!this.state.provider.supportsImageInput){this.emitAcodeEvent("error",{message:"ACode skipped image content from tool result because the provider/model is not configured for image input."});return}const a=await Ie(s.content);if(this.isTurnSuperseded(o))return;this.state.conversation.push({role:"user",content:a});const i=this.state.conversation.find(c=>c.role==="tool"&&c.tool_call_id===t);if(i&&typeof i.content=="string"){let c;try{const r=JSON.parse(i.content);if(typeof r=="object"&&r!==null){const u={...r};"attachments"in u&&(delete u.attachments,c=JSON.stringify(u))}}catch{}if(c===void 0){const r=i.content.replace(/\[(图片|文件)\s*:\s*([^\]\n]*?)\s*\]/gi,"").trim();r!==i.content&&(c=r)}c!==void 0&&c.length>0?i.content=c:c!==void 0&&(i.content="[Tool result contained images; see user message above]")}}appendToolFailureResult(e,t,o){const s=eo(t,o);l(`[ACodeRuntime] \u{1F4E4} appendToolFailureResult: emitting mcp_status tool_result (failed: true) for ${t.exposedName}, result length: ${s.length} chars`),this.emitAcodeEvent("error",{message:`ACode tool failed: ${t.exposedName}: ${G(o)}`,nonFatal:!0}),this.emitAcodeEvent("mcp_status",{action:"tool_result",server:t.kind==="mcp"?t.serverName:"builtin",tool:t.toolName,result:s,failed:!0}),this.state.conversation.push({role:"tool",tool_call_id:e.id,content:s})}filterSharedMcpConnectionsForSubAgent(e){return e.map(t=>({...t,tools:t.tools.filter(o=>_t.has(o.toolName))}))}async connectMcpServers(e,t){const o=[];for(const[s,a]of Object.entries(e))try{const i=new Je({name:"acode",version:"0.1.0"}),c=this.createMcpTransport(a);await x(i.connect(c),t,`ACode MCP server ${s} connect`);const r={serverName:s,client:i,transport:c,tools:[]};i.setNotificationHandler(Ge,()=>{this.refreshMcpConnectionTools(r,t)});const{tools:u}=await x(i.listTools(),t,`ACode MCP server ${s} listTools`);r.tools=Ae(s,u),o.push(r)}catch(i){this.emitAcodeEvent("error",{message:`ACode MCP server failed to connect: ${s}: ${i instanceof Error?i.message:String(i)}`})}return o}async refreshMcpConnectionTools(e,t){try{const{tools:s}=await x(e.client.listTools(),t,`ACode MCP server ${e.serverName} listTools refresh`);e.tools=Ae(e.serverName,s)}catch(s){this.emitAcodeEvent("warning",{message:`ACode MCP server ${e.serverName} tools/list_changed refresh failed: ${s instanceof Error?s.message:String(s)}`});return}if(!this.exposedToolsInitialized)return;const o=this.state.exposedTools.filter(s=>!(s.kind==="mcp"&&s.serverName===e.serverName));this.state.exposedTools=[...o,...e.tools],this.emitAcodeEvent("mcp_status",{servers:this.state.mcpConnections.map(s=>s.serverName),connectedCount:this.state.mcpConnections.length,toolCount:this.state.exposedTools.length,tools:this.state.exposedTools.map(s=>({name:s.exposedName,source:s.kind==="mcp"?`${s.serverName}.${s.toolName}`:`builtin.${s.toolName}`,description:s.description||""}))})}createMcpTransport(e){if(e.type==="stdio"||e.command){if(!e.command)throw new Error("stdio MCP server requires command");return new He({command:e.command,args:e.args,cwd:e.cwd||this.config.workingDirectory,env:{...this.config.env??{},...e.env??{}},stderr:"pipe"})}if(!e.url)throw new Error("remote MCP server requires url");const t=e.headers?{headers:e.headers}:void 0;return e.type==="sse"?new Ke(new URL(e.url),{requestInit:t}):new Qe(new URL(e.url),{requestInit:t})}async fetchProfilePrompt(e){for(const t of e)if(t.tools.find(s=>s.toolName==="get_profile"))try{const s=await x(t.client.callTool({name:"get_profile",arguments:{}},void 0,{timeout:ee}),ee,"ACode startup get_profile"),a=this.extractProfileFromToolResult(s);return so(a)}catch(s){return this.emitAcodeEvent("warning",{message:`ACode failed to fetch profile via ${t.serverName}/get_profile: ${s instanceof Error?s.message:String(s)}`}),""}return""}extractProfileFromToolResult(e){if(!v(e))return null;const t=e.content;if(Array.isArray(t)){for(const o of t)if(v(o)&&typeof o.text=="string"&&o.text.trim())try{const s=JSON.parse(o.text);if(v(s))return s}catch{}}return v(e)?e:null}async disconnectMcpServers(){if(!this.state.ownsMcpConnections){this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1;return}const e=this.state.mcpConnections;this.state.mcpConnections=[],this.state.exposedTools=[],this.exposedToolsInitialized=!1,await Promise.all(e.map(t=>Q(`ACode MCP server ${t.serverName} close`,t.transport.close(),o=>{this.emitAcodeEvent("error",{message:o})},this.state.provider.mcpToolTimeoutMs)))}}j.SKILL_REFRESH_DEBOUNCE_MS=500;export{j as ACodeRuntime};
101
101
 
@@ -65,6 +65,8 @@ export declare class AgentClient {
65
65
 
66
66
  fetchBrowserListenerEvents(): Promise<BrowserListenerEvent[]>;
67
67
 
68
+ notifyBridgeForceMessage(): Promise<void>;
69
+
68
70
  private fetchDirectMessagesWithRecovery;
69
71
 
70
72
  private isRecoverableLongPollError;
@@ -1,2 +1,2 @@
1
- import{configManager as g}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as m}from"./constants.js";import{HttpClient as u}from"./http-client.js";import{logger as s,setMcpNodeLogSink as C,updateStartupLogIdentity as f}from"./logger.js";import{claimRuntimeLaunchBinding as I}from"./runtime-launch-binding.js";import{StatusReporter as y}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class N{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;cachedProfile=null;constructor(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new u(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await I(this.agentConfig,this.serverConfig);if(!e){this.serverConfig.runtimeBridgeBaseUrl=void 0;return}g.applyRuntimeLaunchBinding(e),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new u(this.serverConfig),this.setupWebSocketListeners()}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("profileInfo",e=>{s.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{s.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{s.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,t)=>{const n=t?.toString()||"";s.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,n,this.agentId)}),this.wsClient.on("error",e=>{s.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{s.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()})}async register(){return s.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let t;try{t=await this.getProfileByAgentId(this.agentId)}catch(i){throw s.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,i instanceof Error?i.message:String(i)),i}this.displayName=t.displayName,this.projectId=t.projectId||null,s.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(i){throw s.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,i instanceof Error?i.message:String(i)),i}s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const n=await this.getProfileByAgentId(this.agentId);return this.displayName=n.displayName,this.projectId=n.projectId||null,f(n.roleName||"unknown-role",n.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:n.isOnline?"online":"offline",projectId:n.projectId,workspacePath:n.workspacePath,runtimeStatus:n.runtimeStatus,runtimeSessionId:n.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),t=e.agentId;if(!t)throw new Error("Registration failed: agentId was not returned");return this.agentId=t,this.displayName=e.displayName,this.projectId=e.projectId||null,f(this.agentConfig.roleName||"unknown-role",e.instanceName||t),s.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u72B6\u6001: ${e.status}`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){s.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,s.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{agentId:this.agentId,...e})}async hireColleaguesBatch(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleagues_batch",{agentId:this.agentId,...e})}async callAgentScopedTool(e,t){return this.ensureRegistered(),await this.httpClient.callTool(e,{agentId:this.agentId,...t})}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,t,n){this.ensureRegistered();const i=t||this.projectId||this.agentConfig.projectId;return await this.httpClient.callTool("send_group_message",{agentId:this.agentId,projectId:i,roomId:n,content:e})}async sendDirectMessage(e,t,n=!1,i,r){this.ensureRegistered();const a={agentId:this.agentId,targetId:e,content:t,requireReply:n,waitReply:n,replyToCallId:i};if(typeof r=="number"&&r>0&&(a.timeoutMs=r),n){const d=typeof r=="number"&&r>0?r+3e4:0;return await this.httpClient.callToolOnce("send_dm",a,d)}return await this.httpClient.callTool("send_dm",a)}async sendCallAndWaitReply(e,t,n=6e4){const i=await this.sendDirectMessage(e,t,!0,void 0,n);if(i.reply)return i.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,t,n){return await this.sendDirectMessage(t,n,!1,e)}async getDmHistory(e,t=50,n){this.ensureRegistered();const i={agentId:this.agentId,targetUserId:e,limit:t};return n&&(i.since=n),await this.httpClient.callTool("get_dm_history",i)}async getGroupHistory(e=50,t,n){if(this.ensureRegistered(),t){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:t,limit:e};return n&&(o.since=n),await this.httpClient.callTool("get_group_history",o)}const i=await this.discoverGroupRooms(),r=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(i,r);if(a.length===0)return{messages:[],count:0};const h=(await Promise.all(a.map(async o=>{const l={projectId:r,roomId:o,limit:e};return n&&(l.since=n),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:h,count:h.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const t=this.projectId||this.agentConfig.projectId,n={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(n.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(n.blockTimeoutMs=e.blockTimeoutMs);const i=e.includePipelineTasks?"poll_message":"get_dm_messages",r=await this.fetchDirectMessagesWithRecovery(i,n),a=await this.discoverGroupRooms(),d=this.collectRoomIds(a,t),h=await Promise.all(d.map(async o=>{const l={agentId:this.agentId,projectId:t,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(c){return s.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,c instanceof Error?c.message:String(c)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(r.messages)?r.messages:[],groupMessages:h.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return s.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",t||"(\u7A7A)"),[];try{const n=`${e}/runtime/browser-listeners/${encodeURIComponent(t)}/events`,i=this.serverConfig.runtimeAccessToken||"";s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",n,i.length);const r=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":i},signal:AbortSignal.timeout(3e3)});if(!r.ok)return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",r.status,n),[];const a=await r.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(n){return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),[]}}async fetchDirectMessagesWithRecovery(e,t){if(e==="poll_message")try{return await this.httpClient.callToolOnce(e,t)}catch(n){if(this.isRecoverableLongPollError(n))return s.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",n),{messages:[]};throw n}return await this.httpClient.callTool(e,t)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(t=>!!(t&&typeof t=="object"&&typeof t.msgId=="number"&&typeof t.senderId=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string")):[]}collectRoomIds(e,t){const n=e.groups.filter(i=>i.projectId===t).map(i=>i.id);return Array.from(new Set(n))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async createTaskInstanceComment(e){this.ensureRegistered();const t={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",t)}async submitTaskResult(e,t,n){this.ensureRegistered();const i={agentId:this.agentId,nodeId:e,outputPayload:t};return n&&Array.isArray(n)&&n.length>0&&(i.changeLog=n),await this.httpClient.callTool("submit_task_result",i)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async rejectTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("reject_task",{agentId:this.agentId,nodeId:e,reason:t})}async terminateTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("terminate_task",{agentId:this.agentId,taskInstanceId:e,reason:t})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}start(e,t){if(this.isRunning){s.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=t?.profileHandler||null,this.configHandler=t?.configHandler||null,this.isRunning=!0,s.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(s.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),t?.pollMode??!1?(s.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):s.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),s.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(m)}catch(e){s.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleProfileInfo(e){s.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,s.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(s.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&f(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(s.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const t=typeof e.msgId=="string";s.info(`[AgentClient] \u6536\u5230${t?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const n=await this.messageHandler(e);if(t){const i=e;i.requireReply&&i.callId&&await this.replyToCall(i.callId,i.senderId,n||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(n){const i=typeof e.msgId=="string";if(s.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",i?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,n instanceof Error?n.message:String(n)),i){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,`\u5904\u7406\u5931\u8D25: ${n}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(t=>{this.pollTimer=setTimeout(t,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),s.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,s.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,s.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,t){let n=0;(async()=>{for(;this.isDegradedMode;)try{s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${n+1}/${t===-1?"\u65E0\u9650":t})`);const r=await this.register();s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${r.displayName} (${r.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(r){n++;const a=r instanceof Error?r.message:String(r);if(s.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${n}/${t===-1?"\u65E0\u9650":t}): ${a}`),t>0&&n>=t){s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(d=>setTimeout(d,e))}})().catch(r=>{s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",r instanceof Error?r.message:String(r),r instanceof Error?r.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){s.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new y({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),C(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),s.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){s.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const t=this.agentId;if(!t){s.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(t)&&s.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(n){s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",n instanceof Error?n.message:String(n)),n instanceof Error&&n.stack&&s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",n.stack)}},e),s.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const t=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof t.sendMcpNodeLog!="function"||t.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{N as AgentClient};
1
+ import{configManager as g}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as m}from"./constants.js";import{HttpClient as u}from"./http-client.js";import{logger as s,setMcpNodeLogSink as C,updateStartupLogIdentity as f}from"./logger.js";import{claimRuntimeLaunchBinding as I}from"./runtime-launch-binding.js";import{StatusReporter as y}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class b{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;cachedProfile=null;constructor(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new u(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await I(this.agentConfig,this.serverConfig);if(!e){this.serverConfig.runtimeBridgeBaseUrl=void 0;return}g.applyRuntimeLaunchBinding(e),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new u(this.serverConfig),this.setupWebSocketListeners()}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("profileInfo",e=>{s.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{s.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{s.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,n)=>{const t=n?.toString()||"";s.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,t,this.agentId)}),this.wsClient.on("error",e=>{s.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{s.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()})}async register(){return s.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let n;try{n=await this.getProfileByAgentId(this.agentId)}catch(i){throw s.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,i instanceof Error?i.message:String(i)),i}this.displayName=n.displayName,this.projectId=n.projectId||null,s.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(i){throw s.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,i instanceof Error?i.message:String(i)),i}s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const t=await this.getProfileByAgentId(this.agentId);return this.displayName=t.displayName,this.projectId=t.projectId||null,f(t.roleName||"unknown-role",t.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:t.isOnline?"online":"offline",projectId:t.projectId,workspacePath:t.workspacePath,runtimeStatus:t.runtimeStatus,runtimeSessionId:t.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),n=e.agentId;if(!n)throw new Error("Registration failed: agentId was not returned");return this.agentId=n,this.displayName=e.displayName,this.projectId=e.projectId||null,f(this.agentConfig.roleName||"unknown-role",e.instanceName||n),s.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u72B6\u6001: ${e.status}`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){s.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,s.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{agentId:this.agentId,...e})}async hireColleaguesBatch(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleagues_batch",{agentId:this.agentId,...e})}async callAgentScopedTool(e,n){return this.ensureRegistered(),await this.httpClient.callTool(e,{agentId:this.agentId,...n})}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,n,t){this.ensureRegistered();const i=n||this.projectId||this.agentConfig.projectId;return await this.httpClient.callTool("send_group_message",{agentId:this.agentId,projectId:i,roomId:t,content:e})}async sendDirectMessage(e,n,t=!1,i,r){this.ensureRegistered();const a={agentId:this.agentId,targetId:e,content:n,requireReply:t,waitReply:t,replyToCallId:i};if(typeof r=="number"&&r>0&&(a.timeoutMs=r),t){const d=typeof r=="number"&&r>0?r+3e4:0;return await this.httpClient.callToolOnce("send_dm",a,d)}return await this.httpClient.callTool("send_dm",a)}async sendCallAndWaitReply(e,n,t=6e4){const i=await this.sendDirectMessage(e,n,!0,void 0,t);if(i.reply)return i.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,n,t){return await this.sendDirectMessage(n,t,!1,e)}async getDmHistory(e,n=50,t){this.ensureRegistered();const i={agentId:this.agentId,targetUserId:e,limit:n};return t&&(i.since=t),await this.httpClient.callTool("get_dm_history",i)}async getGroupHistory(e=50,n,t){if(this.ensureRegistered(),n){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:n,limit:e};return t&&(o.since=t),await this.httpClient.callTool("get_group_history",o)}const i=await this.discoverGroupRooms(),r=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(i,r);if(a.length===0)return{messages:[],count:0};const h=(await Promise.all(a.map(async o=>{const l={projectId:r,roomId:o,limit:e};return t&&(l.since=t),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:h,count:h.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const n=this.projectId||this.agentConfig.projectId,t={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(t.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(t.blockTimeoutMs=e.blockTimeoutMs);const i=e.includePipelineTasks?"poll_message":"get_dm_messages",r=await this.fetchDirectMessagesWithRecovery(i,t),a=await this.discoverGroupRooms(),d=this.collectRoomIds(a,n),h=await Promise.all(d.map(async o=>{const l={agentId:this.agentId,projectId:n,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(c){return s.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,c instanceof Error?c.message:String(c)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(r.messages)?r.messages:[],groupMessages:h.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,n=this.agentId;if(!e||!n)return s.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",n||"(\u7A7A)"),[];try{const t=`${e}/runtime/browser-listeners/${encodeURIComponent(n)}/events`,i=this.serverConfig.runtimeAccessToken||"";s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",t,i.length);const r=await fetch(t,{method:"GET",headers:{"X-Runtime-Token":i},signal:AbortSignal.timeout(3e3)});if(!r.ok)return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",r.status,t),[];const a=await r.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(t){return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",t instanceof Error?t.message:String(t)),[]}}async notifyBridgeForceMessage(){const e=this.serverConfig.runtimeBridgeBaseUrl,n=this.agentId;if(!(!e||!n))try{const t=`${e}/runtime/sessions/${encodeURIComponent(n)}/notify-force-message`,i=this.serverConfig.runtimeAccessToken||"",r=await fetch(t,{method:"POST",headers:{"X-Runtime-Token":i},signal:AbortSignal.timeout(3e3)});r.ok||s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5931\u8D25: HTTP %s, url=%s",r.status,t)}catch(t){s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5F02\u5E38: %s",t instanceof Error?t.message:String(t))}}async fetchDirectMessagesWithRecovery(e,n){if(e==="poll_message")try{return await this.httpClient.callToolOnce(e,n)}catch(t){if(this.isRecoverableLongPollError(t))return s.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",t),{messages:[]};throw t}return await this.httpClient.callTool(e,n)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(n=>!!(n&&typeof n=="object"&&typeof n.msgId=="number"&&typeof n.senderId=="string"&&typeof n.content=="string"&&typeof n.timestamp=="string")):[]}collectRoomIds(e,n){const t=e.groups.filter(i=>i.projectId===n).map(i=>i.id);return Array.from(new Set(t))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async createTaskInstanceComment(e){this.ensureRegistered();const n={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",n)}async submitTaskResult(e,n,t){this.ensureRegistered();const i={agentId:this.agentId,nodeId:e,outputPayload:n};return t&&Array.isArray(t)&&t.length>0&&(i.changeLog=t),await this.httpClient.callTool("submit_task_result",i)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async rejectTask(e,n){return this.ensureRegistered(),await this.httpClient.callTool("reject_task",{agentId:this.agentId,nodeId:e,reason:n})}async terminateTask(e,n){return this.ensureRegistered(),await this.httpClient.callTool("terminate_task",{agentId:this.agentId,taskInstanceId:e,reason:n})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}start(e,n){if(this.isRunning){s.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=n?.profileHandler||null,this.configHandler=n?.configHandler||null,this.isRunning=!0,s.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(s.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),n?.pollMode??!1?(s.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):s.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),s.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(m)}catch(e){s.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleProfileInfo(e){s.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,s.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(s.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&f(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(s.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const n=typeof e.msgId=="string";s.info(`[AgentClient] \u6536\u5230${n?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const t=await this.messageHandler(e);if(n){const i=e;i.requireReply&&i.callId&&await this.replyToCall(i.callId,i.senderId,t||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(t){const i=typeof e.msgId=="string";if(s.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",i?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,t instanceof Error?t.message:String(t)),i){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,`\u5904\u7406\u5931\u8D25: ${t}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(n=>{this.pollTimer=setTimeout(n,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),s.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,s.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,s.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,n){let t=0;(async()=>{for(;this.isDegradedMode;)try{s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${t+1}/${n===-1?"\u65E0\u9650":n})`);const r=await this.register();s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${r.displayName} (${r.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(r){t++;const a=r instanceof Error?r.message:String(r);if(s.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${t}/${n===-1?"\u65E0\u9650":n}): ${a}`),n>0&&t>=n){s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(d=>setTimeout(d,e))}})().catch(r=>{s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",r instanceof Error?r.message:String(r),r instanceof Error?r.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){s.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new y({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),C(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),s.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){s.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const n=this.agentId;if(!n){s.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(n)&&s.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(t){s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",t instanceof Error?t.message:String(t)),t instanceof Error&&t.stack&&s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",t.stack)}},e),s.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const n=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof n.sendMcpNodeLog!="function"||n.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{b as AgentClient};
2
2
 
@@ -189,7 +189,7 @@ export declare class McpServer {
189
189
 
190
190
  private sanitizeAgentIdForTodoFile;
191
191
 
192
- private buildTodoReminderNotification;
192
+ private buildTodoBlockNotification;
193
193
 
194
194
  private buildBackgroundTaskNotification;
195
195
  start(): Promise<void>;