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.
@@ -19,6 +19,8 @@ type ACodeRuntimeInstance = {
19
19
  submitQuestionAnswer?(toolCallId: string, answers: Record<string, string>): boolean;
20
20
 
21
21
  detachCurrentToolExecution?(): boolean;
22
+
23
+ notifyForceMessage?(): void;
22
24
  };
23
25
  type ACodeRuntimeConstructor = new (config: {
24
26
  sessionId: string;
@@ -68,6 +70,8 @@ export declare class AcodeSdkAdapter extends EventEmitter implements BaseProvide
68
70
  getProviderSessionId(sessionId: string): string | undefined;
69
71
  getSessionStatus(sessionId: string): SessionStatus | undefined;
70
72
 
73
+ notifyForceMessage(sessionId: string): boolean;
74
+
71
75
  getCapabilities(sessionId: string): RuntimeCapabilities | undefined;
72
76
 
73
77
  getPendingQuestion(sessionId: string): {
@@ -1,4 +1,4 @@
1
- import{EventEmitter as B}from"node:events";import L from"node:path";import q from"node:fs/promises";import{pathToFileURL as N}from"node:url";import{v4 as D}from"uuid";import{getAcodeConfigFile as $,getAcodeSkillsDir as K,getRuntimeHomeDir as H}from"../config.js";import{getReleasedAcodeEntryPath as j}from"../services/acode-package.js";import{getInstanceAiConfigDebugLogger as P}from"../utils/instance-ai-config-debug-logger.js";import{redactForLog as O}from"../services/instance-ai-config-service.js";import{subAgentManager as Q}from"../services/sub-agent-manager-instance.js";import{agentPtyManager as G}from"../services/agent-pty-manager.js";import{resolveAcodeProviderConfig as z}from"./instance-ai-config-resolver.js";import{recordAgentFileChange as J}from"../services/workspaceTaskChangeWatcher.js";import{getBrowserTools as Y,closeBrowserSession as X,registerListenerWakeHook as V,unregisterListenerWakeHook as E}from"../services/browser-session-manager.js";import{isMessagePollingIdleCommand as w,isPollMessageToolDescriptor as Z}from"./acode-tool-names.js";import{IdlePollLoop as tt}from"./idle-poll-loop.js";import{getCanonicalMcpDetail as I,getToolActionInfo as et}from"./types.js";const ot=process.env.ACODE_COMPACTION_DEBUG==="1";function l(...r){ot&&console.log(...r)}const M=["Continue the AgentsWork message loop now.","You MUST call the exact MCP tool named aws-mcp__poll_message as your next action and wait for the next assigned message or task.","Do not answer in plain text before calling aws-mcp__poll_message.","After handling any received work, reply through the appropriate aws-mcp messaging tool, then continue listening again."].join(" "),st=5e3,it=4e4,at=5*6e4,nt=250,rt=2e3,ut=12e4,R=3e3,lt="\u7CFB\u7EDF\u63D0\u9192\uFF1A\u5982\u679C\u4EFB\u52A1\u5DF2\u5B8C\u6210\u6216\u6CA1\u6709\u5176\u5B83\u8981\u505A\u7684\uFF0C\u5148\u8C03\u7528 poll_message \u5DE5\u5177\u963B\u585E\u7B49\u5F85\u65B0\u6D88\u606F\u548C\u6D41\u7A0B\u7EBF\u4EFB\u52A1\u63D0\u9192\uFF1B\u6536\u5230\u6D41\u7A0B\u4EFB\u52A1\u63D0\u9192\u540E\u8C03\u7528 my_task \u67E5\u770B\u5DF2\u7531\u540E\u53F0\u9759\u9ED8\u62A2\u5360\u7684\u4EFB\u52A1\u8BE6\u60C5\u5E76\u76F4\u63A5\u5904\u7406\uFF1B\u5B8C\u6210\u4EFB\u52A1\u540E\u8C03\u7528 submit_task_result \u63D0\u4EA4\u7ED3\u679C\uFF0C\u7136\u540E\u7EE7\u7EED poll_message\u3002 \u8C03\u7528 submit_task_result \u65F6\u8BF7\u4E00\u5E76\u4F20\u5165 changeLog\uFF08\u672C\u6B21\u5904\u7406\u7684\u6587\u4EF6/\u5185\u5BB9\u53D8\u66F4\u65E5\u5FD7\uFF0C\u5305\u542B operation \u4E0E path\uFF09\uFF0C\u7528\u4E8E AI \u56DE\u9000\u3002";function dt(){return L.resolve(j())}function ct(r){return N(L.resolve(r)).href}const U=128e3,k={"claude-4":{contextLimit:2e5,maxOutput:8192},"claude-sonnet-4":{contextLimit:2e5,maxOutput:8192},"claude-3-5-sonnet":{contextLimit:2e5,maxOutput:8192},"claude-3-opus":{contextLimit:2e5,maxOutput:8192},"claude-3-haiku":{contextLimit:2e5,maxOutput:8192},"claude-2":{contextLimit:1e5,maxOutput:4096},"gpt-4o":{contextLimit:128e3,maxOutput:16384},"gpt-4-turbo":{contextLimit:128e3,maxOutput:4096},"gpt-4":{contextLimit:8192,maxOutput:4096},"gpt-3.5-turbo":{contextLimit:16384,maxOutput:4096},o1:{contextLimit:2e5,maxOutput:1e5},"o3-mini":{contextLimit:2e5,maxOutput:1e5},"gemini-2.0-flash":{contextLimit:1048576,maxOutput:8192},"gemini-2.5-pro":{contextLimit:1048576,maxOutput:8192},"gemini-1.5-pro":{contextLimit:2097152,maxOutput:8192},"gemini-1.5-flash":{contextLimit:1048576,maxOutput:8192},deepseek:{contextLimit:64e3,maxOutput:8192},"deepseek-chat":{contextLimit:64e3,maxOutput:8192},"deepseek-reasoner":{contextLimit:64e3,maxOutput:8192},"qwen-max":{contextLimit:32e3,maxOutput:8192},"qwen-plus":{contextLimit:128e3,maxOutput:8192},"qwen-turbo":{contextLimit:1e6,maxOutput:8192},"glm-4":{contextLimit:128e3,maxOutput:4096},"yi-":{contextLimit:2e5,maxOutput:4096},"llama-3":{contextLimit:8192,maxOutput:4096},"llama-2":{contextLimit:4096,maxOutput:4096},mistral:{contextLimit:32e3,maxOutput:4096},mixtral:{contextLimit:32e3,maxOutput:4096},codestral:{contextLimit:256e3,maxOutput:8192},grok:{contextLimit:131072,maxOutput:4096},"nova-":{contextLimit:2e5,maxOutput:8192}};function mt(r){if(!r)return U;const t=r.toLowerCase().trim();if(k[t])return k[t].contextLimit;const e=Object.keys(k).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?k[e[0]].contextLimit:U}const v=4096;function pt(r){if(!r)return v;const t=r.toLowerCase().trim();if(k[t])return k[t].maxOutput;const e=Object.keys(k).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?k[e[0]].maxOutput:v}function gt(r){if(!r||typeof r!="object")return;const t=r,e=b(t.inputTokens,t.input_tokens,t.promptTokens,t.prompt_tokens),o=b(t.outputTokens,t.output_tokens,t.completionTokens,t.completion_tokens);if(!(e===0&&o===0))return{inputTokens:e,outputTokens:o}}function b(...r){for(const t of r){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 0}function F(r){return b(r.estimatedContextTokens,r.contextTokens,r.context_tokens,r.contextUsedTokens,r.context_used_tokens)}function ft(r){return r==="stderr"||r==="mixed"?r:"stdout"}function ht(r){if(!r||typeof r!="object"||Array.isArray(r))return;const t={};for(const[e,o]of Object.entries(r))typeof o=="string"&&(t[e]=o);return Object.keys(t).length>0?t:void 0}function Tt(r){return r.failed===!0}function W(r,t,e){if(!r)return e?`${t}/${e}`:t;const o=`${t}__`;return r.startsWith(o)?I(`${t}__${r.slice(o.length)}`):I(r.replace("/","__"))}function St(r){return r==="read_file"||r==="edit_file"||r==="write_file"||r==="bash"}function At(r){const t=_t(r);return t?[t.directMessages,t.groupMessages,t.messages].some(e=>Array.isArray(e)&&e.length>0):typeof r=="string"&&r.trim().length>0}function _t(r){if(r&&typeof r=="object"&&!Array.isArray(r))return r;if(!(typeof r!="string"||!r.trim()))try{const t=JSON.parse(r);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}class Ft extends B{constructor(){super(...arguments),this.providerId="acode",this.displayName="ACode",this.sessions=new Map,this.listenerWakeHooks=new Map}async startSession(t,e){const o=H(),s=e.mcpConfigPath||$(o),{resolved:n,configContextLimit:i}=await this.resolveAcodeProvider(e,s),a=n.model,u=i??mt(a),c=pt(a),m={sessionId:t,status:"starting",messages:[],createdAt:new Date().toISOString(),totalUsage:{inputTokens:0,outputTokens:0,contextLimit:u,maxOutput:c}};this.sessions.set(t,{adapterSession:m,config:e,runtime:await this.createRuntime(t,a,e,o),autoPollActive:!1}),this.emit("status-change",t,"starting");const d=this.sessions.get(t);if(!d)throw new Error("ACode session was not initialized");const g=()=>{const p=this.sessions.get(t);p&&this.getIdlePollLoop(p).start()};this.listenerWakeHooks.set(t,g),V(e.agentId,g);try{await d.runtime.start(),m.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:d.adapterSession.totalUsage}),e.initialPrompt?.trim()?this.startInitialPromptTurn(t,e.initialPrompt):this.armIdleLoopOrAutoPoll(t)}catch(p){m.status="error",this.emitRuntimeErrorEvent(t,p),this.emit("status-change",t,"error");const h=this.sessions.get(t);throw h?.capabilitiesFallbackTimer&&clearTimeout(h.capabilitiesFallbackTimer),this.sessions.delete(t),E(e.agentId,this.listenerWakeHooks.get(t)),this.listenerWakeHooks.delete(t),p}}async sendMessage(t,e){const o=Date.now();l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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("[ACode] \u25B6\uFE0F sendMessage STARTED"),l(`[ACode] Session: ${t}`),l(`[ACode] Message: ${e.slice(0,100)}${e.length>100?"...":""}`),l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");const s=this.requireSession(t),n=s.adapterSession.status;l(`[ACode] Previous status: ${n}`),this.cancelScheduledAutoPoll(s),s.failedTurnRecoveryScheduled=!1,s.idlePollLoop?.stop();const i={id:D(),sessionId:t,role:"user",content:e,timestamp:new Date().toISOString()};s.adapterSession.messages.push(i),this.emit("conversation-message",t,i),l(`[ACode] Changing status: ${n} \u2192 thinking`),s.adapterSession.status="thinking",this.emit("status-change",t,"thinking"),this.startSubmitTimeoutDetection(t,s,"sendMessage");try{l("[ACode] \u25B6\uFE0F Calling runtime.submit()...");const a=Date.now();await s.runtime.submit(e);const u=Date.now()-a;this.cancelSubmitTimeoutDetection(s),l(`[ACode] \u2705 runtime.submit() completed in ${u}ms`),l(`[ACode] Current status after submit: ${s.adapterSession.status}`),l("[ACode] \u25B6\uFE0F Calling recoverResolvedTurnWithoutTerminalEvent()..."),this.recoverResolvedTurnWithoutTerminalEvent(t),l(`[ACode] Status after recovery: ${s.adapterSession.status}`);const c=Date.now()-o;l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(`[ACode] \u2705 sendMessage COMPLETED in ${c}ms`),l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(a){const u=Date.now()-o;console.error(`[ACode] \u274C sendMessage FAILED after ${u}ms:`,a instanceof Error?a.message:String(a)),this.cancelSubmitTimeoutDetection(s),l("[ACode] \u25B6\uFE0F Calling emitRuntimeError with recover=true..."),this.emitRuntimeError(t,a,{recover:!0}),l(`[ACode] Status after error recovery: ${s.adapterSession.status}`)}}async sendConfirmation(t,e){}async sendQuestionAnswer(t,e){const o=this.sessions.get(t);if(!o)return;const s=o.pendingQuestionToolCallId;if(!s){l(`[AcodeSdkAdapter] sendQuestionAnswer: no pending question for session ${t}`);return}o.pendingQuestionToolCallId=void 0,o.pendingQuestions=void 0,o.runtime.submitQuestionAnswer&&o.runtime.submitQuestionAnswer(s,e),this.startSubmitTimeoutDetection(t,o,"sendQuestionAnswer")}async abortCurrentTurn(t){await this.requireSession(t).runtime.abort()}async resetContext(t){const e=this.requireSession(t);if(this.cancelScheduledAutoPoll(e),e.failedTurnRecoveryScheduled=!1,e.autoPollActive=!1,e.autoPollObservedPollingTool=!1,e.autoPollObservedAssistantText=!1,e.autoPollObservedAnyTool=!1,e.stopAutoPollAfterCurrentTurn=!1,e.idlePollLoop?.stop(),!e.runtime.resetContext)throw new Error("ACode runtime does not support context reset");await e.runtime.resetContext(),e.adapterSession.messages=[];const o=e.adapterSession.totalUsage;if(e.adapterSession.totalUsage={inputTokens:0,outputTokens:0,contextLimit:o.contextLimit,maxOutput:o.maxOutput,inputLimit:o.inputLimit,compactionThreshold:o.compactionThreshold},e.adapterSession.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:e.adapterSession.totalUsage}),e.config.initialPrompt?.trim()){this.startInitialPromptTurn(t,e.config.initialPrompt);return}this.armIdleLoopOrAutoPoll(t)}async terminateSession(t){const e=this.sessions.get(t);if(!e)return;this.cancelScheduledAutoPoll(e),e.failedTurnRecoveryScheduled=!1,e.idlePollLoop?.stop(),e.capabilitiesFallbackTimer&&(clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=void 0),await e.runtime.stop();const o=e.config.agentId;o&&(E(o,this.listenerWakeHooks.get(t)),X(o)),this.listenerWakeHooks.delete(t),e.adapterSession.status="terminated",this.sessions.delete(t),this.emit("status-change",t,"terminated")}getConversation(t){return this.sessions.get(t)?.adapterSession.messages??[]}hasSession(t){return this.sessions.has(t)}getProviderSessionId(t){return this.sessions.has(t)?t:void 0}getSessionStatus(t){return this.sessions.get(t)?.adapterSession.status}getCapabilities(t){return this.sessions.get(t)?.lastCombinedCapabilities}getPendingQuestion(t){const e=this.sessions.get(t);if(e?.pendingQuestionToolCallId)return{toolCallId:e.pendingQuestionToolCallId,questions:e.pendingQuestions??[]}}cleanup(){for(const t of this.sessions.keys())this.terminateSession(t)}setIdleCommands(t,e){const o=this.sessions.get(t);if(o){if(o.idleCommands=e,this.cancelScheduledAutoPoll(o),e.idleInputCommand&&w(e.idleInputCommand)){this.getIdlePollLoop(o).start();return}o.adapterSession.status==="waiting_input"&&(e.idleInputCommand||e.nonInputCommand)&&this.getIdlePollLoop(o).start()}}setRuntimeConstructorForTest(t){this.runtimeConstructor=t}async loadAcodeProviderSection(t){try{const e=await q.readFile(t,"utf-8"),o=JSON.parse(e),n=o.provider?.default,i=n?.options,a=b(o.contextLimit),u={},c=n?.models;if(c&&typeof c=="object"){for(const[m,d]of Object.entries(c))if(d&&typeof d=="object"){const g=b(d.contextLimit);g>0&&(u[m.trim()]=g)}}return{...n?.model?{model:n.model}:{},...i?.baseURL||i?.baseUrl?{baseURL:i?.baseURL||i?.baseUrl}:{},...i?.apiKey?{apiKey:i.apiKey}:{},...a>0?{contextLimit:a}:{},...Object.keys(u).length>0?{modelContextLimits:u}:{}}}catch(e){const o=e instanceof Error?e.message:String(e);return P().log({level:"warn",category:"load",message:`loadAcodeProviderSection failed: ${t}: ${o}`,source:"bridge"}),{}}}async resolveAcodeProvider(t,e){const o=typeof t.model=="string"&&t.model.trim()?t.model.trim():void 0,s=P();s.log({level:"info",category:"resolve",message:"resolveAcodeProvider \u8F93\u5165",source:"bridge",details:{configModel:t.model??null,configInstanceAiConfig:t.instanceAiConfig?O(t.instanceAiConfig):null,configPath:e}});const n={...t.instanceAiConfig?.model?{model:t.instanceAiConfig.model}:{},...t.instanceAiConfig?.baseURL?{baseURL:t.instanceAiConfig.baseURL}:{},...t.instanceAiConfig?.apiKey?{apiKey:t.instanceAiConfig.apiKey}:{},...t.instanceAiConfig?.effort?{effort:t.instanceAiConfig.effort}:{},...o?{model:o}:{}},i=await this.loadAcodeProviderSection(e);let a=i.contextLimit;if(!a&&i.modelContextLimits){const c=o||t.instanceAiConfig?.model||i.model;c&&i.modelContextLimits[c]&&(a=i.modelContextLimits[c])}const u=z(n,i,"acode-default");return s.log({level:"info",category:"resolve",message:"resolveAcodeProvider \u89E3\u6790\u7ED3\u679C",source:"bridge",details:{instanceConfig:O(n),globalConfigModel:i?.model??null,resolvedModel:u.model,resolvedBaseURL:u.baseURL??null,resolvedApiKey:u.apiKey?"[set]":null,configContextLimit:a,resolvedSource:u.source}}),{resolved:u,configPath:e,perSessionModel:o,configContextLimit:a}}async createRuntime(t,e,o,s){const n=await this.loadRuntimeConstructor(),i=o.mcpConfigPath||$(s);let a=[];try{a=await Y(o.agentId,o.scopeKey)}catch(m){l(`[acode-adapter] browser tools injection skipped for agent ${o.agentId}:`,m.message)}const u=new n({sessionId:t,agentId:o.agentId,workingDirectory:o.workingDirectory,configPath:i,skillsDir:K(s),model:e,systemPrompt:typeof o.systemPrompt=="string"?o.systemPrompt:void 0,globalPrompt:typeof o.globalPrompt=="string"?o.globalPrompt:void 0,rolePrompt:typeof o.rolePrompt=="string"?o.rolePrompt:void 0,memory:typeof o.memory=="string"?o.memory:void 0,env:o.envOverrides,subAgentManager:Q,terminalManager:G,...o.subAgentModel?{subAgentModel:o.subAgentModel}:{},...o.subAgentEffort?{subAgentEffort:o.subAgentEffort}:{},...o.instanceAiConfig?.effort?{effort:o.instanceAiConfig.effort}:{},onFileChange:m=>J({...m,agentId:o.agentId,workspacePath:o.workingDirectory}),extraBuiltInTools:a});return P().log({level:"info",category:"resolve",message:"ACode provider resolved",source:"bridge",sessionId:t,details:{resolvedModel:e,perInstanceModel:o.instanceAiConfig?.model||null,perInstanceBaseURL:o.instanceAiConfig?.baseURL?"[set]":null,perInstanceApiKey:o.instanceAiConfig?.apiKey?"[set]":null,configPath:i}}),u.on("event",m=>this.forwardAcodeEvent(m)),u}async loadRuntimeConstructor(){if(this.runtimeConstructor)return this.runtimeConstructor;const t=dt(),e=await import(ct(t));if(!e.ACodeRuntime)throw new Error(`ACode runtime export not found: ${t}`);return this.runtimeConstructor=e.ACodeRuntime,this.runtimeConstructor}requireSession(t){const e=this.sessions.get(t);if(!e)throw new Error("ACode session not found");return e}startInitialPromptTurn(t,e){const o=this.sessions.get(t);o&&(o.adapterSession.status="thinking",this.emit("status-change",t,"thinking"),this.startSubmitTimeoutDetection(t,o,"startInitialPromptTurn"),o.runtime.submit(e).then(()=>{this.cancelSubmitTimeoutDetection(o),this.recoverResolvedTurnWithoutTerminalEvent(t)}).catch(s=>{const n=this.sessions.get(t);n&&(this.cancelSubmitTimeoutDetection(n),this.emitRuntimeError(t,s,{recover:!0}))}))}forwardAcodeEvent(t){const e=this.sessions.get(t.sessionId);if(e){if(t.type==="assistant_delta"){const o=typeof t.data.text=="string"?t.data.text:"";e.autoPollActive&&(e.autoPollObservedAssistantText=!0),e.adapterSession.messages.push({id:D(),sessionId:t.sessionId,role:"assistant",content:o,timestamp:t.timestamp}),this.resetDataFlowWatchdog(t.sessionId,e),this.emitProviderEvent(t,"text_delta",{text:o});return}if(t.type==="thinking_delta"){const o=typeof t.data.text=="string"?t.data.text:"";this.resetDataFlowWatchdog(t.sessionId,e),this.emitProviderEvent(t,"thinking",{text:o});return}if(t.type==="command_output"){this.emitProviderEvent(t,"command_output",{text:typeof t.data.text=="string"?t.data.text:"",stream:ft(t.data.stream),sequence:typeof t.data.sequence=="number"?t.data.sequence:void 0,cwd:typeof t.data.cwd=="string"?t.data.cwd:void 0,commandLineCount:typeof t.data.commandLineCount=="number"?t.data.commandLineCount:void 0,commandFilePath:typeof t.data.commandFilePath=="string"?t.data.commandFilePath:void 0});return}if(t.type==="ai_request"){const o=F(t.data);let s;if(o>0){const a=e.adapterSession.totalUsage.inputTokens;a>0?e.adapterSession.totalUsage.inputTokens=Math.min(o,Math.floor(a*1.5)):e.adapterSession.totalUsage.inputTokens=o,s={...e.adapterSession.totalUsage}}e.adapterSession.status==="compacting"&&(e.adapterSession.status="thinking"),e.adapterSession.status==="waiting_input"&&(e.adapterSession.status="thinking");const i={actionType:"ai_request",actionLabel:"AI\u8BF7\u6C42",actionDetail:this.formatAiRequestActionDetail(t.data)};s&&(i.usage=s),this.emit("status-change",t.sessionId,e.adapterSession.status,i),this.startDataFlowWatchdog(t.sessionId,e),e.adapterSession.status==="thinking"&&e.watchdogSubmitStartTime&&(e.watchdogSubmitStartTime=Date.now()),this.emitProviderEvent(t,"ai_request",{model:typeof t.data.model=="string"?t.data.model:void 0,endpoint:typeof t.data.endpoint=="string"?t.data.endpoint:void 0,requestMethod:typeof t.data.requestMethod=="string"?t.data.requestMethod:void 0,requestUrl:typeof t.data.requestUrl=="string"?t.data.requestUrl:void 0,requestHeaders:ht(t.data.requestHeaders),stream:typeof t.data.stream=="boolean"?t.data.stream:void 0,messageCount:typeof t.data.messageCount=="number"?t.data.messageCount:void 0,toolCount:typeof t.data.toolCount=="number"?t.data.toolCount:void 0,lastUserMessagePreview:typeof t.data.lastUserMessagePreview=="string"?t.data.lastUserMessagePreview:void 0,requestBody:typeof t.data.requestBody=="string"?t.data.requestBody:void 0});return}if(t.type==="turn_complete"){const o=gt(t.data.usage);if(o){const n=e.adapterSession.totalUsage.inputTokens;n>0&&o.inputTokens<Math.floor(n*.2)||(e.adapterSession.totalUsage.inputTokens=o.inputTokens,e.adapterSession.totalUsage.outputTokens=o.outputTokens)}const s=e.adapterSession.status;if(l(`[ACode] turn_complete event received (session: ${t.sessionId}), previous status: ${s}, failed: ${t.data.failed===!0}, aborted: ${t.data.aborted===!0}`),Tt(t.data)){l(`[ACode] Recovering from failed turn_complete (session: ${t.sessionId})`),this.cancelDataFlowWatchdog(e),this.recoverTurnFailure(t.sessionId,e);return}if(t.data.aborted===!0&&e.autoPollActive){l(`[ACode] Recovering from aborted turn_complete (session: ${t.sessionId}), using R2 2s backoff instead of immediate rearm`),this.cancelDataFlowWatchdog(e),this.recoverTurnFailure(t.sessionId,e);return}if(this.cancelDataFlowWatchdog(e),this.emitProviderEvent(t,"turn_complete",{usage:e.adapterSession.totalUsage,responseBody:typeof t.data.responseBody=="string"?t.data.responseBody:void 0,finishReason:typeof t.data.finishReason=="string"?t.data.finishReason:void 0}),e.adapterSession.status="waiting_input",this.emit("status-change",t.sessionId,"waiting_input",{usage:e.adapterSession.totalUsage}),l(`[ACode] Status changed to waiting_input after turn_complete (session: ${t.sessionId})`),e.autoPollActive&&e.autoPollObservedAssistantText&&!e.autoPollObservedPollingTool&&!e.autoPollObservedAnyTool){e.stopAutoPollAfterCurrentTurn=!0,console.warn(`[${this.displayName}] Auto-poll turn produced assistant text without calling any tool; stopping auto-poll rearm for session ${t.sessionId}`);return}this.armIdleLoopOrAutoPoll(t.sessionId);return}if(t.type==="session_complete"){this.cancelDataFlowWatchdog(e),this.cancelScheduledAutoPoll(e),e.failedTurnRecoveryScheduled=!1,e.idlePollLoop?.stop(),e.adapterSession.status="completed",this.emitProviderEvent(t,"session_complete",{exitCode:Number(t.data.exitCode)||0}),this.emit("status-change",t.sessionId,"completed");return}if(t.type==="question_request"){this.cancelDataFlowWatchdog(e),this.cancelSubmitTimeoutDetection(e);const o=typeof t.data.toolCallId=="string"?t.data.toolCallId:"",s=Array.isArray(t.data.questions)?t.data.questions:[];o&&(e.pendingQuestionToolCallId=o,e.pendingQuestions=s),this.emit("ask-user-question",{sessionId:t.sessionId,toolCallId:o||void 0,questions:s});return}if(t.type==="error"){if(t.data.nonFatal){this.resetDataFlowWatchdog(t.sessionId,e),this.emitProviderEvent(t,"error",{text:String(t.data.message||"ACode runtime error")});return}this.cancelDataFlowWatchdog(e),e.adapterSession.status="error",this.emitProviderEvent(t,"error",{text:String(t.data.message||"ACode runtime error")}),this.emit("status-change",t.sessionId,"error"),e.autoPollActive||this.recoverTurnFailure(t.sessionId,e);return}if(t.type==="mcp_status"){if(!t.data.action&&Array.isArray(t.data.tools)){const h=t.data.tools;h.some(f=>Z(f))||console.warn(`[${this.displayName}] ACode runtime is not exposing a poll_message tool. The LLM cannot call poll_message. Please configure an MCP server that provides poll_message (e.g. aws-mcp) in the dashboard panel for this runtime.`);const T=Array.isArray(t.data.servers)?t.data.servers:[],A=h.map(f=>({name:String(f.name??""),source:String(f.source??""),description:String(f.description??"")})).filter(f=>f.name),_={kind:"mcp",mcpServers:T,mcpTools:A};e.cachedMcpCapabilities=_,e.lastMcpCapabilities=_,e.lastCombinedCapabilities={kind:"combined",mcpServers:T,mcpTools:A,skills:e.lastCombinedCapabilities?.skills??[],skillsDir:e.lastCombinedCapabilities?.skillsDir,skillGroups:e.lastCombinedCapabilities?.skillGroups??[]},l(`[cap-diag] MCP capabilities cached: ${T.length} servers, ${A.length} tools`,{sessionId:t.sessionId,servers:T,toolNames:A.map(f=>f.name)}),e.capabilitiesFallbackTimer&&clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=setTimeout(()=>{const f=e.cachedMcpCapabilities;if(!f)return;const y={...f,skills:[],skillGroups:[]};this.emitProviderEvent(t,"runtime_capabilities",{capabilities:y,actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:JSON.stringify(y)}),l(`[cap-diag] MCP capabilities emitted via fallback (skill_status not received within ${R}ms)`,{sessionId:t.sessionId,mcpServers:f.mcpServers,mcpToolsCount:f.mcpTools?.length??0}),e.cachedMcpCapabilities=void 0,e.capabilitiesFallbackTimer=void 0},R);return}const o=String(t.data.action??"");l(`[ACode] \u{1F4E1} mcp_status event: action=${o}, server=${typeof t.data.server=="string"?t.data.server:"?"}, tool=${typeof t.data.tool=="string"?t.data.tool:"?"}, toolUseId=${typeof t.data.toolUseId=="string"?t.data.toolUseId.slice(0,16)+"\u2026":"none"}, failed=${t.data.failed===!0}, session=${t.sessionId}, status=${e.adapterSession.status}`);const s=typeof t.data.server=="string"?t.data.server:"mcp",n=typeof t.data.tool=="string"?t.data.tool:"",i=s&&n?`${s}__${n}`:n||s,a=t.data.arguments&&typeof t.data.arguments=="object"&&!Array.isArray(t.data.arguments)?t.data.arguments:void 0,u=et(i,a);e.autoPollActive&&(e.autoPollObservedAnyTool=!0,u.actionType==="idle"&&(e.autoPollObservedPollingTool=!0));const c=St(u.actionType)?u.actionDetail||W(void 0,s,n):W(u.actionDetail,s,n),m=typeof t.data.toolUseId=="string"?t.data.toolUseId:void 0,d=a?JSON.stringify(a,null,2):void 0,g={toolName:c,rawToolName:i,actionType:u.actionType,actionLabel:u.actionLabel,actionDetail:c,...d?{actionInput:d}:{},...a?{toolInput:a}:{},...m?{toolUseId:m,actionId:m}:{},metadata:{mcpServer:s}};if(t.data.action==="tool_result"){this.emitProviderEvent(t,"tool_use_end",{...g,toolResult:typeof t.data.result=="string"?t.data.result:JSON.stringify(t.data.result??"")});const h=u.actionType==="idle"&&!At(t.data.result)?"waiting_input":"thinking";e.adapterSession.status=h,this.cancelDataFlowWatchdog(e),e.pendingToolEventData=void 0;const C=u.actionType==="idle";this.emit("status-change",t.sessionId,h,C||h==="thinking"?void 0:g);return}const p=u.actionType==="idle"?"waiting_input":"tool_using";e.adapterSession.status=p,p==="tool_using"&&(this.resetDataFlowWatchdog(t.sessionId,e),e.pendingToolEventData={...g}),this.emitProviderEvent(t,"tool_use_start",g),this.emit("status-change",t.sessionId,p,g);return}if(t.type==="skill_status"){const s=(Array.isArray(t.data.skills)?t.data.skills:[]).map(d=>({name:String(d.name??""),description:typeof d.description=="string"?d.description:void 0,directory:typeof d.directory=="string"?d.directory:void 0})).filter(d=>d.name),n=typeof t.data.skillsDir=="string"?t.data.skillsDir:void 0,a=(Array.isArray(t.data.skillGroups)?t.data.skillGroups:[]).map(d=>{const g=Array.isArray(d.skills)?d.skills:[];return{dir:typeof d.dir=="string"?d.dir:"",exists:d.exists===!0,skills:g.map(p=>({name:String(p.name??""),description:typeof p.description=="string"?p.description:void 0,directory:typeof p.directory=="string"?p.directory:void 0})).filter(p=>p.name)}}).filter(d=>d.dir),u=e.cachedMcpCapabilities??e.lastMcpCapabilities,c=e.cachedMcpCapabilities!==void 0,m={kind:"combined",mcpServers:u?.mcpServers??[],mcpTools:u?.mcpTools??[],skills:s,skillsDir:n,skillGroups:a};this.emitProviderEvent(t,"runtime_capabilities",{capabilities:m,actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:JSON.stringify(m)}),e.lastCombinedCapabilities=m,l(`[cap-diag] Combined capabilities emitted ${c?"(startup merge)":"(runtime refresh)"}: ${(u?.mcpTools??[]).length} MCP tools, ${s.length} skills`,{sessionId:t.sessionId,mcpServers:u?.mcpServers??[],skillsDir:n}),e.capabilitiesFallbackTimer&&(clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=void 0),e.cachedMcpCapabilities=void 0;return}if(t.type==="session_started"){const o=F(t.data),s=b(t.data.contextLimit)||void 0,n=b(t.data.maxOutput)||void 0,i=b(t.data.inputLimit)||void 0,a=b(t.data.compactionThreshold)||void 0;let u=!1;o>0&&(e.adapterSession.totalUsage.inputTokens=o,e.adapterSession.totalUsage.outputTokens=0,u=!0),s!==void 0&&(e.adapterSession.totalUsage.contextLimit=s,u=!0),n!==void 0&&(e.adapterSession.totalUsage.maxOutput=n,u=!0),i!==void 0&&(e.adapterSession.totalUsage.inputLimit=i,u=!0),a!==void 0&&(e.adapterSession.totalUsage.compactionThreshold=a,u=!0),u&&this.emit("status-change",t.sessionId,e.adapterSession.status,{usage:e.adapterSession.totalUsage});return}if(t.type==="exit_plan_mode"){e.adapterSession.status="waiting_input";const o=typeof t.data.plan=="string"?t.data.plan:void 0;this.emitProviderEvent(t,"exit_plan_mode",{toolInput:t.data.toolInput&&typeof t.data.toolInput=="object"?t.data.toolInput:void 0,text:o||"\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F"}),this.emit("status-change",t.sessionId,"waiting_input",{actionLabel:"\u5BA1\u6279\u8BA1\u5212",actionDetail:o||"\u7B49\u5F85\u7528\u6237\u5BA1\u6279\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F"});return}if(t.type==="context_compaction"){const o=t.data,s=o.action,n=s==="start",i=s==="end",a=s==="phase",u=o.parentId,c=o.compactionId;let m,d;if(n){const p=String(o.sizeKB??o.sizeBeforeKB??"?"),h=String(o.messageCount??o.messageCountBefore??"?"),C=o.estimatedTokens,T=o.actualInputTokens?`input=${o.actualInputTokens}`:"",A=o.actualOutputTokens?`output=${o.actualOutputTokens}`:"",_=o.trigger?`, \u89E6\u53D1: ${o.trigger}`:"";m="\u4E0A\u4E0B\u6587\u538B\u7F29\u5F00\u59CB",C!==void 0?d=`\u538B\u7F29\u524D: ~${C} tokens, \u6D88\u606F: ${h}\u6761`+(T?`, \u5B9E\u9645 tokens: ${T} ${A}`:"")+_:d=`\u538B\u7F29\u524D: ${p}KB, \u6D88\u606F: ${h}\u6761`+(T?`, \u5B9E\u9645 tokens: ${T} ${A}`:"")+_}else if(a)m=String(o.phaseLabel??"\u538B\u7F29\u9636\u6BB5"),d=String(o.phaseDetail??"");else{const p=o.tokensBefore,h=o.tokensAfter,C=o.freedTokens,T=String(o.sizeBeforeKB??"?"),A=String(o.sizeAfterKB??"?"),_=String(o.freedKB??"?"),f=String(o.strategy??"?"),y=Number(o.prunedToolMessages??0),S=Number(o.summarizedMessages??0);m="\u538B\u7F29\u5B8C\u6210",p!==void 0&&h!==void 0?d=`\u91CA\u653E: ${C??p-h} tokens, ${p} tokens \u2192 ${h} tokens, \u7B56\u7565: ${f}`+(y?`, \u88C1\u526A\u5DE5\u5177: ${y}\u6761`:"")+(S?`, \u6458\u8981\u5316: ${S}\u6761`:""):d=`\u91CA\u653E: ${_}KB, ${T}KB \u2192 ${A}KB, \u7B56\u7565: ${f}`+(y?`, \u88C1\u526A\u5DE5\u5177: ${y}\u6761`:"")+(S?`, \u6458\u8981\u5316: ${S}\u6761`:"")}n&&(e.adapterSession.status="compacting");const g={actionType:"context_compaction",actionLabel:m,actionDetail:d};if(n&&c)g.actionId=c;else if((a||i)&&c)if(g.parentId=c,a){const p=String(o.phase??"unknown");g.actionId=`${c}-phase-${p}`}else g.actionId=`${c}-end`;a&&u&&!g.parentId&&(g.parentId=u),i&&(e.adapterSession.totalUsage.inputTokens=b(o.tokensAfter),e.adapterSession.totalUsage.outputTokens=0,g.usage={...e.adapterSession.totalUsage}),this.emitProviderEvent(t,"context_compaction",g),this.emit("status-change",t.sessionId,"compacting",g);return}this.emitProviderEvent(t,"thinking",{text:JSON.stringify(t.data)})}}emitProviderEvent(t,e,o){this.emit("event",{type:e,sessionId:t.sessionId,timestamp:t.timestamp,data:o})}armIdleLoopOrAutoPoll(t){const e=this.sessions.get(t);if(!(!e||this.isTerminalStatus(e.adapterSession.status))){if(e.idleCommands?.idleInputCommand){this.getIdlePollLoop(e).start();return}this.scheduleAutoPoll(t)}}getIdlePollLoop(t){if(t.idlePollLoop)return t.idlePollLoop;const e=t.adapterSession.sessionId,o=t.config.agentId;return t.idlePollLoop=new tt({getStatus:()=>this.sessions.get(e)?.adapterSession.status,getCommand:()=>this.sessions.get(e)?.idleCommands?.idleInputCommand,isPollingCommand:s=>w(s),preDispatchHook:()=>null,dispatchPollingPrompt:(s,n)=>this.submitAutoPollPrompt(e,n?s:lt,{keepWaitingStatus:!0}),dispatchRegularIdleCommand:s=>this.submitAutoPollPrompt(e,s)}),t.idlePollLoop}submitAutoPollPrompt(t,e,o){const s=this.sessions.get(t);if(!s||this.isTerminalStatus(s.adapterSession.status))return;const n=(s.autoPollToken??0)+1;s.autoPollToken=n,s.autoPollActive=!0,s.autoPollObservedPollingTool=!1,s.autoPollObservedAssistantText=!1,s.autoPollObservedAnyTool=!1,s.stopAutoPollAfterCurrentTurn=!1,o?.keepWaitingStatus||(s.adapterSession.status="thinking",this.emit("status-change",t,"thinking")),this.startSubmitTimeoutDetection(t,s,"submitAutoPollPrompt"),s.runtime.submit(e).catch(i=>{this.emitRuntimeError(t,i)}).finally(()=>{const i=this.sessions.get(t);if(i){if(i.autoPollToken!==n){l(`[ACode] submitAutoPollPrompt.finally: token mismatch (my=${n}, current=${i.autoPollToken}), skipping cleanup \u2014 newer turn has taken over`);return}if(this.cancelSubmitTimeoutDetection(i),i.autoPollActive=!1,i.failedTurnRecoveryScheduled||i.autoPollTimer){i.failedTurnRecoveryScheduled=!1;return}if(i.stopAutoPollAfterCurrentTurn){i.stopAutoPollAfterCurrentTurn=!1,i.autoPollObservedPollingTool=!1,i.autoPollObservedAssistantText=!1,i.autoPollObservedAnyTool=!1;return}if(i.adapterSession.status==="error"){this.recoverTurnFailure(t,i);return}if(i.adapterSession.status==="thinking"||i.adapterSession.status==="tool_using"){this.recoverResolvedTurnWithoutTerminalEvent(t);return}i.adapterSession.status==="waiting_input"&&this.armIdleLoopOrAutoPoll(t)}})}scheduleAutoPoll(t,e=nt){const o=this.sessions.get(t);!o||o.autoPollActive||o.autoPollTimer||this.isTerminalStatus(o.adapterSession.status)||(o.autoPollTimer=setTimeout(()=>{const s=this.sessions.get(t);!s||s.autoPollActive||this.isTerminalStatus(s.adapterSession.status)||(s.autoPollTimer=void 0,this.submitAutoPollPrompt(t,M,{keepWaitingStatus:!0}))},e))}cancelScheduledAutoPoll(t){t.autoPollTimer&&(clearTimeout(t.autoPollTimer),t.autoPollTimer=void 0)}isTerminalStatus(t){return t==="completed"||t==="terminated"}emitRuntimeError(t,e,o){const s=this.sessions.get(t);s&&(s.adapterSession.status="error",this.emitRuntimeErrorEvent(t,e),this.emit("status-change",t,"error"),o?.recover&&this.recoverTurnFailure(t,s))}emitRuntimeErrorEvent(t,e){const o=new Date().toISOString();this.emit("event",{type:"error",sessionId:t,timestamp:o,data:{text:e instanceof Error?e.message:String(e)}})}estimateOutputTokensFromMessages(t){const e=t.filter(o=>o.role==="assistant").map(o=>o.content).join("");return Math.max(0,Math.round(e.length/4))}recoverTurnFailure(t,e){if(this.isTerminalStatus(e.adapterSession.status))return;if(e.adapterSession.status==="tool_using"&&e.pendingToolEventData){const a=e.pendingToolEventData;l(`[ACode] recoverTurnFailure: \u8865\u53D1 tool_use_end (tool: ${a.toolName??"unknown"}) \u5173\u95ED\u65F6\u95F4\u7EBF\u6761\u76EE\uFF0C\u907F\u514D\u6C38\u4E45\u5361\u5728\u5DE5\u5177\u6267\u884C\u72B6\u6001`),this.emit("event",{type:"tool_use_end",sessionId:t,timestamp:new Date().toISOString(),data:{...a,toolResult:"[aborted] \u5DE5\u5177\u6267\u884C\u88AB\u6570\u636E\u6D41\u770B\u95E8\u72D7\u4E2D\u65AD"}}),e.pendingToolEventData=void 0}const o=this.estimateOutputTokensFromMessages(e.adapterSession.messages);if(o>0){const a=e.adapterSession.totalUsage.outputTokens;e.adapterSession.totalUsage.outputTokens=o,l(`[ACode] recoverTurnFailure: \u4F30\u7B97\u8986\u76D6 output tokens ${a} -> ${o} (totalUsage now: input=${e.adapterSession.totalUsage.inputTokens}, output=${e.adapterSession.totalUsage.outputTokens})`)}const s=e.idleCommands?.idleInputCommand,i=!!(s&&w(s))?{actionType:"idle",actionLabel:"\u76D1\u542C\u6D88\u606F",actionDetail:"aws-mcp/poll_message"}:void 0;if(e.autoPollTimer||e.failedTurnRecoveryScheduled){e.adapterSession.status!=="waiting_input"&&(e.adapterSession.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:e.adapterSession.totalUsage,...i}));return}this.cancelScheduledAutoPoll(e),e.adapterSession.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:e.adapterSession.totalUsage,...i}),e.failedTurnRecoveryScheduled=!0,e.autoPollTimer=setTimeout(()=>{const a=this.sessions.get(t);if(!a||a.autoPollActive||this.isTerminalStatus(a.adapterSession.status)){a&&(a.failedTurnRecoveryScheduled=!1);return}a.autoPollTimer=void 0,a.failedTurnRecoveryScheduled=!1,a.idleCommands?.idleInputCommand?this.getIdlePollLoop(a).start():this.submitAutoPollPrompt(t,M,{keepWaitingStatus:!0})},rt)}recoverResolvedTurnWithoutTerminalEvent(t){l(`[ACode] \u25B6\uFE0F recoverResolvedTurnWithoutTerminalEvent called for session ${t}`);const e=this.sessions.get(t);if(!e||this.isTerminalStatus(e.adapterSession.status)){l(`[ACode] Skipping recovery: entry=${!!e}, isTerminal=${e?this.isTerminalStatus(e.adapterSession.status):"N/A"}`);return}if(l(`[ACode] Current status: ${e.adapterSession.status}`),e.adapterSession.status!=="thinking"&&e.adapterSession.status!=="tool_using"){l(`[ACode] Skipping recovery: status is ${e.adapterSession.status} (not thinking/tool_using)`);return}console.warn(`[ACode] \u26A0\uFE0F Detected stuck state: ${e.adapterSession.status} after submit resolved! Recovering to waiting_input. If runtime.submit() is still pending (e.g., built-in tool execution not interruptible by abort()), the submitQueue is deadlocked and subsequent auto-poll/user submits will never execute.`),l("[ACode] Recovering to waiting_input..."),e.adapterSession.status="waiting_input";const o=e.idleCommands?.idleInputCommand,n=!!(o&&w(o))?{actionType:"idle",actionLabel:"\u76D1\u542C\u6D88\u606F",actionDetail:"aws-mcp/poll_message"}:void 0;this.emit("status-change",t,"waiting_input",n),l(`[ACode] \u2705 Recovery complete, status now: ${e.adapterSession.status}`),l("[ACode] \u25B6\uFE0F Arming idle loop or auto-poll..."),this.armIdleLoopOrAutoPoll(t),l("[ACode] \u2705 Idle loop armed, recovery process complete")}startSubmitTimeoutDetection(t,e,o){this.cancelSubmitTimeoutDetection(e),e.watchdogSubmitStartTime=Date.now(),e.watchdogLastDataFlowTime=Date.now(),e.watchdogTimer=setInterval(()=>{const s=this.sessions.get(t);if(!s){this.cancelSubmitTimeoutDetection(e);return}const n=s.adapterSession.status,i=Date.now();if(n==="waiting_input"){s.watchdogSubmitStartTime=i,s.watchdogLastDataFlowTime=i;return}if(n==="tool_using"){const c=i-(s.watchdogLastDataFlowTime||i);if(c>=at){const m=String(s.pendingToolEventData?.rawToolName??"");if(m.endsWith("await_complete")){console.warn(`[ACode] tool_using elapsed ${Math.round(c/1e3)}s but await_complete is running (session: ${t}, tool: ${m}), skipping recovery (sub-agents have their own watchdogs, bg commands have timeout limits)`),s.watchdogSubmitStartTime=i,s.watchdogLastDataFlowTime=i;return}if(console.warn(`[ACode] CRITICAL: tool_using slow timeout triggered after ${Math.round(c/1e3)}s (source: ${o}, session: ${t}). Tool execution likely hung. Forcing recovery via recoverTurnFailure.`),s.runtime.detachCurrentToolExecution?.()){console.warn(`[ACode] tool_using slow (${Math.round(c/1e3)}s): detached tool ${m} to background (session: ${t}); waiting for the real tool_result to continue the turn`),s.watchdogSubmitStartTime=i,s.watchdogLastDataFlowTime=i;return}this.executeWatchdogRecovery(t,s,o,"tool_using_slow",c);return}s.watchdogSubmitStartTime=i;return}if(n!=="thinking")return;const a=i-(s.watchdogSubmitStartTime||i),u=i-(s.watchdogLastDataFlowTime||i);if(u>=it){console.warn(`[ACode] CRITICAL: Data flow watchdog triggered after ${Math.round(u/1e3)}s (source: ${o}, session: ${t}, status: ${n}). No stream data received. Forcing recovery via recoverTurnFailure.`),this.executeWatchdogRecovery(t,s,o,"data_flow",u);return}if(a>=ut){console.warn(`[ACode] CRITICAL: submit timeout detected after ${Math.round(a/1e3)}s (source: ${o}, session: ${t}, status: ${n}). Forcing recovery to prevent permanent state stuck.`),this.executeWatchdogRecovery(t,s,o,"submit_timeout",a);return}},st)}executeWatchdogRecovery(t,e,o,s,n){l(`[ACode] Watchdog (${s}): calling runtime.abort() after ${Math.round(n/1e3)}s...`);try{e.runtime.abort(),l(`[ACode] Watchdog (${s}): runtime.abort() called`)}catch(i){console.warn(`[ACode] \u26A0\uFE0F Watchdog (${s}): runtime.abort() threw: ${i instanceof Error?i.message:String(i)}`)}this.cancelSubmitTimeoutDetection(e),this.recoverTurnFailure(t,e),console.warn(`[ACode] \u26A0\uFE0F Watchdog (${s}) recovery complete. If abort() could not cancel the underlying operation, submitQueue may still be deadlocked.`)}cancelSubmitTimeoutDetection(t){t.watchdogTimer&&(clearInterval(t.watchdogTimer),t.watchdogTimer=void 0),t.watchdogSubmitStartTime=void 0,t.watchdogLastDataFlowTime=void 0}resetDataFlowWatchdog(t,e){e.watchdogLastDataFlowTime=Date.now()}startDataFlowWatchdog(t,e){e.watchdogLastDataFlowTime=Date.now()}cancelDataFlowWatchdog(t){t.watchdogLastDataFlowTime=Date.now()}formatAiRequestActionDetail(t){const e=`
1
+ import{EventEmitter as B}from"node:events";import L from"node:path";import q from"node:fs/promises";import{pathToFileURL as N}from"node:url";import{v4 as D}from"uuid";import{getAcodeConfigFile as $,getAcodeSkillsDir as K,getRuntimeHomeDir as H}from"../config.js";import{getReleasedAcodeEntryPath as j}from"../services/acode-package.js";import{getInstanceAiConfigDebugLogger as P}from"../utils/instance-ai-config-debug-logger.js";import{redactForLog as O}from"../services/instance-ai-config-service.js";import{subAgentManager as Q}from"../services/sub-agent-manager-instance.js";import{agentPtyManager as G}from"../services/agent-pty-manager.js";import{resolveAcodeProviderConfig as z}from"./instance-ai-config-resolver.js";import{recordAgentFileChange as J}from"../services/workspaceTaskChangeWatcher.js";import{getBrowserTools as Y,closeBrowserSession as X,registerListenerWakeHook as V,unregisterListenerWakeHook as E}from"../services/browser-session-manager.js";import{isMessagePollingIdleCommand as w,isPollMessageToolDescriptor as Z}from"./acode-tool-names.js";import{IdlePollLoop as tt}from"./idle-poll-loop.js";import{getCanonicalMcpDetail as I,getToolActionInfo as et}from"./types.js";const ot=process.env.ACODE_COMPACTION_DEBUG==="1";function l(...r){ot&&console.log(...r)}const M=["Continue the AgentsWork message loop now.","You MUST call the exact MCP tool named aws-mcp__poll_message as your next action and wait for the next assigned message or task.","Do not answer in plain text before calling aws-mcp__poll_message.","After handling any received work, reply through the appropriate aws-mcp messaging tool, then continue listening again."].join(" "),st=5e3,it=4e4,at=5*6e4,nt=250,rt=2e3,ut=12e4,R=3e3,lt="\u7CFB\u7EDF\u63D0\u9192\uFF1A\u5982\u679C\u4EFB\u52A1\u5DF2\u5B8C\u6210\u6216\u6CA1\u6709\u5176\u5B83\u8981\u505A\u7684\uFF0C\u5148\u8C03\u7528 poll_message \u5DE5\u5177\u963B\u585E\u7B49\u5F85\u65B0\u6D88\u606F\u548C\u6D41\u7A0B\u7EBF\u4EFB\u52A1\u63D0\u9192\uFF1B\u6536\u5230\u6D41\u7A0B\u4EFB\u52A1\u63D0\u9192\u540E\u8C03\u7528 my_task \u67E5\u770B\u5DF2\u7531\u540E\u53F0\u9759\u9ED8\u62A2\u5360\u7684\u4EFB\u52A1\u8BE6\u60C5\u5E76\u76F4\u63A5\u5904\u7406\uFF1B\u5B8C\u6210\u4EFB\u52A1\u540E\u8C03\u7528 submit_task_result \u63D0\u4EA4\u7ED3\u679C\uFF0C\u7136\u540E\u7EE7\u7EED poll_message\u3002 \u8C03\u7528 submit_task_result \u65F6\u8BF7\u4E00\u5E76\u4F20\u5165 changeLog\uFF08\u672C\u6B21\u5904\u7406\u7684\u6587\u4EF6/\u5185\u5BB9\u53D8\u66F4\u65E5\u5FD7\uFF0C\u5305\u542B operation \u4E0E path\uFF09\uFF0C\u7528\u4E8E AI \u56DE\u9000\u3002";function dt(){return L.resolve(j())}function ct(r){return N(L.resolve(r)).href}const U=128e3,k={"claude-4":{contextLimit:2e5,maxOutput:8192},"claude-sonnet-4":{contextLimit:2e5,maxOutput:8192},"claude-3-5-sonnet":{contextLimit:2e5,maxOutput:8192},"claude-3-opus":{contextLimit:2e5,maxOutput:8192},"claude-3-haiku":{contextLimit:2e5,maxOutput:8192},"claude-2":{contextLimit:1e5,maxOutput:4096},"gpt-4o":{contextLimit:128e3,maxOutput:16384},"gpt-4-turbo":{contextLimit:128e3,maxOutput:4096},"gpt-4":{contextLimit:8192,maxOutput:4096},"gpt-3.5-turbo":{contextLimit:16384,maxOutput:4096},o1:{contextLimit:2e5,maxOutput:1e5},"o3-mini":{contextLimit:2e5,maxOutput:1e5},"gemini-2.0-flash":{contextLimit:1048576,maxOutput:8192},"gemini-2.5-pro":{contextLimit:1048576,maxOutput:8192},"gemini-1.5-pro":{contextLimit:2097152,maxOutput:8192},"gemini-1.5-flash":{contextLimit:1048576,maxOutput:8192},deepseek:{contextLimit:64e3,maxOutput:8192},"deepseek-chat":{contextLimit:64e3,maxOutput:8192},"deepseek-reasoner":{contextLimit:64e3,maxOutput:8192},"qwen-max":{contextLimit:32e3,maxOutput:8192},"qwen-plus":{contextLimit:128e3,maxOutput:8192},"qwen-turbo":{contextLimit:1e6,maxOutput:8192},"glm-4":{contextLimit:128e3,maxOutput:4096},"yi-":{contextLimit:2e5,maxOutput:4096},"llama-3":{contextLimit:8192,maxOutput:4096},"llama-2":{contextLimit:4096,maxOutput:4096},mistral:{contextLimit:32e3,maxOutput:4096},mixtral:{contextLimit:32e3,maxOutput:4096},codestral:{contextLimit:256e3,maxOutput:8192},grok:{contextLimit:131072,maxOutput:4096},"nova-":{contextLimit:2e5,maxOutput:8192}};function mt(r){if(!r)return U;const t=r.toLowerCase().trim();if(k[t])return k[t].contextLimit;const e=Object.keys(k).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?k[e[0]].contextLimit:U}const F=4096;function pt(r){if(!r)return F;const t=r.toLowerCase().trim();if(k[t])return k[t].maxOutput;const e=Object.keys(k).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?k[e[0]].maxOutput:F}function gt(r){if(!r||typeof r!="object")return;const t=r,e=b(t.inputTokens,t.input_tokens,t.promptTokens,t.prompt_tokens),o=b(t.outputTokens,t.output_tokens,t.completionTokens,t.completion_tokens);if(!(e===0&&o===0))return{inputTokens:e,outputTokens:o}}function b(...r){for(const t of r){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 0}function v(r){return b(r.estimatedContextTokens,r.contextTokens,r.context_tokens,r.contextUsedTokens,r.context_used_tokens)}function ft(r){return r==="stderr"||r==="mixed"?r:"stdout"}function ht(r){if(!r||typeof r!="object"||Array.isArray(r))return;const t={};for(const[e,o]of Object.entries(r))typeof o=="string"&&(t[e]=o);return Object.keys(t).length>0?t:void 0}function Tt(r){return r.failed===!0}function W(r,t,e){if(!r)return e?`${t}/${e}`:t;const o=`${t}__`;return r.startsWith(o)?I(`${t}__${r.slice(o.length)}`):I(r.replace("/","__"))}function St(r){return r==="read_file"||r==="edit_file"||r==="write_file"||r==="bash"}function At(r){const t=_t(r);return t?[t.directMessages,t.groupMessages,t.messages].some(e=>Array.isArray(e)&&e.length>0):typeof r=="string"&&r.trim().length>0}function _t(r){if(r&&typeof r=="object"&&!Array.isArray(r))return r;if(!(typeof r!="string"||!r.trim()))try{const t=JSON.parse(r);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}class vt extends B{constructor(){super(...arguments),this.providerId="acode",this.displayName="ACode",this.sessions=new Map,this.listenerWakeHooks=new Map}async startSession(t,e){const o=H(),s=e.mcpConfigPath||$(o),{resolved:n,configContextLimit:i}=await this.resolveAcodeProvider(e,s),a=n.model,u=i??mt(a),c=pt(a),m={sessionId:t,status:"starting",messages:[],createdAt:new Date().toISOString(),totalUsage:{inputTokens:0,outputTokens:0,contextLimit:u,maxOutput:c}};this.sessions.set(t,{adapterSession:m,config:e,runtime:await this.createRuntime(t,a,e,o),autoPollActive:!1}),this.emit("status-change",t,"starting");const d=this.sessions.get(t);if(!d)throw new Error("ACode session was not initialized");const g=()=>{const p=this.sessions.get(t);p&&this.getIdlePollLoop(p).start()};this.listenerWakeHooks.set(t,g),V(e.agentId,g);try{await d.runtime.start(),m.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:d.adapterSession.totalUsage}),e.initialPrompt?.trim()?this.startInitialPromptTurn(t,e.initialPrompt):this.armIdleLoopOrAutoPoll(t)}catch(p){m.status="error",this.emitRuntimeErrorEvent(t,p),this.emit("status-change",t,"error");const h=this.sessions.get(t);throw h?.capabilitiesFallbackTimer&&clearTimeout(h.capabilitiesFallbackTimer),this.sessions.delete(t),E(e.agentId,this.listenerWakeHooks.get(t)),this.listenerWakeHooks.delete(t),p}}async sendMessage(t,e){const o=Date.now();l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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("[ACode] \u25B6\uFE0F sendMessage STARTED"),l(`[ACode] Session: ${t}`),l(`[ACode] Message: ${e.slice(0,100)}${e.length>100?"...":""}`),l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");const s=this.requireSession(t),n=s.adapterSession.status;l(`[ACode] Previous status: ${n}`),this.cancelScheduledAutoPoll(s),s.failedTurnRecoveryScheduled=!1,s.idlePollLoop?.stop();const i={id:D(),sessionId:t,role:"user",content:e,timestamp:new Date().toISOString()};s.adapterSession.messages.push(i),this.emit("conversation-message",t,i),l(`[ACode] Changing status: ${n} \u2192 thinking`),s.adapterSession.status="thinking",this.emit("status-change",t,"thinking"),this.startSubmitTimeoutDetection(t,s,"sendMessage");try{l("[ACode] \u25B6\uFE0F Calling runtime.submit()...");const a=Date.now();await s.runtime.submit(e);const u=Date.now()-a;this.cancelSubmitTimeoutDetection(s),l(`[ACode] \u2705 runtime.submit() completed in ${u}ms`),l(`[ACode] Current status after submit: ${s.adapterSession.status}`),l("[ACode] \u25B6\uFE0F Calling recoverResolvedTurnWithoutTerminalEvent()..."),this.recoverResolvedTurnWithoutTerminalEvent(t),l(`[ACode] Status after recovery: ${s.adapterSession.status}`);const c=Date.now()-o;l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(`[ACode] \u2705 sendMessage COMPLETED in ${c}ms`),l("[ACode] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}catch(a){const u=Date.now()-o;console.error(`[ACode] \u274C sendMessage FAILED after ${u}ms:`,a instanceof Error?a.message:String(a)),this.cancelSubmitTimeoutDetection(s),l("[ACode] \u25B6\uFE0F Calling emitRuntimeError with recover=true..."),this.emitRuntimeError(t,a,{recover:!0}),l(`[ACode] Status after error recovery: ${s.adapterSession.status}`)}}async sendConfirmation(t,e){}async sendQuestionAnswer(t,e){const o=this.sessions.get(t);if(!o)return;const s=o.pendingQuestionToolCallId;if(!s){l(`[AcodeSdkAdapter] sendQuestionAnswer: no pending question for session ${t}`);return}o.pendingQuestionToolCallId=void 0,o.pendingQuestions=void 0,o.runtime.submitQuestionAnswer&&o.runtime.submitQuestionAnswer(s,e),this.startSubmitTimeoutDetection(t,o,"sendQuestionAnswer")}async abortCurrentTurn(t){await this.requireSession(t).runtime.abort()}async resetContext(t){const e=this.requireSession(t);if(this.cancelScheduledAutoPoll(e),e.failedTurnRecoveryScheduled=!1,e.autoPollActive=!1,e.autoPollObservedPollingTool=!1,e.autoPollObservedAssistantText=!1,e.autoPollObservedAnyTool=!1,e.stopAutoPollAfterCurrentTurn=!1,e.idlePollLoop?.stop(),!e.runtime.resetContext)throw new Error("ACode runtime does not support context reset");await e.runtime.resetContext(),e.adapterSession.messages=[];const o=e.adapterSession.totalUsage;if(e.adapterSession.totalUsage={inputTokens:0,outputTokens:0,contextLimit:o.contextLimit,maxOutput:o.maxOutput,inputLimit:o.inputLimit,compactionThreshold:o.compactionThreshold},e.adapterSession.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:e.adapterSession.totalUsage}),e.config.initialPrompt?.trim()){this.startInitialPromptTurn(t,e.config.initialPrompt);return}this.armIdleLoopOrAutoPoll(t)}async terminateSession(t){const e=this.sessions.get(t);if(!e)return;this.cancelScheduledAutoPoll(e),e.failedTurnRecoveryScheduled=!1,e.idlePollLoop?.stop(),e.capabilitiesFallbackTimer&&(clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=void 0),await e.runtime.stop();const o=e.config.agentId;o&&(E(o,this.listenerWakeHooks.get(t)),X(o)),this.listenerWakeHooks.delete(t),e.adapterSession.status="terminated",this.sessions.delete(t),this.emit("status-change",t,"terminated")}getConversation(t){return this.sessions.get(t)?.adapterSession.messages??[]}hasSession(t){return this.sessions.has(t)}getProviderSessionId(t){return this.sessions.has(t)?t:void 0}getSessionStatus(t){return this.sessions.get(t)?.adapterSession.status}notifyForceMessage(t){const e=this.sessions.get(t);return e?.runtime?.notifyForceMessage?(e.runtime.notifyForceMessage(),!0):!1}getCapabilities(t){return this.sessions.get(t)?.lastCombinedCapabilities}getPendingQuestion(t){const e=this.sessions.get(t);if(e?.pendingQuestionToolCallId)return{toolCallId:e.pendingQuestionToolCallId,questions:e.pendingQuestions??[]}}cleanup(){for(const t of this.sessions.keys())this.terminateSession(t)}setIdleCommands(t,e){const o=this.sessions.get(t);if(o){if(o.idleCommands=e,this.cancelScheduledAutoPoll(o),e.idleInputCommand&&w(e.idleInputCommand)){this.getIdlePollLoop(o).start();return}o.adapterSession.status==="waiting_input"&&(e.idleInputCommand||e.nonInputCommand)&&this.getIdlePollLoop(o).start()}}setRuntimeConstructorForTest(t){this.runtimeConstructor=t}async loadAcodeProviderSection(t){try{const e=await q.readFile(t,"utf-8"),o=JSON.parse(e),n=o.provider?.default,i=n?.options,a=b(o.contextLimit),u={},c=n?.models;if(c&&typeof c=="object"){for(const[m,d]of Object.entries(c))if(d&&typeof d=="object"){const g=b(d.contextLimit);g>0&&(u[m.trim()]=g)}}return{...n?.model?{model:n.model}:{},...i?.baseURL||i?.baseUrl?{baseURL:i?.baseURL||i?.baseUrl}:{},...i?.apiKey?{apiKey:i.apiKey}:{},...a>0?{contextLimit:a}:{},...Object.keys(u).length>0?{modelContextLimits:u}:{}}}catch(e){const o=e instanceof Error?e.message:String(e);return P().log({level:"warn",category:"load",message:`loadAcodeProviderSection failed: ${t}: ${o}`,source:"bridge"}),{}}}async resolveAcodeProvider(t,e){const o=typeof t.model=="string"&&t.model.trim()?t.model.trim():void 0,s=P();s.log({level:"info",category:"resolve",message:"resolveAcodeProvider \u8F93\u5165",source:"bridge",details:{configModel:t.model??null,configInstanceAiConfig:t.instanceAiConfig?O(t.instanceAiConfig):null,configPath:e}});const n={...t.instanceAiConfig?.model?{model:t.instanceAiConfig.model}:{},...t.instanceAiConfig?.baseURL?{baseURL:t.instanceAiConfig.baseURL}:{},...t.instanceAiConfig?.apiKey?{apiKey:t.instanceAiConfig.apiKey}:{},...t.instanceAiConfig?.effort?{effort:t.instanceAiConfig.effort}:{},...o?{model:o}:{}},i=await this.loadAcodeProviderSection(e);let a=i.contextLimit;if(!a&&i.modelContextLimits){const c=o||t.instanceAiConfig?.model||i.model;c&&i.modelContextLimits[c]&&(a=i.modelContextLimits[c])}const u=z(n,i,"acode-default");return s.log({level:"info",category:"resolve",message:"resolveAcodeProvider \u89E3\u6790\u7ED3\u679C",source:"bridge",details:{instanceConfig:O(n),globalConfigModel:i?.model??null,resolvedModel:u.model,resolvedBaseURL:u.baseURL??null,resolvedApiKey:u.apiKey?"[set]":null,configContextLimit:a,resolvedSource:u.source}}),{resolved:u,configPath:e,perSessionModel:o,configContextLimit:a}}async createRuntime(t,e,o,s){const n=await this.loadRuntimeConstructor(),i=o.mcpConfigPath||$(s);let a=[];try{a=await Y(o.agentId,o.scopeKey)}catch(m){l(`[acode-adapter] browser tools injection skipped for agent ${o.agentId}:`,m.message)}const u=new n({sessionId:t,agentId:o.agentId,workingDirectory:o.workingDirectory,configPath:i,skillsDir:K(s),model:e,systemPrompt:typeof o.systemPrompt=="string"?o.systemPrompt:void 0,globalPrompt:typeof o.globalPrompt=="string"?o.globalPrompt:void 0,rolePrompt:typeof o.rolePrompt=="string"?o.rolePrompt:void 0,memory:typeof o.memory=="string"?o.memory:void 0,env:o.envOverrides,subAgentManager:Q,terminalManager:G,...o.subAgentModel?{subAgentModel:o.subAgentModel}:{},...o.subAgentEffort?{subAgentEffort:o.subAgentEffort}:{},...o.instanceAiConfig?.effort?{effort:o.instanceAiConfig.effort}:{},onFileChange:m=>J({...m,agentId:o.agentId,workspacePath:o.workingDirectory}),extraBuiltInTools:a});return P().log({level:"info",category:"resolve",message:"ACode provider resolved",source:"bridge",sessionId:t,details:{resolvedModel:e,perInstanceModel:o.instanceAiConfig?.model||null,perInstanceBaseURL:o.instanceAiConfig?.baseURL?"[set]":null,perInstanceApiKey:o.instanceAiConfig?.apiKey?"[set]":null,configPath:i}}),u.on("event",m=>this.forwardAcodeEvent(m)),u}async loadRuntimeConstructor(){if(this.runtimeConstructor)return this.runtimeConstructor;const t=dt(),e=await import(ct(t));if(!e.ACodeRuntime)throw new Error(`ACode runtime export not found: ${t}`);return this.runtimeConstructor=e.ACodeRuntime,this.runtimeConstructor}requireSession(t){const e=this.sessions.get(t);if(!e)throw new Error("ACode session not found");return e}startInitialPromptTurn(t,e){const o=this.sessions.get(t);o&&(o.adapterSession.status="thinking",this.emit("status-change",t,"thinking"),this.startSubmitTimeoutDetection(t,o,"startInitialPromptTurn"),o.runtime.submit(e).then(()=>{this.cancelSubmitTimeoutDetection(o),this.recoverResolvedTurnWithoutTerminalEvent(t)}).catch(s=>{const n=this.sessions.get(t);n&&(this.cancelSubmitTimeoutDetection(n),this.emitRuntimeError(t,s,{recover:!0}))}))}forwardAcodeEvent(t){const e=this.sessions.get(t.sessionId);if(e){if(t.type==="assistant_delta"){const o=typeof t.data.text=="string"?t.data.text:"";e.autoPollActive&&(e.autoPollObservedAssistantText=!0),e.adapterSession.messages.push({id:D(),sessionId:t.sessionId,role:"assistant",content:o,timestamp:t.timestamp}),this.resetDataFlowWatchdog(t.sessionId,e),this.emitProviderEvent(t,"text_delta",{text:o});return}if(t.type==="thinking_delta"){const o=typeof t.data.text=="string"?t.data.text:"";this.resetDataFlowWatchdog(t.sessionId,e),this.emitProviderEvent(t,"thinking",{text:o});return}if(t.type==="command_output"){this.emitProviderEvent(t,"command_output",{text:typeof t.data.text=="string"?t.data.text:"",stream:ft(t.data.stream),sequence:typeof t.data.sequence=="number"?t.data.sequence:void 0,cwd:typeof t.data.cwd=="string"?t.data.cwd:void 0,commandLineCount:typeof t.data.commandLineCount=="number"?t.data.commandLineCount:void 0,commandFilePath:typeof t.data.commandFilePath=="string"?t.data.commandFilePath:void 0});return}if(t.type==="ai_request"){const o=v(t.data);let s;if(o>0){const a=e.adapterSession.totalUsage.inputTokens;a>0?e.adapterSession.totalUsage.inputTokens=Math.min(o,Math.floor(a*1.5)):e.adapterSession.totalUsage.inputTokens=o,s={...e.adapterSession.totalUsage}}e.adapterSession.status==="compacting"&&(e.adapterSession.status="thinking"),e.adapterSession.status==="waiting_input"&&(e.adapterSession.status="thinking");const i={actionType:"ai_request",actionLabel:"AI\u8BF7\u6C42",actionDetail:this.formatAiRequestActionDetail(t.data)};s&&(i.usage=s),this.emit("status-change",t.sessionId,e.adapterSession.status,i),this.startDataFlowWatchdog(t.sessionId,e),e.adapterSession.status==="thinking"&&e.watchdogSubmitStartTime&&(e.watchdogSubmitStartTime=Date.now()),this.emitProviderEvent(t,"ai_request",{model:typeof t.data.model=="string"?t.data.model:void 0,endpoint:typeof t.data.endpoint=="string"?t.data.endpoint:void 0,requestMethod:typeof t.data.requestMethod=="string"?t.data.requestMethod:void 0,requestUrl:typeof t.data.requestUrl=="string"?t.data.requestUrl:void 0,requestHeaders:ht(t.data.requestHeaders),stream:typeof t.data.stream=="boolean"?t.data.stream:void 0,messageCount:typeof t.data.messageCount=="number"?t.data.messageCount:void 0,toolCount:typeof t.data.toolCount=="number"?t.data.toolCount:void 0,lastUserMessagePreview:typeof t.data.lastUserMessagePreview=="string"?t.data.lastUserMessagePreview:void 0,requestBody:typeof t.data.requestBody=="string"?t.data.requestBody:void 0});return}if(t.type==="turn_complete"){const o=gt(t.data.usage);if(o){const n=e.adapterSession.totalUsage.inputTokens;n>0&&o.inputTokens<Math.floor(n*.2)||(e.adapterSession.totalUsage.inputTokens=o.inputTokens,e.adapterSession.totalUsage.outputTokens=o.outputTokens)}const s=e.adapterSession.status;if(l(`[ACode] turn_complete event received (session: ${t.sessionId}), previous status: ${s}, failed: ${t.data.failed===!0}, aborted: ${t.data.aborted===!0}`),Tt(t.data)){l(`[ACode] Recovering from failed turn_complete (session: ${t.sessionId})`),this.cancelDataFlowWatchdog(e),this.recoverTurnFailure(t.sessionId,e);return}if(t.data.aborted===!0&&e.autoPollActive){l(`[ACode] Recovering from aborted turn_complete (session: ${t.sessionId}), using R2 2s backoff instead of immediate rearm`),this.cancelDataFlowWatchdog(e),this.recoverTurnFailure(t.sessionId,e);return}if(this.cancelDataFlowWatchdog(e),this.emitProviderEvent(t,"turn_complete",{usage:e.adapterSession.totalUsage,responseBody:typeof t.data.responseBody=="string"?t.data.responseBody:void 0,finishReason:typeof t.data.finishReason=="string"?t.data.finishReason:void 0}),e.adapterSession.status="waiting_input",this.emit("status-change",t.sessionId,"waiting_input",{usage:e.adapterSession.totalUsage}),l(`[ACode] Status changed to waiting_input after turn_complete (session: ${t.sessionId})`),e.autoPollActive&&e.autoPollObservedAssistantText&&!e.autoPollObservedPollingTool&&!e.autoPollObservedAnyTool){e.stopAutoPollAfterCurrentTurn=!0,console.warn(`[${this.displayName}] Auto-poll turn produced assistant text without calling any tool; stopping auto-poll rearm for session ${t.sessionId}`);return}this.armIdleLoopOrAutoPoll(t.sessionId);return}if(t.type==="session_complete"){this.cancelDataFlowWatchdog(e),this.cancelScheduledAutoPoll(e),e.failedTurnRecoveryScheduled=!1,e.idlePollLoop?.stop(),e.adapterSession.status="completed",this.emitProviderEvent(t,"session_complete",{exitCode:Number(t.data.exitCode)||0}),this.emit("status-change",t.sessionId,"completed");return}if(t.type==="question_request"){this.cancelDataFlowWatchdog(e),this.cancelSubmitTimeoutDetection(e);const o=typeof t.data.toolCallId=="string"?t.data.toolCallId:"",s=Array.isArray(t.data.questions)?t.data.questions:[];o&&(e.pendingQuestionToolCallId=o,e.pendingQuestions=s),this.emit("ask-user-question",{sessionId:t.sessionId,toolCallId:o||void 0,questions:s});return}if(t.type==="error"){if(t.data.nonFatal){this.resetDataFlowWatchdog(t.sessionId,e),this.emitProviderEvent(t,"error",{text:String(t.data.message||"ACode runtime error")});return}this.cancelDataFlowWatchdog(e),e.adapterSession.status="error",this.emitProviderEvent(t,"error",{text:String(t.data.message||"ACode runtime error")}),this.emit("status-change",t.sessionId,"error"),e.autoPollActive||this.recoverTurnFailure(t.sessionId,e);return}if(t.type==="mcp_status"){if(!t.data.action&&Array.isArray(t.data.tools)){const h=t.data.tools;h.some(f=>Z(f))||console.warn(`[${this.displayName}] ACode runtime is not exposing a poll_message tool. The LLM cannot call poll_message. Please configure an MCP server that provides poll_message (e.g. aws-mcp) in the dashboard panel for this runtime.`);const T=Array.isArray(t.data.servers)?t.data.servers:[],A=h.map(f=>({name:String(f.name??""),source:String(f.source??""),description:String(f.description??"")})).filter(f=>f.name),_={kind:"mcp",mcpServers:T,mcpTools:A};e.cachedMcpCapabilities=_,e.lastMcpCapabilities=_,e.lastCombinedCapabilities={kind:"combined",mcpServers:T,mcpTools:A,skills:e.lastCombinedCapabilities?.skills??[],skillsDir:e.lastCombinedCapabilities?.skillsDir,skillGroups:e.lastCombinedCapabilities?.skillGroups??[]},l(`[cap-diag] MCP capabilities cached: ${T.length} servers, ${A.length} tools`,{sessionId:t.sessionId,servers:T,toolNames:A.map(f=>f.name)}),e.capabilitiesFallbackTimer&&clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=setTimeout(()=>{const f=e.cachedMcpCapabilities;if(!f)return;const y={...f,skills:[],skillGroups:[]};this.emitProviderEvent(t,"runtime_capabilities",{capabilities:y,actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:JSON.stringify(y)}),l(`[cap-diag] MCP capabilities emitted via fallback (skill_status not received within ${R}ms)`,{sessionId:t.sessionId,mcpServers:f.mcpServers,mcpToolsCount:f.mcpTools?.length??0}),e.cachedMcpCapabilities=void 0,e.capabilitiesFallbackTimer=void 0},R);return}const o=String(t.data.action??"");l(`[ACode] \u{1F4E1} mcp_status event: action=${o}, server=${typeof t.data.server=="string"?t.data.server:"?"}, tool=${typeof t.data.tool=="string"?t.data.tool:"?"}, toolUseId=${typeof t.data.toolUseId=="string"?t.data.toolUseId.slice(0,16)+"\u2026":"none"}, failed=${t.data.failed===!0}, session=${t.sessionId}, status=${e.adapterSession.status}`);const s=typeof t.data.server=="string"?t.data.server:"mcp",n=typeof t.data.tool=="string"?t.data.tool:"",i=s&&n?`${s}__${n}`:n||s,a=t.data.arguments&&typeof t.data.arguments=="object"&&!Array.isArray(t.data.arguments)?t.data.arguments:void 0,u=et(i,a);e.autoPollActive&&(e.autoPollObservedAnyTool=!0,u.actionType==="idle"&&(e.autoPollObservedPollingTool=!0));const c=St(u.actionType)?u.actionDetail||W(void 0,s,n):W(u.actionDetail,s,n),m=typeof t.data.toolUseId=="string"?t.data.toolUseId:void 0,d=a?JSON.stringify(a,null,2):void 0,g={toolName:c,rawToolName:i,actionType:u.actionType,actionLabel:u.actionLabel,actionDetail:c,...d?{actionInput:d}:{},...a?{toolInput:a}:{},...m?{toolUseId:m,actionId:m}:{},metadata:{mcpServer:s}};if(t.data.action==="tool_result"){this.emitProviderEvent(t,"tool_use_end",{...g,toolResult:typeof t.data.result=="string"?t.data.result:JSON.stringify(t.data.result??"")});const h=u.actionType==="idle"&&!At(t.data.result)?"waiting_input":"thinking";e.adapterSession.status=h,this.cancelDataFlowWatchdog(e),e.pendingToolEventData=void 0;const C=u.actionType==="idle";this.emit("status-change",t.sessionId,h,C||h==="thinking"?void 0:g);return}const p=u.actionType==="idle"?"waiting_input":"tool_using";e.adapterSession.status=p,p==="tool_using"&&(this.resetDataFlowWatchdog(t.sessionId,e),e.pendingToolEventData={...g}),this.emitProviderEvent(t,"tool_use_start",g),this.emit("status-change",t.sessionId,p,g);return}if(t.type==="skill_status"){const s=(Array.isArray(t.data.skills)?t.data.skills:[]).map(d=>({name:String(d.name??""),description:typeof d.description=="string"?d.description:void 0,directory:typeof d.directory=="string"?d.directory:void 0})).filter(d=>d.name),n=typeof t.data.skillsDir=="string"?t.data.skillsDir:void 0,a=(Array.isArray(t.data.skillGroups)?t.data.skillGroups:[]).map(d=>{const g=Array.isArray(d.skills)?d.skills:[];return{dir:typeof d.dir=="string"?d.dir:"",exists:d.exists===!0,skills:g.map(p=>({name:String(p.name??""),description:typeof p.description=="string"?p.description:void 0,directory:typeof p.directory=="string"?p.directory:void 0})).filter(p=>p.name)}}).filter(d=>d.dir),u=e.cachedMcpCapabilities??e.lastMcpCapabilities,c=e.cachedMcpCapabilities!==void 0,m={kind:"combined",mcpServers:u?.mcpServers??[],mcpTools:u?.mcpTools??[],skills:s,skillsDir:n,skillGroups:a};this.emitProviderEvent(t,"runtime_capabilities",{capabilities:m,actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:JSON.stringify(m)}),e.lastCombinedCapabilities=m,l(`[cap-diag] Combined capabilities emitted ${c?"(startup merge)":"(runtime refresh)"}: ${(u?.mcpTools??[]).length} MCP tools, ${s.length} skills`,{sessionId:t.sessionId,mcpServers:u?.mcpServers??[],skillsDir:n}),e.capabilitiesFallbackTimer&&(clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=void 0),e.cachedMcpCapabilities=void 0;return}if(t.type==="session_started"){const o=v(t.data),s=b(t.data.contextLimit)||void 0,n=b(t.data.maxOutput)||void 0,i=b(t.data.inputLimit)||void 0,a=b(t.data.compactionThreshold)||void 0;let u=!1;o>0&&(e.adapterSession.totalUsage.inputTokens=o,e.adapterSession.totalUsage.outputTokens=0,u=!0),s!==void 0&&(e.adapterSession.totalUsage.contextLimit=s,u=!0),n!==void 0&&(e.adapterSession.totalUsage.maxOutput=n,u=!0),i!==void 0&&(e.adapterSession.totalUsage.inputLimit=i,u=!0),a!==void 0&&(e.adapterSession.totalUsage.compactionThreshold=a,u=!0),u&&this.emit("status-change",t.sessionId,e.adapterSession.status,{usage:e.adapterSession.totalUsage});return}if(t.type==="exit_plan_mode"){e.adapterSession.status="waiting_input";const o=typeof t.data.plan=="string"?t.data.plan:void 0;this.emitProviderEvent(t,"exit_plan_mode",{toolInput:t.data.toolInput&&typeof t.data.toolInput=="object"?t.data.toolInput:void 0,text:o||"\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F"}),this.emit("status-change",t.sessionId,"waiting_input",{actionLabel:"\u5BA1\u6279\u8BA1\u5212",actionDetail:o||"\u7B49\u5F85\u7528\u6237\u5BA1\u6279\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F"});return}if(t.type==="context_compaction"){const o=t.data,s=o.action,n=s==="start",i=s==="end",a=s==="phase",u=o.parentId,c=o.compactionId;let m,d;if(n){const p=String(o.sizeKB??o.sizeBeforeKB??"?"),h=String(o.messageCount??o.messageCountBefore??"?"),C=o.estimatedTokens,T=o.actualInputTokens?`input=${o.actualInputTokens}`:"",A=o.actualOutputTokens?`output=${o.actualOutputTokens}`:"",_=o.trigger?`, \u89E6\u53D1: ${o.trigger}`:"";m="\u4E0A\u4E0B\u6587\u538B\u7F29\u5F00\u59CB",C!==void 0?d=`\u538B\u7F29\u524D: ~${C} tokens, \u6D88\u606F: ${h}\u6761`+(T?`, \u5B9E\u9645 tokens: ${T} ${A}`:"")+_:d=`\u538B\u7F29\u524D: ${p}KB, \u6D88\u606F: ${h}\u6761`+(T?`, \u5B9E\u9645 tokens: ${T} ${A}`:"")+_}else if(a)m=String(o.phaseLabel??"\u538B\u7F29\u9636\u6BB5"),d=String(o.phaseDetail??"");else{const p=o.tokensBefore,h=o.tokensAfter,C=o.freedTokens,T=String(o.sizeBeforeKB??"?"),A=String(o.sizeAfterKB??"?"),_=String(o.freedKB??"?"),f=String(o.strategy??"?"),y=Number(o.prunedToolMessages??0),S=Number(o.summarizedMessages??0);m="\u538B\u7F29\u5B8C\u6210",p!==void 0&&h!==void 0?d=`\u91CA\u653E: ${C??p-h} tokens, ${p} tokens \u2192 ${h} tokens, \u7B56\u7565: ${f}`+(y?`, \u88C1\u526A\u5DE5\u5177: ${y}\u6761`:"")+(S?`, \u6458\u8981\u5316: ${S}\u6761`:""):d=`\u91CA\u653E: ${_}KB, ${T}KB \u2192 ${A}KB, \u7B56\u7565: ${f}`+(y?`, \u88C1\u526A\u5DE5\u5177: ${y}\u6761`:"")+(S?`, \u6458\u8981\u5316: ${S}\u6761`:"")}n&&(e.adapterSession.status="compacting");const g={actionType:"context_compaction",actionLabel:m,actionDetail:d};if(n&&c)g.actionId=c;else if((a||i)&&c)if(g.parentId=c,a){const p=String(o.phase??"unknown");g.actionId=`${c}-phase-${p}`}else g.actionId=`${c}-end`;a&&u&&!g.parentId&&(g.parentId=u),i&&(e.adapterSession.totalUsage.inputTokens=b(o.tokensAfter),e.adapterSession.totalUsage.outputTokens=0,g.usage={...e.adapterSession.totalUsage}),this.emitProviderEvent(t,"context_compaction",g),this.emit("status-change",t.sessionId,"compacting",g);return}this.emitProviderEvent(t,"thinking",{text:JSON.stringify(t.data)})}}emitProviderEvent(t,e,o){this.emit("event",{type:e,sessionId:t.sessionId,timestamp:t.timestamp,data:o})}armIdleLoopOrAutoPoll(t){const e=this.sessions.get(t);if(!(!e||this.isTerminalStatus(e.adapterSession.status))){if(e.idleCommands?.idleInputCommand){this.getIdlePollLoop(e).start();return}this.scheduleAutoPoll(t)}}getIdlePollLoop(t){if(t.idlePollLoop)return t.idlePollLoop;const e=t.adapterSession.sessionId,o=t.config.agentId;return t.idlePollLoop=new tt({getStatus:()=>this.sessions.get(e)?.adapterSession.status,getCommand:()=>this.sessions.get(e)?.idleCommands?.idleInputCommand,isPollingCommand:s=>w(s),preDispatchHook:()=>null,dispatchPollingPrompt:(s,n)=>this.submitAutoPollPrompt(e,n?s:lt,{keepWaitingStatus:!0}),dispatchRegularIdleCommand:s=>this.submitAutoPollPrompt(e,s)}),t.idlePollLoop}submitAutoPollPrompt(t,e,o){const s=this.sessions.get(t);if(!s||this.isTerminalStatus(s.adapterSession.status))return;const n=(s.autoPollToken??0)+1;s.autoPollToken=n,s.autoPollActive=!0,s.autoPollObservedPollingTool=!1,s.autoPollObservedAssistantText=!1,s.autoPollObservedAnyTool=!1,s.stopAutoPollAfterCurrentTurn=!1,o?.keepWaitingStatus||(s.adapterSession.status="thinking",this.emit("status-change",t,"thinking")),this.startSubmitTimeoutDetection(t,s,"submitAutoPollPrompt"),s.runtime.submit(e).catch(i=>{this.emitRuntimeError(t,i)}).finally(()=>{const i=this.sessions.get(t);if(i){if(i.autoPollToken!==n){l(`[ACode] submitAutoPollPrompt.finally: token mismatch (my=${n}, current=${i.autoPollToken}), skipping cleanup \u2014 newer turn has taken over`);return}if(this.cancelSubmitTimeoutDetection(i),i.autoPollActive=!1,i.failedTurnRecoveryScheduled||i.autoPollTimer){i.failedTurnRecoveryScheduled=!1;return}if(i.stopAutoPollAfterCurrentTurn){i.stopAutoPollAfterCurrentTurn=!1,i.autoPollObservedPollingTool=!1,i.autoPollObservedAssistantText=!1,i.autoPollObservedAnyTool=!1;return}if(i.adapterSession.status==="error"){this.recoverTurnFailure(t,i);return}if(i.adapterSession.status==="thinking"||i.adapterSession.status==="tool_using"){this.recoverResolvedTurnWithoutTerminalEvent(t);return}i.adapterSession.status==="waiting_input"&&this.armIdleLoopOrAutoPoll(t)}})}scheduleAutoPoll(t,e=nt){const o=this.sessions.get(t);!o||o.autoPollActive||o.autoPollTimer||this.isTerminalStatus(o.adapterSession.status)||(o.autoPollTimer=setTimeout(()=>{const s=this.sessions.get(t);!s||s.autoPollActive||this.isTerminalStatus(s.adapterSession.status)||(s.autoPollTimer=void 0,this.submitAutoPollPrompt(t,M,{keepWaitingStatus:!0}))},e))}cancelScheduledAutoPoll(t){t.autoPollTimer&&(clearTimeout(t.autoPollTimer),t.autoPollTimer=void 0)}isTerminalStatus(t){return t==="completed"||t==="terminated"}emitRuntimeError(t,e,o){const s=this.sessions.get(t);s&&(s.adapterSession.status="error",this.emitRuntimeErrorEvent(t,e),this.emit("status-change",t,"error"),o?.recover&&this.recoverTurnFailure(t,s))}emitRuntimeErrorEvent(t,e){const o=new Date().toISOString();this.emit("event",{type:"error",sessionId:t,timestamp:o,data:{text:e instanceof Error?e.message:String(e)}})}estimateOutputTokensFromMessages(t){const e=t.filter(o=>o.role==="assistant").map(o=>o.content).join("");return Math.max(0,Math.round(e.length/4))}recoverTurnFailure(t,e){if(this.isTerminalStatus(e.adapterSession.status))return;if(e.adapterSession.status==="tool_using"&&e.pendingToolEventData){const a=e.pendingToolEventData;l(`[ACode] recoverTurnFailure: \u8865\u53D1 tool_use_end (tool: ${a.toolName??"unknown"}) \u5173\u95ED\u65F6\u95F4\u7EBF\u6761\u76EE\uFF0C\u907F\u514D\u6C38\u4E45\u5361\u5728\u5DE5\u5177\u6267\u884C\u72B6\u6001`),this.emit("event",{type:"tool_use_end",sessionId:t,timestamp:new Date().toISOString(),data:{...a,toolResult:"[aborted] \u5DE5\u5177\u6267\u884C\u88AB\u6570\u636E\u6D41\u770B\u95E8\u72D7\u4E2D\u65AD"}}),e.pendingToolEventData=void 0}const o=this.estimateOutputTokensFromMessages(e.adapterSession.messages);if(o>0){const a=e.adapterSession.totalUsage.outputTokens;e.adapterSession.totalUsage.outputTokens=o,l(`[ACode] recoverTurnFailure: \u4F30\u7B97\u8986\u76D6 output tokens ${a} -> ${o} (totalUsage now: input=${e.adapterSession.totalUsage.inputTokens}, output=${e.adapterSession.totalUsage.outputTokens})`)}const s=e.idleCommands?.idleInputCommand,i=!!(s&&w(s))?{actionType:"idle",actionLabel:"\u76D1\u542C\u6D88\u606F",actionDetail:"aws-mcp/poll_message"}:void 0;if(e.autoPollTimer||e.failedTurnRecoveryScheduled){e.adapterSession.status!=="waiting_input"&&(e.adapterSession.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:e.adapterSession.totalUsage,...i}));return}this.cancelScheduledAutoPoll(e),e.adapterSession.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:e.adapterSession.totalUsage,...i}),e.failedTurnRecoveryScheduled=!0,e.autoPollTimer=setTimeout(()=>{const a=this.sessions.get(t);if(!a||a.autoPollActive||this.isTerminalStatus(a.adapterSession.status)){a&&(a.failedTurnRecoveryScheduled=!1);return}a.autoPollTimer=void 0,a.failedTurnRecoveryScheduled=!1,a.idleCommands?.idleInputCommand?this.getIdlePollLoop(a).start():this.submitAutoPollPrompt(t,M,{keepWaitingStatus:!0})},rt)}recoverResolvedTurnWithoutTerminalEvent(t){l(`[ACode] \u25B6\uFE0F recoverResolvedTurnWithoutTerminalEvent called for session ${t}`);const e=this.sessions.get(t);if(!e||this.isTerminalStatus(e.adapterSession.status)){l(`[ACode] Skipping recovery: entry=${!!e}, isTerminal=${e?this.isTerminalStatus(e.adapterSession.status):"N/A"}`);return}if(l(`[ACode] Current status: ${e.adapterSession.status}`),e.adapterSession.status!=="thinking"&&e.adapterSession.status!=="tool_using"){l(`[ACode] Skipping recovery: status is ${e.adapterSession.status} (not thinking/tool_using)`);return}console.warn(`[ACode] \u26A0\uFE0F Detected stuck state: ${e.adapterSession.status} after submit resolved! Recovering to waiting_input. If runtime.submit() is still pending (e.g., built-in tool execution not interruptible by abort()), the submitQueue is deadlocked and subsequent auto-poll/user submits will never execute.`),l("[ACode] Recovering to waiting_input..."),e.adapterSession.status="waiting_input";const o=e.idleCommands?.idleInputCommand,n=!!(o&&w(o))?{actionType:"idle",actionLabel:"\u76D1\u542C\u6D88\u606F",actionDetail:"aws-mcp/poll_message"}:void 0;this.emit("status-change",t,"waiting_input",n),l(`[ACode] \u2705 Recovery complete, status now: ${e.adapterSession.status}`),l("[ACode] \u25B6\uFE0F Arming idle loop or auto-poll..."),this.armIdleLoopOrAutoPoll(t),l("[ACode] \u2705 Idle loop armed, recovery process complete")}startSubmitTimeoutDetection(t,e,o){this.cancelSubmitTimeoutDetection(e),e.watchdogSubmitStartTime=Date.now(),e.watchdogLastDataFlowTime=Date.now(),e.watchdogTimer=setInterval(()=>{const s=this.sessions.get(t);if(!s){this.cancelSubmitTimeoutDetection(e);return}const n=s.adapterSession.status,i=Date.now();if(n==="waiting_input"){s.watchdogSubmitStartTime=i,s.watchdogLastDataFlowTime=i;return}if(n==="tool_using"){const c=i-(s.watchdogLastDataFlowTime||i);if(c>=at){const m=String(s.pendingToolEventData?.rawToolName??"");if(m.endsWith("await_complete")){console.warn(`[ACode] tool_using elapsed ${Math.round(c/1e3)}s but await_complete is running (session: ${t}, tool: ${m}), skipping recovery (sub-agents have their own watchdogs, bg commands have timeout limits)`),s.watchdogSubmitStartTime=i,s.watchdogLastDataFlowTime=i;return}if(console.warn(`[ACode] CRITICAL: tool_using slow timeout triggered after ${Math.round(c/1e3)}s (source: ${o}, session: ${t}). Tool execution likely hung. Forcing recovery via recoverTurnFailure.`),s.runtime.detachCurrentToolExecution?.()){console.warn(`[ACode] tool_using slow (${Math.round(c/1e3)}s): detached tool ${m} to background (session: ${t}); waiting for the real tool_result to continue the turn`),s.watchdogSubmitStartTime=i,s.watchdogLastDataFlowTime=i;return}this.executeWatchdogRecovery(t,s,o,"tool_using_slow",c);return}s.watchdogSubmitStartTime=i;return}if(n!=="thinking")return;const a=i-(s.watchdogSubmitStartTime||i),u=i-(s.watchdogLastDataFlowTime||i);if(u>=it){console.warn(`[ACode] CRITICAL: Data flow watchdog triggered after ${Math.round(u/1e3)}s (source: ${o}, session: ${t}, status: ${n}). No stream data received. Forcing recovery via recoverTurnFailure.`),this.executeWatchdogRecovery(t,s,o,"data_flow",u);return}if(a>=ut){console.warn(`[ACode] CRITICAL: submit timeout detected after ${Math.round(a/1e3)}s (source: ${o}, session: ${t}, status: ${n}). Forcing recovery to prevent permanent state stuck.`),this.executeWatchdogRecovery(t,s,o,"submit_timeout",a);return}},st)}executeWatchdogRecovery(t,e,o,s,n){l(`[ACode] Watchdog (${s}): calling runtime.abort() after ${Math.round(n/1e3)}s...`);try{e.runtime.abort(),l(`[ACode] Watchdog (${s}): runtime.abort() called`)}catch(i){console.warn(`[ACode] \u26A0\uFE0F Watchdog (${s}): runtime.abort() threw: ${i instanceof Error?i.message:String(i)}`)}this.cancelSubmitTimeoutDetection(e),this.recoverTurnFailure(t,e),console.warn(`[ACode] \u26A0\uFE0F Watchdog (${s}) recovery complete. If abort() could not cancel the underlying operation, submitQueue may still be deadlocked.`)}cancelSubmitTimeoutDetection(t){t.watchdogTimer&&(clearInterval(t.watchdogTimer),t.watchdogTimer=void 0),t.watchdogSubmitStartTime=void 0,t.watchdogLastDataFlowTime=void 0}resetDataFlowWatchdog(t,e){e.watchdogLastDataFlowTime=Date.now()}startDataFlowWatchdog(t,e){e.watchdogLastDataFlowTime=Date.now()}cancelDataFlowWatchdog(t){t.watchdogLastDataFlowTime=Date.now()}formatAiRequestActionDetail(t){const e=`
2
2
 
3
3
  \u8BF7\u6C42\u5934:
4
4
  `,o=`
@@ -7,5 +7,5 @@ import{EventEmitter as B}from"node:events";import L from"node:path";import q fro
7
7
  `,n=typeof t.model=="string"?t.model:"",i=typeof t.endpoint=="string"?t.endpoint:typeof t.requestUrl=="string"?t.requestUrl:"",a=typeof t.requestMethod=="string"?t.requestMethod:"",u=typeof t.stream=="boolean"?t.stream:void 0,c=typeof t.messageCount=="number"?t.messageCount:void 0,m=typeof t.toolCount=="number"?t.toolCount:void 0,d=typeof t.lastUserMessagePreview=="string"?t.lastUserMessagePreview:"",g=[n?`\u6A21\u578B: ${n}`:void 0,i?`\u63A5\u53E3: ${i}`:void 0,a?`\u65B9\u6CD5: ${a}`:void 0,u!==void 0?`\u6D41\u5F0F: ${u?"\u662F":"\u5426"}`:void 0,c!==void 0?`\u4E0A\u4E0B\u6587\u6D88\u606F: ${c}`:void 0,m!==void 0?`\u53EF\u7528\u5DE5\u5177: ${m}`:void 0,d?`\u6700\u540E\u8BF7\u6C42: ${d}`:void 0].filter(S=>!!S),p=/^(authorization|x-api-key|api-key|cookie|set-cookie|x-auth-token|token)$/i,h=t.requestHeaders,C=h?Object.entries(h).filter(([S])=>!p.test(S)).map(([S,x])=>`${S}: ${x}`).filter(S=>S.trim().length>0):[],T=g.join(`
8
8
  `)||"ACode \u6B63\u5728\u53D1\u9001 AI \u8BF7\u6C42",A=C.length>0?`${e}${C.join(`
9
9
  `)}`:"",_=typeof t.requestBody=="string"?t.requestBody:"",f=_.length>6e4?`${_.slice(0,6e4)}
10
- ...(\u8BF7\u6C42\u4F53\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD)`:_,y=f?`${o}${f}`:"";return`${T}${A}${y}`}}export{Ft as AcodeSdkAdapter,Tt as isFailedAcodeTurnComplete,ct as toAcodeEsmImportSpecifier};
10
+ ...(\u8BF7\u6C42\u4F53\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD)`:_,y=f?`${o}${f}`:"";return`${T}${A}${y}`}}export{vt as AcodeSdkAdapter,Tt as isFailedAcodeTurnComplete,ct as toAcodeEsmImportSpecifier};
11
11
 
@@ -329,6 +329,8 @@ export declare abstract class BaseProviderAdapter extends EventEmitter {
329
329
 
330
330
  abstract getSessionStatus(sessionId: string): SessionStatus | undefined;
331
331
 
332
+ abstract notifyForceMessage?(sessionId: string): boolean;
333
+
332
334
  abstract getSessionPid?(sessionId: string): number | undefined;
333
335
 
334
336
  abstract getCapabilities?(sessionId: string): RuntimeCapabilities | undefined;
@@ -1,2 +1,2 @@
1
- import{execSync as b}from"node:child_process";import{Router as R}from"express";import{adapterRegistry as k}from"../adapter/index.js";import{validateToken as h}from"../middleware/auth.js";import{isProcessRunning as y,findOrphanProcessByAgentId as P,findOrphanProcessByWorkspace as T}from"../services/process-detector.js";import{findPersistedSessionByAgentId as I,loadPersistedSessions as F,removePersistedSession as A}from"../services/terminal-persistence.js";import{createLogger as K}from"../utils/logger.js";import{sdkSessions as g,cleanupSdkSessionByAgentId as C}from"./terminal.js";const c=K("sessions"),S=R();function j(m,n,e){const r=String(m||"").trim();if(r){const s=String(n||"").trim(),t=String(e||"").trim().toLowerCase();return r.toLowerCase()==="tool_using"&&s.toLowerCase()==="waiting_input"&&t==="idle"?s:r}return String(n||"").trim()||"running"}S.get("/sessions",h,async(m,n)=>{try{const r=Array.from(g.entries()).map(([d,p])=>{const u=k.get(p.providerId||"claude-code"),a=j(u.getSessionStatus(d),p.currentRuntimeStatus,p.currentRuntimeActionType);return{sessionId:d,agentId:p.agentId,workspacePath:p.workspacePath,status:a,runtimeStatus:a,runtimeActionType:p.currentRuntimeActionType,runtimeActionLabel:p.currentRuntimeActionLabel,runtimeActionDetail:p.currentRuntimeActionDetail,mode:"sdk",startedAt:null}}),o=await F(),s=new Set(r.map(d=>d.sessionId)),t=o.filter(d=>!s.has(d.sessionId)),i={ok:!0,active:r,persisted:t};n.json(i)}catch(e){const r=e;n.status(500).json({error:r.message})}}),S.post("/sessions/recover",h,async(m,n)=>{const{agentId:e,workspacePath:r,command:o}=m.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{const s=Array.from(g.entries()).find(([,f])=>f.agentId===e);if(s){const f=k.get(s[1].providerId||"claude-code"),v=j(f.getSessionStatus(s[0]),s[1].currentRuntimeStatus,s[1].currentRuntimeActionType);n.json({ok:!0,sessionId:s[0],agentId:e,workspacePath:s[1].workspacePath,command:s[1].config.command,status:v,runtimeStatus:v,runtimeActionType:s[1].currentRuntimeActionType,runtimeActionLabel:s[1].currentRuntimeActionLabel,runtimeActionDetail:s[1].currentRuntimeActionDetail,mode:"sdk",recovered:!1,message:"SDK session already active"});return}const t=await I(e);let i=!1,d;if(t?.pid&&y(t.pid))i=!0,d=t.pid,c.info(`[Recover] Detected orphan process for agentId=${e}, pid=${t.pid}`);else if(t?.mode==="sdk"||!t?.pid){const f=await P(e);f&&(i=!0,d=f.pid,c.info(`[Recover] Found orphan process by agentId search: agentId=${e}, pid=${f.pid}`))}const p=r||t?.workspacePath,u=o||t?.command||"acode",a=t?.mode||"sdk";if(!p){n.status(400).json({error:"workspacePath is required (not found in persisted session)"});return}if(i&&d){c.info(`[Recover] Returning orphan process info for agentId=${e}`),n.json({ok:!0,sessionId:t?.sessionId||"",agentId:e,workspacePath:p,command:u,status:"orphan_detected",runtimeStatus:t?.runtimeStatus,runtimeActionType:t?.runtimeActionType,runtimeActionLabel:t?.runtimeActionLabel,runtimeActionDetail:t?.runtimeActionDetail,recovered:!1,orphan:{pid:d,message:"Found orphan process still running. Manual intervention may be required."},mode:a});return}await A(t?.sessionId||"");const l={ok:!1,sessionId:t?.sessionId||"",agentId:e,workspacePath:p,command:u,status:"stopped",recovered:!1,message:"No active SDK session found; start a new SDK runtime session instead."};n.json(l)}catch(s){const t=s;c.error("Error:",t),n.status(500).json({error:t.message})}}),S.post("/search-orphan",h,async(m,n)=>{const{agentId:e,workspacePath:r}=m.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{const o=Array.from(g.entries()).find(([,a])=>a.agentId===e);let s=!1,t,i;if(o){const[a,l]=o,f=k.get(l.providerId||"claude-code");t=f.getSessionPid?.(a),i=l.config?.command;const v=t?y(t):!1,w=f.getSessionStatus(a),D=w==="completed"||w==="terminated"||w==="error";if(v)s=!0;else if(t&&!v)c.info(`[search-orphan] Cleaning up stale SDK session (process dead): agentId=${e}, sessionId=${a}, pid=${t}`),g.delete(a),await A(a);else if(D){c.info(`[search-orphan] Cleaning up stale in-process SDK session (status=${w}): agentId=${e}, sessionId=${a}`);try{await f.terminateSession(a)}catch($){c.warn(`[search-orphan] Failed to terminate stale in-process session: ${$}`)}g.delete(a),await A(a)}else{c.info(`[search-orphan] Terminating unreachable in-process SDK session: agentId=${e}, sessionId=${a}, status=${w||"unknown"}`);try{await f.abortCurrentTurn(a).catch(()=>{}),await f.terminateSession(a)}catch($){c.warn(`[search-orphan] Failed to terminate in-process session: ${$}`)}g.delete(a),await A(a)}}const d=await P(e);if(d){c.info(`[search-orphan] Found orphan process for agentId=${e}, pid=${d.pid}`),n.json({ok:!0,agentId:e,hasActiveSession:s,found:!0,orphan:{pid:d.pid,command:d.command,cwd:d.cwd,startedAt:d.startedAt,message:"Found orphan process. Click terminate to stop it."}});return}if(s&&t){c.info(`[search-orphan] Active session process still running, reporting as terminable orphan: agentId=${e}, pid=${t}`),n.json({ok:!0,agentId:e,hasActiveSession:!0,found:!0,orphan:{pid:t,command:i||"(active SDK session)",message:"Found active SDK session process. Click terminate to stop it."}});return}const p=await I(e);if(p?.pid&&y(p.pid)){c.info(`[search-orphan] Found orphan by persisted PID: agentId=${e}, pid=${p.pid}`),n.json({ok:!0,agentId:e,hasActiveSession:s,found:!0,orphan:{pid:p.pid,command:p.command||"(persisted session)",message:"Found orphan process by persisted PID. Click terminate to stop it."}});return}const u=r||p?.workspacePath;if(u){const a=await T(u);if(a){c.info(`[search-orphan] Found orphan by workspace: agentId=${e}, pid=${a.pid}, workspace=${u}`),n.json({ok:!0,agentId:e,hasActiveSession:s,found:!0,orphan:{pid:a.pid,command:a.command,message:"Found orphan process by workspace path. Click terminate to stop it."}});return}}c.info(`[search-orphan] No orphan process found for agentId=${e}, hasActiveSession=${!!s}`),n.json({ok:!0,agentId:e,hasActiveSession:!!s,found:!1,orphan:null,message:s?"Agent has active session in runtime-bridge":"No orphan process and no active session found"})}catch(o){const s=o;c.error("[search-orphan] Error:",s),n.status(500).json({error:s.message})}}),S.post("/terminate-orphan",h,async(m,n)=>{const{agentId:e,pid:r}=m.body;if(!e||!r){n.status(400).json({error:"agentId and pid are required"});return}try{const o=Array.from(g.entries()).find(([,i])=>i.agentId===e);if(o){const[i,d]=o,p=k.get(d.providerId||"claude-code");try{await p.terminateSession(i)}catch(u){c.warn(`[terminate-orphan] Failed to terminate SDK session for agentId=${e}:`,u)}g.delete(i),await A(i),c.info(`[terminate-orphan] Cleaned up SDK session for agentId=${e}, sessionId=${i}`)}if(!y(r)){n.json({ok:!0,agentId:e,pid:r,terminated:!1,message:"Process already terminated"});return}const s=process.platform;let t=!1;if(s==="win32")try{b(`taskkill /PID ${r} /T /F`,{encoding:"utf8",timeout:5e3}),t=!0}catch(i){c.warn(`[terminate-orphan] taskkill failed for pid=${r}:`,i)}else try{process.kill(r,"SIGTERM"),t=!0}catch(i){c.warn(`[terminate-orphan] kill failed for pid=${r}:`,i)}t?(c.info(`[terminate-orphan] Terminated orphan process for agentId=${e}, pid=${r}`),n.json({ok:!0,agentId:e,pid:r,terminated:!0,message:"Orphan process terminated successfully"})):n.json({ok:!0,agentId:e,pid:r,terminated:!1,message:"Failed to terminate process"})}catch(o){const s=o;c.error("[terminate-orphan] Error:",s),n.status(500).json({error:s.message})}}),S.get("/sessions/by-agent/:agentId",h,async(m,n)=>{const e=m.params.agentId,r=Array.isArray(e)?e[0]:e;if(!r){n.status(400).json({error:"agentId is required"});return}try{const o=Array.from(g.entries()).find(([,t])=>t.agentId===r);if(o){const t=k.get(o[1].providerId||"claude-code"),i=t.getSessionPid?.(o[0]),d=j(t.getSessionStatus(o[0]),o[1].currentRuntimeStatus,o[1].currentRuntimeActionType);n.json({ok:!0,sessionId:o[0],agentId:r,workspacePath:o[1].workspacePath,status:d,runtimeStatus:d,isActive:!0,mode:"sdk",pid:i,isManaged:!0,providerId:o[1].providerId});return}const s=await I(r);if(s){const{isProcessRunning:t}=await import("../services/process-detector.js"),i=s.pid?t(s.pid):!1;n.json({ok:!0,sessionId:s.sessionId,agentId:r,workspacePath:s.workspacePath,command:s.command,status:i?"orphan":"stopped",runtimeStatus:s.runtimeStatus,runtimeActionType:s.runtimeActionType,runtimeActionLabel:s.runtimeActionLabel,runtimeActionDetail:s.runtimeActionDetail,startedAt:s.startedAt,isActive:!1,mode:s.mode,pid:s.pid,isManaged:!1,isProcessAlive:i,isOrphan:i});return}n.json({ok:!0,agentId:r,status:"none",isActive:!1,isManaged:!1})}catch(o){const s=o;c.error("[sessions/by-agent] Error:",s),n.status(500).json({error:s.message})}}),S.post("/takeover-session",h,async(m,n)=>{const{agentId:e}=m.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{const r=Array.from(g.entries()).find(([,t])=>t.agentId===e);if(r){n.json({ok:!0,agentId:e,sessionId:r[0],mode:"sdk",status:"running",isActive:!0,recovered:!1,message:"SDK session already active"});return}const o=await I(e);if(!o){n.status(404).json({error:"No persisted session found for this agentId",agentId:e});return}let s=!1;if(o.mode==="sdk"&&(s=!!await P(e),!s&&o.pid&&(s=y(o.pid))),!s){c.info(`[takeover-session] Process not alive for agentId=${e}, mode=${o.mode}`),n.json({ok:!1,agentId:e,status:"process_not_alive",isActive:!1,message:"Agent process is no longer running"});return}if(c.info(`[takeover-session] Taking over session for agentId=${e}, mode=${o.mode}, pid=${o.pid}`),o.mode==="sdk"){const t=await P(e);t?(c.info(`[takeover-session] Found SDK process for agentId=${e}, pid=${t.pid}`),n.json({ok:!0,agentId:e,sessionId:o.sessionId,mode:"sdk",status:"running",isActive:!0,recovered:!0,pid:t.pid||o.pid,message:"SDK session process found, can be taken over by aws-mcp-server"})):n.json({ok:!1,agentId:e,status:"process_not_alive",isActive:!1,message:"SDK process not found"})}else n.status(410).json({error:"Session takeover is no longer supported; start a new SDK runtime session.",agentId:e,mode:"sdk"})}catch(r){const o=r;c.error("[takeover-session] Error:",o),n.status(500).json({error:o.message})}}),S.post("/terminate-tree",h,async(m,n)=>{const{agentId:e,sessionId:r}=m.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{let o=r;if(!o){const l=await I(e);if(!l){n.status(404).json({error:"Session not found for this agentId"});return}o=l.sessionId}const s=g.get(o);let t,i;if(s)t=k.get(s.providerId||"claude-code").getSessionPid?.(o),i="sdk";else{const l=await I(e);if(!l?.pid){n.status(404).json({error:"Session PID not found"});return}t=l.pid,i=l.mode||"sdk"}const{terminateProcessTree:d,waitForProcessExit:p}=await import("../services/process-detector.js");if(!t){n.status(404).json({error:"PID not found"});return}const u=await d(t),a=await p(t,5e3);C(e),await import("../services/terminal-persistence.js").then(l=>l.removePersistedSession(o)),c.info(`[terminate-tree] Terminated process tree for agentId=${e}, pid=${t}, mode=${i}, terminated=${u.terminated}, failed=${u.failed}, exited=${a}`),n.json({ok:!0,agentId:e,pid:t,mode:i,terminated:u.terminated,failed:u.failed,exited:a,message:a?`Successfully terminated ${u.terminated} processes`:`Terminated ${u.terminated} processes, but process ${t} still running`})}catch(o){const s=o;c.error("[terminate-tree] Error:",s),n.status(500).json({error:s.message})}}),S.get("/health/:agentId",h,async(m,n)=>{const e=m.params.agentId,r=Array.isArray(e)?e[0]:e;if(!r){n.status(400).json({error:"agentId is required"});return}try{const o=await I(r);if(!o){n.status(404).json({error:"Session not found"});return}const s=g.get(o.sessionId),t=!!s,{checkProcessHealth:i}=await import("../services/process-detector.js"),d={sessionId:o.sessionId,mode:o.mode,workspacePath:o.workspacePath,isManaged:t,isActive:!!s};if(o.pid){const p=await i(o.pid,r);Object.assign(d,p)}else Object.assign(d,{pid:0,alive:!1,cpu:0,memoryMB:0,status:"dead",lastUpdate:new Date});n.json({agentId:r,...d})}catch(o){const s=o;c.error("[health] Error:",s),n.status(500).json({error:s.message})}});export{j as resolveActiveSdkSessionSnapshotStatus,S as sessionsRouter};
1
+ import{execSync as b}from"node:child_process";import{Router as R}from"express";import{adapterRegistry as I}from"../adapter/index.js";import{validateToken as S,validateTokenOrLoopback as T}from"../middleware/auth.js";import{isProcessRunning as w,findOrphanProcessByAgentId as P,findOrphanProcessByWorkspace as F}from"../services/process-detector.js";import{findPersistedSessionByAgentId as k,loadPersistedSessions as K,removePersistedSession as A}from"../services/terminal-persistence.js";import{createLogger as E}from"../utils/logger.js";import{sdkSessions as g,cleanupSdkSessionByAgentId as C}from"./terminal.js";const c=E("sessions"),h=R();h.post("/sessions/:agentId/notify-force-message",T,(u,n)=>{const e=String(u.params.agentId??"").trim();if(!e){n.status(400).json({ok:!1,error:"agentId is required"});return}const r=Array.from(g.entries()).find(([,i])=>i.agentId===e);if(!r){n.json({ok:!0,notified:!1,message:"No active SDK session for this agentId"});return}const[o,s]=r,t=I.get(s.providerId||"claude-code");if(typeof t.notifyForceMessage=="function"){const i=t.notifyForceMessage(o);n.json({ok:!0,notified:i})}else n.json({ok:!0,notified:!1,message:"Adapter does not support force message notification"})});function j(u,n,e){const r=String(u||"").trim();if(r){const s=String(n||"").trim(),t=String(e||"").trim().toLowerCase();return r.toLowerCase()==="tool_using"&&s.toLowerCase()==="waiting_input"&&t==="idle"?s:r}return String(n||"").trim()||"running"}h.get("/sessions",S,async(u,n)=>{try{const r=Array.from(g.entries()).map(([d,p])=>{const m=I.get(p.providerId||"claude-code"),a=j(m.getSessionStatus(d),p.currentRuntimeStatus,p.currentRuntimeActionType);return{sessionId:d,agentId:p.agentId,workspacePath:p.workspacePath,status:a,runtimeStatus:a,runtimeActionType:p.currentRuntimeActionType,runtimeActionLabel:p.currentRuntimeActionLabel,runtimeActionDetail:p.currentRuntimeActionDetail,mode:"sdk",startedAt:null}}),o=await K(),s=new Set(r.map(d=>d.sessionId)),t=o.filter(d=>!s.has(d.sessionId)),i={ok:!0,active:r,persisted:t};n.json(i)}catch(e){const r=e;n.status(500).json({error:r.message})}}),h.post("/sessions/recover",S,async(u,n)=>{const{agentId:e,workspacePath:r,command:o}=u.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{const s=Array.from(g.entries()).find(([,l])=>l.agentId===e);if(s){const l=I.get(s[1].providerId||"claude-code"),v=j(l.getSessionStatus(s[0]),s[1].currentRuntimeStatus,s[1].currentRuntimeActionType);n.json({ok:!0,sessionId:s[0],agentId:e,workspacePath:s[1].workspacePath,command:s[1].config.command,status:v,runtimeStatus:v,runtimeActionType:s[1].currentRuntimeActionType,runtimeActionLabel:s[1].currentRuntimeActionLabel,runtimeActionDetail:s[1].currentRuntimeActionDetail,mode:"sdk",recovered:!1,message:"SDK session already active"});return}const t=await k(e);let i=!1,d;if(t?.pid&&w(t.pid))i=!0,d=t.pid,c.info(`[Recover] Detected orphan process for agentId=${e}, pid=${t.pid}`);else if(t?.mode==="sdk"||!t?.pid){const l=await P(e);l&&(i=!0,d=l.pid,c.info(`[Recover] Found orphan process by agentId search: agentId=${e}, pid=${l.pid}`))}const p=r||t?.workspacePath,m=o||t?.command||"acode",a=t?.mode||"sdk";if(!p){n.status(400).json({error:"workspacePath is required (not found in persisted session)"});return}if(i&&d){c.info(`[Recover] Returning orphan process info for agentId=${e}`),n.json({ok:!0,sessionId:t?.sessionId||"",agentId:e,workspacePath:p,command:m,status:"orphan_detected",runtimeStatus:t?.runtimeStatus,runtimeActionType:t?.runtimeActionType,runtimeActionLabel:t?.runtimeActionLabel,runtimeActionDetail:t?.runtimeActionDetail,recovered:!1,orphan:{pid:d,message:"Found orphan process still running. Manual intervention may be required."},mode:a});return}await A(t?.sessionId||"");const f={ok:!1,sessionId:t?.sessionId||"",agentId:e,workspacePath:p,command:m,status:"stopped",recovered:!1,message:"No active SDK session found; start a new SDK runtime session instead."};n.json(f)}catch(s){const t=s;c.error("Error:",t),n.status(500).json({error:t.message})}}),h.post("/search-orphan",S,async(u,n)=>{const{agentId:e,workspacePath:r}=u.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{const o=Array.from(g.entries()).find(([,a])=>a.agentId===e);let s=!1,t,i;if(o){const[a,f]=o,l=I.get(f.providerId||"claude-code");t=l.getSessionPid?.(a),i=f.config?.command;const v=t?w(t):!1,y=l.getSessionStatus(a),D=y==="completed"||y==="terminated"||y==="error";if(v)s=!0;else if(t&&!v)c.info(`[search-orphan] Cleaning up stale SDK session (process dead): agentId=${e}, sessionId=${a}, pid=${t}`),g.delete(a),await A(a);else if(D){c.info(`[search-orphan] Cleaning up stale in-process SDK session (status=${y}): agentId=${e}, sessionId=${a}`);try{await l.terminateSession(a)}catch($){c.warn(`[search-orphan] Failed to terminate stale in-process session: ${$}`)}g.delete(a),await A(a)}else{c.info(`[search-orphan] Terminating unreachable in-process SDK session: agentId=${e}, sessionId=${a}, status=${y||"unknown"}`);try{await l.abortCurrentTurn(a).catch(()=>{}),await l.terminateSession(a)}catch($){c.warn(`[search-orphan] Failed to terminate in-process session: ${$}`)}g.delete(a),await A(a)}}const d=await P(e);if(d){c.info(`[search-orphan] Found orphan process for agentId=${e}, pid=${d.pid}`),n.json({ok:!0,agentId:e,hasActiveSession:s,found:!0,orphan:{pid:d.pid,command:d.command,cwd:d.cwd,startedAt:d.startedAt,message:"Found orphan process. Click terminate to stop it."}});return}if(s&&t){c.info(`[search-orphan] Active session process still running, reporting as terminable orphan: agentId=${e}, pid=${t}`),n.json({ok:!0,agentId:e,hasActiveSession:!0,found:!0,orphan:{pid:t,command:i||"(active SDK session)",message:"Found active SDK session process. Click terminate to stop it."}});return}const p=await k(e);if(p?.pid&&w(p.pid)){c.info(`[search-orphan] Found orphan by persisted PID: agentId=${e}, pid=${p.pid}`),n.json({ok:!0,agentId:e,hasActiveSession:s,found:!0,orphan:{pid:p.pid,command:p.command||"(persisted session)",message:"Found orphan process by persisted PID. Click terminate to stop it."}});return}const m=r||p?.workspacePath;if(m){const a=await F(m);if(a){c.info(`[search-orphan] Found orphan by workspace: agentId=${e}, pid=${a.pid}, workspace=${m}`),n.json({ok:!0,agentId:e,hasActiveSession:s,found:!0,orphan:{pid:a.pid,command:a.command,message:"Found orphan process by workspace path. Click terminate to stop it."}});return}}c.info(`[search-orphan] No orphan process found for agentId=${e}, hasActiveSession=${!!s}`),n.json({ok:!0,agentId:e,hasActiveSession:!!s,found:!1,orphan:null,message:s?"Agent has active session in runtime-bridge":"No orphan process and no active session found"})}catch(o){const s=o;c.error("[search-orphan] Error:",s),n.status(500).json({error:s.message})}}),h.post("/terminate-orphan",S,async(u,n)=>{const{agentId:e,pid:r}=u.body;if(!e||!r){n.status(400).json({error:"agentId and pid are required"});return}try{const o=Array.from(g.entries()).find(([,i])=>i.agentId===e);if(o){const[i,d]=o,p=I.get(d.providerId||"claude-code");try{await p.terminateSession(i)}catch(m){c.warn(`[terminate-orphan] Failed to terminate SDK session for agentId=${e}:`,m)}g.delete(i),await A(i),c.info(`[terminate-orphan] Cleaned up SDK session for agentId=${e}, sessionId=${i}`)}if(!w(r)){n.json({ok:!0,agentId:e,pid:r,terminated:!1,message:"Process already terminated"});return}const s=process.platform;let t=!1;if(s==="win32")try{b(`taskkill /PID ${r} /T /F`,{encoding:"utf8",timeout:5e3}),t=!0}catch(i){c.warn(`[terminate-orphan] taskkill failed for pid=${r}:`,i)}else try{process.kill(r,"SIGTERM"),t=!0}catch(i){c.warn(`[terminate-orphan] kill failed for pid=${r}:`,i)}t?(c.info(`[terminate-orphan] Terminated orphan process for agentId=${e}, pid=${r}`),n.json({ok:!0,agentId:e,pid:r,terminated:!0,message:"Orphan process terminated successfully"})):n.json({ok:!0,agentId:e,pid:r,terminated:!1,message:"Failed to terminate process"})}catch(o){const s=o;c.error("[terminate-orphan] Error:",s),n.status(500).json({error:s.message})}}),h.get("/sessions/by-agent/:agentId",S,async(u,n)=>{const e=u.params.agentId,r=Array.isArray(e)?e[0]:e;if(!r){n.status(400).json({error:"agentId is required"});return}try{const o=Array.from(g.entries()).find(([,t])=>t.agentId===r);if(o){const t=I.get(o[1].providerId||"claude-code"),i=t.getSessionPid?.(o[0]),d=j(t.getSessionStatus(o[0]),o[1].currentRuntimeStatus,o[1].currentRuntimeActionType);n.json({ok:!0,sessionId:o[0],agentId:r,workspacePath:o[1].workspacePath,status:d,runtimeStatus:d,isActive:!0,mode:"sdk",pid:i,isManaged:!0,providerId:o[1].providerId});return}const s=await k(r);if(s){const{isProcessRunning:t}=await import("../services/process-detector.js"),i=s.pid?t(s.pid):!1;n.json({ok:!0,sessionId:s.sessionId,agentId:r,workspacePath:s.workspacePath,command:s.command,status:i?"orphan":"stopped",runtimeStatus:s.runtimeStatus,runtimeActionType:s.runtimeActionType,runtimeActionLabel:s.runtimeActionLabel,runtimeActionDetail:s.runtimeActionDetail,startedAt:s.startedAt,isActive:!1,mode:s.mode,pid:s.pid,isManaged:!1,isProcessAlive:i,isOrphan:i});return}n.json({ok:!0,agentId:r,status:"none",isActive:!1,isManaged:!1})}catch(o){const s=o;c.error("[sessions/by-agent] Error:",s),n.status(500).json({error:s.message})}}),h.post("/takeover-session",S,async(u,n)=>{const{agentId:e}=u.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{const r=Array.from(g.entries()).find(([,t])=>t.agentId===e);if(r){n.json({ok:!0,agentId:e,sessionId:r[0],mode:"sdk",status:"running",isActive:!0,recovered:!1,message:"SDK session already active"});return}const o=await k(e);if(!o){n.status(404).json({error:"No persisted session found for this agentId",agentId:e});return}let s=!1;if(o.mode==="sdk"&&(s=!!await P(e),!s&&o.pid&&(s=w(o.pid))),!s){c.info(`[takeover-session] Process not alive for agentId=${e}, mode=${o.mode}`),n.json({ok:!1,agentId:e,status:"process_not_alive",isActive:!1,message:"Agent process is no longer running"});return}if(c.info(`[takeover-session] Taking over session for agentId=${e}, mode=${o.mode}, pid=${o.pid}`),o.mode==="sdk"){const t=await P(e);t?(c.info(`[takeover-session] Found SDK process for agentId=${e}, pid=${t.pid}`),n.json({ok:!0,agentId:e,sessionId:o.sessionId,mode:"sdk",status:"running",isActive:!0,recovered:!0,pid:t.pid||o.pid,message:"SDK session process found, can be taken over by aws-mcp-server"})):n.json({ok:!1,agentId:e,status:"process_not_alive",isActive:!1,message:"SDK process not found"})}else n.status(410).json({error:"Session takeover is no longer supported; start a new SDK runtime session.",agentId:e,mode:"sdk"})}catch(r){const o=r;c.error("[takeover-session] Error:",o),n.status(500).json({error:o.message})}}),h.post("/terminate-tree",S,async(u,n)=>{const{agentId:e,sessionId:r}=u.body;if(!e){n.status(400).json({error:"agentId is required"});return}try{let o=r;if(!o){const f=await k(e);if(!f){n.status(404).json({error:"Session not found for this agentId"});return}o=f.sessionId}const s=g.get(o);let t,i;if(s)t=I.get(s.providerId||"claude-code").getSessionPid?.(o),i="sdk";else{const f=await k(e);if(!f?.pid){n.status(404).json({error:"Session PID not found"});return}t=f.pid,i=f.mode||"sdk"}const{terminateProcessTree:d,waitForProcessExit:p}=await import("../services/process-detector.js");if(!t){n.status(404).json({error:"PID not found"});return}const m=await d(t),a=await p(t,5e3);C(e),await import("../services/terminal-persistence.js").then(f=>f.removePersistedSession(o)),c.info(`[terminate-tree] Terminated process tree for agentId=${e}, pid=${t}, mode=${i}, terminated=${m.terminated}, failed=${m.failed}, exited=${a}`),n.json({ok:!0,agentId:e,pid:t,mode:i,terminated:m.terminated,failed:m.failed,exited:a,message:a?`Successfully terminated ${m.terminated} processes`:`Terminated ${m.terminated} processes, but process ${t} still running`})}catch(o){const s=o;c.error("[terminate-tree] Error:",s),n.status(500).json({error:s.message})}}),h.get("/health/:agentId",S,async(u,n)=>{const e=u.params.agentId,r=Array.isArray(e)?e[0]:e;if(!r){n.status(400).json({error:"agentId is required"});return}try{const o=await k(r);if(!o){n.status(404).json({error:"Session not found"});return}const s=g.get(o.sessionId),t=!!s,{checkProcessHealth:i}=await import("../services/process-detector.js"),d={sessionId:o.sessionId,mode:o.mode,workspacePath:o.workspacePath,isManaged:t,isActive:!!s};if(o.pid){const p=await i(o.pid,r);Object.assign(d,p)}else Object.assign(d,{pid:0,alive:!1,cpu:0,memoryMB:0,status:"dead",lastUpdate:new Date});n.json({agentId:r,...d})}catch(o){const s=o;c.error("[health] Error:",s),n.status(500).json({error:s.message})}});export{j as resolveActiveSdkSessionSnapshotStatus,h as sessionsRouter};
2
2