aws-runtime-bridge 1.9.112 → 1.9.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
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 k,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 u(...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,lt=12e4,R=3e3,ut="\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,w={"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(w[t])return w[t].contextLimit;const e=Object.keys(w).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?w[e[0]].contextLimit:U}const v=4096;function pt(r){if(!r)return v;const t=r.toLowerCase().trim();if(w[t])return w[t].maxOutput;const e=Object.keys(w).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?w[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 At(r){return r==="read_file"||r==="edit_file"||r==="write_file"||r==="bash"}function St(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,l=i??mt(a),c=pt(a),m={sessionId:t,status:"starting",messages:[],createdAt:new Date().toISOString(),totalUsage:{inputTokens:0,outputTokens:0,contextLimit:l,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();u("[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"),u("[ACode] \u25B6\uFE0F sendMessage STARTED"),u(`[ACode] Session: ${t}`),u(`[ACode] Message: ${e.slice(0,100)}${e.length>100?"...":""}`),u("[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;u(`[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),u(`[ACode] Changing status: ${n} \u2192 thinking`),s.adapterSession.status="thinking",this.emit("status-change",t,"thinking"),this.startSubmitTimeoutDetection(t,s,"sendMessage");try{u("[ACode] \u25B6\uFE0F Calling runtime.submit()...");const a=Date.now();await s.runtime.submit(e);const l=Date.now()-a;this.cancelSubmitTimeoutDetection(s),u(`[ACode] \u2705 runtime.submit() completed in ${l}ms`),u(`[ACode] Current status after submit: ${s.adapterSession.status}`),u("[ACode] \u25B6\uFE0F Calling recoverResolvedTurnWithoutTerminalEvent()..."),this.recoverResolvedTurnWithoutTerminalEvent(t),u(`[ACode] Status after recovery: ${s.adapterSession.status}`);const c=Date.now()-o;u("[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"),u(`[ACode] \u2705 sendMessage COMPLETED in ${c}ms`),u("[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 l=Date.now()-o;console.error(`[ACode] \u274C sendMessage FAILED after ${l}ms:`,a instanceof Error?a.message:String(a)),this.cancelSubmitTimeoutDetection(s),u("[ACode] \u25B6\uFE0F Calling emitRuntimeError with recover=true..."),this.emitRuntimeError(t,a,{recover:!0}),u(`[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){u(`[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&&k(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),l={},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&&(l[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(l).length>0?{modelContextLimits:l}:{}}}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 l=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:l.model,resolvedBaseURL:l.baseURL??null,resolvedApiKey:l.apiKey?"[set]":null,configContextLimit:a,resolvedSource:l.source}}),{resolved:l,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,typeof o.browserAllowPrivate=="boolean"?{allowPrivate:o.browserAllowPrivate}:void 0)}catch(m){u(`[acode-adapter] browser tools injection skipped for agent ${o.agentId}:`,m.message)}const l=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}}),l.on("event",m=>this.forwardAcodeEvent(m)),l}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(u(`[ACode] turn_complete event received (session: ${t.sessionId}), previous status: ${s}, failed: ${t.data.failed===!0}, aborted: ${t.data.aborted===!0}`),Tt(t.data)){u(`[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){u(`[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}),u(`[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:[],S=h.map(f=>({name:String(f.name??""),source:String(f.source??""),description:String(f.description??"")})).filter(f=>f.name),_={kind:"mcp",mcpServers:T,mcpTools:S};e.cachedMcpCapabilities=_,e.lastMcpCapabilities=_,e.lastCombinedCapabilities={kind:"combined",mcpServers:T,mcpTools:S,skills:e.lastCombinedCapabilities?.skills??[],skillsDir:e.lastCombinedCapabilities?.skillsDir,skillGroups:e.lastCombinedCapabilities?.skillGroups??[]},u(`[cap-diag] MCP capabilities cached: ${T.length} servers, ${S.length} tools`,{sessionId:t.sessionId,servers:T,toolNames:S.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)}),u(`[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??"");u(`[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,l=et(i,a);e.autoPollActive&&(e.autoPollObservedAnyTool=!0,l.actionType==="idle"&&(e.autoPollObservedPollingTool=!0));const c=At(l.actionType)?l.actionDetail||W(void 0,s,n):W(l.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:l.actionType,actionLabel:l.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=l.actionType==="idle"&&!St(t.data.result)?"waiting_input":"thinking";e.adapterSession.status=h,this.cancelDataFlowWatchdog(e),e.pendingToolEventData=void 0;const C=l.actionType==="idle";this.emit("status-change",t.sessionId,h,C||h==="thinking"?void 0:g);return}const p=l.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),l=e.cachedMcpCapabilities??e.lastMcpCapabilities,c=e.cachedMcpCapabilities!==void 0,m={kind:"combined",mcpServers:l?.mcpServers??[],mcpTools:l?.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,u(`[cap-diag] Combined capabilities emitted ${c?"(startup merge)":"(runtime refresh)"}: ${(l?.mcpTools??[]).length} MCP tools, ${s.length} skills`,{sessionId:t.sessionId,mcpServers:l?.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 l=!1;o>0&&(e.adapterSession.totalUsage.inputTokens=o,e.adapterSession.totalUsage.outputTokens=0,l=!0),s!==void 0&&(e.adapterSession.totalUsage.contextLimit=s,l=!0),n!==void 0&&(e.adapterSession.totalUsage.maxOutput=n,l=!0),i!==void 0&&(e.adapterSession.totalUsage.inputLimit=i,l=!0),a!==void 0&&(e.adapterSession.totalUsage.compactionThreshold=a,l=!0),l&&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",l=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}`:"",S=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} ${S}`:"")+_:d=`\u538B\u7F29\u524D: ${p}KB, \u6D88\u606F: ${h}\u6761`+(T?`, \u5B9E\u9645 tokens: ${T} ${S}`:"")+_}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??"?"),S=String(o.sizeAfterKB??"?"),_=String(o.freedKB??"?"),f=String(o.strategy??"?"),y=Number(o.prunedToolMessages??0),A=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`:"")+(A?`, \u6458\u8981\u5316: ${A}\u6761`:""):d=`\u91CA\u653E: ${_}KB, ${T}KB \u2192 ${S}KB, \u7B56\u7565: ${f}`+(y?`, \u88C1\u526A\u5DE5\u5177: ${y}\u6761`:"")+(A?`, \u6458\u8981\u5316: ${A}\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&&l&&!g.parentId&&(g.parentId=l),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=>k(s),preDispatchHook:()=>null,dispatchPollingPrompt:(s,n)=>this.submitAutoPollPrompt(e,n?s:ut,{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){u(`[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;u(`[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,u(`[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&&k(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){u(`[ACode] \u25B6\uFE0F recoverResolvedTurnWithoutTerminalEvent called for session ${t}`);const e=this.sessions.get(t);if(!e||this.isTerminalStatus(e.adapterSession.status)){u(`[ACode] Skipping recovery: entry=${!!e}, isTerminal=${e?this.isTerminalStatus(e.adapterSession.status):"N/A"}`);return}if(u(`[ACode] Current status: ${e.adapterSession.status}`),e.adapterSession.status!=="thinking"&&e.adapterSession.status!=="tool_using"){u(`[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.`),u("[ACode] Recovering to waiting_input..."),e.adapterSession.status="waiting_input";const o=e.idleCommands?.idleInputCommand,n=!!(o&&k(o))?{actionType:"idle",actionLabel:"\u76D1\u542C\u6D88\u606F",actionDetail:"aws-mcp/poll_message"}:void 0;this.emit("status-change",t,"waiting_input",n),u(`[ACode] \u2705 Recovery complete, status now: ${e.adapterSession.status}`),u("[ACode] \u25B6\uFE0F Arming idle loop or auto-poll..."),this.armIdleLoopOrAutoPoll(t),u("[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),l=i-(s.watchdogLastDataFlowTime||i);if(l>=it){console.warn(`[ACode] CRITICAL: Data flow watchdog triggered after ${Math.round(l/1e3)}s (source: ${o}, session: ${t}, status: ${n}). No stream data received. Forcing recovery via recoverTurnFailure.`),this.executeWatchdogRecovery(t,s,o,"data_flow",l);return}if(a>=lt){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){u(`[ACode] Watchdog (${s}): calling runtime.abort() after ${Math.round(n/1e3)}s...`);try{e.runtime.abort(),u(`[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 q}from"node:events";import $ from"node:path";import N from"node:fs/promises";import{pathToFileURL as H}from"node:url";import{v4 as O}from"uuid";import{getAcodeConfigFile as D,getAcodeSkillsDir as K,getRuntimeHomeDir as j}from"../config.js";import{getReleasedAcodeEntryPath as Q}from"../services/acode-package.js";import{getInstanceAiConfigDebugLogger as x}from"../utils/instance-ai-config-debug-logger.js";import{redactForLog as E}from"../services/instance-ai-config-service.js";import{subAgentManager as G}from"../services/sub-agent-manager-instance.js";import{agentPtyManager as J}from"../services/agent-pty-manager.js";import{resolveAcodeProviderConfig as z}from"./instance-ai-config-resolver.js";import{recordAgentFileChange as Y}from"../services/workspaceTaskChangeWatcher.js";import{getBrowserTools as X,closeBrowserSession as V,registerListenerWakeHook as Z,unregisterListenerWakeHook as M}from"../services/browser-session-manager.js";import{isMessagePollingIdleCommand as P,isPollMessageToolDescriptor as tt}from"./acode-tool-names.js";import{IdlePollLoop as et}from"./idle-poll-loop.js";import{getCanonicalMcpDetail as I,getToolActionInfo as ot}from"./types.js";const st=process.env.ACODE_COMPACTION_DEBUG==="1";function l(...r){st&&console.log(...r)}const it=process.env.ACODE_TOKEN_DEBUG==="1";function w(...r){it&&console.log("[TokenDebug][Adapter]",...r)}const U=["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(" "),at=5e3,nt=4e4,rt=5*6e4,ut=250,lt=2e3,dt=12e4,R=3e3,ct="\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 mt(){return $.resolve(Q())}function pt(r){return H($.resolve(r)).href}const F=128e3,y={"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 gt(r){if(!r)return F;const t=r.toLowerCase().trim();if(y[t])return y[t].contextLimit;const e=Object.keys(y).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?y[e[0]].contextLimit:F}const v=4096;function ft(r){if(!r)return v;const t=r.toLowerCase().trim();if(y[t])return y[t].maxOutput;const e=Object.keys(y).filter(o=>t.startsWith(o)).sort((o,s)=>s.length-o.length);return e.length>0?y[e[0]].maxOutput:v}function ht(r){if(!r||typeof r!="object")return;const t=r,e=f(t.inputTokens,t.input_tokens,t.promptTokens,t.prompt_tokens),o=f(t.outputTokens,t.output_tokens,t.completionTokens,t.completion_tokens);if(e===0&&o===0)return;let s=f(t.cacheHitTokens,t.promptCacheHitTokens,t.prompt_cache_hit_tokens),a=f(t.cacheMissTokens,t.promptCacheMissTokens,t.prompt_cache_miss_tokens),i=t.cacheHitTokens!==void 0||t.cacheMissTokens!==void 0||t.promptCacheHitTokens!==void 0||t.promptCacheMissTokens!==void 0||t.prompt_cache_hit_tokens!==void 0||t.prompt_cache_miss_tokens!==void 0;if(s===0&&a===0){const n=f(t.cache_read_input_tokens),u=f(t.cache_creation_input_tokens);n>0||u>0?(s=n,a=u+f(t.input_tokens),i=!0):(s=f(t.cache_hit_tokens),a=f(t.cache_miss_tokens),i=i||t.cache_hit_tokens!==void 0||t.cache_miss_tokens!==void 0)}if(s===0&&a===0){const n=f(t.prompt_tokens_details?.cached_tokens);n>0&&(s=n,a=e>n?e-n:0,i=!0)}return{inputTokens:e,outputTokens:o,...s>0||a>0?{cacheHitTokens:s,cacheMissTokens:a}:{},...i?{hasCache:!0}:{}}}function f(...r){for(const t of r){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 0}function B(r){return f(r.estimatedContextTokens,r.contextTokens,r.context_tokens,r.contextUsedTokens,r.context_used_tokens)}function Tt(r){return r==="stderr"||r==="mixed"?r:"stdout"}function _t(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 St(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 At(r){return r==="read_file"||r==="edit_file"||r==="write_file"||r==="bash"}function kt(r){const t=Ct(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 Ct(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 Wt extends q{constructor(){super(...arguments),this.providerId="acode",this.displayName="ACode",this.sessions=new Map,this.listenerWakeHooks=new Map}async startSession(t,e){const o=j(),s=e.mcpConfigPath||D(o),{resolved:a,configContextLimit:i}=await this.resolveAcodeProvider(e,s),n=a.model,u=i??gt(n),m=ft(n),d={sessionId:t,status:"starting",messages:[],createdAt:new Date().toISOString(),totalUsage:{inputTokens:0,outputTokens:0,contextLimit:u,maxOutput:m,cacheHitTokens:0,cacheMissTokens:0}};this.sessions.set(t,{adapterSession:d,config:e,runtime:await this.createRuntime(t,n,e,o),autoPollActive:!1}),this.emit("status-change",t,"starting");const c=this.sessions.get(t);if(!c)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),Z(e.agentId,g);try{await c.runtime.start(),d.status="waiting_input",this.emit("status-change",t,"waiting_input",{usage:c.adapterSession.totalUsage}),e.initialPrompt?.trim()?this.startInitialPromptTurn(t,e.initialPrompt):this.armIdleLoopOrAutoPoll(t)}catch(p){d.status="error",this.emitRuntimeErrorEvent(t,p),this.emit("status-change",t,"error");const T=this.sessions.get(t);throw T?.capabilitiesFallbackTimer&&clearTimeout(T.capabilitiesFallbackTimer),this.sessions.delete(t),M(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),a=s.adapterSession.status;l(`[ACode] Previous status: ${a}`),this.cancelScheduledAutoPoll(s),s.failedTurnRecoveryScheduled=!1,s.idlePollLoop?.stop();const i={id:O(),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: ${a} \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 n=Date.now();await s.runtime.submit(e);const u=Date.now()-n;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 m=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 ${m}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(n){const u=Date.now()-o;console.error(`[ACode] \u274C sendMessage FAILED after ${u}ms:`,n instanceof Error?n.message:String(n)),this.cancelSubmitTimeoutDetection(s),l("[ACode] \u25B6\uFE0F Calling emitRuntimeError with recover=true..."),this.emitRuntimeError(t,n,{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,cacheHitTokens:o.cacheHitTokens,cacheMissTokens:o.cacheMissTokens},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&&(M(o,this.listenerWakeHooks.get(t)),V(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&&P(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 N.readFile(t,"utf-8"),o=JSON.parse(e),a=o.provider?.default,i=a?.options,n=f(o.contextLimit),u={},m=a?.models;if(m&&typeof m=="object"){for(const[d,c]of Object.entries(m))if(c&&typeof c=="object"){const g=f(c.contextLimit);g>0&&(u[d.trim()]=g)}}return{...a?.model?{model:a.model}:{},...i?.baseURL||i?.baseUrl?{baseURL:i?.baseURL||i?.baseUrl}:{},...i?.apiKey?{apiKey:i.apiKey}:{},...n>0?{contextLimit:n}:{},...Object.keys(u).length>0?{modelContextLimits:u}:{}}}catch(e){const o=e instanceof Error?e.message:String(e);return x().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=x();s.log({level:"info",category:"resolve",message:"resolveAcodeProvider \u8F93\u5165",source:"bridge",details:{configModel:t.model??null,configInstanceAiConfig:t.instanceAiConfig?E(t.instanceAiConfig):null,configPath:e}});const a={...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 n=i.contextLimit;if(!n&&i.modelContextLimits){const m=o||t.instanceAiConfig?.model||i.model;m&&i.modelContextLimits[m]&&(n=i.modelContextLimits[m])}const u=z(a,i,"acode-default");return s.log({level:"info",category:"resolve",message:"resolveAcodeProvider \u89E3\u6790\u7ED3\u679C",source:"bridge",details:{instanceConfig:E(a),globalConfigModel:i?.model??null,resolvedModel:u.model,resolvedBaseURL:u.baseURL??null,resolvedApiKey:u.apiKey?"[set]":null,configContextLimit:n,resolvedSource:u.source}}),{resolved:u,configPath:e,perSessionModel:o,configContextLimit:n}}async createRuntime(t,e,o,s){const a=await this.loadRuntimeConstructor(),i=o.mcpConfigPath||D(s);let n=[];try{n=await X(o.agentId,o.scopeKey,typeof o.browserAllowPrivate=="boolean"?{allowPrivate:o.browserAllowPrivate}:void 0)}catch(d){l(`[acode-adapter] browser tools injection skipped for agent ${o.agentId}:`,d.message)}const u=new a({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:G,terminalManager:J,...o.subAgentModel?{subAgentModel:o.subAgentModel}:{},...o.subAgentEffort?{subAgentEffort:o.subAgentEffort}:{},...o.instanceAiConfig?.effort?{effort:o.instanceAiConfig.effort}:{},onFileChange:d=>Y({...d,agentId:o.agentId,workspacePath:o.workingDirectory}),extraBuiltInTools:n});return x().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",d=>this.forwardAcodeEvent(d)),u}async loadRuntimeConstructor(){if(this.runtimeConstructor)return this.runtimeConstructor;const t=mt(),e=await import(pt(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 a=this.sessions.get(t);a&&(this.cancelSubmitTimeoutDetection(a),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:O(),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:Tt(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=B(t.data),s=t.data.lastUsage,a=f(s?.inputTokens),i=f(s?.outputTokens),n=f(s?.cacheHitTokens),u=f(s?.cacheMissTokens),m=!!(s&&(a>0||i>0));let d;if(m&&(a>0&&(e.adapterSession.totalUsage.inputTokens=a),i>0&&(e.adapterSession.totalUsage.outputTokens=i),(s?.cacheHitTokens!==void 0||s?.cacheMissTokens!==void 0)&&(e.adapterSession.totalUsage.cacheHitTokens=n,e.adapterSession.totalUsage.cacheMissTokens=u),d={...e.adapterSession.totalUsage},w(`ai_request lastUsage applied: ${JSON.stringify(s)} -> totalUsage=${JSON.stringify(e.adapterSession.totalUsage)}`)),!m&&o>0){const p=e.adapterSession.totalUsage.inputTokens;p>0?e.adapterSession.totalUsage.inputTokens=Math.min(o,Math.floor(p*1.5)):e.adapterSession.totalUsage.inputTokens=o,d={...e.adapterSession.totalUsage}}e.adapterSession.status==="compacting"&&(e.adapterSession.status="thinking"),e.adapterSession.status==="waiting_input"&&(e.adapterSession.status="thinking");const g={actionType:"ai_request",actionLabel:"AI\u8BF7\u6C42",actionDetail:this.formatAiRequestActionDetail(t.data)};d&&(g.usage=d),w(`ai_request handled: estimatedContextTokens=${t.data.estimatedContextTokens??"n/a"} totalUsage=${JSON.stringify(e.adapterSession.totalUsage)} displayUsage=${JSON.stringify(d??null)}`),this.emit("status-change",t.sessionId,e.adapterSession.status,g),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:_t(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=ht(t.data.usage);if(o){const a=e.adapterSession.totalUsage.inputTokens,i=a>0&&o.inputTokens<Math.floor(a*.2)&&!o.hasCache;w(`turn_complete usage: raw=${JSON.stringify(t.data.usage)} parsed=${JSON.stringify(o)} currentInput=${a} threshold20pct=${Math.floor(a*.2)} isFallbackUsage=${i}`),i?o.outputTokens>0&&(e.adapterSession.totalUsage.outputTokens=o.outputTokens):(e.adapterSession.totalUsage.inputTokens=o.inputTokens,e.adapterSession.totalUsage.outputTokens=o.outputTokens),(o.cacheHitTokens||o.cacheMissTokens)&&(e.adapterSession.totalUsage.cacheHitTokens=o.cacheHitTokens,e.adapterSession.totalUsage.cacheMissTokens=o.cacheMissTokens,l(`[ACode] \u{1F4B0} Cache usage (overwrite from runtime cumulative): hit=${e.adapterSession.totalUsage.cacheHitTokens}, miss=${e.adapterSession.totalUsage.cacheMissTokens} (turn delta: hit=${o.cacheHitTokens||0}, miss=${o.cacheMissTokens||0})`)),w(`totalUsage after turn_complete: ${JSON.stringify(e.adapterSession.totalUsage)}`)}else w(`turn_complete has NO parseable usage: raw=${JSON.stringify(t.data.usage)} failed=${t.data.failed===!0} aborted=${t.data.aborted===!0}`);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}`),St(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}),w(`status-change emitted (waiting_input after turn_complete): usage=${JSON.stringify(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 T=t.data.tools;T.some(h=>tt(h))||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 _=Array.isArray(t.data.servers)?t.data.servers:[],A=T.map(h=>({name:String(h.name??""),source:String(h.source??""),description:String(h.description??"")})).filter(h=>h.name),k={kind:"mcp",mcpServers:_,mcpTools:A};e.cachedMcpCapabilities=k,e.lastMcpCapabilities=k,e.lastCombinedCapabilities={kind:"combined",mcpServers:_,mcpTools:A,skills:e.lastCombinedCapabilities?.skills??[],skillsDir:e.lastCombinedCapabilities?.skillsDir,skillGroups:e.lastCombinedCapabilities?.skillGroups??[]},l(`[cap-diag] MCP capabilities cached: ${_.length} servers, ${A.length} tools`,{sessionId:t.sessionId,servers:_,toolNames:A.map(h=>h.name)}),e.capabilitiesFallbackTimer&&clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=setTimeout(()=>{const h=e.cachedMcpCapabilities;if(!h)return;const b={...h,skills:[],skillGroups:[]};this.emitProviderEvent(t,"runtime_capabilities",{capabilities:b,actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:JSON.stringify(b)}),l(`[cap-diag] MCP capabilities emitted via fallback (skill_status not received within ${R}ms)`,{sessionId:t.sessionId,mcpServers:h.mcpServers,mcpToolsCount:h.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",a=typeof t.data.tool=="string"?t.data.tool:"",i=s&&a?`${s}__${a}`:a||s,n=t.data.arguments&&typeof t.data.arguments=="object"&&!Array.isArray(t.data.arguments)?t.data.arguments:void 0,u=ot(i,n);e.autoPollActive&&(e.autoPollObservedAnyTool=!0,u.actionType==="idle"&&(e.autoPollObservedPollingTool=!0));const m=At(u.actionType)?u.actionDetail||W(void 0,s,a):W(u.actionDetail,s,a),d=typeof t.data.toolUseId=="string"?t.data.toolUseId:void 0,c=n?JSON.stringify(n,null,2):void 0,g={toolName:m,rawToolName:i,actionType:u.actionType,actionLabel:u.actionLabel,actionDetail:m,...c?{actionInput:c}:{},...n?{toolInput:n}:{},...d?{toolUseId:d,actionId:d}:{},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 T=u.actionType==="idle"&&!kt(t.data.result)?"waiting_input":"thinking";e.adapterSession.status=T,this.cancelDataFlowWatchdog(e),e.pendingToolEventData=void 0;const C=u.actionType==="idle";this.emit("status-change",t.sessionId,T,C||T==="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(c=>({name:String(c.name??""),description:typeof c.description=="string"?c.description:void 0,directory:typeof c.directory=="string"?c.directory:void 0})).filter(c=>c.name),a=typeof t.data.skillsDir=="string"?t.data.skillsDir:void 0,n=(Array.isArray(t.data.skillGroups)?t.data.skillGroups:[]).map(c=>{const g=Array.isArray(c.skills)?c.skills:[];return{dir:typeof c.dir=="string"?c.dir:"",exists:c.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(c=>c.dir),u=e.cachedMcpCapabilities??e.lastMcpCapabilities,m=e.cachedMcpCapabilities!==void 0,d={kind:"combined",mcpServers:u?.mcpServers??[],mcpTools:u?.mcpTools??[],skills:s,skillsDir:a,skillGroups:n};this.emitProviderEvent(t,"runtime_capabilities",{capabilities:d,actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:JSON.stringify(d)}),e.lastCombinedCapabilities=d,l(`[cap-diag] Combined capabilities emitted ${m?"(startup merge)":"(runtime refresh)"}: ${(u?.mcpTools??[]).length} MCP tools, ${s.length} skills`,{sessionId:t.sessionId,mcpServers:u?.mcpServers??[],skillsDir:a}),e.capabilitiesFallbackTimer&&(clearTimeout(e.capabilitiesFallbackTimer),e.capabilitiesFallbackTimer=void 0),e.cachedMcpCapabilities=void 0;return}if(t.type==="session_started"){const o=B(t.data),s=f(t.data.contextLimit)||void 0,a=f(t.data.maxOutput)||void 0,i=f(t.data.inputLimit)||void 0,n=f(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),a!==void 0&&(e.adapterSession.totalUsage.maxOutput=a,u=!0),i!==void 0&&(e.adapterSession.totalUsage.inputLimit=i,u=!0),n!==void 0&&(e.adapterSession.totalUsage.compactionThreshold=n,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,a=s==="start",i=s==="end",n=s==="phase",u=o.parentId,m=o.compactionId;let d,c;if(a){const p=String(o.sizeKB??o.sizeBeforeKB??"?"),T=String(o.messageCount??o.messageCountBefore??"?"),C=o.estimatedTokens,_=o.actualInputTokens?`input=${o.actualInputTokens}`:"",A=o.actualOutputTokens?`output=${o.actualOutputTokens}`:"",k=o.trigger?`, \u89E6\u53D1: ${o.trigger}`:"";d="\u4E0A\u4E0B\u6587\u538B\u7F29\u5F00\u59CB",C!==void 0?c=`\u538B\u7F29\u524D: ~${C} tokens, \u6D88\u606F: ${T}\u6761`+(_?`, \u5B9E\u9645 tokens: ${_} ${A}`:"")+k:c=`\u538B\u7F29\u524D: ${p}KB, \u6D88\u606F: ${T}\u6761`+(_?`, \u5B9E\u9645 tokens: ${_} ${A}`:"")+k}else if(n)d=String(o.phaseLabel??"\u538B\u7F29\u9636\u6BB5"),c=String(o.phaseDetail??"");else{const p=o.tokensBefore,T=o.tokensAfter,C=o.freedTokens,_=String(o.sizeBeforeKB??"?"),A=String(o.sizeAfterKB??"?"),k=String(o.freedKB??"?"),h=String(o.strategy??"?"),b=Number(o.prunedToolMessages??0),S=Number(o.summarizedMessages??0);d="\u538B\u7F29\u5B8C\u6210",p!==void 0&&T!==void 0?c=`\u91CA\u653E: ${C??p-T} tokens, ${p} tokens \u2192 ${T} tokens, \u7B56\u7565: ${h}`+(b?`, \u88C1\u526A\u5DE5\u5177: ${b}\u6761`:"")+(S?`, \u6458\u8981\u5316: ${S}\u6761`:""):c=`\u91CA\u653E: ${k}KB, ${_}KB \u2192 ${A}KB, \u7B56\u7565: ${h}`+(b?`, \u88C1\u526A\u5DE5\u5177: ${b}\u6761`:"")+(S?`, \u6458\u8981\u5316: ${S}\u6761`:"")}a&&(e.adapterSession.status="compacting");const g={actionType:"context_compaction",actionLabel:d,actionDetail:c};if(a&&m)g.actionId=m;else if((n||i)&&m)if(g.parentId=m,n){const p=String(o.phase??"unknown");g.actionId=`${m}-phase-${p}`}else g.actionId=`${m}-end`;n&&u&&!g.parentId&&(g.parentId=u),i&&(e.adapterSession.totalUsage.inputTokens=f(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 et({getStatus:()=>this.sessions.get(e)?.adapterSession.status,getCommand:()=>this.sessions.get(e)?.idleCommands?.idleInputCommand,isPollingCommand:s=>P(s),preDispatchHook:()=>null,dispatchPollingPrompt:(s,a)=>this.submitAutoPollPrompt(e,a?s:ct,{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 a=(s.autoPollToken??0)+1;s.autoPollToken=a,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!==a){l(`[ACode] submitAutoPollPrompt.finally: token mismatch (my=${a}, 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=ut){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,U,{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 n=e.pendingToolEventData;l(`[ACode] recoverTurnFailure: \u8865\u53D1 tool_use_end (tool: ${n.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:{...n,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 n=e.adapterSession.totalUsage.outputTokens;e.adapterSession.totalUsage.outputTokens=o,l(`[ACode] recoverTurnFailure: \u4F30\u7B97\u8986\u76D6 output tokens ${n} -> ${o} (totalUsage now: input=${e.adapterSession.totalUsage.inputTokens}, output=${e.adapterSession.totalUsage.outputTokens})`)}const s=e.idleCommands?.idleInputCommand,i=!!(s&&P(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 n=this.sessions.get(t);if(!n||n.autoPollActive||this.isTerminalStatus(n.adapterSession.status)){n&&(n.failedTurnRecoveryScheduled=!1);return}n.autoPollTimer=void 0,n.failedTurnRecoveryScheduled=!1,n.idleCommands?.idleInputCommand?this.getIdlePollLoop(n).start():this.submitAutoPollPrompt(t,U,{keepWaitingStatus:!0})},lt)}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,a=!!(o&&P(o))?{actionType:"idle",actionLabel:"\u76D1\u542C\u6D88\u606F",actionDetail:"aws-mcp/poll_message"}:void 0;this.emit("status-change",t,"waiting_input",a),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 a=s.adapterSession.status,i=Date.now();if(a==="waiting_input"){s.watchdogSubmitStartTime=i,s.watchdogLastDataFlowTime=i;return}if(a==="tool_using"){const m=i-(s.watchdogLastDataFlowTime||i);if(m>=rt){const d=String(s.pendingToolEventData?.rawToolName??"");if(d.endsWith("await_complete")){console.warn(`[ACode] tool_using elapsed ${Math.round(m/1e3)}s but await_complete is running (session: ${t}, tool: ${d}), 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(m/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(m/1e3)}s): detached tool ${d} 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",m);return}s.watchdogSubmitStartTime=i;return}if(a!=="thinking")return;const n=i-(s.watchdogSubmitStartTime||i),u=i-(s.watchdogLastDataFlowTime||i);if(u>=nt){console.warn(`[ACode] CRITICAL: Data flow watchdog triggered after ${Math.round(u/1e3)}s (source: ${o}, session: ${t}, status: ${a}). No stream data received. Forcing recovery via recoverTurnFailure.`),this.executeWatchdogRecovery(t,s,o,"data_flow",u);return}if(n>=dt){console.warn(`[ACode] CRITICAL: submit timeout detected after ${Math.round(n/1e3)}s (source: ${o}, session: ${t}, status: ${a}). Forcing recovery to prevent permanent state stuck.`),this.executeWatchdogRecovery(t,s,o,"submit_timeout",n);return}},at)}executeWatchdogRecovery(t,e,o,s,a){l(`[ACode] Watchdog (${s}): calling runtime.abort() after ${Math.round(a/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=`
5
5
 
6
6
  \u8BF7\u6C42\u4F53:
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:"",l=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,l!==void 0?`\u6D41\u5F0F: ${l?"\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(A=>!!A),p=/^(authorization|x-api-key|api-key|cookie|set-cookie|x-auth-token|token)$/i,h=t.requestHeaders,C=h?Object.entries(h).filter(([A])=>!p.test(A)).map(([A,x])=>`${A}: ${x}`).filter(A=>A.trim().length>0):[],T=g.join(`
8
- `)||"ACode \u6B63\u5728\u53D1\u9001 AI \u8BF7\u6C42",S=C.length>0?`${e}${C.join(`
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}${S}${y}`}}export{Ft as AcodeSdkAdapter,Tt as isFailedAcodeTurnComplete,ct as toAcodeEsmImportSpecifier};
7
+ `,a=typeof t.model=="string"?t.model:"",i=typeof t.endpoint=="string"?t.endpoint:typeof t.requestUrl=="string"?t.requestUrl:"",n=typeof t.requestMethod=="string"?t.requestMethod:"",u=typeof t.stream=="boolean"?t.stream:void 0,m=typeof t.messageCount=="number"?t.messageCount:void 0,d=typeof t.toolCount=="number"?t.toolCount:void 0,c=typeof t.lastUserMessagePreview=="string"?t.lastUserMessagePreview:"",g=[a?`\u6A21\u578B: ${a}`:void 0,i?`\u63A5\u53E3: ${i}`:void 0,n?`\u65B9\u6CD5: ${n}`:void 0,u!==void 0?`\u6D41\u5F0F: ${u?"\u662F":"\u5426"}`:void 0,m!==void 0?`\u4E0A\u4E0B\u6587\u6D88\u606F: ${m}`:void 0,d!==void 0?`\u53EF\u7528\u5DE5\u5177: ${d}`:void 0,c?`\u6700\u540E\u8BF7\u6C42: ${c}`:void 0].filter(S=>!!S),p=/^(authorization|x-api-key|api-key|cookie|set-cookie|x-auth-token|token)$/i,T=t.requestHeaders,C=T?Object.entries(T).filter(([S])=>!p.test(S)).map(([S,L])=>`${S}: ${L}`).filter(S=>S.trim().length>0):[],_=g.join(`
8
+ `)||"ACode \u6B63\u5728\u53D1\u9001 AI \u8BF7\u6C42",A=C.length>0?`${e}${C.join(`
9
+ `)}`:"",k=typeof t.requestBody=="string"?t.requestBody:"",h=k.length>6e4?`${k.slice(0,6e4)}
10
+ ...(\u8BF7\u6C42\u4F53\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD)`:k,b=h?`${o}${h}`:"";return`${_}${A}${b}`}}export{Wt as AcodeSdkAdapter,St as isFailedAcodeTurnComplete,pt as toAcodeEsmImportSpecifier};
11
11
 
@@ -40,6 +40,10 @@ export interface RuntimeTokenUsage {
40
40
  inputLimit?: number;
41
41
 
42
42
  compactionThreshold?: number;
43
+
44
+ cacheHitTokens?: number;
45
+
46
+ cacheMissTokens?: number;
43
47
  }
44
48
  export type CommandOutputStream = "stdout" | "stderr" | "mixed";
45
49
  export interface RuntimeStatusActionInfo {
@@ -45,6 +45,8 @@ export declare function resolveStatusChangeUsage(actionInfo?: RuntimeStatusActio
45
45
  maxOutput?: number;
46
46
  inputLimit?: number;
47
47
  compactionThreshold?: number;
48
+ cacheHitTokens?: number;
49
+ cacheMissTokens?: number;
48
50
  } | undefined;
49
51
  export declare function resolveStatusChangeRuntimeState(status: string, actionInfo?: RuntimeStatusActionInfo): {
50
52
  status: string;
@@ -1,54 +1,54 @@
1
- import{spawn as He}from"node:child_process";import{promises as N}from"node:fs";import be from"node:os";import j from"node:path";import{TextDecoder as ee}from"node:util";import{Router as Qe}from"express";import{v4 as Xe}from"uuid";import Ce from"axios";import{adapterRegistry as w,getToolActionInfo as ye,isTransientClipboardPasteFilePath as $e,redactTransientClipboardPastePaths as q,registerSdkProviders as Ge,resolveSdkProviderIdByCommand as Je}from"../adapter/index.js";import{validateToken as S}from"../middleware/auth.js";import{getAgentProcessManager as he}from"../services/agent-process-manager.js";import{setAgentFeatures as Ve,getAgentFeatures as Ye}from"../services/instance-features.js";import{getAiConfigService as Ze}from"../services/cc-switch-sdk.js";import{prepareAcodeInstanceConfig as et,redactForLog as te}from"../services/instance-ai-config-service.js";import{enqueueMcpLaunchBinding as tt}from"../services/mcp-launch-binding-queue.js";import{resolveSchedulerBaseUrlFromToken as _e}from"../services/auto-register.js";import{findClaudeCodeProcesses as nt,isProcessRunning as rt}from"../services/process-detector.js";import{bridgeEventBuffer as De,sendOutput as Q,sendQuestionRequest as ot,sendStatus as _}from"../services/session-output.js";import{getAllPushStats as st,startHeartbeatScheduler as it}from"../services/event-delta-pusher.js";import{forgetSession as v,onSdkToolUseEnd as at,onSdkToolUseStart as ct}from"../services/sdk-tool-file-change-recorder.js";import{findPersistedSessionByAgentId as ut,removePersistedSession as F,savePersistedSessions as dt,updatePersistedSessionAutoCommands as lt,updatePersistedSessionRuntimeState as mt,upsertPersistedSession as ft}from"../services/terminal-persistence.js";import{getInstanceAiConfigDebugLogger as pt}from"../utils/instance-ai-config-debug-logger.js";import{logger as h}from"../utils/logger.js";const A=Qe();function Pe(e){const n=e.header("X-Runtime-Token");return n&&n.trim()?n.trim():(e.header("Authorization")||"").match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||void 0}const f=new Map,gt=45e3,ne=new Map;function yt(e){if(ne.has(e))return;const n=setInterval(()=>{const t=f.get(e);if(!t){E(e);return}const r=t.currentRuntimeStatus;if(r!=="thinking"&&r!=="tool_using"&&r!=="compacting"){E(e);return}_(t.agentId,e,r,void 0,void 0,{runtimeAccessToken:t.runtimeAccessToken,schedulerBaseUrl:t.schedulerBaseUrl}).catch(()=>{})},gt);ne.set(e,n)}function E(e){const n=ne.get(e);n&&(clearInterval(n),ne.delete(e))}const Re=4e3,ht=`
1
+ import{spawn as We}from"node:child_process";import{promises as N}from"node:fs";import be from"node:os";import j from"node:path";import{TextDecoder as ee}from"node:util";import{Router as Qe}from"express";import{v4 as Xe}from"uuid";import Ce from"axios";import{adapterRegistry as w,getToolActionInfo as ye,isTransientClipboardPasteFilePath as $e,redactTransientClipboardPastePaths as q,registerSdkProviders as Ge,resolveSdkProviderIdByCommand as Je}from"../adapter/index.js";import{validateToken as S}from"../middleware/auth.js";import{getAgentProcessManager as he}from"../services/agent-process-manager.js";import{setAgentFeatures as Ve,getAgentFeatures as Ye}from"../services/instance-features.js";import{getAiConfigService as Ze}from"../services/cc-switch-sdk.js";import{prepareAcodeInstanceConfig as et,redactForLog as te}from"../services/instance-ai-config-service.js";import{enqueueMcpLaunchBinding as tt}from"../services/mcp-launch-binding-queue.js";import{resolveSchedulerBaseUrlFromToken as _e}from"../services/auto-register.js";import{findClaudeCodeProcesses as nt,isProcessRunning as rt}from"../services/process-detector.js";import{bridgeEventBuffer as De,sendOutput as Q,sendQuestionRequest as ot,sendStatus as _}from"../services/session-output.js";import{getAllPushStats as st,startHeartbeatScheduler as it}from"../services/event-delta-pusher.js";import{forgetSession as v,onSdkToolUseEnd as at,onSdkToolUseStart as ct}from"../services/sdk-tool-file-change-recorder.js";import{findPersistedSessionByAgentId as ut,removePersistedSession as F,savePersistedSessions as dt,updatePersistedSessionAutoCommands as lt,updatePersistedSessionRuntimeState as mt,upsertPersistedSession as ft}from"../services/terminal-persistence.js";import{getInstanceAiConfigDebugLogger as pt}from"../utils/instance-ai-config-debug-logger.js";import{logger as h}from"../utils/logger.js";const A=Qe();function Pe(e){const t=e.header("X-Runtime-Token");return t&&t.trim()?t.trim():(e.header("Authorization")||"").match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||void 0}const f=new Map,gt=45e3,ne=new Map;function yt(e){if(ne.has(e))return;const t=setInterval(()=>{const n=f.get(e);if(!n){x(e);return}const r=n.currentRuntimeStatus;if(r!=="thinking"&&r!=="tool_using"&&r!=="compacting"){x(e);return}_(n.agentId,e,r,void 0,void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl}).catch(()=>{})},gt);ne.set(e,t)}function x(e){const t=ne.get(e);t&&(clearInterval(t),ne.delete(e))}const Re=4e3,ht=`
2
2
 
3
3
  \u8BF7\u6C42\u4F53:
4
- `;function Ie(e){if(e==null||typeof e!="object"||Array.isArray(e))return;const n=e,t={};return typeof n.model=="string"&&n.model.trim()&&(t.model=n.model.trim()),typeof n.baseURL=="string"&&n.baseURL.trim()&&(t.baseURL=n.baseURL.trim()),typeof n.apiKey=="string"&&n.apiKey.trim()&&(t.apiKey=n.apiKey.trim()),typeof n.effort=="string"&&n.effort.trim()&&(t.effort=n.effort.trim()),t}const It=`
4
+ `;function Ie(e){if(e==null||typeof e!="object"||Array.isArray(e))return;const t=e,n={};return typeof t.model=="string"&&t.model.trim()&&(n.model=t.model.trim()),typeof t.baseURL=="string"&&t.baseURL.trim()&&(n.baseURL=t.baseURL.trim()),typeof t.apiKey=="string"&&t.apiKey.trim()&&(n.apiKey=t.apiKey.trim()),typeof t.effort=="string"&&t.effort.trim()&&(n.effort=t.effort.trim()),n}const It=`
5
5
 
6
6
  \u8BF7\u6C42\u5934:
7
- `,K=new Set;async function St(e,n){const t=[],r=[],s=j.join(e,".agentswork","memory");try{const c=(await N.readdir(s)).filter(u=>u.endsWith(".json")),d=await Promise.all(c.map(async u=>{try{const l=await N.readFile(j.join(s,u),"utf-8");return JSON.parse(l)}catch{return h.warn("[loadAgentStartupMemories] Failed to parse memory file: %s",j.join(s,u)),null}}));for(const u of d)if(u?.by_uri)for(const l of Object.values(u.by_uri)){const m=l.memory_type||"memory",p=(l.content||"").trim();p&&(m==="recently_memory"?t.push({title:l.title,content:p,uri:l.uri||""}):m==="agent_memory"&&r.push({title:l.title,content:p,uri:l.uri||""}))}}catch{h.debug("[loadAgentStartupMemories] \u65E0\u6CD5\u8BFB\u53D6\u8BB0\u5FC6\u76EE\u5F55: %s",s)}if(t.length===0&&r.length===0&&n?.schedulerBaseUrl&&n?.runtimeAccessToken&&n?.agentId){const a=`${n.schedulerBaseUrl.replace(/\/+$/,"")}/mcp/call`,c={"Content-Type":"application/json","X-Runtime-Token":n.runtimeAccessToken,Authorization:`Bearer ${n.runtimeAccessToken}`},d=["recently_memory","agent_memory"],u=await Promise.allSettled(d.map(l=>fetch(a,{method:"POST",headers:c,body:JSON.stringify({tool:"list_memories",arguments:{agentId:n.agentId,memory_type:l}})}).then(m=>{if(!m.ok)throw new Error(`Server returned ${m.status}`);return m.json()})));for(let l=0;l<u.length;l++){const m=u[l];if(m.status!=="fulfilled")continue;const p=m.value;if(!Array.isArray(p))continue;const T=d[l]==="recently_memory"?t:r;for(const y of p){const g=(y.content||"").trim();g&&T.push({title:y.title,content:g,uri:y.uri||""})}}(t.length>0||r.length>0)&&h.info(`[loadAgentStartupMemories] Loaded ${t.length} task(s) and ${r.length} memory(s) from server for ${n.agentId}`)}const o=10;t.sort((a,c)=>c.uri.localeCompare(a.uri)),r.sort((a,c)=>c.uri.localeCompare(a.uri));const i=[];if(t.length>0){const c=t.slice(0,o).map((d,u)=>`${d.title?`\u3010${d.title}\u3011`:`\u6761\u76EE ${u+1}`}
7
+ `,K=new Set;async function St(e,t){const n=[],r=[],o=j.join(e,".agentswork","memory");try{const c=(await N.readdir(o)).filter(u=>u.endsWith(".json")),d=await Promise.all(c.map(async u=>{try{const l=await N.readFile(j.join(o,u),"utf-8");return JSON.parse(l)}catch{return h.warn("[loadAgentStartupMemories] Failed to parse memory file: %s",j.join(o,u)),null}}));for(const u of d)if(u?.by_uri)for(const l of Object.values(u.by_uri)){const m=l.memory_type||"memory",p=(l.content||"").trim();p&&(m==="recently_memory"?n.push({title:l.title,content:p,uri:l.uri||""}):m==="agent_memory"&&r.push({title:l.title,content:p,uri:l.uri||""}))}}catch{h.debug("[loadAgentStartupMemories] \u65E0\u6CD5\u8BFB\u53D6\u8BB0\u5FC6\u76EE\u5F55: %s",o)}if(n.length===0&&r.length===0&&t?.schedulerBaseUrl&&t?.runtimeAccessToken&&t?.agentId){const a=`${t.schedulerBaseUrl.replace(/\/+$/,"")}/mcp/call`,c={"Content-Type":"application/json","X-Runtime-Token":t.runtimeAccessToken,Authorization:`Bearer ${t.runtimeAccessToken}`},d=["recently_memory","agent_memory"],u=await Promise.allSettled(d.map(l=>fetch(a,{method:"POST",headers:c,body:JSON.stringify({tool:"list_memories",arguments:{agentId:t.agentId,memory_type:l}})}).then(m=>{if(!m.ok)throw new Error(`Server returned ${m.status}`);return m.json()})));for(let l=0;l<u.length;l++){const m=u[l];if(m.status!=="fulfilled")continue;const p=m.value;if(!Array.isArray(p))continue;const T=d[l]==="recently_memory"?n:r;for(const y of p){const g=(y.content||"").trim();g&&T.push({title:y.title,content:g,uri:y.uri||""})}}(n.length>0||r.length>0)&&h.info(`[loadAgentStartupMemories] Loaded ${n.length} task(s) and ${r.length} memory(s) from server for ${t.agentId}`)}const s=10;n.sort((a,c)=>c.uri.localeCompare(a.uri)),r.sort((a,c)=>c.uri.localeCompare(a.uri));const i=[];if(n.length>0){const c=n.slice(0,s).map((d,u)=>`${d.title?`\u3010${d.title}\u3011`:`\u6761\u76EE ${u+1}`}
8
8
  ${d.content}`);i.push(`\u3010\u77ED\u671F\u8BB0\u5FC6\u3011
9
9
  ${c.join(`
10
10
 
11
- `)}`),t.length>o&&i.push(`... \u53CA\u53E6\u5916 ${t.length-o} \u6761\u77ED\u671F\u8BB0\u5FC6`)}if(r.length>0){const c=r.slice(0,o).map(d=>{const u=d.title?`\u3010${d.title}\u3011`:"";return u?`${u}
11
+ `)}`),n.length>s&&i.push(`... \u53CA\u53E6\u5916 ${n.length-s} \u6761\u77ED\u671F\u8BB0\u5FC6`)}if(r.length>0){const c=r.slice(0,s).map(d=>{const u=d.title?`\u3010${d.title}\u3011`:"";return u?`${u}
12
12
  ${d.content}`:d.content});i.push(`\u3010agent\u8BA4\u77E5\u3011
13
13
  ${c.join(`
14
14
 
15
- `)}`),r.length>o&&i.push(`... \u53CA\u53E6\u5916 ${r.length-o} \u6761 agent \u8BA4\u77E5`)}if(i.length!==0)return i.join(`
15
+ `)}`),r.length>s&&i.push(`... \u53CA\u53E6\u5916 ${r.length-s} \u6761 agent \u8BA4\u77E5`)}if(i.length!==0)return i.join(`
16
16
 
17
- `)}function At(e,n){return e!=="acode"?{supported:!1,statusCode:400,error:"context reset without restart is only supported by ACode"}:n?{supported:!0}:{supported:!1,statusCode:500,error:"ACode adapter does not expose resetContext"}}function Tt(e){return e!=="acode"}function kt(e){const n=typeof e=="object"&&e!==null&&"suppressStatus"in e&&e.suppressStatus===!0,t=typeof e=="object"&&e!==null&&"reason"in e&&typeof e.reason=="string"&&e.reason.trim()?e.reason.trim():void 0;return{statusNotified:!n,reason:t}}function re(e){const n=e?.usage;if(!n)return;const t=Number.isFinite(n.inputTokens)?n.inputTokens:0,r=Number.isFinite(n.outputTokens)?n.outputTokens:0;return t<=0&&r<=0&&!n.contextLimit&&!n.maxOutput&&!n.inputLimit&&!n.compactionThreshold?void 0:{inputTokens:t,outputTokens:r,...n.contextLimit?{contextLimit:n.contextLimit}:{},...n.maxOutput?{maxOutput:n.maxOutput}:{},...n.inputLimit?{inputLimit:n.inputLimit}:{},...n.compactionThreshold?{compactionThreshold:n.compactionThreshold}:{}}}function wt(e,n){const t=String(e||"").trim().toLowerCase(),r=String(n?.actionType||"").trim().toLowerCase();return t==="tool_using"&&r==="idle"?n?{status:"waiting_input",actionInfo:n}:{status:"waiting_input"}:n?{status:e,actionInfo:n}:{status:e}}const X=new Map,bt="utf-8",Me="utf-8",xe=300,Ee=6e4;function G(e){return String(e).padStart(2,"0")}function Ct(e,n=new Date){const t=n.getFullYear(),r=G(n.getMonth()+1),s=G(n.getDate()),o=G(n.getHours()),i=G(n.getMinutes()),a=`${t}${r}${s}-${o}${i}${G(n.getSeconds())}-${String(n.getMilliseconds()).padStart(3,"0")}`;return j.join(be.homedir(),".acode","cmd-dist",e,`${t}-${r}-${s}`,o,i,`${a}-cmd.out`)}function $t(e){if(!e)return 0;const n=e.replace(/\r\n/g,`
17
+ `)}function At(e,t){return e!=="acode"?{supported:!1,statusCode:400,error:"context reset without restart is only supported by ACode"}:t?{supported:!0}:{supported:!1,statusCode:500,error:"ACode adapter does not expose resetContext"}}function Tt(e){return e!=="acode"}function kt(e){const t=typeof e=="object"&&e!==null&&"suppressStatus"in e&&e.suppressStatus===!0,n=typeof e=="object"&&e!==null&&"reason"in e&&typeof e.reason=="string"&&e.reason.trim()?e.reason.trim():void 0;return{statusNotified:!t,reason:n}}function re(e){const t=e?.usage;if(!t)return;const n=Number.isFinite(t.inputTokens)?t.inputTokens:0,r=Number.isFinite(t.outputTokens)?t.outputTokens:0;if(n<=0&&r<=0&&!t.contextLimit&&!t.maxOutput&&!t.inputLimit&&!t.compactionThreshold)return;const o={inputTokens:n,outputTokens:r,...t.contextLimit?{contextLimit:t.contextLimit}:{},...t.maxOutput?{maxOutput:t.maxOutput}:{},...t.inputLimit?{inputLimit:t.inputLimit}:{},...t.compactionThreshold?{compactionThreshold:t.compactionThreshold}:{},...t.cacheHitTokens?{cacheHitTokens:t.cacheHitTokens}:{},...t.cacheMissTokens?{cacheMissTokens:t.cacheMissTokens}:{}};return process.env.ACODE_TOKEN_DEBUG==="1"&&(o.inputTokens>0||o.outputTokens>0||o.cacheHitTokens!==void 0||o.cacheMissTokens!==void 0)&&console.log(`[TokenDebug][Terminal] resolveStatusChangeUsage: input=${o.inputTokens} output=${o.outputTokens} cacheHit=${o.cacheHitTokens??"(none)"} cacheMiss=${o.cacheMissTokens??"(none)"} actionType=${e?.actionType??"(none)"}`),o}function wt(e,t){const n=String(e||"").trim().toLowerCase(),r=String(t?.actionType||"").trim().toLowerCase();return n==="tool_using"&&r==="idle"?t?{status:"waiting_input",actionInfo:t}:{status:"waiting_input"}:t?{status:e,actionInfo:t}:{status:e}}const X=new Map,bt="utf-8",Me="utf-8",Ee=300,xe=6e4;function G(e){return String(e).padStart(2,"0")}function Ct(e,t=new Date){const n=t.getFullYear(),r=G(t.getMonth()+1),o=G(t.getDate()),s=G(t.getHours()),i=G(t.getMinutes()),a=`${n}${r}${o}-${s}${i}${G(t.getSeconds())}-${String(t.getMilliseconds()).padStart(3,"0")}`;return j.join(be.homedir(),".acode","cmd-dist",e,`${n}-${r}-${o}`,s,i,`${a}-cmd.out`)}function $t(e){if(!e)return 0;const t=e.replace(/\r\n/g,`
18
18
  `).replace(/\r/g,`
19
- `),t=n.endsWith(`
20
- `)?n.slice(0,-1):n;return t?t.split(`
21
- `).length:1}function _t(e,n=xe){return`\r
22
- [ACode] \u547D\u4EE4\u8F93\u51FA\u8D85\u8FC7 ${n} \u884C\uFF0C\u5B8C\u6574\u8F93\u51FA\u5DF2\u5199\u5165: ${e}\r
19
+ `),n=t.endsWith(`
20
+ `)?t.slice(0,-1):t;return n?n.split(`
21
+ `).length:1}function _t(e,t=Ee){return`\r
22
+ [ACode] \u547D\u4EE4\u8F93\u51FA\u8D85\u8FC7 ${t} \u884C\uFF0C\u5B8C\u6574\u8F93\u51FA\u5DF2\u5199\u5165: ${e}\r
23
23
  [ACode] Agent \u53EF\u81EA\u884C\u8BFB\u53D6\u8BE5\u6587\u4EF6\uFF0C\u6216\u5728\u8BE5\u6587\u4EF6\u4E2D\u641C\u7D22\u9700\u8981\u7684\u5185\u5BB9\u3002\r
24
- `}function Dt(e=Ee){return`\r
24
+ `}function Dt(e=xe){return`\r
25
25
  [ACode] \u547D\u4EE4\u8D85\u8FC7 ${Math.round(e/1e3)} \u79D2\u6CA1\u6709\u65B0\u7684\u8F93\u51FA\uFF0C\u5DF2\u505C\u6B62\u6267\u884C\u5E76\u4FDD\u7559\u6B64\u524D\u8F93\u51FA\u3002\r
26
- `}async function Le(e){const n=e.outputPath||Ct(e.agentId,e.startedAt);return e.outputPath=n,await N.mkdir(j.dirname(n),{recursive:!0}),await N.writeFile(n,e.chunks.join(""),"utf-8"),n}function Pt(e){return String(e??"").replace(/\r/g,`
27
- `).trim()}function Rt(e=process.platform,n=process.env){const t=n.AWS_TERMINAL_OUTPUT_ENCODING?.trim();return t||(e==="win32"?bt:Me)}function Ue(e=Rt()){if(e!=="utf-8")try{return new ee(e,{fatal:!1})}catch{return new ee(Me,{fatal:!1})}return Mt()}function Mt(){let e=null,n=null,t=null;const r=[];function s(o){try{return new ee(o,{fatal:!1})}catch{return new ee("utf-8",{fatal:!1})}}return{decode(o,i){if(o!=null&&r.push(o instanceof ArrayBuffer?Buffer.from(o):Buffer.isBuffer(o)?o:Buffer.from(o.buffer,o.byteOffset,o.byteLength)),t==="gb18030")return n||(n=s("gb18030")),n.decode(o,i);e||(e=s("utf-8"));const a=e.decode(o,i);if(t===null&&a.includes("\uFFFD")){t="gb18030",n=s("gb18030");const c=Buffer.concat(r);return n.decode(c)}return t===null&&!i?.stream&&(t="utf-8"),a}}}function oe(e,n,t=!1){return t?e.decode():!n||n.length===0?"":e.decode(n,{stream:!0})}function xt(e){const n=e.trim().match(/^cd(?:\s+(.*))?$/i);if(!n)return;const t=n[1]?.trim();if(!t)return null;const r=t.replace(/^\/d\s+/i,"").trim();return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function Et(e){const n=X.get(e.sessionId);if(n)return n;const t={currentDirectory:e.workspacePath,runningProcess:null};return X.set(e.sessionId,t),t}function je(e){for(const n of f.values())if(n.agentId===e)return n}async function Lt(e){const n=w.get(e.providerId||"claude-code"),t=se(n.getSessionStatus(e.sessionId),e.currentRuntimeStatus,e.currentRuntimeActionType);return{sessionId:e.sessionId,status:t,runtimeStatus:t,runtimeActionType:e.currentRuntimeActionType,runtimeActionLabel:e.currentRuntimeActionLabel,runtimeActionDetail:e.currentRuntimeActionDetail,agentId:e.agentId,workspacePath:e.workspacePath,command:e.config.command,mode:"sdk",providerSessionId:n.getProviderSessionId(e.sessionId),reused:!0}}function se(e,n,t){const r=String(e||"").trim();if(r){const o=String(n||"").trim(),i=String(t||"").trim().toLowerCase();return r.toLowerCase()==="tool_using"&&o.toLowerCase()==="waiting_input"&&i==="idle"?o:r}return String(n||"").trim()||"running"}function Ut(e,n=rt){return e.pid?n(e.pid)?Fe(e.command)==="acode"?{reusable:!1,reason:"in-process-provider"}:{reusable:!0,reason:"active-pid"}:{reusable:!1,reason:"dead-pid"}:{reusable:!1,reason:"missing-pid"}}function Kn(e){const n=je(e);if(!n)h.info(`[cleanupSdkSessionByAgentId] No active SDK session found for agentId=${e}, cleaning residual state anyway`);else{const t=n.sessionId;return h.info(`[cleanupSdkSessionByAgentId] Cleaning up SDK session for agentId=${e}, sessionId=${t}`),E(t),f.delete(t),v(t),ie(t),F(t).catch(r=>{h.warn(`[cleanupSdkSessionByAgentId] Failed to remove persisted session for agentId=${e}: ${r}`)}),t}K.has(e)&&(K.delete(e),h.info(`[cleanupSdkSessionByAgentId] Released startingAgents lock for agentId=${e}`))}function ie(e){const n=X.get(e);if(!n?.runningProcess){X.delete(e);return}try{n.runningProcess.kill()}catch{}finally{n.runningProcess=null,X.delete(e)}}function b(e,n){n&&(e.seq+=1,Q(e.agentId,n,e.sessionId,e.seq,void 0,{runtimeAccessToken:e.runtimeAccessToken,schedulerBaseUrl:e.schedulerBaseUrl}).catch(()=>{}))}function Se(e){return`\x1B[36m${e}>\x1B[0m `}function jt(e,n){return n==="~"?be.homedir():j.resolve(e,n)}async function Bt(e,n,t){const r=xt(t);if(r===void 0)return!1;if(r===null)return b(e,`${n.currentDirectory}\r
28
- `),!0;const s=jt(n.currentDirectory,r);try{return(await N.stat(s)).isDirectory()?(n.currentDirectory=s,b(e,`${n.currentDirectory}\r
29
- `),!0):(b(e,`cd: not a directory: ${s}\r
30
- `),!0)}catch(o){const i=o instanceof Error?o.message:String(o);return b(e,`cd: ${i}\r
31
- `),!0}}async function Ot(e,n){const t=f.get(e);if(!t)throw new Error("SDK session not found");const r=Pt(n),s=Et(t);if(!r)return{started:!1,cwd:s.currentDirectory};if(s.runningProcess)throw new Error("A terminal command is already running for this session");const o=q(r);if(b(t,`${Se(s.currentDirectory)}${o}\r
32
- `),$e(r))return b(t,`[Terminal Warning] \u68C0\u6D4B\u5230\u526A\u8D34\u677F\u4E34\u65F6 paste \u6587\u4EF6\u8DEF\u5F84\uFF0C\u5DF2\u8DF3\u8FC7\u6267\u884C\u3002\u8BF7\u7C98\u8D34\u6587\u4EF6\u5185\u5BB9\u6216\u4F7F\u7528\u663E\u5F0F\u8BFB\u53D6\u547D\u4EE4\u3002\r
33
- `),b(t,Se(s.currentDirectory)),{started:!1,cwd:s.currentDirectory};if(await Bt(t,s,r))return{started:!1,cwd:s.currentDirectory};await _(t.agentId,e,"tool_using",{actionType:"bash",actionLabel:"\u7EC8\u7AEF\u547D\u4EE4",actionDetail:o},void 0,{runtimeAccessToken:t.runtimeAccessToken,schedulerBaseUrl:t.schedulerBaseUrl});const a=He(r,{cwd:s.currentDirectory,shell:!0,env:Be(t.agentId,t.workspacePath,process.env,t.config.envOverrides)});s.runningProcess=a;const c=Ue(),d=Ue(),u=t.providerId==="acode",l={agentId:t.agentId,startedAt:new Date,chunks:[],spilled:!1};let m;const p=()=>{m&&(clearTimeout(m),m=void 0)},T=()=>{p(),m=setTimeout(()=>{s.runningProcess===a&&(b(t,Dt()),a.kill())},Ee)},y=(g,C=!0)=>{if(g&&(u&&l.chunks.push(g),u&&C&&T(),!(u&&l.spilled))){if(u&&$t(l.chunks.join(""))>xe){l.spilled=!0,Le(l).then($=>{b(t,_t($))}).catch($=>{const x=$ instanceof Error?$.message:String($);b(t,`\r
34
- [ACode] \u547D\u4EE4\u8F93\u51FA\u843D\u76D8\u5931\u8D25: ${x}\r
35
- `)});return}b(t,g)}};return u&&T(),a.stdout.on("data",g=>{y(oe(c,g))}),a.stderr.on("data",g=>{y(oe(d,g))}),a.on("error",g=>{b(t,`\r
26
+ `}async function Le(e){const t=e.outputPath||Ct(e.agentId,e.startedAt);return e.outputPath=t,await N.mkdir(j.dirname(t),{recursive:!0}),await N.writeFile(t,e.chunks.join(""),"utf-8"),t}function Pt(e){return String(e??"").replace(/\r/g,`
27
+ `).trim()}function Rt(e=process.platform,t=process.env){const n=t.AWS_TERMINAL_OUTPUT_ENCODING?.trim();return n||(e==="win32"?bt:Me)}function Ue(e=Rt()){if(e!=="utf-8")try{return new ee(e,{fatal:!1})}catch{return new ee(Me,{fatal:!1})}return Mt()}function Mt(){let e=null,t=null,n=null;const r=[];function o(s){try{return new ee(s,{fatal:!1})}catch{return new ee("utf-8",{fatal:!1})}}return{decode(s,i){if(s!=null&&r.push(s instanceof ArrayBuffer?Buffer.from(s):Buffer.isBuffer(s)?s:Buffer.from(s.buffer,s.byteOffset,s.byteLength)),n==="gb18030")return t||(t=o("gb18030")),t.decode(s,i);e||(e=o("utf-8"));const a=e.decode(s,i);if(n===null&&a.includes("\uFFFD")){n="gb18030",t=o("gb18030");const c=Buffer.concat(r);return t.decode(c)}return n===null&&!i?.stream&&(n="utf-8"),a}}}function oe(e,t,n=!1){return n?e.decode():!t||t.length===0?"":e.decode(t,{stream:!0})}function Et(e){const t=e.trim().match(/^cd(?:\s+(.*))?$/i);if(!t)return;const n=t[1]?.trim();if(!n)return null;const r=n.replace(/^\/d\s+/i,"").trim();return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function xt(e){const t=X.get(e.sessionId);if(t)return t;const n={currentDirectory:e.workspacePath,runningProcess:null};return X.set(e.sessionId,n),n}function je(e){for(const t of f.values())if(t.agentId===e)return t}async function Lt(e){const t=w.get(e.providerId||"claude-code"),n=se(t.getSessionStatus(e.sessionId),e.currentRuntimeStatus,e.currentRuntimeActionType);return{sessionId:e.sessionId,status:n,runtimeStatus:n,runtimeActionType:e.currentRuntimeActionType,runtimeActionLabel:e.currentRuntimeActionLabel,runtimeActionDetail:e.currentRuntimeActionDetail,agentId:e.agentId,workspacePath:e.workspacePath,command:e.config.command,mode:"sdk",providerSessionId:t.getProviderSessionId(e.sessionId),reused:!0}}function se(e,t,n){const r=String(e||"").trim();if(r){const s=String(t||"").trim(),i=String(n||"").trim().toLowerCase();return r.toLowerCase()==="tool_using"&&s.toLowerCase()==="waiting_input"&&i==="idle"?s:r}return String(t||"").trim()||"running"}function Ut(e,t=rt){return e.pid?t(e.pid)?Fe(e.command)==="acode"?{reusable:!1,reason:"in-process-provider"}:{reusable:!0,reason:"active-pid"}:{reusable:!1,reason:"dead-pid"}:{reusable:!1,reason:"missing-pid"}}function Kn(e){const t=je(e);if(!t)h.info(`[cleanupSdkSessionByAgentId] No active SDK session found for agentId=${e}, cleaning residual state anyway`);else{const n=t.sessionId;return h.info(`[cleanupSdkSessionByAgentId] Cleaning up SDK session for agentId=${e}, sessionId=${n}`),x(n),f.delete(n),v(n),ie(n),F(n).catch(r=>{h.warn(`[cleanupSdkSessionByAgentId] Failed to remove persisted session for agentId=${e}: ${r}`)}),n}K.has(e)&&(K.delete(e),h.info(`[cleanupSdkSessionByAgentId] Released startingAgents lock for agentId=${e}`))}function ie(e){const t=X.get(e);if(!t?.runningProcess){X.delete(e);return}try{t.runningProcess.kill()}catch{}finally{t.runningProcess=null,X.delete(e)}}function b(e,t){t&&(e.seq+=1,Q(e.agentId,t,e.sessionId,e.seq,void 0,{runtimeAccessToken:e.runtimeAccessToken,schedulerBaseUrl:e.schedulerBaseUrl}).catch(()=>{}))}function Se(e){return`\x1B[36m${e}>\x1B[0m `}function jt(e,t){return t==="~"?be.homedir():j.resolve(e,t)}async function Bt(e,t,n){const r=Et(n);if(r===void 0)return!1;if(r===null)return b(e,`${t.currentDirectory}\r
28
+ `),!0;const o=jt(t.currentDirectory,r);try{return(await N.stat(o)).isDirectory()?(t.currentDirectory=o,b(e,`${t.currentDirectory}\r
29
+ `),!0):(b(e,`cd: not a directory: ${o}\r
30
+ `),!0)}catch(s){const i=s instanceof Error?s.message:String(s);return b(e,`cd: ${i}\r
31
+ `),!0}}async function Ot(e,t){const n=f.get(e);if(!n)throw new Error("SDK session not found");const r=Pt(t),o=xt(n);if(!r)return{started:!1,cwd:o.currentDirectory};if(o.runningProcess)throw new Error("A terminal command is already running for this session");const s=q(r);if(b(n,`${Se(o.currentDirectory)}${s}\r
32
+ `),$e(r))return b(n,`[Terminal Warning] \u68C0\u6D4B\u5230\u526A\u8D34\u677F\u4E34\u65F6 paste \u6587\u4EF6\u8DEF\u5F84\uFF0C\u5DF2\u8DF3\u8FC7\u6267\u884C\u3002\u8BF7\u7C98\u8D34\u6587\u4EF6\u5185\u5BB9\u6216\u4F7F\u7528\u663E\u5F0F\u8BFB\u53D6\u547D\u4EE4\u3002\r
33
+ `),b(n,Se(o.currentDirectory)),{started:!1,cwd:o.currentDirectory};if(await Bt(n,o,r))return{started:!1,cwd:o.currentDirectory};await _(n.agentId,e,"tool_using",{actionType:"bash",actionLabel:"\u7EC8\u7AEF\u547D\u4EE4",actionDetail:s},void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl});const a=We(r,{cwd:o.currentDirectory,shell:!0,env:Be(n.agentId,n.workspacePath,process.env,n.config.envOverrides)});o.runningProcess=a;const c=Ue(),d=Ue(),u=n.providerId==="acode",l={agentId:n.agentId,startedAt:new Date,chunks:[],spilled:!1};let m;const p=()=>{m&&(clearTimeout(m),m=void 0)},T=()=>{p(),m=setTimeout(()=>{o.runningProcess===a&&(b(n,Dt()),a.kill())},xe)},y=(g,C=!0)=>{if(g&&(u&&l.chunks.push(g),u&&C&&T(),!(u&&l.spilled))){if(u&&$t(l.chunks.join(""))>Ee){l.spilled=!0,Le(l).then($=>{b(n,_t($))}).catch($=>{const E=$ instanceof Error?$.message:String($);b(n,`\r
34
+ [ACode] \u547D\u4EE4\u8F93\u51FA\u843D\u76D8\u5931\u8D25: ${E}\r
35
+ `)});return}b(n,g)}};return u&&T(),a.stdout.on("data",g=>{y(oe(c,g))}),a.stderr.on("data",g=>{y(oe(d,g))}),a.on("error",g=>{b(n,`\r
36
36
  [Terminal Error] ${g.message}\r
37
- `)}),a.on("close",(g,C)=>{p(),s.runningProcess=null,y(oe(c,void 0,!0),!1),y(oe(d,void 0,!0),!1),l.spilled&&Le(l).catch($=>{const x=$ instanceof Error?$.message:String($);b(t,`\r
38
- [ACode] \u547D\u4EE4\u8F93\u51FA\u6700\u7EC8\u843D\u76D8\u5931\u8D25: ${x}\r
39
- `)}),g&&g!==0?b(t,`\r
37
+ `)}),a.on("close",(g,C)=>{p(),o.runningProcess=null,y(oe(c,void 0,!0),!1),y(oe(d,void 0,!0),!1),l.spilled&&Le(l).catch($=>{const E=$ instanceof Error?$.message:String($);b(n,`\r
38
+ [ACode] \u547D\u4EE4\u8F93\u51FA\u6700\u7EC8\u843D\u76D8\u5931\u8D25: ${E}\r
39
+ `)}),g&&g!==0?b(n,`\r
40
40
  [exit ${g}]\r
41
- `):C&&b(t,`\r
41
+ `):C&&b(n,`\r
42
42
  [signal ${C}]\r
43
- `),b(t,Se(s.currentDirectory)),_(t.agentId,e,"waiting_input",void 0,void 0,{runtimeAccessToken:t.runtimeAccessToken,schedulerBaseUrl:t.schedulerBaseUrl})}),{started:!0,cwd:s.currentDirectory}}function Be(e,n,t,r){const s={};for(const[o,i]of Object.entries(t))i!==void 0&&(s[o]=i);if(n&&(s.AWS_WORKSPACE_PATH=String(n)),r)for(const[o,i]of Object.entries(r)){const a=o.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(s[a]=c)}return s.AWS_AGENT_ID=String(e),s.AWS_MCP_CLAIM_LAUNCH_BINDING="true",s}function Nt(e){const n=e.trim(),t=n[0],r=n[n.length-1];return(t==='"'||t==="'")&&t===r?n.slice(1,-1):n}async function qt(e){const n=String(e);if(!$e(n))return n;const t=Nt(n);return j.isAbsolute(t)?N.readFile(t,"utf-8"):n}function Oe(e,n){const t={};for(const s of[e?.env,n])if(s)for(const[o,i]of Object.entries(s)){const a=o.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(t[a]=c)}const r=t.ANTHROPIC_MODEL?.trim()||t.CODEX_MODEL?.trim()||void 0;return{envOverrides:t,model:r}}async function vt(){try{return await Ze().readClaudeCodeConfig()}catch(e){return console.warn(`[Runtime] Failed to read saved ClaudeCode AI config: ${e.message}`),{}}}function Ft(e){if(e==null)return;const t=(typeof e=="string"?e:JSON.stringify(e,null,2)).trim();if(t)return t.length<=Re?t:`${t.slice(0,Re)}
44
- ...\uFF08\u7ED3\u679C\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`}function Kt(e){try{const n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return["directMessages","groupMessages","messages"].some(t=>Array.isArray(n[t])&&n[t].length>0)}catch{}return e.trim().length>0}function zt(e){if(e.data.actionType==="mcp")return!0;const t=String(e.data.toolName||"").toLowerCase();return t.startsWith("mcp__")||t.includes("-mcp__")||t.includes("mcp_")}function Wt(e){if(e.type!=="tool_use_end")return;const n=Ft(e.data.toolResult??e.data.actionResult);if(!n)return;const t=ye(e.data.toolName,e.data.toolInput),r=e.data.actionType||t.actionType;if(!(r==="idle"&&!Kt(n)))return r==="mcp"&&zt(e)?{actionType:"mcp",actionLabel:"MCP\u8FD4\u56DE",actionDetail:e.data.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:n}:{actionType:r,actionLabel:e.data.actionLabel||t.actionLabel,actionDetail:e.data.actionDetail||t.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:n}}function Ht(e){if(e.type==="ai_request"){const n=e.data.model?` ${e.data.model}`:"",t=e.data.lastUserMessagePreview?`\uFF1A${e.data.lastUserMessagePreview}`:"";return`\r
45
- [ACode] \u6B63\u5728\u8BF7\u6C42\u6A21\u578B${n}${t}\r
43
+ `),b(n,Se(o.currentDirectory)),_(n.agentId,e,"waiting_input",void 0,void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl})}),{started:!0,cwd:o.currentDirectory}}function Be(e,t,n,r){const o={};for(const[s,i]of Object.entries(n))i!==void 0&&(o[s]=i);if(t&&(o.AWS_WORKSPACE_PATH=String(t)),r)for(const[s,i]of Object.entries(r)){const a=s.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(o[a]=c)}return o.AWS_AGENT_ID=String(e),o.AWS_MCP_CLAIM_LAUNCH_BINDING="true",o}function Nt(e){const t=e.trim(),n=t[0],r=t[t.length-1];return(n==='"'||n==="'")&&n===r?t.slice(1,-1):t}async function qt(e){const t=String(e);if(!$e(t))return t;const n=Nt(t);return j.isAbsolute(n)?N.readFile(n,"utf-8"):t}function Oe(e,t){const n={};for(const o of[e?.env,t])if(o)for(const[s,i]of Object.entries(o)){const a=s.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(n[a]=c)}const r=n.ANTHROPIC_MODEL?.trim()||n.CODEX_MODEL?.trim()||void 0;return{envOverrides:n,model:r}}async function vt(){try{return await Ze().readClaudeCodeConfig()}catch(e){return console.warn(`[Runtime] Failed to read saved ClaudeCode AI config: ${e.message}`),{}}}function Ft(e){if(e==null)return;const n=(typeof e=="string"?e:JSON.stringify(e,null,2)).trim();if(n)return n.length<=Re?n:`${n.slice(0,Re)}
44
+ ...\uFF08\u7ED3\u679C\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`}function Kt(e){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return["directMessages","groupMessages","messages"].some(n=>Array.isArray(t[n])&&t[n].length>0)}catch{}return e.trim().length>0}function zt(e){if(e.data.actionType==="mcp")return!0;const n=String(e.data.toolName||"").toLowerCase();return n.startsWith("mcp__")||n.includes("-mcp__")||n.includes("mcp_")}function Ht(e){if(e.type!=="tool_use_end")return;const t=Ft(e.data.toolResult??e.data.actionResult);if(!t)return;const n=ye(e.data.toolName,e.data.toolInput),r=e.data.actionType||n.actionType;if(!(r==="idle"&&!Kt(t)))return r==="mcp"&&zt(e)?{actionType:"mcp",actionLabel:"MCP\u8FD4\u56DE",actionDetail:e.data.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:t}:{actionType:r,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:e.data.actionDetail||n.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:t}}function Wt(e){if(e.type==="ai_request"){const t=e.data.model?` ${e.data.model}`:"",n=e.data.lastUserMessagePreview?`\uFF1A${e.data.lastUserMessagePreview}`:"";return`\r
45
+ [ACode] \u6B63\u5728\u8BF7\u6C42\u6A21\u578B${t}${n}\r
46
46
  `}if(e.type==="text_delta"||e.type==="thinking"||e.type==="command_output")return e.data.text||void 0;if(e.type==="error")return e.data.text?`\r
47
47
  [SDK Error] ${e.data.text}\r
48
- `:void 0}function Qt(e){const n=Jt(e);return{sourceEventType:e.type,logCategory:"acode",...Gt(e),...n?{logLevel:Xt(e),logMessage:n}:{}}}function Xt(e){return e.type==="error"?"error":e.type==="command_output"&&e.data.stream==="stderr"?"warn":"info"}function Gt(e){return e.type!=="command_output"?{}:{...typeof e.data.stream=="string"?{stream:e.data.stream}:{},...typeof e.data.sequence=="number"?{sequence:e.data.sequence}:{},...typeof e.data.cwd=="string"?{cwd:e.data.cwd}:{},...typeof e.data.commandFilePath=="string"?{commandFilePath:e.data.commandFilePath}:{},...typeof e.data.commandLineCount=="number"?{commandLineCount:e.data.commandLineCount}:{}}}function Jt(e){if(e.type==="ai_request"){const n=e.data.model||"unknown-model",t=e.data.endpoint?` @ ${e.data.endpoint}`:"",r=typeof e.data.toolCount=="number"?`, tools=${e.data.toolCount}`:"";return`AI request started: ${n}${t}${r}`}if(e.type==="tool_use_start")return Ne(e,"\u5F00\u59CB");if(e.type==="tool_use_end")return Ne(e,"\u5B8C\u6210");if(e.type==="command_output")return Zt(e);if(e.type==="turn_complete")return`Turn completed${e.data.finishReason?`, finish=${e.data.finishReason}`:""}`;if(e.type==="session_complete")return`Session completed: exitCode=${e.data.exitCode??0}`;if(e.type==="error")return e.data.text||"ACode runtime error"}const Vt=/\x1b\[[0-9;?]*[a-zA-Z]/g;function Yt(e){return e.replace(Vt,"")}function Zt(e){const n=typeof e.data.stream=="string"?e.data.stream:"mixed",t=typeof e.data.sequence=="number"?` #${e.data.sequence}`:"",r=Yt(String(e.data.text||"")).replace(/\s+/g," ").trim(),s=r.length>240?`${r.slice(0,240)}...`:r;return`\u547D\u4EE4\u8F93\u51FA(${n}${t}): ${s||"(empty)"}`}function Ne(e,n){const t=ye(e.data.toolName,e.data.toolInput),r=e.data.actionLabel||t.actionLabel||"\u8C03\u7528\u5DE5\u5177",s=qe(e,t);return s?`${n}${r}: ${s}`:`${n}${r}: ${e.data.actionDetail||e.data.toolName||"tool"}`}function qe(e,n){const t=e.data.toolInput;return n.actionType==="bash"?en(t)||e.data.actionDetail||n.actionDetail:n.actionType==="read_file"||n.actionType==="edit_file"||n.actionType==="write_file"?tn(t)||e.data.actionDetail||n.actionDetail:e.data.actionDetail||n.actionDetail}function en(e){const n=Ae(e?.command,e?.cmd);if(n)return n;if(Array.isArray(e?.argv)){const t=e.argv.map(r=>String(r??"").trim()).filter(Boolean).join(" ");return t?q(t):void 0}return Ae(e?.args)}function tn(e){const n=ve(e?.paths);return n.length>0?n.length===1?n[0]:`${n.length}\u4E2A\u6587\u4EF6: ${n.join(", ")}`:Ae(e?.file_path,e?.filePath,e?.path,e?.target_file,e?.targetFile)}function Ae(...e){for(const n of e){if(typeof n=="string"&&n.trim())return q(n.trim());if(Array.isArray(n)){const t=ve(n)[0];if(t)return t}}}function ve(e){return Array.isArray(e)?e.map(n=>typeof n=="string"?n.trim():"").filter(Boolean).map(n=>q(n)):[]}function nn(e){if(!(!e||Object.keys(e).length===0))try{const n=q(JSON.stringify(e,null,2));return n.length>8e3?`${n.slice(0,8e3)}
49
- ...\uFF08\u8F93\u5165\u53C2\u6570\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`:n}catch{return}}function rn(e){const n=[e.model?`\u6A21\u578B: ${e.model}`:void 0,e.endpoint||e.requestUrl?`\u63A5\u53E3: ${e.endpoint||e.requestUrl}`:void 0,e.requestMethod?`\u65B9\u6CD5: ${e.requestMethod}`:void 0,typeof e.stream=="boolean"?`\u6D41\u5F0F: ${e.stream?"\u662F":"\u5426"}`:void 0,typeof e.messageCount=="number"?`\u4E0A\u4E0B\u6587\u6D88\u606F: ${e.messageCount}`:void 0,typeof e.toolCount=="number"?`\u53EF\u7528\u5DE5\u5177: ${e.toolCount}`:void 0,e.lastUserMessagePreview?`\u6700\u540E\u8BF7\u6C42: ${e.lastUserMessagePreview}`:void 0].filter(i=>!!i),t=on(e.requestHeaders),r=n.join(`
50
- `)||"ACode \u6B63\u5728\u53D1\u9001 AI \u8BF7\u6C42",s=t.length>0?`${It}${t.join(`
51
- `)}`:"",o=e.requestBody?`${ht}${e.requestBody}`:"";return`${r}${s}${o}`}function on(e){return e?Object.entries(e).map(([n,t])=>`${n}: ${t}`).filter(n=>n.trim().length>0):[]}function sn(e,n){return String(n||"").trim().toLowerCase()!=="waiting_input"?!1:e.type==="thinking"||e.type==="text_delta"}function an(e){for(const n of["estimatedContextTokens","contextTokens","context_tokens","contextUsedTokens","context_used_tokens"]){const t=e[n],r=Number(t);if(Number.isFinite(r)&&r>0)return r}}function cn(e,n){if(!sn(e,n)){if(e.type==="ai_request"){const t=an(e.data);return{status:"thinking",actionInfo:{actionType:"ai_request",actionLabel:"AI\u8BF7\u6C42",actionDetail:rn(e.data),...t!==void 0?{usage:{inputTokens:t,outputTokens:0}}:{}}}}if(e.type==="background_command_completed")return{status:"tool_result",actionInfo:{actionType:"background_command",actionLabel:"\u540E\u53F0\u547D\u4EE4",actionDetail:"background_command_completed"}};if(e.type==="thinking"||e.type==="text_delta")return{status:"thinking"};if(e.type==="tool_use_start"){const t=ye(e.data.toolName,e.data.toolInput),r=qe(e,t),s=nn(e.data.toolInput);return e.data.actionType==="idle"||t.actionType==="idle"?{status:"waiting_input",actionInfo:{actionType:e.data.actionType||t.actionType,actionLabel:e.data.actionLabel||t.actionLabel,actionDetail:r||e.data.actionDetail||t.actionDetail||e.data.toolName,actionInput:s,actionId:e.data.actionId||e.data.toolUseId}}:{status:"tool_using",actionInfo:{actionType:e.data.actionType||t.actionType,actionLabel:e.data.actionLabel||t.actionLabel,actionDetail:r||e.data.actionDetail||t.actionDetail||e.data.toolName,actionInput:s,actionId:e.data.actionId||e.data.toolUseId}}}if(e.type==="turn_complete")return{status:"waiting_input",actionInfo:e.data.usage?{usage:e.data.usage}:void 0};if(e.type==="error")return{status:"error"};if(e.type==="context_compaction")return{status:"compacting",actionInfo:{actionType:"context_compaction",actionLabel:e.data.actionLabel,actionDetail:e.data.actionDetail,...e.data.actionId?{actionId:e.data.actionId}:{},...e.data.parentId?{parentId:e.data.parentId}:{}}};if(e.type==="runtime_capabilities")return{status:n||"waiting_input",actionInfo:{actionType:"runtime_capabilities",actionLabel:e.data.actionLabel||"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:e.data.actionDetail}}}}const L=new Map,ae=new Map,ce=new Map,J=new Map,un=20,dn=500,ln=3e4;async function ue(e,n=ln,t=2){for(let r=0;r<=t;r++){const s=new AbortController;let o;try{const i=e(s.signal);i.catch(()=>{}),await Promise.race([i,new Promise((a,c)=>{o=setTimeout(()=>{s.abort(),c(new Error(`sendOutput timeout after ${n}ms`))},n)})]),o&&clearTimeout(o);return}catch(i){o&&clearTimeout(o);const a=i instanceof Error?i.message:String(i);if(r<t){const c=1e3*(r+1);h.warn(`sendOutput attempt ${r+1}/${t+1} failed (${a}), retrying in ${c}ms...`),await new Promise(d=>setTimeout(d,c));continue}h.warn(`sendOutput failed after ${t+1} attempts (${a}), giving up to unblock serial queue`)}}}function de(e,n){const t=n?`${e}:${n}`:void 0;let r,s;if(t)r=J.get(t),s=t;else{const p=[];for(const[T,y]of J)T.startsWith(e+":")&&y.buffer&&p.push(y.sourceEventType);for(const T of p)de(e,T);return}if(!r||!r.buffer)return;r.timer=null;const o=r.buffer,i=r.seq,a=r.entry,c=r.sourceEventType;r.buffer="",s&&J.delete(s);const d={sourceEventType:c,logCategory:"acode"},u={runtimeAccessToken:a.runtimeAccessToken,schedulerBaseUrl:a.schedulerBaseUrl},m=(L.get(e)??Promise.resolve()).then(()=>ue(p=>Q(a.agentId,o,e,i,d,u,p)),()=>ue(p=>Q(a.agentId,o,e,i,d,u,p)));L.set(e,m),m.finally(()=>{L.get(e)===m&&L.delete(e)})}function mn(e,n){const t=Ht(e);if(!t)return;n.seq+=1;const r=n.seq,s=Qt(e),o={runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl};if((e.type==="command_output"||e.type==="text_delta"||e.type==="thinking")&&t.length<un){const c=`${e.sessionId}:${e.type}`;let d=J.get(c);if(d||(d={buffer:"",seq:0,timer:null,entry:n,sourceEventType:e.type}),d.buffer+=t,d.seq=r,d.entry=n,!d.timer){const u=e.sessionId,l=e.type;d.timer=setTimeout(()=>de(u,l),dn)}J.set(c,d);return}de(e.sessionId);const a=(L.get(e.sessionId)??Promise.resolve()).then(()=>ue(c=>Q(n.agentId,t,e.sessionId,r,s,o,c)),()=>ue(c=>Q(n.agentId,t,e.sessionId,r,s,o,c)));L.set(e.sessionId,a),a.finally(()=>{L.get(e.sessionId)===a&&L.delete(e.sessionId)})}function Fe(e){return Je(e)}let Ke=!1;function fn(){Ke||(Ge(w,pn),it(),Ke=!0)}function pn(e,n){e.on("event",t=>{const r=f.get(t.sessionId);if(r){if(t.type==="tool_use_start"?ct(r.sessionId,t.data.toolUseId||t.data.actionId,t.data.toolInput,t.data.toolName,r.workspacePath):t.type==="tool_use_end"&&at(t,{sessionId:r.sessionId,agentId:r.agentId,workspacePath:r.workspacePath,providerId:r.providerId}),console.log(`[${n.displayName} Adapter] Event: ${t.type} for session ${t.sessionId}`),!(t.type==="thinking"||t.type==="text_delta"||t.type==="tool_use_start"||t.type==="context_compaction"||t.type==="ai_request")){t.type==="runtime_capabilities"&&t.data.actionDetail&&(r.cachedCapabilitiesActionDetail=t.data.actionDetail);const i=cn(t,r.currentRuntimeStatus);i&&_(r.agentId,t.sessionId,i.status,i.actionInfo,re(i.actionInfo),{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},t.timestamp?new Date(t.timestamp).getTime():void 0,t.type)}mn(t,r);const o=Wt(t);if(o){const i={runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},a=t.timestamp?new Date(t.timestamp).getTime():void 0;String(t.data?.toolName||"").toLowerCase()==="browser_launch"?(async()=>{for(let u=0;u<3;u++){if(await _(r.agentId,t.sessionId,"tool_result",o,void 0,i,a,t.type)!==void 0)return;u<2&&await new Promise(m=>setTimeout(m,3e3*(u+1)))}})().catch(d=>console.warn("[Runtime] browser_launch sendStatus retry exhausted:",d)):_(r.agentId,t.sessionId,"tool_result",o,void 0,i,a,t.type)}}}),e.on("status-change",(t,r,s)=>{const o=f.get(t);if(o){de(t),r==="thinking"||r==="tool_using"||r==="compacting"?yt(t):E(t);const i=wt(r,s);o.currentRuntimeStatus=i.status;const a=o.currentRuntimeActionDetail??"",c=a.includes("poll_message")||a.includes("get_message"),u=!(i.actionInfo?.actionType==="ai_request")&&(i.status==="thinking"||i.status==="waiting_input")&&(o.currentRuntimeActionType==="idle"||o.currentRuntimeActionType==="mcp")&&c;(i.actionInfo?.actionType||!u)&&(o.currentRuntimeActionType=i.actionInfo?.actionType,o.currentRuntimeActionLabel=i.actionInfo?.actionLabel,o.currentRuntimeActionDetail=i.actionInfo?.actionDetail,o.currentRuntimeActionInput=i.actionInfo?.actionInput),console.log(`[${n.displayName} Adapter] Status changed: ${i.status} for agent ${o.agentId}`,i.actionInfo||""),mt(t,{runtimeStatus:i.status,runtimeActionType:o.currentRuntimeActionType,runtimeActionLabel:o.currentRuntimeActionLabel,runtimeActionDetail:o.currentRuntimeActionDetail});const l=i.actionInfo?.actionType?i.actionInfo:o.currentRuntimeActionType?{actionType:o.currentRuntimeActionType,actionLabel:o.currentRuntimeActionLabel??"",actionDetail:o.currentRuntimeActionDetail,actionInput:o.currentRuntimeActionInput}:void 0;if(i.status==="compacting"){const p=(ae.get(t)??Promise.resolve()).then(async()=>{for(let y=0;y<=2;y++){if(await _(o.agentId,t,i.status,l,re(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})!==void 0)return;y<2&&(h.warn(`[${n.displayName}] compaction sendStatus attempt ${y+1} failed (HTTP), retrying in ${1e3*(y+1)}ms...`),await new Promise(C=>setTimeout(C,1e3*(y+1))))}h.warn(`[${n.displayName}] compaction sendStatus failed after 3 attempts, event may be lost`)}).catch(T=>{h.warn(`[${n.displayName}] compaction status chain error:`,T)});ae.set(t,p),p.finally(()=>{ae.get(t)===p&&ae.delete(t)})}else{const m=u&&!i.actionInfo?.actionType;if(l?.actionType==="idle"||o.currentRuntimeActionType==="idle"&&u){const y=(ce.get(t)??Promise.resolve()).then(async()=>{for(let C=0;C<=2;C++){if(await _(o.agentId,t,i.status,m?void 0:l,re(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})!==void 0)return;C<2&&await new Promise(x=>setTimeout(x,1e3*(C+1)))}h.warn(`[${n.displayName}] idle tool sendStatus failed after 3 attempts, status may be stale (frontend will fall back to timeline tool_use event)`)}).catch(g=>{h.warn(`[${n.displayName}] idle status chain error:`,g)});ce.set(t,y),y.finally(()=>{ce.get(t)===y&&ce.delete(t)})}else _(o.agentId,t,i.status,m?void 0:l,re(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}if(i.status==="waiting_input"&&o.cachedCapabilitiesActionDetail){const m=o.cachedCapabilitiesActionDetail;o.cachedCapabilitiesActionDetail=void 0,console.log(`[${n.displayName} Adapter] Re-sending cached runtime_capabilities for agent ${o.agentId} (session stabilized to waiting_input)`),_(o.agentId,t,"waiting_input",{actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:m},void 0,{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}}}),e.on("ask-user-question",t=>{const r=f.get(t.sessionId);r&&(console.log(`[${n.displayName} Adapter] AskUserQuestion for agent ${r.agentId}`),ot(r.agentId,t.sessionId,Array.isArray(t.questions)?t.questions:[],{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},t.toolCallId))}),e.on("permission-request",t=>{const r=f.get(t.sessionId);if(r){console.log(`[${n.displayName} Adapter] Permission request: ${t.toolName} for agent ${r.agentId}`);const s=t.toolInput?q(JSON.stringify(t.toolInput).slice(0,400)):void 0;_(r.agentId,t.sessionId,"waiting_input",{actionType:"other",actionLabel:"\u6743\u9650\u786E\u8BA4",actionDetail:s||t.toolName},void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl})}})}A.post("/start",S,async(e,n)=>{const{agentId:t,workspacePath:r,mode:s="sdk"}=e.body||{};if(!t||!r){n.status(400).json({error:"agentId and workspacePath are required"});return}const o=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||_e(Pe(e))||void 0;tt({agentId:String(t),workspacePath:String(r),serverUrl:e.body?.serverUrl||o,runtimeAccessToken:e.body?.runtimeAccessToken,userId:e.body?.userId,schedulerBaseUrl:o}),e.body?.runtimeFeatures!=null&&(Ve(String(t),e.body.runtimeFeatures),console.log(`[Runtime] agent ${t} \u542F\u52A8\u4E0B\u53D1\u80FD\u529B\u5F00\u5173: ${JSON.stringify(Ye(String(t)))}`)),s&&s!=="sdk"&&console.warn(`[Runtime] Unsupported runtime mode "${s}" requested for agent ${t}; starting SDK session instead.`),await gn(e,n)});async function gn(e,n){const{agentId:t,workspacePath:r,command:s,autoAccept:o=!0,initialPrompt:i,systemPrompt:a,globalPrompt:c,rolePrompt:d,memory:u,mcpConfigPath:l,extraMcpServers:m,envOverrides:p,idleInputAutoCommand:T,nonInputAutoCommand:y,model:g,instanceAiConfig:C,subAgentModel:$,subAgentEffort:x,scopeKey:Te,browserAllowPrivate:ke}=e.body||{},z=pt();z.log({level:"info",category:"launch",message:"startSdkSession: \u6536\u5230\u542F\u52A8\u8BF7\u6C42",source:"bridge",agentId:String(t||"").trim()||void 0,details:{reqBodyKeys:Object.keys(e.body||{}),perInstanceAiConfig:C?te(C):null,perAgentModel:g??null}});let D=null;const I=String(t||"").trim(),le=String(e.body?.runtimeAccessToken||"").trim()||void 0,B=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||_e(Pe(e))||void 0;B?h.info(`[startSdkSession] \u56DE\u8C03\u76EE\u6807 server: ${B} (agentId=${I})`):h.warn(`[startSdkSession] \u672A\u89E3\u6790\u5230 schedulerBaseUrl\uFF0C\u5C06\u56DE\u9000\u5230\u9ED8\u8BA4\u5730\u5740 (agentId=${I})`);try{if(fn(),!I){n.status(400).json({error:"agentId is required"});return}const O=je(I);if(O){n.json(await Lt(O));return}const k=await ut(I);if(k){const P=Ut(k);if(!P.reusable)console.warn(`[Runtime] Ignoring stale persisted SDK session for agentId=${I}, sessionId=${k.sessionId}, reason=${P.reason}`),await F(k.sessionId);else{const R=se(k.runtimeStatus,k.runtimeStatus,k.runtimeActionType);n.json({sessionId:k.sessionId,status:R,runtimeStatus:R,runtimeActionType:k.runtimeActionType,runtimeActionLabel:k.runtimeActionLabel,runtimeActionDetail:k.runtimeActionDetail,agentId:k.agentId,workspacePath:k.workspacePath,command:k.command,mode:k.mode||"sdk",pid:k.pid,reused:!0,persistedOnly:!0});return}}if(K.has(I)){n.status(409).json({error:"SDK session is already starting for this agent"});return}K.add(I);const Sn=(s||"acode").toLowerCase(),M=Fe(s),ze=w.get(M);D=Xe();const We=M==="claude-code"?await vt():null,V=Oe(M==="claude-code"?We:null,p),W=M==="acode"?g?String(g).trim():void 0:(()=>{const P=g?String(g).trim():void 0,R=V.model?String(V.model).trim():void 0;return P||R})();z.log({level:"info",category:"resolve",message:"\u6A21\u578B\u89E3\u6790\u7ED3\u679C",source:"bridge",agentId:I,sessionId:D??void 0,details:{perAgentModel:g??null,globalModel:V.model??null,resolvedModel:W??null,providerId:M,note:M==="acode"?"adapter handles full priority":"request > global"}});const me={...V.envOverrides};W&&(me.ANTHROPIC_MODEL=W,me.CODEX_MODEL=W);let H,fe=l;if(M==="acode"){const P=C||{},R=await et({apiOverrides:Ie(P)??void 0,agentId:I,sessionId:D??void 0,runtimeBridgeBaseUrl:B});H=R.instanceConfig.config,fe=R.perInstanceConfigPath,z.log({level:"info",category:"apply",message:"prepareAcodeInstanceConfig \u5B8C\u6210",source:"bridge",agentId:I,sessionId:D??void 0,details:{sanitizedApiOverrides:Ie(P)?te(Ie(P)):null,resolvedInstanceAiConfig:H?te(H):null,perInstanceConfigPath:fe,instanceConfigSources:R.instanceConfig.source??null}})}let we=a||void 0,pe,ge,Y;if(M==="acode")if(pe=typeof c=="string"&&c.trim()||void 0,ge=typeof d=="string"&&d.trim()||void 0,typeof u=="string"&&u.trim())Y=u.trim();else{const P=await St(r,{schedulerBaseUrl:B,runtimeAccessToken:le,agentId:I});P&&(Y=P,h.info(`[startSdkSession] Auto-loaded memories for ACode agent ${I}`))}else if(typeof c=="string"&&c.trim()||typeof d=="string"&&d.trim()||typeof u=="string"&&u.trim()){const R=[c,d,u,a].filter(Z=>typeof Z=="string"&&Z.trim().length>0).map(Z=>Z.trim());we=R.length>0?R.join(`
48
+ `:void 0}function Qt(e){const t=Jt(e);return{sourceEventType:e.type,logCategory:"acode",...Gt(e),...t?{logLevel:Xt(e),logMessage:t}:{}}}function Xt(e){return e.type==="error"?"error":e.type==="command_output"&&e.data.stream==="stderr"?"warn":"info"}function Gt(e){return e.type!=="command_output"?{}:{...typeof e.data.stream=="string"?{stream:e.data.stream}:{},...typeof e.data.sequence=="number"?{sequence:e.data.sequence}:{},...typeof e.data.cwd=="string"?{cwd:e.data.cwd}:{},...typeof e.data.commandFilePath=="string"?{commandFilePath:e.data.commandFilePath}:{},...typeof e.data.commandLineCount=="number"?{commandLineCount:e.data.commandLineCount}:{}}}function Jt(e){if(e.type==="ai_request"){const t=e.data.model||"unknown-model",n=e.data.endpoint?` @ ${e.data.endpoint}`:"",r=typeof e.data.toolCount=="number"?`, tools=${e.data.toolCount}`:"";return`AI request started: ${t}${n}${r}`}if(e.type==="tool_use_start")return Ne(e,"\u5F00\u59CB");if(e.type==="tool_use_end")return Ne(e,"\u5B8C\u6210");if(e.type==="command_output")return Zt(e);if(e.type==="turn_complete")return`Turn completed${e.data.finishReason?`, finish=${e.data.finishReason}`:""}`;if(e.type==="session_complete")return`Session completed: exitCode=${e.data.exitCode??0}`;if(e.type==="error")return e.data.text||"ACode runtime error"}const Vt=/\x1b\[[0-9;?]*[a-zA-Z]/g;function Yt(e){return e.replace(Vt,"")}function Zt(e){const t=typeof e.data.stream=="string"?e.data.stream:"mixed",n=typeof e.data.sequence=="number"?` #${e.data.sequence}`:"",r=Yt(String(e.data.text||"")).replace(/\s+/g," ").trim(),o=r.length>240?`${r.slice(0,240)}...`:r;return`\u547D\u4EE4\u8F93\u51FA(${t}${n}): ${o||"(empty)"}`}function Ne(e,t){const n=ye(e.data.toolName,e.data.toolInput),r=e.data.actionLabel||n.actionLabel||"\u8C03\u7528\u5DE5\u5177",o=qe(e,n);return o?`${t}${r}: ${o}`:`${t}${r}: ${e.data.actionDetail||e.data.toolName||"tool"}`}function qe(e,t){const n=e.data.toolInput;return t.actionType==="bash"?en(n)||e.data.actionDetail||t.actionDetail:t.actionType==="read_file"||t.actionType==="edit_file"||t.actionType==="write_file"?tn(n)||e.data.actionDetail||t.actionDetail:e.data.actionDetail||t.actionDetail}function en(e){const t=Ae(e?.command,e?.cmd);if(t)return t;if(Array.isArray(e?.argv)){const n=e.argv.map(r=>String(r??"").trim()).filter(Boolean).join(" ");return n?q(n):void 0}return Ae(e?.args)}function tn(e){const t=ve(e?.paths);return t.length>0?t.length===1?t[0]:`${t.length}\u4E2A\u6587\u4EF6: ${t.join(", ")}`:Ae(e?.file_path,e?.filePath,e?.path,e?.target_file,e?.targetFile)}function Ae(...e){for(const t of e){if(typeof t=="string"&&t.trim())return q(t.trim());if(Array.isArray(t)){const n=ve(t)[0];if(n)return n}}}function ve(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean).map(t=>q(t)):[]}function nn(e){if(!(!e||Object.keys(e).length===0))try{const t=q(JSON.stringify(e,null,2));return t.length>8e3?`${t.slice(0,8e3)}
49
+ ...\uFF08\u8F93\u5165\u53C2\u6570\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`:t}catch{return}}function rn(e){const t=[e.model?`\u6A21\u578B: ${e.model}`:void 0,e.endpoint||e.requestUrl?`\u63A5\u53E3: ${e.endpoint||e.requestUrl}`:void 0,e.requestMethod?`\u65B9\u6CD5: ${e.requestMethod}`:void 0,typeof e.stream=="boolean"?`\u6D41\u5F0F: ${e.stream?"\u662F":"\u5426"}`:void 0,typeof e.messageCount=="number"?`\u4E0A\u4E0B\u6587\u6D88\u606F: ${e.messageCount}`:void 0,typeof e.toolCount=="number"?`\u53EF\u7528\u5DE5\u5177: ${e.toolCount}`:void 0,e.lastUserMessagePreview?`\u6700\u540E\u8BF7\u6C42: ${e.lastUserMessagePreview}`:void 0].filter(i=>!!i),n=on(e.requestHeaders),r=t.join(`
50
+ `)||"ACode \u6B63\u5728\u53D1\u9001 AI \u8BF7\u6C42",o=n.length>0?`${It}${n.join(`
51
+ `)}`:"",s=e.requestBody?`${ht}${e.requestBody}`:"";return`${r}${o}${s}`}function on(e){return e?Object.entries(e).map(([t,n])=>`${t}: ${n}`).filter(t=>t.trim().length>0):[]}function sn(e,t){return String(t||"").trim().toLowerCase()!=="waiting_input"?!1:e.type==="thinking"||e.type==="text_delta"}function an(e){for(const t of["estimatedContextTokens","contextTokens","context_tokens","contextUsedTokens","context_used_tokens"]){const n=e[t],r=Number(n);if(Number.isFinite(r)&&r>0)return r}}function cn(e,t){if(!sn(e,t)){if(e.type==="ai_request"){const n=an(e.data);return{status:"thinking",actionInfo:{actionType:"ai_request",actionLabel:"AI\u8BF7\u6C42",actionDetail:rn(e.data),...n!==void 0?{usage:{inputTokens:n,outputTokens:0}}:{}}}}if(e.type==="background_command_completed")return{status:"tool_result",actionInfo:{actionType:"background_command",actionLabel:"\u540E\u53F0\u547D\u4EE4",actionDetail:"background_command_completed"}};if(e.type==="thinking"||e.type==="text_delta")return{status:"thinking"};if(e.type==="tool_use_start"){const n=ye(e.data.toolName,e.data.toolInput),r=qe(e,n),o=nn(e.data.toolInput);return e.data.actionType==="idle"||n.actionType==="idle"?{status:"waiting_input",actionInfo:{actionType:e.data.actionType||n.actionType,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:r||e.data.actionDetail||n.actionDetail||e.data.toolName,actionInput:o,actionId:e.data.actionId||e.data.toolUseId}}:{status:"tool_using",actionInfo:{actionType:e.data.actionType||n.actionType,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:r||e.data.actionDetail||n.actionDetail||e.data.toolName,actionInput:o,actionId:e.data.actionId||e.data.toolUseId}}}if(e.type==="turn_complete")return{status:"waiting_input",actionInfo:e.data.usage?{usage:e.data.usage}:void 0};if(e.type==="error")return{status:"error"};if(e.type==="context_compaction")return{status:"compacting",actionInfo:{actionType:"context_compaction",actionLabel:e.data.actionLabel,actionDetail:e.data.actionDetail,...e.data.actionId?{actionId:e.data.actionId}:{},...e.data.parentId?{parentId:e.data.parentId}:{}}};if(e.type==="runtime_capabilities")return{status:t||"waiting_input",actionInfo:{actionType:"runtime_capabilities",actionLabel:e.data.actionLabel||"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:e.data.actionDetail}}}}const L=new Map,ae=new Map,ce=new Map,J=new Map,un=20,dn=500,ln=3e4;async function ue(e,t=ln,n=2){for(let r=0;r<=n;r++){const o=new AbortController;let s;try{const i=e(o.signal);i.catch(()=>{}),await Promise.race([i,new Promise((a,c)=>{s=setTimeout(()=>{o.abort(),c(new Error(`sendOutput timeout after ${t}ms`))},t)})]),s&&clearTimeout(s);return}catch(i){s&&clearTimeout(s);const a=i instanceof Error?i.message:String(i);if(r<n){const c=1e3*(r+1);h.warn(`sendOutput attempt ${r+1}/${n+1} failed (${a}), retrying in ${c}ms...`),await new Promise(d=>setTimeout(d,c));continue}h.warn(`sendOutput failed after ${n+1} attempts (${a}), giving up to unblock serial queue`)}}}function de(e,t){const n=t?`${e}:${t}`:void 0;let r,o;if(n)r=J.get(n),o=n;else{const p=[];for(const[T,y]of J)T.startsWith(e+":")&&y.buffer&&p.push(y.sourceEventType);for(const T of p)de(e,T);return}if(!r||!r.buffer)return;r.timer=null;const s=r.buffer,i=r.seq,a=r.entry,c=r.sourceEventType;r.buffer="",o&&J.delete(o);const d={sourceEventType:c,logCategory:"acode"},u={runtimeAccessToken:a.runtimeAccessToken,schedulerBaseUrl:a.schedulerBaseUrl},m=(L.get(e)??Promise.resolve()).then(()=>ue(p=>Q(a.agentId,s,e,i,d,u,p)),()=>ue(p=>Q(a.agentId,s,e,i,d,u,p)));L.set(e,m),m.finally(()=>{L.get(e)===m&&L.delete(e)})}function mn(e,t){const n=Wt(e);if(!n)return;t.seq+=1;const r=t.seq,o=Qt(e),s={runtimeAccessToken:t.runtimeAccessToken,schedulerBaseUrl:t.schedulerBaseUrl};if((e.type==="command_output"||e.type==="text_delta"||e.type==="thinking")&&n.length<un){const c=`${e.sessionId}:${e.type}`;let d=J.get(c);if(d||(d={buffer:"",seq:0,timer:null,entry:t,sourceEventType:e.type}),d.buffer+=n,d.seq=r,d.entry=t,!d.timer){const u=e.sessionId,l=e.type;d.timer=setTimeout(()=>de(u,l),dn)}J.set(c,d);return}de(e.sessionId);const a=(L.get(e.sessionId)??Promise.resolve()).then(()=>ue(c=>Q(t.agentId,n,e.sessionId,r,o,s,c)),()=>ue(c=>Q(t.agentId,n,e.sessionId,r,o,s,c)));L.set(e.sessionId,a),a.finally(()=>{L.get(e.sessionId)===a&&L.delete(e.sessionId)})}function Fe(e){return Je(e)}let Ke=!1;function fn(){Ke||(Ge(w,pn),it(),Ke=!0)}function pn(e,t){e.on("event",n=>{const r=f.get(n.sessionId);if(r){if(n.type==="tool_use_start"?ct(r.sessionId,n.data.toolUseId||n.data.actionId,n.data.toolInput,n.data.toolName,r.workspacePath):n.type==="tool_use_end"&&at(n,{sessionId:r.sessionId,agentId:r.agentId,workspacePath:r.workspacePath,providerId:r.providerId}),console.log(`[${t.displayName} Adapter] Event: ${n.type} for session ${n.sessionId}`),!(n.type==="thinking"||n.type==="text_delta"||n.type==="tool_use_start"||n.type==="context_compaction"||n.type==="ai_request")){n.type==="runtime_capabilities"&&n.data.actionDetail&&(r.cachedCapabilitiesActionDetail=n.data.actionDetail);const i=cn(n,r.currentRuntimeStatus);i&&_(r.agentId,n.sessionId,i.status,i.actionInfo,re(i.actionInfo),{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},n.timestamp?new Date(n.timestamp).getTime():void 0,n.type)}mn(n,r);const s=Ht(n);if(s){const i={runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},a=n.timestamp?new Date(n.timestamp).getTime():void 0;String(n.data?.toolName||"").toLowerCase()==="browser_launch"?(async()=>{for(let u=0;u<3;u++){if(await _(r.agentId,n.sessionId,"tool_result",s,void 0,i,a,n.type)!==void 0)return;u<2&&await new Promise(m=>setTimeout(m,3e3*(u+1)))}})().catch(d=>console.warn("[Runtime] browser_launch sendStatus retry exhausted:",d)):_(r.agentId,n.sessionId,"tool_result",s,void 0,i,a,n.type)}}}),e.on("status-change",(n,r,o)=>{const s=f.get(n);if(s){de(n),r==="thinking"||r==="tool_using"||r==="compacting"?yt(n):x(n);const i=wt(r,o);s.currentRuntimeStatus=i.status;const a=s.currentRuntimeActionDetail??"",c=a.includes("poll_message")||a.includes("get_message"),u=!(i.actionInfo?.actionType==="ai_request")&&(i.status==="thinking"||i.status==="waiting_input")&&(s.currentRuntimeActionType==="idle"||s.currentRuntimeActionType==="mcp")&&c;(i.actionInfo?.actionType||!u)&&(s.currentRuntimeActionType=i.actionInfo?.actionType,s.currentRuntimeActionLabel=i.actionInfo?.actionLabel,s.currentRuntimeActionDetail=i.actionInfo?.actionDetail,s.currentRuntimeActionInput=i.actionInfo?.actionInput),console.log(`[${t.displayName} Adapter] Status changed: ${i.status} for agent ${s.agentId}`,i.actionInfo||""),mt(n,{runtimeStatus:i.status,runtimeActionType:s.currentRuntimeActionType,runtimeActionLabel:s.currentRuntimeActionLabel,runtimeActionDetail:s.currentRuntimeActionDetail});const l=i.actionInfo?.actionType?i.actionInfo:s.currentRuntimeActionType?{actionType:s.currentRuntimeActionType,actionLabel:s.currentRuntimeActionLabel??"",actionDetail:s.currentRuntimeActionDetail,actionInput:s.currentRuntimeActionInput}:void 0;if(i.status==="compacting"){const p=(ae.get(n)??Promise.resolve()).then(async()=>{for(let y=0;y<=2;y++){if(await _(s.agentId,n,i.status,l,re(i.actionInfo),{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl})!==void 0)return;y<2&&(h.warn(`[${t.displayName}] compaction sendStatus attempt ${y+1} failed (HTTP), retrying in ${1e3*(y+1)}ms...`),await new Promise(C=>setTimeout(C,1e3*(y+1))))}h.warn(`[${t.displayName}] compaction sendStatus failed after 3 attempts, event may be lost`)}).catch(T=>{h.warn(`[${t.displayName}] compaction status chain error:`,T)});ae.set(n,p),p.finally(()=>{ae.get(n)===p&&ae.delete(n)})}else{const m=u&&!i.actionInfo?.actionType;if(l?.actionType==="idle"||s.currentRuntimeActionType==="idle"&&u){const y=(ce.get(n)??Promise.resolve()).then(async()=>{for(let C=0;C<=2;C++){if(await _(s.agentId,n,i.status,m?void 0:l,re(i.actionInfo),{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl})!==void 0)return;C<2&&await new Promise(E=>setTimeout(E,1e3*(C+1)))}h.warn(`[${t.displayName}] idle tool sendStatus failed after 3 attempts, status may be stale (frontend will fall back to timeline tool_use event)`)}).catch(g=>{h.warn(`[${t.displayName}] idle status chain error:`,g)});ce.set(n,y),y.finally(()=>{ce.get(n)===y&&ce.delete(n)})}else _(s.agentId,n,i.status,m?void 0:l,re(i.actionInfo),{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl})}if(i.status==="waiting_input"&&s.cachedCapabilitiesActionDetail){const m=s.cachedCapabilitiesActionDetail;s.cachedCapabilitiesActionDetail=void 0,console.log(`[${t.displayName} Adapter] Re-sending cached runtime_capabilities for agent ${s.agentId} (session stabilized to waiting_input)`),_(s.agentId,n,"waiting_input",{actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:m},void 0,{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl})}}}),e.on("ask-user-question",n=>{const r=f.get(n.sessionId);r&&(console.log(`[${t.displayName} Adapter] AskUserQuestion for agent ${r.agentId}`),ot(r.agentId,n.sessionId,Array.isArray(n.questions)?n.questions:[],{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},n.toolCallId))}),e.on("permission-request",n=>{const r=f.get(n.sessionId);if(r){console.log(`[${t.displayName} Adapter] Permission request: ${n.toolName} for agent ${r.agentId}`);const o=n.toolInput?q(JSON.stringify(n.toolInput).slice(0,400)):void 0;_(r.agentId,n.sessionId,"waiting_input",{actionType:"other",actionLabel:"\u6743\u9650\u786E\u8BA4",actionDetail:o||n.toolName},void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl})}})}A.post("/start",S,async(e,t)=>{const{agentId:n,workspacePath:r,mode:o="sdk"}=e.body||{};if(!n||!r){t.status(400).json({error:"agentId and workspacePath are required"});return}const s=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||_e(Pe(e))||void 0;tt({agentId:String(n),workspacePath:String(r),serverUrl:e.body?.serverUrl||s,runtimeAccessToken:e.body?.runtimeAccessToken,userId:e.body?.userId,schedulerBaseUrl:s}),e.body?.runtimeFeatures!=null&&(Ve(String(n),e.body.runtimeFeatures),console.log(`[Runtime] agent ${n} \u542F\u52A8\u4E0B\u53D1\u80FD\u529B\u5F00\u5173: ${JSON.stringify(Ye(String(n)))}`)),o&&o!=="sdk"&&console.warn(`[Runtime] Unsupported runtime mode "${o}" requested for agent ${n}; starting SDK session instead.`),await gn(e,t)});async function gn(e,t){const{agentId:n,workspacePath:r,command:o,autoAccept:s=!0,initialPrompt:i,systemPrompt:a,globalPrompt:c,rolePrompt:d,memory:u,mcpConfigPath:l,extraMcpServers:m,envOverrides:p,idleInputAutoCommand:T,nonInputAutoCommand:y,model:g,instanceAiConfig:C,subAgentModel:$,subAgentEffort:E,scopeKey:Te,browserAllowPrivate:ke}=e.body||{},z=pt();z.log({level:"info",category:"launch",message:"startSdkSession: \u6536\u5230\u542F\u52A8\u8BF7\u6C42",source:"bridge",agentId:String(n||"").trim()||void 0,details:{reqBodyKeys:Object.keys(e.body||{}),perInstanceAiConfig:C?te(C):null,perAgentModel:g??null}});let D=null;const I=String(n||"").trim(),le=String(e.body?.runtimeAccessToken||"").trim()||void 0,B=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||_e(Pe(e))||void 0;B?h.info(`[startSdkSession] \u56DE\u8C03\u76EE\u6807 server: ${B} (agentId=${I})`):h.warn(`[startSdkSession] \u672A\u89E3\u6790\u5230 schedulerBaseUrl\uFF0C\u5C06\u56DE\u9000\u5230\u9ED8\u8BA4\u5730\u5740 (agentId=${I})`);try{if(fn(),!I){t.status(400).json({error:"agentId is required"});return}const O=je(I);if(O){t.json(await Lt(O));return}const k=await ut(I);if(k){const P=Ut(k);if(!P.reusable)console.warn(`[Runtime] Ignoring stale persisted SDK session for agentId=${I}, sessionId=${k.sessionId}, reason=${P.reason}`),await F(k.sessionId);else{const R=se(k.runtimeStatus,k.runtimeStatus,k.runtimeActionType);t.json({sessionId:k.sessionId,status:R,runtimeStatus:R,runtimeActionType:k.runtimeActionType,runtimeActionLabel:k.runtimeActionLabel,runtimeActionDetail:k.runtimeActionDetail,agentId:k.agentId,workspacePath:k.workspacePath,command:k.command,mode:k.mode||"sdk",pid:k.pid,reused:!0,persistedOnly:!0});return}}if(K.has(I)){t.status(409).json({error:"SDK session is already starting for this agent"});return}K.add(I);const Sn=(o||"acode").toLowerCase(),M=Fe(o),ze=w.get(M);D=Xe();const He=M==="claude-code"?await vt():null,V=Oe(M==="claude-code"?He:null,p),H=M==="acode"?g?String(g).trim():void 0:(()=>{const P=g?String(g).trim():void 0,R=V.model?String(V.model).trim():void 0;return P||R})();z.log({level:"info",category:"resolve",message:"\u6A21\u578B\u89E3\u6790\u7ED3\u679C",source:"bridge",agentId:I,sessionId:D??void 0,details:{perAgentModel:g??null,globalModel:V.model??null,resolvedModel:H??null,providerId:M,note:M==="acode"?"adapter handles full priority":"request > global"}});const me={...V.envOverrides};H&&(me.ANTHROPIC_MODEL=H,me.CODEX_MODEL=H);let W,fe=l;if(M==="acode"){const P=C||{},R=await et({apiOverrides:Ie(P)??void 0,agentId:I,sessionId:D??void 0,runtimeBridgeBaseUrl:B});W=R.instanceConfig.config,fe=R.perInstanceConfigPath,z.log({level:"info",category:"apply",message:"prepareAcodeInstanceConfig \u5B8C\u6210",source:"bridge",agentId:I,sessionId:D??void 0,details:{sanitizedApiOverrides:Ie(P)?te(Ie(P)):null,resolvedInstanceAiConfig:W?te(W):null,perInstanceConfigPath:fe,instanceConfigSources:R.instanceConfig.source??null}})}let we=a||void 0,pe,ge,Y;if(M==="acode")if(pe=typeof c=="string"&&c.trim()||void 0,ge=typeof d=="string"&&d.trim()||void 0,typeof u=="string"&&u.trim())Y=u.trim();else{const P=await St(r,{schedulerBaseUrl:B,runtimeAccessToken:le,agentId:I});P&&(Y=P,h.info(`[startSdkSession] Auto-loaded memories for ACode agent ${I}`))}else if(typeof c=="string"&&c.trim()||typeof d=="string"&&d.trim()||typeof u=="string"&&u.trim()){const R=[c,d,u,a].filter(Z=>typeof Z=="string"&&Z.trim().length>0).map(Z=>Z.trim());we=R.length>0?R.join(`
52
52
 
53
- `):void 0}const U={command:s||"acode",workingDirectory:r,agentId:I,...Te?{scopeKey:Te}:{},...typeof ke=="boolean"?{browserAllowPrivate:ke}:{},autoAccept:!!o,initialPrompt:i,systemPrompt:we,...pe!==void 0?{globalPrompt:pe}:{},...ge!==void 0?{rolePrompt:ge}:{},...Y!==void 0?{memory:Y}:{},model:W,mcpConfigPath:fe,...H?{instanceAiConfig:H}:{},...typeof $=="string"&&$.trim()?{subAgentModel:$.trim()}:{},...typeof x=="string"&&x.trim()?{subAgentEffort:x.trim()}:{},extraMcpServers:m||{},envOverrides:Be(String(t),String(r),process.env,me)};z.log({level:"info",category:"launch",message:"\u4F20\u9012\u7ED9 Adapter \u7684\u5B8C\u6574 AdapterSessionConfig",source:"bridge",agentId:I,sessionId:D,details:{adapterModel:U.model??null,adapterInstanceAiConfig:U.instanceAiConfig?te(U.instanceAiConfig):null,adapterMcpConfigPath:U.mcpConfigPath??null}}),await z.flush(),f.set(D,{agentId:I,workspacePath:r,sessionId:D,config:U,providerId:M,seq:0,runtimeAccessToken:le,schedulerBaseUrl:B}),n.json({sessionId:D,status:"starting",runtimeStatus:"starting",agentId:I,workspacePath:r,command:U.command,mode:"sdk"}),yn({sessionId:D,agentId:I,config:U,adapter:ze,providerId:M,idleInputAutoCommand:T,nonInputAutoCommand:y,runtimeAccessToken:le,requestedSchedulerBaseUrl:B})}catch(O){if(D&&(E(D),f.delete(D),v(D)),I&&K.delete(I),!n.headersSent){const k=O instanceof Error?O.message:String(O);n.status(500).json({error:`Failed to start SDK session: ${k}`})}}}async function yn(e){const{sessionId:n,agentId:t,config:r,adapter:s,providerId:o,idleInputAutoCommand:i,nonInputAutoCommand:a,runtimeAccessToken:c,requestedSchedulerBaseUrl:d}=e;try{await s.startSession(n,r),(i||a)&&s.setIdleCommands?.(n,{idleInputCommand:i||"",nonInputCommand:a||""});let u;if(Tt(o))try{if(await new Promise(m=>setTimeout(m,500)),u=s.getSessionPid?.(n),!u){const p=(await nt()).find(T=>T.agentId===t||T.cwd===r.workingDirectory||T.command.includes(r.workingDirectory));p&&(u=p.pid,console.log(`[Runtime] Found SDK process PID: ${u} for agentId=${t}`))}}catch(m){console.warn(`[Runtime] Failed to get SDK PID for agentId=${t}:`,m)}const l=se(s.getSessionStatus(n),f.get(n)?.currentRuntimeStatus,f.get(n)?.currentRuntimeActionType);await ft({sessionId:n,agentId:t,workspacePath:r.workingDirectory,command:r.command,startedAt:new Date().toISOString(),status:"running",runtimeStatus:l,mode:"sdk",pid:u,providerSessionId:s.getProviderSessionId(n)}),u&&await he().startProcess({agentId:t,sessionId:n,pid:u,mode:"sdk",workspacePath:r.workingDirectory,command:r.command}),await hn({agentId:t,sessionId:n,sdkPid:u,status:l,schedulerBaseUrl:d,runtimeAccessToken:c})}catch(u){E(n),f.delete(n),v(n),await F(n);const l=u instanceof Error?u.message:String(u);console.error(`[Runtime] Background SDK session startup failed for agentId=${t}: ${l}`),await In({agentId:t,sessionId:n,schedulerBaseUrl:d,runtimeAccessToken:c,errorMessage:l})}finally{K.delete(t)}}async function hn(e){const{agentId:n,sessionId:t,sdkPid:r,status:s,schedulerBaseUrl:o,runtimeAccessToken:i}=e;if(!o||!i){h.debug(`[Runtime] notifyServerSessionReady skipped: missing schedulerBaseUrl or runtimeAccessToken for agentId=${n}`);return}const a=`${o.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await Ce.post(a,{agentId:n,sessionId:t,status:s,pid:r},{headers:{"X-Runtime-Token":i,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session ready: agentId=${n}, sessionId=${t}, status=${s}`)}catch(c){const d=c instanceof Error?c.message:String(c);h.warn(`[Runtime] Failed to notify server session ready: agentId=${n}, error=${d}`)}}async function In(e){const{agentId:n,sessionId:t,schedulerBaseUrl:r,runtimeAccessToken:s}=e;if(!r||!s)return;const o=`${r.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await Ce.post(o,{agentId:n,sessionId:t,status:"stopped"},{headers:{"X-Runtime-Token":s,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session failed: agentId=${n}, sessionId=${t}`)}catch(i){const a=i instanceof Error?i.message:String(i);h.warn(`[Runtime] Failed to notify server session failed: agentId=${n}, error=${a}`)}}A.post("/sdk/message",S,async(e,n)=>{const{sessionId:t,message:r}=e.body||{};if(!t||!r){n.status(400).json({error:"sessionId and message are required"});return}const s=f.get(t);if(!s){n.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code";await w.get(o).sendMessage(t,r),n.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);n.status(500).json({error:i})}}),A.post("/sdk/answer",S,async(e,n)=>{const{sessionId:t,answers:r}=e.body||{};if(!t||!r){n.status(400).json({error:"sessionId and answers are required"});return}const s=f.get(t);if(!s){n.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code",i=w.get(o);i.sendQuestionAnswer&&await i.sendQuestionAnswer(t,r),n.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);n.status(500).json({error:i})}}),A.post("/sdk/confirm",S,async(e,n)=>{const{sessionId:t,accept:r}=e.body||{};if(!t){n.status(400).json({error:"sessionId is required"});return}const s=f.get(t);if(!s){n.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code";await w.get(o).sendConfirmation(t,!!r),n.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);n.status(500).json({error:i})}}),A.post("/sdk/abort",S,async(e,n)=>{const{sessionId:t}=e.body||{};if(!t){n.status(400).json({error:"sessionId is required"});return}const r=f.get(t);if(!r){n.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code";await w.get(s).abortCurrentTurn(t),n.json({ok:!0})}catch(s){const o=s instanceof Error?s.message:String(s);n.status(500).json({error:o})}}),A.post("/sdk/stop",S,async(e,n)=>{const{sessionId:t}=e.body||{};if(!t){n.status(400).json({error:"sessionId is required"});return}const r=f.get(t);if(!r){n.json({ok:!0,status:"stopped"});return}try{const s=r.providerId||"claude-code",o=w.get(s);o.abortCurrentTurn(t).catch(()=>{}),await o.terminateSession(t),E(t),f.delete(t),v(t),ie(t),await F(t),await he().removeProcess(r.agentId),await _(r.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl}),n.json({ok:!0,status:"stopped"})}catch(s){const o=s instanceof Error?s.message:String(s);n.status(500).json({error:o})}}),A.get("/sdk/status/:sessionId",S,(e,n)=>{const t=e.params.sessionId;if(!t){n.status(400).json({error:"sessionId is required"});return}const r=f.get(t);if(!r){n.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",o=w.get(s),i=o.getSessionStatus(t),a=o.getConversation(t);n.json({sessionId:t,status:i,agentId:r.agentId,workspacePath:r.workspacePath,messageCount:a.length})}catch(s){const o=s instanceof Error?s.message:String(s);n.status(500).json({error:o})}}),A.get("/sdk/capabilities/:sessionId",S,(e,n)=>{const t=e.params.sessionId;if(!t){n.status(400).json({error:"sessionId is required"});return}const r=f.get(t);if(!r){n.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",i=w.get(s).getCapabilities?.(t)??null;n.json({ok:!0,sessionId:t,agentId:r.agentId,capabilities:i,fetchedAt:Date.now()})}catch(s){const o=s instanceof Error?s.message:String(s);n.status(500).json({error:o})}}),A.get("/sdk/pending-questions/:sessionId",S,(e,n)=>{const t=e.params.sessionId;if(!t){n.status(400).json({error:"sessionId is required"});return}const r=f.get(t);if(!r){n.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",i=w.get(s).getPendingQuestion?.(t)??null;n.json({ok:!0,sessionId:t,agentId:r.agentId,pendingQuestion:i?{toolCallId:i.toolCallId,questions:i.questions}:null,fetchedAt:Date.now()})}catch(s){const o=s instanceof Error?s.message:String(s);n.status(500).json({error:o})}}),A.post("/command",S,async(e,n)=>{const{sessionId:t,command:r}=e.body||{};if(!t||r===void 0||r===null){n.status(400).json({error:"sessionId and command are required"});return}try{const s=await Ot(String(t),r);n.json({ok:!0,mode:"terminal",...s})}catch(s){const o=s instanceof Error?s.message:String(s);n.status(500).json({error:o})}}),A.post("/input",S,async(e,n)=>{const{sessionId:t,input:r,mode:s}=e.body||{};if(!t||r===void 0||r===null){n.status(400).json({error:"sessionId and input are required"});return}const o=f.get(t);if(!o){n.status(404).json({error:"SDK session not found"});return}try{const i=o.providerId||"claude-code",a=w.get(i);if(s==="shortcut"){if(!a.sendShortcutInput){n.status(400).json({error:"shortcut input is not supported by this SDK provider"});return}await a.sendShortcutInput(t,String(r)),n.json({ok:!0,mode:"shortcut"});return}await a.sendMessage(t,await qt(r)),n.json({ok:!0,mode:"sdk"})}catch(i){const a=i instanceof Error?i.message:String(i);n.status(500).json({error:a})}}),A.post("/update-auto-commands",S,async(e,n)=>{const{agentId:t,idleInputAutoCommand:r="",nonInputAutoCommand:s=""}=e.body||{},o=String(t||"").trim();if(!o){n.status(400).json({error:"agentId is required"});return}const i=[...f.values()].find(c=>c.agentId===o),a={idleInputCommand:String(r||""),nonInputCommand:String(s||"")};try{let c=!1;i&&(w.get(i.providerId||"claude-code").setIdleCommands?.(i.sessionId,a),c=!0);const d=await lt(o,{idleInputAutoCommand:a.idleInputCommand,nonInputAutoCommand:a.nonInputCommand});n.json({ok:!0,mode:"sdk",sessionUpdated:c,persistedUpdated:d})}catch(c){const d=c instanceof Error?c.message:String(c);n.status(500).json({ok:!1,mode:"sdk",error:d})}}),A.post("/resize",S,(e,n)=>{const{sessionId:t,cols:r,rows:s}=e.body||{};if(!t||!r||!s){n.status(400).json({error:"sessionId, cols, rows are required"});return}if(!f.has(t)){n.status(404).json({error:"SDK session not found"});return}n.json({ok:!0,mode:"sdk",noop:!0,cols:Number(r),rows:Number(s)})}),A.post("/reset-context",S,async(e,n)=>{const{sessionId:t,reason:r}=e.body||{};if(!t){n.status(400).json({error:"sessionId is required"});return}const s=f.get(t);if(!s){n.status(404).json({error:"SDK session not found"});return}const o=s.providerId||"claude-code",i=w.get(o),a=i.resetContext?.bind(i),c=At(o,!!a);if(!c.supported){n.status(c.statusCode).json({error:c.error});return}if(!a){n.status(500).json({error:"ACode adapter does not expose resetContext"});return}try{await a(String(t));const d=se(i.getSessionStatus(String(t)),s.currentRuntimeStatus,s.currentRuntimeActionType);n.json({ok:!0,contextReset:!0,sessionId:t,status:d,runtimeStatus:d,agentId:s.agentId,mode:"sdk",providerId:o,reason:typeof r=="string"&&r.trim()?r.trim():void 0})}catch(d){const u=d instanceof Error?d.message:String(d);n.status(500).json({ok:!1,contextReset:!1,mode:"sdk",error:u})}}),A.post("/stop",S,async(e,n)=>{const{sessionId:t}=e.body||{},r=kt(e.body);if(!t){n.status(400).json({error:"sessionId is required"});return}const s=f.get(t);if(!s){await F(t),n.json({ok:!0,status:"stopped",mode:"none",statusNotified:!1,reason:r.reason});return}const o=s.agentId;try{console.log(`[Runtime] Stopping SDK session ${t}; suppressStatus=${!r.statusNotified}, reason=${r.reason||"unspecified"}`);const i=s.providerId||"claude-code",a=w.get(i);a.abortCurrentTurn(t).catch(()=>{}),await a.terminateSession(t),E(t),f.delete(t),v(t),ie(t),await F(t),await he().removeProcess(o),r.statusNotified?await _(o,null,"stopped",void 0,void 0,{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl}):console.log(`[Runtime] Stopped status notification suppressed for SDK session ${t}; reason=${r.reason||"unspecified"}`),n.json({ok:!0,status:"stopped",mode:"sdk",statusNotified:r.statusNotified,reason:r.reason})}catch(i){const a=i instanceof Error?i.message:String(i);console.error(`[Runtime] Failed to terminate SDK session ${t}:`,a),n.status(500).json({ok:!1,status:"stop_failed",mode:"sdk",error:a})}}),A.post("/stop-all",S,async(e,n)=>{const t=[],r=[];for(const[s,o]of f.entries())try{const i=o.providerId||"claude-code",a=w.get(i);a.abortCurrentTurn(s).catch(()=>{}),await a.terminateSession(s),E(s),f.delete(s),v(s),ie(s),t.push(s),await _(o.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}catch(i){const a=i instanceof Error?i.message:String(i);r.push(`SDK ${s}: ${a}`)}try{await dt([]),console.log("[Runtime] \u5DF2\u6E05\u7A7A\u6240\u6709\u6301\u4E45\u5316\u4F1A\u8BDD")}catch(s){const o=s instanceof Error?s.message:String(s);r.push(`Persistence: ${o}`)}n.json({ok:!0,stopped:{sdk:t.length},errors:r.length>0?r:void 0})}),A.get("/events/last/:n",S,(e,n)=>{const t=parseInt(e.params.n,10);if(!Number.isFinite(t)||t<1){n.status(400).json({error:":n must be a positive integer"});return}const r=De.getLastN(t);n.json({ok:!0,count:r.length,entries:r})}),A.get("/events/since/:index",S,(e,n)=>{const t=parseInt(e.params.index,10);if(!Number.isFinite(t)||t<0){n.status(400).json({error:":index must be a non-negative integer"});return}const r=De.getSinceIndex(t);n.json({ok:!0,entries:r.entries,nextIndex:r.nextIndex,oldestIndex:r.oldestIndex,dataLoss:r.oldestIndex>t+1})}),A.get("/events/push-stats",S,(e,n)=>{const t=st();n.json({ok:!0,count:t.length,agents:t})});export{Ct as buildAcodeCommandOutputPath,Oe as buildClaudeCodeLaunchConfig,Be as buildRuntimeEnv,Qt as buildSdkOutputMetadata,Wt as buildToolResultTimelineActionInfo,Kn as cleanupSdkSessionByAgentId,$t as countTerminalOutputLines,Ue as createTerminalOutputDecoder,oe as decodeTerminalOutputChunk,Ut as evaluatePersistedSessionReuse,Dt as formatCommandInactivityTimeoutNotice,_t as formatCommandOutputSpilloverNotice,Ht as formatSdkOutputEvent,Se as formatTerminalPrompt,Pt as normalizeTerminalCommandInput,kt as parseRuntimeStopOptions,xt as parseTerminalDirectoryChangeTarget,ue as raceSendOutputWithRetry,At as resolveRuntimeContextResetSupport,cn as resolveRuntimeStatusFromProviderEvent,qt as resolveSdkInputMessage,Fe as resolveSdkProviderId,se as resolveSdkSessionDisplayStatus,wt as resolveStatusChangeRuntimeState,re as resolveStatusChangeUsage,Rt as resolveTerminalOutputEncoding,f as sdkSessions,Tt as shouldProbeSdkProcessPid,A as terminalRouter};
53
+ `):void 0}const U={command:o||"acode",workingDirectory:r,agentId:I,...Te?{scopeKey:Te}:{},...typeof ke=="boolean"?{browserAllowPrivate:ke}:{},autoAccept:!!s,initialPrompt:i,systemPrompt:we,...pe!==void 0?{globalPrompt:pe}:{},...ge!==void 0?{rolePrompt:ge}:{},...Y!==void 0?{memory:Y}:{},model:H,mcpConfigPath:fe,...W?{instanceAiConfig:W}:{},...typeof $=="string"&&$.trim()?{subAgentModel:$.trim()}:{},...typeof E=="string"&&E.trim()?{subAgentEffort:E.trim()}:{},extraMcpServers:m||{},envOverrides:Be(String(n),String(r),process.env,me)};z.log({level:"info",category:"launch",message:"\u4F20\u9012\u7ED9 Adapter \u7684\u5B8C\u6574 AdapterSessionConfig",source:"bridge",agentId:I,sessionId:D,details:{adapterModel:U.model??null,adapterInstanceAiConfig:U.instanceAiConfig?te(U.instanceAiConfig):null,adapterMcpConfigPath:U.mcpConfigPath??null}}),await z.flush(),f.set(D,{agentId:I,workspacePath:r,sessionId:D,config:U,providerId:M,seq:0,runtimeAccessToken:le,schedulerBaseUrl:B}),t.json({sessionId:D,status:"starting",runtimeStatus:"starting",agentId:I,workspacePath:r,command:U.command,mode:"sdk"}),yn({sessionId:D,agentId:I,config:U,adapter:ze,providerId:M,idleInputAutoCommand:T,nonInputAutoCommand:y,runtimeAccessToken:le,requestedSchedulerBaseUrl:B})}catch(O){if(D&&(x(D),f.delete(D),v(D)),I&&K.delete(I),!t.headersSent){const k=O instanceof Error?O.message:String(O);t.status(500).json({error:`Failed to start SDK session: ${k}`})}}}async function yn(e){const{sessionId:t,agentId:n,config:r,adapter:o,providerId:s,idleInputAutoCommand:i,nonInputAutoCommand:a,runtimeAccessToken:c,requestedSchedulerBaseUrl:d}=e;try{await o.startSession(t,r),(i||a)&&o.setIdleCommands?.(t,{idleInputCommand:i||"",nonInputCommand:a||""});let u;if(Tt(s))try{if(await new Promise(m=>setTimeout(m,500)),u=o.getSessionPid?.(t),!u){const p=(await nt()).find(T=>T.agentId===n||T.cwd===r.workingDirectory||T.command.includes(r.workingDirectory));p&&(u=p.pid,console.log(`[Runtime] Found SDK process PID: ${u} for agentId=${n}`))}}catch(m){console.warn(`[Runtime] Failed to get SDK PID for agentId=${n}:`,m)}const l=se(o.getSessionStatus(t),f.get(t)?.currentRuntimeStatus,f.get(t)?.currentRuntimeActionType);await ft({sessionId:t,agentId:n,workspacePath:r.workingDirectory,command:r.command,startedAt:new Date().toISOString(),status:"running",runtimeStatus:l,mode:"sdk",pid:u,providerSessionId:o.getProviderSessionId(t)}),u&&await he().startProcess({agentId:n,sessionId:t,pid:u,mode:"sdk",workspacePath:r.workingDirectory,command:r.command}),await hn({agentId:n,sessionId:t,sdkPid:u,status:l,schedulerBaseUrl:d,runtimeAccessToken:c})}catch(u){x(t),f.delete(t),v(t),await F(t);const l=u instanceof Error?u.message:String(u);console.error(`[Runtime] Background SDK session startup failed for agentId=${n}: ${l}`),await In({agentId:n,sessionId:t,schedulerBaseUrl:d,runtimeAccessToken:c,errorMessage:l})}finally{K.delete(n)}}async function hn(e){const{agentId:t,sessionId:n,sdkPid:r,status:o,schedulerBaseUrl:s,runtimeAccessToken:i}=e;if(!s||!i){h.debug(`[Runtime] notifyServerSessionReady skipped: missing schedulerBaseUrl or runtimeAccessToken for agentId=${t}`);return}const a=`${s.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await Ce.post(a,{agentId:t,sessionId:n,status:o,pid:r},{headers:{"X-Runtime-Token":i,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session ready: agentId=${t}, sessionId=${n}, status=${o}`)}catch(c){const d=c instanceof Error?c.message:String(c);h.warn(`[Runtime] Failed to notify server session ready: agentId=${t}, error=${d}`)}}async function In(e){const{agentId:t,sessionId:n,schedulerBaseUrl:r,runtimeAccessToken:o}=e;if(!r||!o)return;const s=`${r.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await Ce.post(s,{agentId:t,sessionId:n,status:"stopped"},{headers:{"X-Runtime-Token":o,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session failed: agentId=${t}, sessionId=${n}`)}catch(i){const a=i instanceof Error?i.message:String(i);h.warn(`[Runtime] Failed to notify server session failed: agentId=${t}, error=${a}`)}}A.post("/sdk/message",S,async(e,t)=>{const{sessionId:n,message:r}=e.body||{};if(!n||!r){t.status(400).json({error:"sessionId and message are required"});return}const o=f.get(n);if(!o){t.status(404).json({error:"SDK session not found"});return}try{const s=o.providerId||"claude-code";await w.get(s).sendMessage(n,r),t.json({ok:!0})}catch(s){const i=s instanceof Error?s.message:String(s);t.status(500).json({error:i})}}),A.post("/sdk/answer",S,async(e,t)=>{const{sessionId:n,answers:r}=e.body||{};if(!n||!r){t.status(400).json({error:"sessionId and answers are required"});return}const o=f.get(n);if(!o){t.status(404).json({error:"SDK session not found"});return}try{const s=o.providerId||"claude-code",i=w.get(s);i.sendQuestionAnswer&&await i.sendQuestionAnswer(n,r),t.json({ok:!0})}catch(s){const i=s instanceof Error?s.message:String(s);t.status(500).json({error:i})}}),A.post("/sdk/confirm",S,async(e,t)=>{const{sessionId:n,accept:r}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const o=f.get(n);if(!o){t.status(404).json({error:"SDK session not found"});return}try{const s=o.providerId||"claude-code";await w.get(s).sendConfirmation(n,!!r),t.json({ok:!0})}catch(s){const i=s instanceof Error?s.message:String(s);t.status(500).json({error:i})}}),A.post("/sdk/abort",S,async(e,t)=>{const{sessionId:n}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const o=r.providerId||"claude-code";await w.get(o).abortCurrentTurn(n),t.json({ok:!0})}catch(o){const s=o instanceof Error?o.message:String(o);t.status(500).json({error:s})}}),A.post("/sdk/stop",S,async(e,t)=>{const{sessionId:n}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.json({ok:!0,status:"stopped"});return}try{const o=r.providerId||"claude-code",s=w.get(o);s.abortCurrentTurn(n).catch(()=>{}),await s.terminateSession(n),x(n),f.delete(n),v(n),ie(n),await F(n),await he().removeProcess(r.agentId),await _(r.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl}),t.json({ok:!0,status:"stopped"})}catch(o){const s=o instanceof Error?o.message:String(o);t.status(500).json({error:s})}}),A.get("/sdk/status/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const o=r.providerId||"claude-code",s=w.get(o),i=s.getSessionStatus(n),a=s.getConversation(n);t.json({sessionId:n,status:i,agentId:r.agentId,workspacePath:r.workspacePath,messageCount:a.length})}catch(o){const s=o instanceof Error?o.message:String(o);t.status(500).json({error:s})}}),A.get("/sdk/capabilities/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const o=r.providerId||"claude-code",i=w.get(o).getCapabilities?.(n)??null;t.json({ok:!0,sessionId:n,agentId:r.agentId,capabilities:i,fetchedAt:Date.now()})}catch(o){const s=o instanceof Error?o.message:String(o);t.status(500).json({error:s})}}),A.get("/sdk/pending-questions/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const o=r.providerId||"claude-code",i=w.get(o).getPendingQuestion?.(n)??null;t.json({ok:!0,sessionId:n,agentId:r.agentId,pendingQuestion:i?{toolCallId:i.toolCallId,questions:i.questions}:null,fetchedAt:Date.now()})}catch(o){const s=o instanceof Error?o.message:String(o);t.status(500).json({error:s})}}),A.post("/command",S,async(e,t)=>{const{sessionId:n,command:r}=e.body||{};if(!n||r===void 0||r===null){t.status(400).json({error:"sessionId and command are required"});return}try{const o=await Ot(String(n),r);t.json({ok:!0,mode:"terminal",...o})}catch(o){const s=o instanceof Error?o.message:String(o);t.status(500).json({error:s})}}),A.post("/input",S,async(e,t)=>{const{sessionId:n,input:r,mode:o}=e.body||{};if(!n||r===void 0||r===null){t.status(400).json({error:"sessionId and input are required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}try{const i=s.providerId||"claude-code",a=w.get(i);if(o==="shortcut"){if(!a.sendShortcutInput){t.status(400).json({error:"shortcut input is not supported by this SDK provider"});return}await a.sendShortcutInput(n,String(r)),t.json({ok:!0,mode:"shortcut"});return}await a.sendMessage(n,await qt(r)),t.json({ok:!0,mode:"sdk"})}catch(i){const a=i instanceof Error?i.message:String(i);t.status(500).json({error:a})}}),A.post("/update-auto-commands",S,async(e,t)=>{const{agentId:n,idleInputAutoCommand:r="",nonInputAutoCommand:o=""}=e.body||{},s=String(n||"").trim();if(!s){t.status(400).json({error:"agentId is required"});return}const i=[...f.values()].find(c=>c.agentId===s),a={idleInputCommand:String(r||""),nonInputCommand:String(o||"")};try{let c=!1;i&&(w.get(i.providerId||"claude-code").setIdleCommands?.(i.sessionId,a),c=!0);const d=await lt(s,{idleInputAutoCommand:a.idleInputCommand,nonInputAutoCommand:a.nonInputCommand});t.json({ok:!0,mode:"sdk",sessionUpdated:c,persistedUpdated:d})}catch(c){const d=c instanceof Error?c.message:String(c);t.status(500).json({ok:!1,mode:"sdk",error:d})}}),A.post("/resize",S,(e,t)=>{const{sessionId:n,cols:r,rows:o}=e.body||{};if(!n||!r||!o){t.status(400).json({error:"sessionId, cols, rows are required"});return}if(!f.has(n)){t.status(404).json({error:"SDK session not found"});return}t.json({ok:!0,mode:"sdk",noop:!0,cols:Number(r),rows:Number(o)})}),A.post("/reset-context",S,async(e,t)=>{const{sessionId:n,reason:r}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const o=f.get(n);if(!o){t.status(404).json({error:"SDK session not found"});return}const s=o.providerId||"claude-code",i=w.get(s),a=i.resetContext?.bind(i),c=At(s,!!a);if(!c.supported){t.status(c.statusCode).json({error:c.error});return}if(!a){t.status(500).json({error:"ACode adapter does not expose resetContext"});return}try{await a(String(n));const d=se(i.getSessionStatus(String(n)),o.currentRuntimeStatus,o.currentRuntimeActionType);t.json({ok:!0,contextReset:!0,sessionId:n,status:d,runtimeStatus:d,agentId:o.agentId,mode:"sdk",providerId:s,reason:typeof r=="string"&&r.trim()?r.trim():void 0})}catch(d){const u=d instanceof Error?d.message:String(d);t.status(500).json({ok:!1,contextReset:!1,mode:"sdk",error:u})}}),A.post("/stop",S,async(e,t)=>{const{sessionId:n}=e.body||{},r=kt(e.body);if(!n){t.status(400).json({error:"sessionId is required"});return}const o=f.get(n);if(!o){await F(n),t.json({ok:!0,status:"stopped",mode:"none",statusNotified:!1,reason:r.reason});return}const s=o.agentId;try{console.log(`[Runtime] Stopping SDK session ${n}; suppressStatus=${!r.statusNotified}, reason=${r.reason||"unspecified"}`);const i=o.providerId||"claude-code",a=w.get(i);a.abortCurrentTurn(n).catch(()=>{}),await a.terminateSession(n),x(n),f.delete(n),v(n),ie(n),await F(n),await he().removeProcess(s),r.statusNotified?await _(s,null,"stopped",void 0,void 0,{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl}):console.log(`[Runtime] Stopped status notification suppressed for SDK session ${n}; reason=${r.reason||"unspecified"}`),t.json({ok:!0,status:"stopped",mode:"sdk",statusNotified:r.statusNotified,reason:r.reason})}catch(i){const a=i instanceof Error?i.message:String(i);console.error(`[Runtime] Failed to terminate SDK session ${n}:`,a),t.status(500).json({ok:!1,status:"stop_failed",mode:"sdk",error:a})}}),A.post("/stop-all",S,async(e,t)=>{const n=[],r=[];for(const[o,s]of f.entries())try{const i=s.providerId||"claude-code",a=w.get(i);a.abortCurrentTurn(o).catch(()=>{}),await a.terminateSession(o),x(o),f.delete(o),v(o),ie(o),n.push(o),await _(s.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl})}catch(i){const a=i instanceof Error?i.message:String(i);r.push(`SDK ${o}: ${a}`)}try{await dt([]),console.log("[Runtime] \u5DF2\u6E05\u7A7A\u6240\u6709\u6301\u4E45\u5316\u4F1A\u8BDD")}catch(o){const s=o instanceof Error?o.message:String(o);r.push(`Persistence: ${s}`)}t.json({ok:!0,stopped:{sdk:n.length},errors:r.length>0?r:void 0})}),A.get("/events/last/:n",S,(e,t)=>{const n=parseInt(e.params.n,10);if(!Number.isFinite(n)||n<1){t.status(400).json({error:":n must be a positive integer"});return}const r=De.getLastN(n);t.json({ok:!0,count:r.length,entries:r})}),A.get("/events/since/:index",S,(e,t)=>{const n=parseInt(e.params.index,10);if(!Number.isFinite(n)||n<0){t.status(400).json({error:":index must be a non-negative integer"});return}const r=De.getSinceIndex(n);t.json({ok:!0,entries:r.entries,nextIndex:r.nextIndex,oldestIndex:r.oldestIndex,dataLoss:r.oldestIndex>n+1})}),A.get("/events/push-stats",S,(e,t)=>{const n=st();t.json({ok:!0,count:n.length,agents:n})});export{Ct as buildAcodeCommandOutputPath,Oe as buildClaudeCodeLaunchConfig,Be as buildRuntimeEnv,Qt as buildSdkOutputMetadata,Ht as buildToolResultTimelineActionInfo,Kn as cleanupSdkSessionByAgentId,$t as countTerminalOutputLines,Ue as createTerminalOutputDecoder,oe as decodeTerminalOutputChunk,Ut as evaluatePersistedSessionReuse,Dt as formatCommandInactivityTimeoutNotice,_t as formatCommandOutputSpilloverNotice,Wt as formatSdkOutputEvent,Se as formatTerminalPrompt,Pt as normalizeTerminalCommandInput,kt as parseRuntimeStopOptions,Et as parseTerminalDirectoryChangeTarget,ue as raceSendOutputWithRetry,At as resolveRuntimeContextResetSupport,cn as resolveRuntimeStatusFromProviderEvent,qt as resolveSdkInputMessage,Fe as resolveSdkProviderId,se as resolveSdkSessionDisplayStatus,wt as resolveStatusChangeRuntimeState,re as resolveStatusChangeUsage,Rt as resolveTerminalOutputEncoding,f as sdkSessions,Tt as shouldProbeSdkProcessPid,A as terminalRouter};
54
54