aws-runtime-bridge 1.9.40 → 1.9.41
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.
- package/dist/adapter/AcodeSdkAdapter.d.ts +31 -4
- package/dist/adapter/AcodeSdkAdapter.d.ts.map +1 -1
- package/dist/adapter/AcodeSdkAdapter.js +382 -57
- package/dist/adapter/ClaudeSdkAdapter.d.ts.map +1 -1
- package/dist/adapter/ClaudeSdkAdapter.js +1 -0
- package/dist/adapter/OpencodeSdkAdapter.d.ts +19 -0
- package/dist/adapter/OpencodeSdkAdapter.d.ts.map +1 -1
- package/dist/adapter/OpencodeSdkAdapter.js +62 -0
- package/dist/adapter/types.d.ts +21 -6
- package/dist/adapter/types.d.ts.map +1 -1
- package/dist/adapter/types.js +10 -1
- package/dist/index.js +11 -0
- package/dist/routes/ai-sources.js +4 -1
- package/dist/routes/dashboard.d.ts.map +1 -1
- package/dist/routes/dashboard.js +1 -1
- package/dist/routes/runtime-binding.d.ts.map +1 -1
- package/dist/routes/runtime-binding.js +6 -3
- package/dist/routes/sessions.js +89 -4
- package/dist/routes/sub-agents.js +15 -1
- package/dist/routes/terminal.d.ts +3 -0
- package/dist/routes/terminal.d.ts.map +1 -1
- package/dist/routes/terminal.js +122 -5
- package/dist/services/acode-package.d.ts +8 -1
- package/dist/services/acode-package.d.ts.map +1 -1
- package/dist/services/acode-package.js +33 -4
- package/dist/services/aws-client-agent-mcp.d.ts.map +1 -1
- package/dist/services/aws-client-agent-mcp.js +11 -4
- package/dist/services/fileSnapshotStore.js +1 -1
- package/dist/services/legacy-path-migration.d.ts +3 -0
- package/dist/services/legacy-path-migration.d.ts.map +1 -0
- package/dist/services/legacy-path-migration.js +66 -0
- package/dist/services/lifecycle-state.d.ts.map +1 -1
- package/dist/services/lifecycle-state.js +1 -1
- package/dist/services/runtime-binding.d.ts +5 -0
- package/dist/services/runtime-binding.d.ts.map +1 -1
- package/dist/services/runtime-binding.js +33 -1
- package/dist/services/session-output.d.ts +7 -1
- package/dist/services/session-output.d.ts.map +1 -1
- package/dist/services/session-output.js +16 -2
- package/package/acode/dist/built-in-file-tools.d.ts.map +1 -1
- package/package/acode/dist/built-in-file-tools.js +504 -3
- package/package/acode/dist/compaction.d.ts +43 -7
- package/package/acode/dist/compaction.d.ts.map +1 -1
- package/package/acode/dist/compaction.js +286 -31
- package/package/acode/dist/runtime.d.ts +120 -0
- package/package/acode/dist/runtime.d.ts.map +1 -1
- package/package/acode/dist/runtime.js +921 -71
- package/package/acode/dist/sub-agent-manager.d.ts +96 -1
- package/package/acode/dist/sub-agent-manager.d.ts.map +1 -1
- package/package/acode/dist/sub-agent-manager.js +293 -3
- package/package/acode/dist/sub-agent-store.d.ts +8 -1
- package/package/acode/dist/sub-agent-store.d.ts.map +1 -1
- package/package/acode/dist/sub-agent-store.js +55 -0
- package/package/acode/dist/sub-agent-types.d.ts +4 -0
- package/package/acode/dist/sub-agent-types.d.ts.map +1 -1
- package/package/acode/dist/types.d.ts +19 -0
- package/package/acode/dist/types.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +9 -0
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/agent-client.js +69 -10
- package/package/aws-client-agent-mcp/dist/agent-client.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/config.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/config.js +4 -0
- package/package/aws-client-agent-mcp/dist/config.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/constants.d.ts +2 -0
- package/package/aws-client-agent-mcp/dist/constants.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/constants.js +3 -1
- package/package/aws-client-agent-mcp/dist/constants.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/context-manager.d.ts +4 -1
- package/package/aws-client-agent-mcp/dist/context-manager.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/context-manager.js +6 -2
- package/package/aws-client-agent-mcp/dist/context-manager.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/context-manager.test.js +5 -0
- package/package/aws-client-agent-mcp/dist/context-manager.test.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +5 -0
- package/package/aws-client-agent-mcp/dist/http-client.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/http-client.js +15 -1
- package/package/aws-client-agent-mcp/dist/http-client.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +92 -34
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.js +606 -208
- package/package/aws-client-agent-mcp/dist/mcp-server.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.test.js +151 -51
- package/package/aws-client-agent-mcp/dist/mcp-server.test.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +7 -0
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +18 -0
- package/package/aws-client-agent-mcp/dist/mcp-tools.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts +32 -9
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/memory-store.js +58 -19
- package/package/aws-client-agent-mcp/dist/memory-store.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/memory-tools.js +3 -3
- package/package/aws-client-agent-mcp/dist/memory-tools.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/message-buffer.d.ts +13 -0
- package/package/aws-client-agent-mcp/dist/message-buffer.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/message-buffer.js +23 -0
- package/package/aws-client-agent-mcp/dist/message-buffer.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/server-memory-store.d.ts +13 -0
- package/package/aws-client-agent-mcp/dist/server-memory-store.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/server-memory-store.js +18 -0
- package/package/aws-client-agent-mcp/dist/server-memory-store.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/types.d.ts +9 -0
- package/package/aws-client-agent-mcp/dist/types.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/types.js.map +1 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.d.ts +34 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.d.ts.map +1 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.js +146 -18
- package/package/aws-client-agent-mcp/dist/websocket-client.js.map +1 -1
- package/package.json +1 -1
|
@@ -17,7 +17,7 @@ import { ACodeCommandRegistry } from "./commands/commandRegistry.js";
|
|
|
17
17
|
import { calculateCompactionThreshold, COMPACTION_LLM_PROMPT_TEMPLATE, conversationSizeKB, estimateConversationTokens, performCompaction, pruneToolOutputs, summarizeConversation, } from "./compaction.js";
|
|
18
18
|
import { loadAcodeConfig, loadAcodeSkillGroup } from "./config.js";
|
|
19
19
|
import { ACodeHookBus, findDeniedHookResult } from "./hooks/hookBus.js";
|
|
20
|
-
import { isMcpPollingToolName } from "./mcpToolNames.js";
|
|
20
|
+
import { isMcpPollingToolName, getSemanticToolName } from "./mcpToolNames.js";
|
|
21
21
|
function cloneChatContentPart(part) {
|
|
22
22
|
if (part.type === "text") {
|
|
23
23
|
return { type: "text", text: part.text };
|
|
@@ -66,13 +66,54 @@ function normalizeText(value) {
|
|
|
66
66
|
return text || undefined;
|
|
67
67
|
}
|
|
68
68
|
const DEFAULT_PROVIDER_REQUEST_TIMEOUT_MS = 60_000;
|
|
69
|
+
/**
|
|
70
|
+
* 单次 provider 请求的总时长上限(毫秒)。默认 10 分钟。
|
|
71
|
+
* 超过该总预算即终止整个请求(含流式读取),不论是否仍在持续接收 chunk。
|
|
72
|
+
* 与 requestTimeoutMs(流式空闲超时 / 非流式分段超时)配合:只要每个 chunk 间隔不超过 60s,
|
|
73
|
+
* 但整体跑满 10min 仍会断开,避免长流式请求无限挂起。
|
|
74
|
+
* 0 = 不设总时长上限(仅靠 requestTimeoutMs 保护)。
|
|
75
|
+
*/
|
|
76
|
+
const DEFAULT_PROVIDER_REQUEST_TOTAL_TIMEOUT_MS = 10 * 60_000;
|
|
69
77
|
const DEFAULT_PROVIDER_REQUEST_RETRY_COUNT = 2;
|
|
78
|
+
/**
|
|
79
|
+
* 无限重试哨兵值:配置 requestRetryCount 为 -1 时,
|
|
80
|
+
* provider 请求在遇到可重试错误(超时/网络错误等)时无限重试,
|
|
81
|
+
* 直到请求成功、用户中止或会话终止。
|
|
82
|
+
* 启用后同时禁用总时长上限(requestTotalTimeoutMs 无效),
|
|
83
|
+
* 仅依靠单次请求超时(requestTimeoutMs)保护。
|
|
84
|
+
*/
|
|
85
|
+
const INFINITE_RETRY_SENTINEL = -1;
|
|
70
86
|
const DEFAULT_PROVIDER_REQUEST_RETRY_DELAY_MS = 1000;
|
|
71
87
|
const DEFAULT_MCP_TOOL_CALL_TIMEOUT_MS = 60_000;
|
|
72
88
|
const DEFAULT_MCP_POLLING_TOOL_CALL_TIMEOUT_MS = 0;
|
|
73
89
|
const MCP_SDK_MAX_SAFE_TIMEOUT_MS = 2_147_483_647;
|
|
90
|
+
/**
|
|
91
|
+
* 子 agent 通过共享 MCP 连接允许调用的工具白名单。
|
|
92
|
+
* 与 aws-client-agent-mcp 的 MEMORY_TOOL_NAMES 保持一致,
|
|
93
|
+
* 防止子 agent 调用 poll_message/send_group 等与父 agent 冲突的工具。
|
|
94
|
+
*/
|
|
95
|
+
const SUB_AGENT_ALLOWED_MCP_TOOLS = new Set([
|
|
96
|
+
"create_memory",
|
|
97
|
+
"read_memory",
|
|
98
|
+
"update_memory",
|
|
99
|
+
"delete_memory",
|
|
100
|
+
"search_memory",
|
|
101
|
+
"list_memories",
|
|
102
|
+
"get_memory_stats",
|
|
103
|
+
"list_memories_by_file",
|
|
104
|
+
// Memory 过期回忆工具:memory_expiration 委托子 agent 需调用以整理过期记忆
|
|
105
|
+
"memory_recurrence",
|
|
106
|
+
"memory_recurrence_complete",
|
|
107
|
+
]);
|
|
74
108
|
const DEFAULT_BASH_BUILT_IN_TOOL_TIMEOUT_MS = 10 * 60_000 + 2000;
|
|
75
109
|
const DEFAULT_RUNTIME_SHUTDOWN_TIMEOUT_MS = 10_000;
|
|
110
|
+
/**
|
|
111
|
+
* 当 poll_message 返回的全部消息被 memory 自动委托处理后,重新 poll 前的等待间隔。
|
|
112
|
+
* 防止紧密循环:MCP doPollMessage 对 updating memory 每次都返回通知,
|
|
113
|
+
* 而 processMemoryAutoDelegates 因 URI 已在处理中而返回 null,
|
|
114
|
+
* 导致 while(true) 无延迟重 poll,引发状态快速跳动(思考→MCP→跳过)最终连接丢失。
|
|
115
|
+
*/
|
|
116
|
+
const DELEGATE_REPOLL_DELAY_MS = 5_000;
|
|
76
117
|
const MAX_INLINE_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
77
118
|
const MAX_REQUEST_BODY_BYTES = 800 * 1024;
|
|
78
119
|
/**
|
|
@@ -95,6 +136,24 @@ function runtimeDebugLog(...args) {
|
|
|
95
136
|
}
|
|
96
137
|
/** 当 provider 未配置 contextLimit 时使用的默认值 */
|
|
97
138
|
const FALLBACK_CONTEXT_LIMIT = 64_000;
|
|
139
|
+
/**
|
|
140
|
+
* 解析 provider 的压缩配置,返回实际用于触发压缩的 contextLimit/maxOutput/inputLimit/threshold。
|
|
141
|
+
* 供 session_started 事件、startCompactionDebugLog、requestChatCompletion 共用,
|
|
142
|
+
* 确保前端显示的压缩点与后端实际触发阈值完全一致(消除前端自算公式的脱节)。
|
|
143
|
+
*/
|
|
144
|
+
function resolveCompactionConfig(provider) {
|
|
145
|
+
const contextLimit = (provider.contextLimit && provider.contextLimit > 0)
|
|
146
|
+
? provider.contextLimit
|
|
147
|
+
: FALLBACK_CONTEXT_LIMIT;
|
|
148
|
+
const maxOutput = (provider.maxOutput && provider.maxOutput > 0)
|
|
149
|
+
? provider.maxOutput
|
|
150
|
+
: 8_192;
|
|
151
|
+
const inputLimit = (provider.inputLimit && provider.inputLimit > 0)
|
|
152
|
+
? provider.inputLimit
|
|
153
|
+
: undefined;
|
|
154
|
+
const threshold = calculateCompactionThreshold(contextLimit, maxOutput, inputLimit);
|
|
155
|
+
return { contextLimit, maxOutput, inputLimit, threshold };
|
|
156
|
+
}
|
|
98
157
|
async function withTimeout(operation, timeoutMs, label, onTimeout) {
|
|
99
158
|
if (timeoutMs <= 0) {
|
|
100
159
|
return await operation;
|
|
@@ -128,6 +187,10 @@ function normalizeNonNegativeInteger(value, fallback) {
|
|
|
128
187
|
return 0;
|
|
129
188
|
}
|
|
130
189
|
const numeric = typeof value === "number" ? value : Number(value);
|
|
190
|
+
// -1 是无限重试哨兵值,直接透传
|
|
191
|
+
if (numeric === INFINITE_RETRY_SENTINEL) {
|
|
192
|
+
return INFINITE_RETRY_SENTINEL;
|
|
193
|
+
}
|
|
131
194
|
return Number.isFinite(numeric) && numeric > 0
|
|
132
195
|
? Math.floor(numeric)
|
|
133
196
|
: fallback;
|
|
@@ -169,6 +232,18 @@ function estimateContextTokens(systemPrompt, exposedTools) {
|
|
|
169
232
|
}
|
|
170
233
|
return Math.ceil(charCount / ESTIMATED_CHARS_PER_TOKEN);
|
|
171
234
|
}
|
|
235
|
+
/**
|
|
236
|
+
* 估算 exposedTools 定义的 token 开销。
|
|
237
|
+
* tools 的 JSON schema(函数名、描述、参数定义)会被序列化进请求体,
|
|
238
|
+
* 占用可观 token 数(十几个工具可达数千 tokens),必须计入上下文估算。
|
|
239
|
+
* 否则 estimateConversationTokens 系统性偏低,导致主动压缩阈值无法触达。
|
|
240
|
+
*/
|
|
241
|
+
function estimateToolsTokens(exposedTools) {
|
|
242
|
+
if (exposedTools.length === 0)
|
|
243
|
+
return 0;
|
|
244
|
+
const toolsJson = JSON.stringify(toOpenAiTools(exposedTools));
|
|
245
|
+
return estimateTokensFromText(toolsJson);
|
|
246
|
+
}
|
|
172
247
|
async function delay(ms) {
|
|
173
248
|
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
174
249
|
}
|
|
@@ -196,6 +271,36 @@ function modelSupportsImageInput(model, defaultProvider, providerOptions) {
|
|
|
196
271
|
* 解析 ACode 当前会话模型:优先显式启动参数,其次兼容 cc-switch 写入的
|
|
197
272
|
* OpenCode-style `provider.default.model`,最后回落到旧版 top-level model。
|
|
198
273
|
*/
|
|
274
|
+
/**
|
|
275
|
+
* 按优先级从 provider 配置中查找字段值:
|
|
276
|
+
* 1. options.*(通用配置)
|
|
277
|
+
* 2. models.<currentModel>.*(当前模型专属配置,面板初始化写入的位置)
|
|
278
|
+
* 3. provider.*(provider 级别兜底)
|
|
279
|
+
*
|
|
280
|
+
* @param optionsValue providerOptions 上的值(已取出)
|
|
281
|
+
* @param defaultProvider provider.default 对象
|
|
282
|
+
* @param currentModel 当前使用的模型名
|
|
283
|
+
* @param fieldName 要查找的字段名(如 "contextLimit")
|
|
284
|
+
*/
|
|
285
|
+
function resolveProviderConfigValue(optionsValue, defaultProvider, currentModel, fieldName) {
|
|
286
|
+
// 1. options 级别优先
|
|
287
|
+
if (optionsValue !== undefined)
|
|
288
|
+
return optionsValue;
|
|
289
|
+
if (!defaultProvider)
|
|
290
|
+
return undefined;
|
|
291
|
+
// 2. models.<modelName>.<fieldName>
|
|
292
|
+
const models = defaultProvider.models;
|
|
293
|
+
if (isRecord(models)) {
|
|
294
|
+
const modelConfig = models[currentModel];
|
|
295
|
+
if (isRecord(modelConfig)) {
|
|
296
|
+
const modelValue = modelConfig[fieldName];
|
|
297
|
+
if (modelValue !== undefined)
|
|
298
|
+
return modelValue;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// 3. provider 级别兜底
|
|
302
|
+
return defaultProvider[fieldName];
|
|
303
|
+
}
|
|
199
304
|
function resolveProviderConfig(config, acodeConfig) {
|
|
200
305
|
const defaultProvider = acodeConfig.provider?.default;
|
|
201
306
|
const providerOptions = defaultProvider?.options;
|
|
@@ -203,17 +308,36 @@ function resolveProviderConfig(config, acodeConfig) {
|
|
|
203
308
|
defaultProvider?.model ||
|
|
204
309
|
acodeConfig.model ||
|
|
205
310
|
"acode-default";
|
|
311
|
+
// effort 优先级:runtime config (per-session/per-instance) > provider options (acode.json) > provider default
|
|
312
|
+
const effort = normalizeText(config.effort) ||
|
|
313
|
+
normalizeText(providerOptions?.effort) ||
|
|
314
|
+
normalizeText(defaultProvider?.effort) ||
|
|
315
|
+
undefined;
|
|
206
316
|
return {
|
|
207
317
|
model,
|
|
208
318
|
baseURL: normalizeText(providerOptions?.baseURL || providerOptions?.baseUrl),
|
|
209
319
|
apiKey: normalizeText(providerOptions?.apiKey),
|
|
320
|
+
effort,
|
|
210
321
|
systemPrompt: config.systemPrompt || acodeConfig.systemPrompt,
|
|
211
322
|
stream: providerOptions?.stream !== false,
|
|
212
|
-
|
|
323
|
+
// ★ 安全修复:使用 normalizePositiveInteger 禁止设为 0,
|
|
324
|
+
// 0 会导致 withTimeout 直接返回 operation(禁用超时),
|
|
325
|
+
// fetch 挂起时请求永久不返回,agent 死锁。
|
|
326
|
+
requestTimeoutMs: normalizePositiveInteger(providerOptions?.requestTimeoutMs ?? providerOptions?.timeoutMs, DEFAULT_PROVIDER_REQUEST_TIMEOUT_MS),
|
|
327
|
+
requestTotalTimeoutMs: normalizePositiveInteger(providerOptions?.requestTotalTimeoutMs, DEFAULT_PROVIDER_REQUEST_TOTAL_TIMEOUT_MS),
|
|
213
328
|
requestRetryCount: normalizeNonNegativeInteger(providerOptions?.requestRetryCount, DEFAULT_PROVIDER_REQUEST_RETRY_COUNT),
|
|
214
329
|
mcpToolTimeoutMs: normalizePositiveInteger(providerOptions?.mcpToolTimeoutMs, DEFAULT_MCP_TOOL_CALL_TIMEOUT_MS),
|
|
215
330
|
mcpPollingToolTimeoutMs: normalizeNonNegativeInteger(providerOptions?.mcpPollingToolTimeoutMs, DEFAULT_MCP_POLLING_TOOL_CALL_TIMEOUT_MS),
|
|
216
331
|
supportsImageInput: modelSupportsImageInput(model, defaultProvider, providerOptions),
|
|
332
|
+
// ★ 从 provider 配置中读取 contextLimit/inputLimit/maxOutput,
|
|
333
|
+
// requestChatCompletion 和 startCompactionDebugLog 使用这些值计算压缩触发阈值。
|
|
334
|
+
// 按优先级查找三个位置:
|
|
335
|
+
// 1. provider.default.options.*(options 级别,通用配置)
|
|
336
|
+
// 2. provider.default.models.<modelName>.*(模型级别,面板初始化写入的位置)
|
|
337
|
+
// 3. provider.default.*(provider 级别兜底)
|
|
338
|
+
contextLimit: normalizeNonNegativeInteger(resolveProviderConfigValue(providerOptions?.contextLimit, defaultProvider, model, "contextLimit"), 0) || undefined,
|
|
339
|
+
inputLimit: normalizeNonNegativeInteger(resolveProviderConfigValue(providerOptions?.inputLimit, defaultProvider, model, "inputLimit"), 0) || undefined,
|
|
340
|
+
maxOutput: normalizeNonNegativeInteger(resolveProviderConfigValue(providerOptions?.maxOutput, defaultProvider, model, "maxOutput"), 0) || undefined,
|
|
217
341
|
};
|
|
218
342
|
}
|
|
219
343
|
function appendTextPart(parts, text) {
|
|
@@ -522,8 +646,14 @@ function coerceArguments(rawArguments) {
|
|
|
522
646
|
}
|
|
523
647
|
}
|
|
524
648
|
function getBuiltInToolTimeoutMs(tool, args, fallbackTimeoutMs) {
|
|
525
|
-
//
|
|
526
|
-
|
|
649
|
+
// 阻塞等待型工具不受超时限制:
|
|
650
|
+
// - ask_user_question: 阻塞等待用户回答
|
|
651
|
+
// - await_sub_agents: 永久阻塞等待指定子 agent 数组到达终态
|
|
652
|
+
const BLOCKING_BUILT_IN_TOOL_NAMES = new Set([
|
|
653
|
+
ASK_USER_QUESTION_TOOL_NAME,
|
|
654
|
+
"await_sub_agents",
|
|
655
|
+
]);
|
|
656
|
+
if (BLOCKING_BUILT_IN_TOOL_NAMES.has(tool.toolName)) {
|
|
527
657
|
return 0;
|
|
528
658
|
}
|
|
529
659
|
if (tool.toolName !== "Bash") {
|
|
@@ -848,6 +978,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
848
978
|
model: "acode-default",
|
|
849
979
|
stream: false,
|
|
850
980
|
requestTimeoutMs: DEFAULT_PROVIDER_REQUEST_TIMEOUT_MS,
|
|
981
|
+
requestTotalTimeoutMs: DEFAULT_PROVIDER_REQUEST_TOTAL_TIMEOUT_MS,
|
|
851
982
|
requestRetryCount: DEFAULT_PROVIDER_REQUEST_RETRY_COUNT,
|
|
852
983
|
mcpToolTimeoutMs: DEFAULT_MCP_TOOL_CALL_TIMEOUT_MS,
|
|
853
984
|
mcpPollingToolTimeoutMs: DEFAULT_MCP_POLLING_TOOL_CALL_TIMEOUT_MS,
|
|
@@ -855,6 +986,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
855
986
|
},
|
|
856
987
|
permissions: { mode: "default", allow: [], deny: [] },
|
|
857
988
|
mcpConnections: [],
|
|
989
|
+
ownsMcpConnections: true,
|
|
858
990
|
exposedTools: [],
|
|
859
991
|
commands: [],
|
|
860
992
|
commandRegistry: new ACodeCommandRegistry([]),
|
|
@@ -863,6 +995,12 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
863
995
|
accumulatedOutputTokens: 0,
|
|
864
996
|
};
|
|
865
997
|
this.abortController = null;
|
|
998
|
+
/**
|
|
999
|
+
* 正在处理中的 memory 子 agent 跟踪表。
|
|
1000
|
+
* key = memory URI,value = subId(用于防止同一 memory 被重复委托)。
|
|
1001
|
+
* 子 agent 完成后通过 SubAgentManager 事件回调移除对应 URI。
|
|
1002
|
+
*/
|
|
1003
|
+
this.pendingMemorySubAgents = new Map();
|
|
866
1004
|
this.submitQueue = Promise.resolve();
|
|
867
1005
|
this.activeTurn = false;
|
|
868
1006
|
this.abortRequested = false;
|
|
@@ -895,6 +1033,10 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
895
1033
|
this.hookBus.register(handler);
|
|
896
1034
|
}
|
|
897
1035
|
}
|
|
1036
|
+
/** 获取当前已暴露的工具名称列表(供 SubAgentManager 记录) */
|
|
1037
|
+
getAvailableTools() {
|
|
1038
|
+
return this.state.exposedTools.map((tool) => tool.exposedName);
|
|
1039
|
+
}
|
|
898
1040
|
emitAcodeEvent(type, data) {
|
|
899
1041
|
const event = {
|
|
900
1042
|
type,
|
|
@@ -962,7 +1104,13 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
962
1104
|
`resolvedModel=${provider.model}, baseURL=${provider.baseURL ?? "(none)"}, apiKey=${provider.apiKey ? "[set]" : "(none)"}, ` +
|
|
963
1105
|
`configPath=${this.config.configPath ?? "(none)"}`);
|
|
964
1106
|
const permissions = resolvePermissionConfig(this.config, acodeConfig);
|
|
965
|
-
|
|
1107
|
+
// 子 agent 复用父 agent 的 MCP 连接,避免启动新 MCP server 进程后 401
|
|
1108
|
+
// 共享连接时只暴露 memory 工具,防止子 agent 调用 poll_message/send_group 等
|
|
1109
|
+
// 与父 agent 冲突的工具(原设计通过 AWS_SUB_AGENT=true 限制,共享连接绕过了该机制)
|
|
1110
|
+
const mcpConnections = this.config.sharedMcpConnections
|
|
1111
|
+
? this.filterSharedMcpConnectionsForSubAgent(this.config.sharedMcpConnections)
|
|
1112
|
+
: await this.connectMcpServers(acodeConfig.mcpServers ?? {}, provider.mcpToolTimeoutMs);
|
|
1113
|
+
const ownsMcpConnections = !this.config.sharedMcpConnections;
|
|
966
1114
|
// 获取用户 profile 信息并拼接在 rolePrompt 下方
|
|
967
1115
|
const profilePrompt = await this.fetchProfilePrompt(mcpConnections);
|
|
968
1116
|
const agentId = this.config.agentId || "unknown";
|
|
@@ -1027,6 +1175,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1027
1175
|
provider,
|
|
1028
1176
|
permissions,
|
|
1029
1177
|
mcpConnections,
|
|
1178
|
+
ownsMcpConnections,
|
|
1030
1179
|
exposedTools,
|
|
1031
1180
|
commands,
|
|
1032
1181
|
commandRegistry,
|
|
@@ -1039,11 +1188,22 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1039
1188
|
model: provider.model,
|
|
1040
1189
|
commandCount: commands.length,
|
|
1041
1190
|
});
|
|
1191
|
+
// ★ emit 实际用于触发压缩的配置,前端 AgentContextPanel 直接显示此阈值,
|
|
1192
|
+
// 消除前端自算公式与后端实际触发阈值(min(动态比例, hardLimit-reserved))的脱节。
|
|
1193
|
+
// 注意:此处的 contextLimit/maxOutput/inputLimit 来自 resolveProviderConfig(读 provider.default.* 三级),
|
|
1194
|
+
// 与 adapter 的 totalUsage.contextLimit(读顶层+查表)可能不同源——前端应以这里 emit 的值为准。
|
|
1195
|
+
const compactionConfig = resolveCompactionConfig(provider);
|
|
1042
1196
|
this.emitAcodeEvent("session_started", {
|
|
1043
1197
|
workingDirectory: this.config.workingDirectory,
|
|
1044
1198
|
model: provider.model,
|
|
1045
1199
|
commandCount: commands.length,
|
|
1046
1200
|
estimatedContextTokens: estimateContextTokens(systemMessagesPlainText, exposedTools),
|
|
1201
|
+
contextLimit: compactionConfig.contextLimit,
|
|
1202
|
+
maxOutput: compactionConfig.maxOutput,
|
|
1203
|
+
...(compactionConfig.inputLimit !== undefined
|
|
1204
|
+
? { inputLimit: compactionConfig.inputLimit }
|
|
1205
|
+
: {}),
|
|
1206
|
+
compactionThreshold: compactionConfig.threshold,
|
|
1047
1207
|
});
|
|
1048
1208
|
this.emitAcodeEvent("mcp_status", {
|
|
1049
1209
|
configPath: this.config.configPath,
|
|
@@ -1266,20 +1426,12 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1266
1426
|
if (this.compactionDebugTimer)
|
|
1267
1427
|
return;
|
|
1268
1428
|
const provider = this.state.provider;
|
|
1269
|
-
const contextLimit
|
|
1270
|
-
? provider.contextLimit
|
|
1271
|
-
: FALLBACK_CONTEXT_LIMIT;
|
|
1272
|
-
const maxOutput = (provider.maxOutput && provider.maxOutput > 0)
|
|
1273
|
-
? provider.maxOutput
|
|
1274
|
-
: 8_192;
|
|
1275
|
-
const inputLimit = (provider.inputLimit && provider.inputLimit > 0)
|
|
1276
|
-
? provider.inputLimit
|
|
1277
|
-
: undefined;
|
|
1278
|
-
const triggerThreshold = calculateCompactionThreshold(contextLimit, maxOutput, inputLimit);
|
|
1429
|
+
const { contextLimit, maxOutput, inputLimit, threshold: triggerThreshold } = resolveCompactionConfig(provider);
|
|
1279
1430
|
this.compactionDebugTimer = setInterval(() => {
|
|
1280
1431
|
try {
|
|
1281
1432
|
const actualUsed = this.state.accumulatedInputTokens + this.state.accumulatedOutputTokens;
|
|
1282
|
-
const estimatedUsed = estimateConversationTokens(this.state.conversation)
|
|
1433
|
+
const estimatedUsed = estimateConversationTokens(this.state.conversation)
|
|
1434
|
+
+ estimateToolsTokens(this.state.exposedTools);
|
|
1283
1435
|
const effectiveUsed = Math.max(actualUsed, estimatedUsed);
|
|
1284
1436
|
const sizeKB = conversationSizeKB(this.state.conversation);
|
|
1285
1437
|
const isRunning = this.state.started && !this.state.terminated;
|
|
@@ -1329,8 +1481,17 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1329
1481
|
*/
|
|
1330
1482
|
async submit(message) {
|
|
1331
1483
|
const contextVersion = this.contextVersion;
|
|
1332
|
-
|
|
1333
|
-
|
|
1484
|
+
runtimeDebugLog(`[ACodeRuntime] 📬 submit() queued: contextVersion=${contextVersion}, ` +
|
|
1485
|
+
`activeTurn=${this.activeTurn}, abortRequested=${this.abortRequested}, ` +
|
|
1486
|
+
`terminated=${this.state.terminated}, message.length=${message.length}`);
|
|
1487
|
+
const queued = this.submitQueue.then(() => {
|
|
1488
|
+
runtimeDebugLog(`[ACodeRuntime] ▶️ executeSubmit dequeued: contextVersion=${contextVersion}`);
|
|
1489
|
+
return this.executeSubmit(message, contextVersion);
|
|
1490
|
+
});
|
|
1491
|
+
this.submitQueue = queued.catch(() => {
|
|
1492
|
+
runtimeDebugLog(`[ACodeRuntime] 📬 submit() queued item rejected (catch swallowed)`);
|
|
1493
|
+
});
|
|
1494
|
+
runtimeDebugLog(`[ACodeRuntime] 📬 submit() returning queued promise`);
|
|
1334
1495
|
return queued;
|
|
1335
1496
|
}
|
|
1336
1497
|
/**
|
|
@@ -1456,7 +1617,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1456
1617
|
});
|
|
1457
1618
|
// ★ token 用量已在 runModelTurn 中按迭代更新到 state(非累加),
|
|
1458
1619
|
// 此处不再累加,避免 actualUsed 跨轮只增不减导致 shouldCompact 永远为 true。
|
|
1459
|
-
// finalUsage
|
|
1620
|
+
// finalUsage 用于 turn_complete 事件的 usage 上报(当前迭代的上下文用量,覆盖式)。
|
|
1460
1621
|
runtimeDebugLog(`[ACodeRuntime] 💰 Current context usage: ` +
|
|
1461
1622
|
`input=${this.state.accumulatedInputTokens}, ` +
|
|
1462
1623
|
`output=${this.state.accumulatedOutputTokens}` +
|
|
@@ -1492,15 +1653,17 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1492
1653
|
const finallyDuration = Date.now() - turnStartTime;
|
|
1493
1654
|
runtimeDebugLog(`[ACodeRuntime] 🔚 executeSubmit finally block entered after ${finallyDuration}ms`);
|
|
1494
1655
|
runtimeDebugLog(`[ACodeRuntime] 🔍 turnCompleted=${turnCompleted}, activeTurn=${this.activeTurn}, ` +
|
|
1495
|
-
`abortRequested=${this.abortRequested}`
|
|
1656
|
+
`abortRequested=${this.abortRequested}, contextVersion=${contextVersion}, ` +
|
|
1657
|
+
`currentContextVersion=${this.contextVersion}`);
|
|
1496
1658
|
this.activeTurn = false;
|
|
1497
1659
|
this.abortRequested = false;
|
|
1498
1660
|
// 关键修复:如果异常路径没有发射 turn_complete,强制发射一个
|
|
1499
1661
|
// 这确保 adapter 层的 recoverResolvedTurnWithoutTerminalEvent 能够正确触发
|
|
1500
1662
|
if (!turnCompleted && !this.isTurnSuperseded(contextVersion)) {
|
|
1501
|
-
console.error(`[ACodeRuntime] 🚨 CRITICAL: executeSubmit finally block reached without turn_complete event
|
|
1502
|
-
|
|
1503
|
-
|
|
1663
|
+
console.error(`[ACodeRuntime] 🚨 CRITICAL: executeSubmit finally block reached without turn_complete event! ` +
|
|
1664
|
+
`Duration: ${finallyDuration}ms. ` +
|
|
1665
|
+
`This indicates a code path that should have emitted turn_complete but didn't. ` +
|
|
1666
|
+
`Forcing failed turn_complete to prevent state stuck.`);
|
|
1504
1667
|
this.emitAcodeEvent("error", {
|
|
1505
1668
|
message: "ACode turn completed without proper completion event (internal error)",
|
|
1506
1669
|
});
|
|
@@ -1511,8 +1674,19 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1511
1674
|
}
|
|
1512
1675
|
/** 中止当前轮次;由执行轮次统一发出一个终态事件,避免 aborted/failed 双终态。 */
|
|
1513
1676
|
async abort() {
|
|
1677
|
+
const hadController = this.abortController !== null;
|
|
1678
|
+
const wasActiveTurn = this.activeTurn;
|
|
1514
1679
|
this.abortRequested = this.activeTurn;
|
|
1515
|
-
this.abortController
|
|
1680
|
+
if (this.abortController) {
|
|
1681
|
+
runtimeDebugLog(`[ACodeRuntime] ⛔ abort() calling abortController.abort() (activeTurn=${wasActiveTurn})`);
|
|
1682
|
+
this.abortController.abort();
|
|
1683
|
+
}
|
|
1684
|
+
else {
|
|
1685
|
+
console.warn(`[ACodeRuntime] ⛔ abort() called but abortController is null! ` +
|
|
1686
|
+
`activeTurn=${wasActiveTurn}, abortRequested will be set to ${wasActiveTurn}. ` +
|
|
1687
|
+
`This means abort() CANNOT cancel any running fetch/stream — ` +
|
|
1688
|
+
`if a built-in tool is executing, it will NOT be interrupted.`);
|
|
1689
|
+
}
|
|
1516
1690
|
this.abortController = null;
|
|
1517
1691
|
// ask_user_question 等待用户回答期间被 abort,需 reject 所有 waiter
|
|
1518
1692
|
this.rejectAllQuestionWaiters("aborted");
|
|
@@ -1566,7 +1740,12 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1566
1740
|
description: opts.description,
|
|
1567
1741
|
prompt: opts.prompt,
|
|
1568
1742
|
workingDirectory,
|
|
1569
|
-
parentConfig
|
|
1743
|
+
parentConfig: {
|
|
1744
|
+
...parentConfig,
|
|
1745
|
+
// 注入父 agent 的 MCP 连接,子 agent 复用而非启动新 MCP server 进程
|
|
1746
|
+
// 避免 launch binding 已被父 agent 消费后子 agent 401
|
|
1747
|
+
sharedMcpConnections: this.state?.mcpConnections,
|
|
1748
|
+
},
|
|
1570
1749
|
});
|
|
1571
1750
|
// 自动 start(非阻塞,立即返回)
|
|
1572
1751
|
await manager.start(subId);
|
|
@@ -1753,16 +1932,16 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1753
1932
|
const rtOutputTokens = response.usage.completion_tokens ?? response.usage.output_tokens;
|
|
1754
1933
|
if (typeof rtInputTokens === "number" &&
|
|
1755
1934
|
typeof rtOutputTokens === "number") {
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
}
|
|
1935
|
+
// ★ finalUsage 记录当前迭代的实际 token 用量(覆盖式,非累加)。
|
|
1936
|
+
// prompt_tokens 代表本次请求时 provider 看到的完整上下文大小,
|
|
1937
|
+
// 若跨迭代累加会得到 N × 上下文大小 的无意义总和,导致 turn_complete
|
|
1938
|
+
// 上报的 usage 远超真实上下文,前端"上下文"标签会瞬间跳到几 M 再跳回。
|
|
1939
|
+
// 改为覆盖式,与 state.accumulatedInputTokens 及 AcodeSdkAdapter 的
|
|
1940
|
+
// "当前上下文"语义保持一致。
|
|
1941
|
+
finalUsage = {
|
|
1942
|
+
inputTokens: rtInputTokens,
|
|
1943
|
+
outputTokens: rtOutputTokens,
|
|
1944
|
+
};
|
|
1766
1945
|
accumulatedPromptTokens += rtInputTokens;
|
|
1767
1946
|
// ★ 更新 state 为当前迭代的实际 token 用量(非累加)
|
|
1768
1947
|
// prompt_tokens 代表本次请求时 provider 看到的完整上下文大小,
|
|
@@ -1771,7 +1950,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1771
1950
|
this.state.accumulatedInputTokens = rtInputTokens;
|
|
1772
1951
|
this.state.accumulatedOutputTokens = rtOutputTokens;
|
|
1773
1952
|
runtimeDebugLog(`[ACodeRuntime] 💰 Token usage: input=${rtInputTokens}, output=${rtOutputTokens} ` +
|
|
1774
|
-
`(turn accumulated: input=${accumulatedPromptTokens}
|
|
1953
|
+
`(turn accumulated cost: input=${accumulatedPromptTokens})`);
|
|
1775
1954
|
}
|
|
1776
1955
|
}
|
|
1777
1956
|
this.state.conversation.push({
|
|
@@ -1881,7 +2060,14 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1881
2060
|
abortController.abort();
|
|
1882
2061
|
});
|
|
1883
2062
|
if (!response.ok) {
|
|
1884
|
-
|
|
2063
|
+
// ★ 防御修复:用 withTimeout 包裹 response.text(),防止错误响应 body stream 挂起
|
|
2064
|
+
const errorBody = await withTimeout(response.text(), provider.requestTimeoutMs, "ACode LLM summarization error response body", () => {
|
|
2065
|
+
abortController.abort();
|
|
2066
|
+
});
|
|
2067
|
+
const truncatedBody = errorBody.length > 500
|
|
2068
|
+
? `${errorBody.slice(0, 500)}...(truncated, total ${errorBody.length} chars)`
|
|
2069
|
+
: errorBody;
|
|
2070
|
+
throw new Error(`ACode LLM summarization request failed: ${response.status} ${truncatedBody}`);
|
|
1885
2071
|
}
|
|
1886
2072
|
const payload = (await response.json());
|
|
1887
2073
|
const content = payload.choices?.[0]?.message?.content;
|
|
@@ -1896,28 +2082,17 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1896
2082
|
if (!baseURL) {
|
|
1897
2083
|
throw new Error("ACode provider baseURL is not configured");
|
|
1898
2084
|
}
|
|
1899
|
-
// 主动上下文压缩:在发送 AI 请求前检测 token
|
|
1900
|
-
//
|
|
1901
|
-
|
|
1902
|
-
const contextLimit = (provider.contextLimit && provider.contextLimit > 0)
|
|
1903
|
-
? provider.contextLimit
|
|
1904
|
-
: FALLBACK_CONTEXT_LIMIT;
|
|
1905
|
-
const maxOutput = (provider.maxOutput && provider.maxOutput > 0)
|
|
1906
|
-
? provider.maxOutput
|
|
1907
|
-
: 8_192;
|
|
1908
|
-
// ★ 融合 OpenCode 预算思路:优先用 inputLimit(部分 Provider input+output 总额 ≠ context 上限)
|
|
1909
|
-
// 未配置 inputLimit 时降级到 contextLimit,行为与改进前一致。
|
|
1910
|
-
const inputLimit = (provider.inputLimit && provider.inputLimit > 0)
|
|
1911
|
-
? provider.inputLimit
|
|
1912
|
-
: undefined;
|
|
1913
|
-
// ★ 阈值 = min(contextLimit × 55%, hardLimit - reserved)
|
|
1914
|
-
// hardLimit = inputLimit ?? contextLimit
|
|
1915
|
-
// reserved = min(COMPACTION_BUFFER, maxOutput) // buffer 不超过输出上限
|
|
1916
|
-
const compactionThreshold = calculateCompactionThreshold(contextLimit, maxOutput, inputLimit);
|
|
2085
|
+
// 主动上下文压缩:在发送 AI 请求前检测 token 是否溢出。
|
|
2086
|
+
// ★ 与 session_started 事件 emit 的阈值同源(resolveCompactionConfig),保证前端显示 = 实际触发。
|
|
2087
|
+
const { contextLimit, maxOutput, inputLimit, threshold: compactionThreshold } = resolveCompactionConfig(provider);
|
|
1917
2088
|
// 使用 effectiveUsed = max(actualUsed, estimatedUsed)
|
|
1918
2089
|
// 因为部分 provider 不返回 usage 数据(actualUsed=0),此时降级到文本估算
|
|
1919
2090
|
const actualUsed = this.state.accumulatedInputTokens + this.state.accumulatedOutputTokens;
|
|
1920
|
-
|
|
2091
|
+
// ★ 估算时加入 tools 定义开销,使估算更接近实际请求 token 数。
|
|
2092
|
+
// 之前只估算 conversation 消息,遗漏了 tools 的 JSON schema(可达数千 tokens),
|
|
2093
|
+
// 导致估算系统性偏低、主动压缩阈值无法触达。
|
|
2094
|
+
const estimatedUsed = estimateConversationTokens(this.state.conversation)
|
|
2095
|
+
+ estimateToolsTokens(this.state.exposedTools);
|
|
1921
2096
|
const effectiveUsed = Math.max(actualUsed, estimatedUsed);
|
|
1922
2097
|
const shouldCompact = effectiveUsed >= compactionThreshold;
|
|
1923
2098
|
runtimeDebugLog(`[ACodeRuntime] 🔍 Compaction check: ` +
|
|
@@ -1944,6 +2119,9 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1944
2119
|
const result = await performCompaction(this.state.conversation, contextLimit, maxOutput, {
|
|
1945
2120
|
llmSummarizer: (input) => this.summarizeConversationWithLLM(input),
|
|
1946
2121
|
onPhase: (phaseEvent) => this.handleCompactionPhase(compactionId, phaseEvent),
|
|
2122
|
+
// 传入 effectiveUsed 修复文本估算低于实际 token 数时
|
|
2123
|
+
// post-prune isOverflow 误判导致 summarize 被跳过的问题
|
|
2124
|
+
actualUsedTokens: effectiveUsed,
|
|
1947
2125
|
});
|
|
1948
2126
|
const sizeAfterKB = conversationSizeKB(this.state.conversation);
|
|
1949
2127
|
this.emitAcodeEvent("context_compaction", {
|
|
@@ -1954,6 +2132,8 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1954
2132
|
freedKB: Math.round((sizeBeforeKB - sizeAfterKB) * 10) / 10,
|
|
1955
2133
|
strategy: result.strategy,
|
|
1956
2134
|
freedTokens: result.freedTokens,
|
|
2135
|
+
tokensBefore: result.tokensBefore,
|
|
2136
|
+
tokensAfter: result.tokensAfter,
|
|
1957
2137
|
prunedToolMessages: result.prunedToolMessages,
|
|
1958
2138
|
summarizedMessages: result.summarizedMessages,
|
|
1959
2139
|
messageCountBefore: result.messageCountBefore,
|
|
@@ -1981,6 +2161,16 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
1981
2161
|
messages: this.state.conversation,
|
|
1982
2162
|
stream: provider.stream,
|
|
1983
2163
|
};
|
|
2164
|
+
// ★ 思考强度:写入 reasoning_effort 字段,兼容 OpenAI o-series 及兼容 API。
|
|
2165
|
+
// 未配置 effort 时不写入,由 provider 使用默认值。
|
|
2166
|
+
if (provider.effort) {
|
|
2167
|
+
body.reasoning_effort = provider.effort;
|
|
2168
|
+
}
|
|
2169
|
+
// ★ 流式请求必须设置 stream_options.include_usage,否则 provider 不返回 usage,
|
|
2170
|
+
// 导致 accumulatedInputTokens 永远为 0,主动压缩无法基于实际用量触发。
|
|
2171
|
+
if (provider.stream) {
|
|
2172
|
+
body.stream_options = { include_usage: true };
|
|
2173
|
+
}
|
|
1984
2174
|
if (allowedTools.length > 0) {
|
|
1985
2175
|
body.tools = toOpenAiTools(allowedTools);
|
|
1986
2176
|
body.tool_choice = "auto";
|
|
@@ -2011,9 +2201,10 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2011
2201
|
};
|
|
2012
2202
|
let body = buildBody();
|
|
2013
2203
|
emitAiRequest(body);
|
|
2014
|
-
const
|
|
2204
|
+
const infiniteRetries = provider.requestRetryCount === INFINITE_RETRY_SENTINEL;
|
|
2205
|
+
const maxAttempts = infiniteRetries ? Infinity : provider.requestRetryCount + 1;
|
|
2015
2206
|
let contextOverflowCompacted = false;
|
|
2016
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
2207
|
+
for (let attempt = 1; infiniteRetries || attempt <= maxAttempts; attempt += 1) {
|
|
2017
2208
|
const requestAbortController = new AbortController();
|
|
2018
2209
|
this.abortController = requestAbortController;
|
|
2019
2210
|
let timedOut = false;
|
|
@@ -2029,7 +2220,20 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2029
2220
|
requestAbortController.abort();
|
|
2030
2221
|
});
|
|
2031
2222
|
if (!response.ok) {
|
|
2032
|
-
|
|
2223
|
+
// ★ 防御修复:用 withTimeout 包裹 response.text(),
|
|
2224
|
+
// 防止 502/503 等错误响应的 body stream 挂起导致永久阻塞。
|
|
2225
|
+
// 外层 withTimeout(requestTotalTimeoutMs, 10min) 兜底太晚,
|
|
2226
|
+
// 且看门狗可能已被重试 error 事件禁用。
|
|
2227
|
+
const errorBody = await withTimeout(response.text(), provider.requestTimeoutMs, "ACode provider error response body", () => {
|
|
2228
|
+
timedOut = true;
|
|
2229
|
+
requestAbortController.abort();
|
|
2230
|
+
});
|
|
2231
|
+
// ★ 截断过长的错误响应体(如 Cloudflare 502 HTML 页面可达数 KB),
|
|
2232
|
+
// 避免错误消息通过事件链路传播时造成 HTTP POST body 过大或日志膨胀
|
|
2233
|
+
const truncatedBody = errorBody.length > 500
|
|
2234
|
+
? `${errorBody.slice(0, 500)}...(truncated, total ${errorBody.length} chars)`
|
|
2235
|
+
: errorBody;
|
|
2236
|
+
throw new Error(`ACode provider request failed: ${response.status} ${truncatedBody}`);
|
|
2033
2237
|
}
|
|
2034
2238
|
const contentType = response.headers?.get?.("content-type") || "";
|
|
2035
2239
|
if (provider.stream &&
|
|
@@ -2049,7 +2253,14 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2049
2253
|
return {};
|
|
2050
2254
|
}
|
|
2051
2255
|
return payload;
|
|
2052
|
-
})(),
|
|
2256
|
+
})(),
|
|
2257
|
+
// ★ 安全修复:即使无限重试也保留总预算超时兜底,
|
|
2258
|
+
// 防止 provider 持续发送 SSE keep-alive 导致 idle timeout 永不触发、
|
|
2259
|
+
// 请求永久挂起。用户可通过配置更大的 requestTotalTimeoutMs 值来放宽限制。
|
|
2260
|
+
provider.requestTotalTimeoutMs, "ACode provider request total", () => {
|
|
2261
|
+
// 总预算超时:abort 底层 fetch / stream reader,避免泄漏
|
|
2262
|
+
requestAbortController.abort();
|
|
2263
|
+
});
|
|
2053
2264
|
}
|
|
2054
2265
|
catch (error) {
|
|
2055
2266
|
let requestError;
|
|
@@ -2070,12 +2281,14 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2070
2281
|
// 这里不通过 performCompaction(它会先检查 isOverflow),
|
|
2071
2282
|
// 而是直接调用 summarizeConversation 进行强制摘要化
|
|
2072
2283
|
const sizeBeforeKB = conversationSizeKB(this.state.conversation);
|
|
2284
|
+
const tokensBeforeOC = estimateConversationTokens(this.state.conversation); // tokensBefore 命名冲突,加 OC 后缀
|
|
2073
2285
|
const msgCountBefore = this.state.conversation.length;
|
|
2074
2286
|
const compactionId = `compaction-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
2075
2287
|
this.emitAcodeEvent("context_compaction", {
|
|
2076
2288
|
action: "start",
|
|
2077
2289
|
compactionId,
|
|
2078
2290
|
sizeKB: sizeBeforeKB,
|
|
2291
|
+
estimatedTokens: tokensBeforeOC,
|
|
2079
2292
|
messageCount: msgCountBefore,
|
|
2080
2293
|
model: provider.model,
|
|
2081
2294
|
trigger: "provider_overflow_error",
|
|
@@ -2094,6 +2307,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2094
2307
|
});
|
|
2095
2308
|
this.emitCompactionPhase(compactionId, "summarize_done", "阶段2: 摘要化对话", `摘要化了 ${summarizedCount} 条消息`);
|
|
2096
2309
|
const sizeAfterKB = conversationSizeKB(this.state.conversation);
|
|
2310
|
+
const tokensAfterOC = estimateConversationTokens(this.state.conversation);
|
|
2097
2311
|
const msgCountAfter = this.state.conversation.length;
|
|
2098
2312
|
contextOverflowCompacted = true;
|
|
2099
2313
|
const compactedCount = pruneResult.prunedCount + summarizedCount;
|
|
@@ -2103,6 +2317,8 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2103
2317
|
sizeBeforeKB,
|
|
2104
2318
|
sizeAfterKB,
|
|
2105
2319
|
freedKB: Math.round((sizeBeforeKB - sizeAfterKB) * 10) / 10,
|
|
2320
|
+
tokensBefore: tokensBeforeOC,
|
|
2321
|
+
tokensAfter: tokensAfterOC,
|
|
2106
2322
|
messageCountBefore: msgCountBefore,
|
|
2107
2323
|
messageCountAfter: msgCountAfter,
|
|
2108
2324
|
strategy: summarizedCount > 0 ? "summarize" : "prune",
|
|
@@ -2125,7 +2341,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2125
2341
|
attempt -= 1;
|
|
2126
2342
|
continue;
|
|
2127
2343
|
}
|
|
2128
|
-
const shouldRetry = attempt < maxAttempts &&
|
|
2344
|
+
const shouldRetry = (infiniteRetries || attempt < maxAttempts) &&
|
|
2129
2345
|
!this.abortRequested &&
|
|
2130
2346
|
!this.state.terminated &&
|
|
2131
2347
|
isRetryableProviderRequestError(requestError);
|
|
@@ -2133,7 +2349,11 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2133
2349
|
throw requestError;
|
|
2134
2350
|
}
|
|
2135
2351
|
this.emitAcodeEvent("error", {
|
|
2136
|
-
message: `ACode provider request attempt ${attempt}
|
|
2352
|
+
message: `ACode provider request attempt ${attempt}${infiniteRetries ? '' : `/${maxAttempts}`} failed; retrying: ${requestError.message}`,
|
|
2353
|
+
// ★ 关键修复:重试中的错误是瞬态的,不是致命错误。
|
|
2354
|
+
// 如果不标记 nonFatal,适配器会把 status 设为 "error" 并取消看门狗,
|
|
2355
|
+
// 导致后续重试尝试挂起时看门狗无法检测,agent 永久卡死。
|
|
2356
|
+
nonFatal: true,
|
|
2137
2357
|
});
|
|
2138
2358
|
await delay(DEFAULT_PROVIDER_REQUEST_RETRY_DELAY_MS * attempt);
|
|
2139
2359
|
}
|
|
@@ -2226,14 +2446,20 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2226
2446
|
}
|
|
2227
2447
|
const toolName = toolCall.function.name;
|
|
2228
2448
|
runtimeDebugLog(`[ACodeRuntime] 🔍 Looking up tool: ${toolName}`);
|
|
2229
|
-
|
|
2449
|
+
let tool = this.state.exposedTools.find((item) => item.exposedName === toolName);
|
|
2450
|
+
if (!tool) {
|
|
2451
|
+
tool = this.state.exposedTools.find((item) => item.toolName === toolName);
|
|
2452
|
+
if (tool) {
|
|
2453
|
+
runtimeDebugLog(`[ACodeRuntime] ↩️ 裸名回退匹配: ${toolName} -> ${tool.exposedName}`);
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2230
2456
|
if (!tool) {
|
|
2231
|
-
console.error(`[ACodeRuntime] ❌ Tool not found: ${
|
|
2457
|
+
console.error(`[ACodeRuntime] ❌ Tool not found: ${toolName}, ` +
|
|
2232
2458
|
`available tools: ${this.state.exposedTools.map(t => t.exposedName).join(", ")}`);
|
|
2233
2459
|
this.state.conversation.push({
|
|
2234
2460
|
role: "tool",
|
|
2235
2461
|
tool_call_id: toolCall.id,
|
|
2236
|
-
content: `ACode MCP tool not found: ${
|
|
2462
|
+
content: `ACode MCP tool not found: ${toolName}`,
|
|
2237
2463
|
});
|
|
2238
2464
|
continue;
|
|
2239
2465
|
}
|
|
@@ -2269,7 +2495,13 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2269
2495
|
argumentsPreview: summarizeToolArguments(toolArguments),
|
|
2270
2496
|
});
|
|
2271
2497
|
const toolStart = Date.now();
|
|
2272
|
-
|
|
2498
|
+
const toolTimeoutMs = getBuiltInToolTimeoutMs(tool, toolArguments, this.state.provider.mcpToolTimeoutMs);
|
|
2499
|
+
runtimeDebugLog(`[ACodeRuntime] ▶️ Executing built-in tool: ${tool.exposedName} ` +
|
|
2500
|
+
`(timeout: ${toolTimeoutMs}ms, abortRequested: ${this.abortRequested})`);
|
|
2501
|
+
if (toolTimeoutMs <= 0) {
|
|
2502
|
+
console.warn(`[ACodeRuntime] ⚠️ Built-in tool ${tool.exposedName} has NO timeout (timeoutMs=${toolTimeoutMs})! ` +
|
|
2503
|
+
`If this tool hangs, executeSubmit will NEVER resolve, blocking the submit queue permanently.`);
|
|
2504
|
+
}
|
|
2273
2505
|
const result = await withTimeout(tool.execute(toolArguments, {
|
|
2274
2506
|
onOutput: (outputEvent) => {
|
|
2275
2507
|
this.emitAcodeEvent("command_output", {
|
|
@@ -2288,7 +2520,7 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2288
2520
|
});
|
|
2289
2521
|
},
|
|
2290
2522
|
toolCallId: toolCall.id,
|
|
2291
|
-
}),
|
|
2523
|
+
}), toolTimeoutMs, `ACode built-in tool ${tool.toolName}`);
|
|
2292
2524
|
const toolDuration = Date.now() - toolStart;
|
|
2293
2525
|
runtimeDebugLog(`[ACodeRuntime] ✅ Built-in tool ${tool.exposedName} completed in ${toolDuration}ms`);
|
|
2294
2526
|
if (this.isTurnSuperseded(contextVersion)) {
|
|
@@ -2367,7 +2599,11 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2367
2599
|
const toolStart = Date.now();
|
|
2368
2600
|
runtimeDebugLog(`[ACodeRuntime] ▶️ Executing MCP tool: ${tool.exposedName} ` +
|
|
2369
2601
|
`(timeout: ${toolTimeoutMs}ms, polling: ${isPollingTool})`);
|
|
2370
|
-
|
|
2602
|
+
// poll_message 工具需要同时检测子 agent 完成事件(有就返回类型),
|
|
2603
|
+
// 使用 sub-agent race 包装器替代直接 MCP 调用。
|
|
2604
|
+
const result = isPollingTool && getSemanticToolName(tool.toolName) === "poll_message"
|
|
2605
|
+
? await this.callPollMessageWithSubAgentRace(connection, tool, toolArguments, toolTimeoutMs)
|
|
2606
|
+
: await this.callMcpToolWithTimeout(connection, tool, toolArguments, toolTimeoutMs, isPollingTool);
|
|
2371
2607
|
const toolDuration = Date.now() - toolStart;
|
|
2372
2608
|
runtimeDebugLog(`[ACodeRuntime] ✅ MCP tool ${tool.exposedName} completed in ${toolDuration}ms`);
|
|
2373
2609
|
if (this.isTurnSuperseded(contextVersion)) {
|
|
@@ -2400,14 +2636,37 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2400
2636
|
await this.appendSyntheticMultimodalUserMessage(resultText, toolCall.id, contextVersion);
|
|
2401
2637
|
}
|
|
2402
2638
|
catch (error) {
|
|
2403
|
-
|
|
2639
|
+
const isTimeout = error instanceof Error &&
|
|
2640
|
+
error.message.includes("timed out after");
|
|
2641
|
+
const isAbortError = error instanceof Error &&
|
|
2642
|
+
error.name === "AbortError";
|
|
2643
|
+
console.error(`[ACodeRuntime] ❌ Tool execution failed: ${toolCall.function.name}`, `isTimeout=${isTimeout}, isAbortError=${isAbortError}`, error instanceof Error ? error.message : String(error));
|
|
2404
2644
|
if (this.isTurnSuperseded(contextVersion)) {
|
|
2645
|
+
runtimeDebugLog(`[ACodeRuntime] ️ Turn superseded after tool error, skipping`);
|
|
2405
2646
|
return;
|
|
2406
2647
|
}
|
|
2407
2648
|
if (this.abortRequested || this.state.terminated) {
|
|
2408
|
-
|
|
2649
|
+
// ★ 修复 BUG(时间线永久卡在"编辑文件"):
|
|
2650
|
+
// abort/termination 时原实现直接 rethrow,跳过 appendToolFailureResult
|
|
2651
|
+
// (3752 行的 mcp_status tool_result 发射),导致 adapter 永远收不到 tool_result,
|
|
2652
|
+
// tool_use_end 永不发射,前端时间线永久卡在 tool_use_start 创建的工具条目。
|
|
2653
|
+
// 修复:在 rethrow 前补发一个带 failed=true 的 tool_result,关闭时间线条目。
|
|
2654
|
+
runtimeDebugLog(`[ACodeRuntime] ⚠️ Rethrowing error due to abort/termination ` +
|
|
2655
|
+
`(abortRequested=${this.abortRequested}, terminated=${this.state.terminated})`);
|
|
2656
|
+
runtimeDebugLog(`[ACodeRuntime] 📤 Emitting mcp_status tool_result (failed, aborted) ` +
|
|
2657
|
+
`for ${tool.exposedName} before rethrow to close timeline entry`);
|
|
2658
|
+
this.emitAcodeEvent("mcp_status", {
|
|
2659
|
+
action: "tool_result",
|
|
2660
|
+
server: tool.kind === "mcp" ? tool.serverName : "builtin",
|
|
2661
|
+
tool: tool.toolName,
|
|
2662
|
+
result: `[aborted] ${error instanceof Error ? error.message : String(error)}`,
|
|
2663
|
+
failed: true,
|
|
2664
|
+
aborted: true,
|
|
2665
|
+
});
|
|
2409
2666
|
throw error instanceof Error ? error : new Error(String(error));
|
|
2410
2667
|
}
|
|
2668
|
+
runtimeDebugLog(`[ACodeRuntime] Calling appendToolFailureResult for ${tool.exposedName} ` +
|
|
2669
|
+
`(isTimeout=${isTimeout})`);
|
|
2411
2670
|
this.appendToolFailureResult(toolCall, tool, error);
|
|
2412
2671
|
}
|
|
2413
2672
|
}
|
|
@@ -2415,13 +2674,19 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2415
2674
|
}
|
|
2416
2675
|
async callMcpToolWithTimeout(connection, tool, toolArguments, timeoutMs, retrySdkTimeout) {
|
|
2417
2676
|
const sdkTimeout = timeoutMs > 0 ? timeoutMs : MCP_SDK_MAX_SAFE_TIMEOUT_MS;
|
|
2677
|
+
// 子 agent 共享父 agent 的 MCP 连接时,注入标记让 MCP server 跳过状态上报
|
|
2678
|
+
// (StatusReporter 绑定父 agentId,子 agent 的事件不应出现在父 agent 时间线上)
|
|
2679
|
+
const isSubAgent = Boolean(this.config.sharedMcpConnections);
|
|
2680
|
+
const finalArguments = isSubAgent
|
|
2681
|
+
? { ...toolArguments, _aws_sub_agent: true }
|
|
2682
|
+
: toolArguments;
|
|
2418
2683
|
while (true) {
|
|
2419
2684
|
const stopWaiter = this.createRuntimeStopWaiter(`ACode MCP tool ${tool.serverName}/${tool.toolName}`);
|
|
2420
2685
|
try {
|
|
2421
2686
|
return await withTimeout(Promise.race([
|
|
2422
2687
|
connection.client.callTool({
|
|
2423
2688
|
name: tool.toolName,
|
|
2424
|
-
arguments:
|
|
2689
|
+
arguments: finalArguments,
|
|
2425
2690
|
}, undefined, { timeout: sdkTimeout }),
|
|
2426
2691
|
stopWaiter.promise,
|
|
2427
2692
|
]), timeoutMs, `ACode MCP tool ${tool.serverName}/${tool.toolName}`);
|
|
@@ -2441,6 +2706,568 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2441
2706
|
}
|
|
2442
2707
|
}
|
|
2443
2708
|
}
|
|
2709
|
+
/**
|
|
2710
|
+
* 将子 agent 终态通知转为 poll_message 格式的合成 DirectMessage。
|
|
2711
|
+
* 主流程:构建符合 MCP poll_message 返回格式的 JSON 字符串。
|
|
2712
|
+
*/
|
|
2713
|
+
static formatSubAgentCompletionAsPollResult(notifications) {
|
|
2714
|
+
const directMessages = notifications.map((n) => {
|
|
2715
|
+
const summary = n.error
|
|
2716
|
+
? `Sub-agent ${n.subId} [${n.status}]: ${n.description}\nError: ${n.error}`
|
|
2717
|
+
: `Sub-agent ${n.subId} [${n.status}]: ${n.description}\nOutput: ${n.output.length > 500 ? n.output.slice(0, 500) + "... (truncated)" : n.output}`;
|
|
2718
|
+
return {
|
|
2719
|
+
msgId: `subagent-completion-${n.subId}-${Date.now()}`,
|
|
2720
|
+
senderId: "ACode-Runtime",
|
|
2721
|
+
senderName: "系统",
|
|
2722
|
+
content: summary,
|
|
2723
|
+
requireReply: false,
|
|
2724
|
+
prompt: `Sub-agent ${n.subId} (${n.description}) has reached terminal state: ${n.status}. Review its output and decide next steps.`,
|
|
2725
|
+
timestamp: new Date().toISOString(),
|
|
2726
|
+
};
|
|
2727
|
+
});
|
|
2728
|
+
return {
|
|
2729
|
+
content: [
|
|
2730
|
+
{
|
|
2731
|
+
type: "text",
|
|
2732
|
+
text: JSON.stringify({
|
|
2733
|
+
directMessages,
|
|
2734
|
+
groupMessages: [],
|
|
2735
|
+
fromBuffer: false,
|
|
2736
|
+
systemMessages: [],
|
|
2737
|
+
}, null, 2),
|
|
2738
|
+
},
|
|
2739
|
+
],
|
|
2740
|
+
};
|
|
2741
|
+
}
|
|
2742
|
+
/**
|
|
2743
|
+
* 将子 agent 终态通知合并到已有的 MCP poll_message 返回结果中。
|
|
2744
|
+
* 主流程:解析 MCP 返回的 JSON -> 将通知转为 DirectMessage 插入到 directMessages 前面 -> 重新序列化。
|
|
2745
|
+
*/
|
|
2746
|
+
static mergeSubAgentCompletionsIntoMcpResult(mcpResult, notifications) {
|
|
2747
|
+
if (notifications.length === 0)
|
|
2748
|
+
return mcpResult;
|
|
2749
|
+
// 提取 MCP 结果中的文本
|
|
2750
|
+
const resultText = toToolResultText(mcpResult);
|
|
2751
|
+
let parsed;
|
|
2752
|
+
try {
|
|
2753
|
+
parsed = JSON.parse(resultText);
|
|
2754
|
+
}
|
|
2755
|
+
catch {
|
|
2756
|
+
// 如果 MCP 结果不是 JSON(异常情况),直接返回原结果
|
|
2757
|
+
return mcpResult;
|
|
2758
|
+
}
|
|
2759
|
+
const subAgentMessages = notifications.map((n) => {
|
|
2760
|
+
const summary = n.error
|
|
2761
|
+
? `Sub-agent ${n.subId} [${n.status}]: ${n.description}\nError: ${n.error}`
|
|
2762
|
+
: `Sub-agent ${n.subId} [${n.status}]: ${n.description}\nOutput: ${n.output.length > 500 ? n.output.slice(0, 500) + "... (truncated)" : n.output}`;
|
|
2763
|
+
return {
|
|
2764
|
+
msgId: `subagent-completion-${n.subId}-${Date.now()}`,
|
|
2765
|
+
senderId: "ACode-Runtime",
|
|
2766
|
+
senderName: "系统",
|
|
2767
|
+
content: summary,
|
|
2768
|
+
requireReply: false,
|
|
2769
|
+
prompt: `Sub-agent ${n.subId} (${n.description}) has reached terminal state: ${n.status}. Review its output and decide next steps.`,
|
|
2770
|
+
timestamp: new Date().toISOString(),
|
|
2771
|
+
};
|
|
2772
|
+
});
|
|
2773
|
+
const mergedDirectMessages = [
|
|
2774
|
+
...subAgentMessages,
|
|
2775
|
+
...(parsed.directMessages ?? []),
|
|
2776
|
+
];
|
|
2777
|
+
return {
|
|
2778
|
+
content: [
|
|
2779
|
+
{
|
|
2780
|
+
type: "text",
|
|
2781
|
+
text: JSON.stringify({
|
|
2782
|
+
...parsed,
|
|
2783
|
+
directMessages: mergedDirectMessages,
|
|
2784
|
+
}, null, 2),
|
|
2785
|
+
},
|
|
2786
|
+
],
|
|
2787
|
+
};
|
|
2788
|
+
}
|
|
2789
|
+
/**
|
|
2790
|
+
* Memory 自动委托 sub-agent 完成一轮后的外部重新检查。
|
|
2791
|
+
*
|
|
2792
|
+
* 查询服务端 memory 真实状态(通过 MCP 工具直接调用,非 LLM 自报),
|
|
2793
|
+
* 判断 sub-agent 是否真正完成了处理:
|
|
2794
|
+
* - memory_file_change:检查每条 memory 的 memory_status 是否已回到 normal
|
|
2795
|
+
* - memory_expiration:检查每条 memory 是否已续期(expiresAt 在未来)或已清理(read 返回 null)
|
|
2796
|
+
* - memory_cleanup:检查 get_memory_stats 中对应类型/域是否仍 exceeded
|
|
2797
|
+
*
|
|
2798
|
+
* 若仍有未完成项,返回 { done: false, continueMessage } 包含 "经检查,未完成对xxx的处理,请继续"
|
|
2799
|
+
* 及具体未完成列表,由 SubAgentManager 注入同一 sub-agent 的下一轮 submit。
|
|
2800
|
+
*
|
|
2801
|
+
* recheck 自身出错(MCP 连接不可用、工具调用超时等)时返回 { done: true },不阻塞 sub-agent 结束。
|
|
2802
|
+
*/
|
|
2803
|
+
async recheckMemoryDelegate(type, uris, output, turn) {
|
|
2804
|
+
const connection = this.state.mcpConnections.find((c) => c.serverName === 'aws-client-agent-mcp');
|
|
2805
|
+
if (!connection) {
|
|
2806
|
+
runtimeDebugLog(`[ACodeRuntime] recheckMemoryDelegate: aws-client-agent-mcp connection not found, treating as done`);
|
|
2807
|
+
return { done: true };
|
|
2808
|
+
}
|
|
2809
|
+
try {
|
|
2810
|
+
if (type === 'memory_file_change') {
|
|
2811
|
+
return await this.recheckMemoryFileChange(connection, uris);
|
|
2812
|
+
}
|
|
2813
|
+
if (type === 'memory_expiration') {
|
|
2814
|
+
return await this.recheckMemoryExpiration(connection, uris);
|
|
2815
|
+
}
|
|
2816
|
+
return await this.recheckMemoryCleanup(connection, uris);
|
|
2817
|
+
}
|
|
2818
|
+
catch (err) {
|
|
2819
|
+
runtimeDebugLog(`[ACodeRuntime] recheckMemoryDelegate failed (type=${type}, turn=${turn}): ` +
|
|
2820
|
+
`${err instanceof Error ? err.message : String(err)}, treating as done`);
|
|
2821
|
+
return { done: true };
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
/**
|
|
2825
|
+
* 通过 MCP read_memory 工具读取单条 memory 记录。
|
|
2826
|
+
* 注入 _aws_sub_agent=true 避免状态上报污染父 agent 时间线。
|
|
2827
|
+
* 返回 null 表示 memory 不存在或读取失败。
|
|
2828
|
+
*/
|
|
2829
|
+
async readMemoryViaMcp(connection, uri) {
|
|
2830
|
+
try {
|
|
2831
|
+
const result = await withTimeout(connection.client.callTool({
|
|
2832
|
+
name: 'read_memory',
|
|
2833
|
+
arguments: { uri, _aws_sub_agent: true },
|
|
2834
|
+
}, undefined, { timeout: 30_000 }), 30_000, `recheck read_memory ${uri}`);
|
|
2835
|
+
const text = toToolResultText(result);
|
|
2836
|
+
const parsed = JSON.parse(text);
|
|
2837
|
+
if (parsed === null || parsed === undefined)
|
|
2838
|
+
return null;
|
|
2839
|
+
if (typeof parsed !== 'object' || Array.isArray(parsed))
|
|
2840
|
+
return null;
|
|
2841
|
+
return parsed;
|
|
2842
|
+
}
|
|
2843
|
+
catch {
|
|
2844
|
+
return null;
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
/** recheck memory_file_change:检查 memory_status 是否仍为 updating */
|
|
2848
|
+
async recheckMemoryFileChange(connection, uris) {
|
|
2849
|
+
const stillUpdating = [];
|
|
2850
|
+
await Promise.all(uris.map(async (uri) => {
|
|
2851
|
+
const mem = await this.readMemoryViaMcp(connection, uri);
|
|
2852
|
+
if (mem && mem.memory_status === 'updating') {
|
|
2853
|
+
stillUpdating.push(uri);
|
|
2854
|
+
}
|
|
2855
|
+
}));
|
|
2856
|
+
if (stillUpdating.length === 0) {
|
|
2857
|
+
runtimeDebugLog(`[ACodeRuntime] recheck memory_file_change: all ${uris.length} URIs done (memory_status=normal or deleted)`);
|
|
2858
|
+
return { done: true };
|
|
2859
|
+
}
|
|
2860
|
+
const list = stillUpdating.map((u) => `- ${u}`).join('\n');
|
|
2861
|
+
runtimeDebugLog(`[ACodeRuntime] recheck memory_file_change: ${stillUpdating.length}/${uris.length} URIs still updating`);
|
|
2862
|
+
return {
|
|
2863
|
+
done: false,
|
|
2864
|
+
continueMessage: `经检查,未完成对以下 memory 的更新,请继续:\n${list}\n\n` +
|
|
2865
|
+
`这些 memory 的 memory_status 仍为 "updating"。请重新 read_memory 查看内容,` +
|
|
2866
|
+
`查看绑定文件最新内容,并调用 update_memory 完成更新。`,
|
|
2867
|
+
};
|
|
2868
|
+
}
|
|
2869
|
+
/** recheck memory_expiration:检查 expiresAt 是否仍过期 或 memory_status 是否仍为 recalling */
|
|
2870
|
+
async recheckMemoryExpiration(connection, uris) {
|
|
2871
|
+
const stillExpired = [];
|
|
2872
|
+
const now = Date.now();
|
|
2873
|
+
await Promise.all(uris.map(async (uri) => {
|
|
2874
|
+
const mem = await this.readMemoryViaMcp(connection, uri);
|
|
2875
|
+
if (!mem)
|
|
2876
|
+
return; // memory 已删除/不存在 → 视为已处理
|
|
2877
|
+
const expiresAt = mem.expiresAt ?? mem.expires_at;
|
|
2878
|
+
const isRecalling = mem.memory_status === 'recalling';
|
|
2879
|
+
const isExpired = typeof expiresAt === 'string' && new Date(expiresAt).getTime() < now;
|
|
2880
|
+
if (isRecalling || isExpired) {
|
|
2881
|
+
stillExpired.push(uri);
|
|
2882
|
+
}
|
|
2883
|
+
}));
|
|
2884
|
+
if (stillExpired.length === 0) {
|
|
2885
|
+
runtimeDebugLog(`[ACodeRuntime] recheck memory_expiration: all ${uris.length} URIs done (renewed, cleaned, or no longer expired)`);
|
|
2886
|
+
return { done: true };
|
|
2887
|
+
}
|
|
2888
|
+
const list = stillExpired.map((u) => `- ${u}`).join('\n');
|
|
2889
|
+
runtimeDebugLog(`[ACodeRuntime] recheck memory_expiration: ${stillExpired.length}/${uris.length} URIs still expired or recalling`);
|
|
2890
|
+
return {
|
|
2891
|
+
done: false,
|
|
2892
|
+
continueMessage: `经检查,未完成对以下 memory 的处理,请继续:\n${list}\n\n` +
|
|
2893
|
+
`这些 memory 仍处于过期或回忆中状态。请调用 memory_recurrence 获取内容,` +
|
|
2894
|
+
`对需要保留的调用 update_memory 续期,对无价值的调用 memory_recurrence_complete 清理。`,
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
/** recheck memory_cleanup:检查 get_memory_stats 中对应类型/域是否仍 exceeded */
|
|
2898
|
+
async recheckMemoryCleanup(connection, uris) {
|
|
2899
|
+
// delegate URIs 格式为 "${memoryType}/${domain}"
|
|
2900
|
+
let stats;
|
|
2901
|
+
try {
|
|
2902
|
+
const result = await withTimeout(connection.client.callTool({
|
|
2903
|
+
name: 'get_memory_stats',
|
|
2904
|
+
arguments: { _aws_sub_agent: true },
|
|
2905
|
+
}, undefined, { timeout: 30_000 }), 30_000, 'recheck get_memory_stats');
|
|
2906
|
+
const text = toToolResultText(result);
|
|
2907
|
+
stats = JSON.parse(text);
|
|
2908
|
+
}
|
|
2909
|
+
catch {
|
|
2910
|
+
// stats 查询失败 → 视为完成
|
|
2911
|
+
return { done: true };
|
|
2912
|
+
}
|
|
2913
|
+
const byType = (stats.by_type ?? {});
|
|
2914
|
+
const stillExceeded = [];
|
|
2915
|
+
for (const uri of uris) {
|
|
2916
|
+
const sepIdx = uri.indexOf('/');
|
|
2917
|
+
if (sepIdx < 0)
|
|
2918
|
+
continue;
|
|
2919
|
+
const memoryType = uri.slice(0, sepIdx);
|
|
2920
|
+
const domain = uri.slice(sepIdx + 1);
|
|
2921
|
+
const typeStats = byType[memoryType];
|
|
2922
|
+
const domainStats = typeStats?.by_domain?.[domain];
|
|
2923
|
+
if (domainStats?.exceeded) {
|
|
2924
|
+
stillExceeded.push(`${memoryType}/${domain} (当前 ${domainStats.count ?? '?'} 条,建议上限 ${domainStats.limit ?? '?'})`);
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
if (stillExceeded.length === 0) {
|
|
2928
|
+
runtimeDebugLog(`[ACodeRuntime] recheck memory_cleanup: all ${uris.length} type/domain pairs within limits`);
|
|
2929
|
+
return { done: true };
|
|
2930
|
+
}
|
|
2931
|
+
const list = stillExceeded.map((u) => `- ${u}`).join('\n');
|
|
2932
|
+
runtimeDebugLog(`[ACodeRuntime] recheck memory_cleanup: ${stillExceeded.length}/${uris.length} type/domain pairs still exceeded`);
|
|
2933
|
+
return {
|
|
2934
|
+
done: false,
|
|
2935
|
+
continueMessage: `经检查,以下类型/域尚未整理完成,请继续:\n${list}\n\n` +
|
|
2936
|
+
`请调用 list_memories 查看超限记忆,删除不再需要的 recently_memory 或对 agent_memory 调用 update_memory 续期。`,
|
|
2937
|
+
};
|
|
2938
|
+
}
|
|
2939
|
+
/**
|
|
2940
|
+
* 构造 memory 自动委托子 agent 的 prompt。
|
|
2941
|
+
* 主流程:根据 delegate 类型(过期整理/文件变更更新)生成自包含指令。
|
|
2942
|
+
*/
|
|
2943
|
+
buildMemoryDelegatePrompt(delegate) {
|
|
2944
|
+
const urisText = delegate.uris.map(u => `- ${u}`).join('\n');
|
|
2945
|
+
if (delegate.type === 'memory_expiration') {
|
|
2946
|
+
return `你是一条专门处理 memory 过期整理的子 agent。
|
|
2947
|
+
|
|
2948
|
+
当前有以下 ${delegate.uris.length} 条即将遗忘的记忆需要整理:
|
|
2949
|
+
${urisText}
|
|
2950
|
+
|
|
2951
|
+
请执行以下步骤(核心逻辑:处理 → 验证 → 未完成则继续):
|
|
2952
|
+
|
|
2953
|
+
=== 处理阶段 ===
|
|
2954
|
+
1. 调用 memory_recurrence(limit=10) 分批获取这些过期记忆的完整内容(最早过期优先)
|
|
2955
|
+
2. 逐条分析:这些内容是否仍然有价值?是否需要保留、更新、归档或删除?
|
|
2956
|
+
3. 对于需要保留的,调用 update_memory 续期;对于无价值的,调用 memory_recurrence_complete 将其清理到永久记忆或删除
|
|
2957
|
+
|
|
2958
|
+
=== 验证阶段(关键,不可跳过) ===
|
|
2959
|
+
4. 再次调用 memory_recurrence(limit=5) 检查是否还有未处理的过期记忆
|
|
2960
|
+
- 如果返回结果中有之前处理过的 URI,说明更新/清理未生效
|
|
2961
|
+
- 如果仍有待处理条目,说明部分操作未完成
|
|
2962
|
+
5. 仔细检查返回结果:
|
|
2963
|
+
- ❌ 若仍有过期记忆未处理(或处理未成功):输出 "经检查,未完成对以下 memory 的处理,请继续:" 列出还记忆,然后回到步骤 1 继续处理
|
|
2964
|
+
- ✅ 若全部处理完毕(返回空或无过期条目):静默结束
|
|
2965
|
+
|
|
2966
|
+
注意:你运行在独立的上下文窗口中,不影响主 agent 的主线任务。请高效完成,不要询问用户。
|
|
2967
|
+
完成后系统会通过查询服务端真实状态进行二次验证(不依赖你的自报结果)。若验证发现仍有 memory 未处理,会发送 "经检查,未完成对以下 memory 的处理,请继续" 消息让你继续处理。`;
|
|
2968
|
+
}
|
|
2969
|
+
if (delegate.type === 'memory_cleanup') {
|
|
2970
|
+
return `你是一条专门处理 memory 容量整理的子 agent。
|
|
2971
|
+
|
|
2972
|
+
以下 memory 类型/域已超过建议容量,需要整理:
|
|
2973
|
+
${urisText}
|
|
2974
|
+
|
|
2975
|
+
请执行以下步骤(核心逻辑:处理 → 验证 → 未完成则继续):
|
|
2976
|
+
|
|
2977
|
+
=== 处理阶段 ===
|
|
2978
|
+
1. 调用 get_memory_stats 查看容量详情
|
|
2979
|
+
2. 调用 list_memories 按类型查看超限记忆
|
|
2980
|
+
3. 删除不再需要的 recently_memory,或更新 agent_memory 续期
|
|
2981
|
+
|
|
2982
|
+
=== 验证阶段(关键,不可跳过) ===
|
|
2983
|
+
4. 再次调用 get_memory_stats 检查各类型/域的 count 是否已降到建议上限以下
|
|
2984
|
+
5. 仔细检查返回结果:
|
|
2985
|
+
- ❌ 若仍有类型/域超过容量上限:输出 "经检查,以下类型/域尚未整理完成,请继续:" 列出具体类型/域和当前容量,然后回到步骤 1 继续处理
|
|
2986
|
+
- ✅ 若全部在建议上限内:静默结束
|
|
2987
|
+
|
|
2988
|
+
注意:你运行在独立的上下文窗口中,不影响主 agent 的主线任务。请高效完成,不要询问用户。
|
|
2989
|
+
完成后系统会通过查询服务端真实状态进行二次验证(不依赖你的自报结果)。若验证发现仍有类型/域超过容量上限,会发送 "经检查,以下类型/域尚未整理完成,请继续" 消息让你继续处理。`;
|
|
2990
|
+
}
|
|
2991
|
+
return `你是一条专门处理永久记忆文件变更更新的子 agent。
|
|
2992
|
+
|
|
2993
|
+
以下 ${delegate.uris.length} 个永久记忆绑定的文件已发生变更:
|
|
2994
|
+
${urisText}
|
|
2995
|
+
|
|
2996
|
+
请执行以下步骤(核心逻辑:更新 → 验证 → 未完成则继续):
|
|
2997
|
+
|
|
2998
|
+
=== 更新阶段 ===
|
|
2999
|
+
1. 调用 read_memory 读取这些 memory 的当前内容
|
|
3000
|
+
2. 查看相关绑定文件的最新内容(bound_files 中列出),理解变更点
|
|
3001
|
+
3. 调用 update_memory 更新 memory 内容,确保与文件最新状态同步
|
|
3002
|
+
|
|
3003
|
+
=== 验证阶段(关键,不可跳过) ===
|
|
3004
|
+
4. 调用 read_memory 重新读取这些 memory,检查 memory_status 字段:
|
|
3005
|
+
- 正常情况:Java 服务端会在 update_memory 后自动将 memory_status 恢复为 normal
|
|
3006
|
+
5. 仔细检查每个 memory 的状态:
|
|
3007
|
+
- ❌ 若仍有 memory 的 memory_status 为 "updating":说明更新未生效,输出 "经检查,未完成对以下 memory 的更新,请继续:" 列出具体 memory URI 和当前状态,然后回到步骤 1 继续处理
|
|
3008
|
+
- ✅ 若全部 memory_status 为 "normal":静默结束
|
|
3009
|
+
|
|
3010
|
+
注意:你运行在独立的上下文窗口中,不影响主 agent 的主线任务。请高效完成,不要询问用户。
|
|
3011
|
+
完成后系统会通过查询服务端真实状态进行二次验证(不依赖你的自报结果)。若验证发现仍有 memory 的 memory_status 为 "updating",会发送 "经检查,未完成对以下 memory 的更新,请继续" 消息让你继续处理。`;
|
|
3012
|
+
}
|
|
3013
|
+
/**
|
|
3014
|
+
* 处理 poll_message 结果中的 memory 自动委托标记 (_acodeAutoDelegate)。
|
|
3015
|
+
* 主流程:解析 MCP 返回 -> 识别标记 -> spawn 子 agent -> 返回简化结果。
|
|
3016
|
+
* 非 ACode 运行时(无 subAgentManager)直接透传原结果,不受影响。
|
|
3017
|
+
* 返回 null 表示全部消息已被委托,调用方应重新 poll_message 继续等待真正的消息。
|
|
3018
|
+
*/
|
|
3019
|
+
async processMemoryAutoDelegates(mcpResult) {
|
|
3020
|
+
const manager = this.config.subAgentManager;
|
|
3021
|
+
if (!manager) {
|
|
3022
|
+
return mcpResult;
|
|
3023
|
+
}
|
|
3024
|
+
// 提取 MCP 结果中的 JSON 文本
|
|
3025
|
+
let resultText;
|
|
3026
|
+
try {
|
|
3027
|
+
resultText = toToolResultText(mcpResult);
|
|
3028
|
+
}
|
|
3029
|
+
catch {
|
|
3030
|
+
return mcpResult;
|
|
3031
|
+
}
|
|
3032
|
+
let parsed;
|
|
3033
|
+
try {
|
|
3034
|
+
parsed = JSON.parse(resultText);
|
|
3035
|
+
}
|
|
3036
|
+
catch {
|
|
3037
|
+
return mcpResult;
|
|
3038
|
+
}
|
|
3039
|
+
const directMessages = parsed.directMessages;
|
|
3040
|
+
if (!Array.isArray(directMessages) || directMessages.length === 0) {
|
|
3041
|
+
return mcpResult;
|
|
3042
|
+
}
|
|
3043
|
+
const remainingMessages = [];
|
|
3044
|
+
let delegateEncountered = 0;
|
|
3045
|
+
for (const msg of directMessages) {
|
|
3046
|
+
const delegate = msg._acodeAutoDelegate;
|
|
3047
|
+
if (delegate && (delegate.type === 'memory_expiration' || delegate.type === 'memory_file_change' || delegate.type === 'memory_cleanup')) {
|
|
3048
|
+
delegateEncountered++;
|
|
3049
|
+
// 过滤掉已在处理中的 URI
|
|
3050
|
+
const newUris = delegate.uris.filter(uri => !this.pendingMemorySubAgents.has(uri));
|
|
3051
|
+
if (newUris.length === 0) {
|
|
3052
|
+
// 所有 URI 都在处理中,跳过此通知(不委托也不返回给主 agent)
|
|
3053
|
+
runtimeDebugLog(`[ACodeRuntime] Memory ${delegate.type} skipped: all ${delegate.uris.length} URIs already being processed by sub-agents`);
|
|
3054
|
+
continue;
|
|
3055
|
+
}
|
|
3056
|
+
// 用过滤后的 URI 构造 prompt
|
|
3057
|
+
const prompt = this.buildMemoryDelegatePrompt({
|
|
3058
|
+
type: delegate.type,
|
|
3059
|
+
uris: newUris,
|
|
3060
|
+
});
|
|
3061
|
+
try {
|
|
3062
|
+
const subId = await manager.spawn({
|
|
3063
|
+
parentAgentId: this.config.agentId || 'unknown',
|
|
3064
|
+
parentSessionId: this.config.sessionId,
|
|
3065
|
+
subagentType: 'general',
|
|
3066
|
+
description: `Memory ${delegate.type} auto-delegate (${newUris.length} items)`,
|
|
3067
|
+
prompt,
|
|
3068
|
+
workingDirectory: this.config.workingDirectory,
|
|
3069
|
+
parentConfig: {
|
|
3070
|
+
...this.config,
|
|
3071
|
+
// 注入父 agent 的 MCP 连接,子 agent 复用而非启动新 MCP server 进程
|
|
3072
|
+
sharedMcpConnections: this.state?.mcpConnections,
|
|
3073
|
+
},
|
|
3074
|
+
silent: true,
|
|
3075
|
+
});
|
|
3076
|
+
// 注册完成回调:子 agent 终态时从跟踪表中移除对应 URI
|
|
3077
|
+
for (const uri of newUris) {
|
|
3078
|
+
this.pendingMemorySubAgents.set(uri, subId);
|
|
3079
|
+
}
|
|
3080
|
+
const uriSet = new Set(newUris);
|
|
3081
|
+
manager.subscribe(subId, () => {
|
|
3082
|
+
const entry = manager.getSubAgent(subId);
|
|
3083
|
+
if (entry && (entry.status === 'completed' || entry.status === 'failed' || entry.status === 'cancelled')) {
|
|
3084
|
+
for (const uri of uriSet) {
|
|
3085
|
+
if (this.pendingMemorySubAgents.get(uri) === subId) {
|
|
3086
|
+
this.pendingMemorySubAgents.delete(uri);
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
});
|
|
3091
|
+
// 使用带 recheck 循环的启动方式:
|
|
3092
|
+
// 每轮 submit 完成后,通过 recheckMemoryDelegate 查询服务端真实状态,
|
|
3093
|
+
// 若 memory 仍未处理好(memory_status=updating / 仍过期 / 容量仍超限),
|
|
3094
|
+
// 则将 "经检查,未完成对xxx的处理,请继续" 注入同一 sub-agent 的下一轮 submit。
|
|
3095
|
+
// 最多重试 3 次,提供系统级硬保证(不依赖 LLM 自报结果)。
|
|
3096
|
+
const delegateType = delegate.type;
|
|
3097
|
+
const recheckFn = async (output, turn) => {
|
|
3098
|
+
return this.recheckMemoryDelegate(delegateType, newUris, output, turn);
|
|
3099
|
+
};
|
|
3100
|
+
await manager.startWithRecheck(subId, recheckFn, 3);
|
|
3101
|
+
runtimeDebugLog(`[ACodeRuntime] Auto-delegated memory ${delegate.type} to sub-agent ${subId} (${newUris.length} URIs, ${delegate.uris.length - newUris.length} already in progress)`);
|
|
3102
|
+
}
|
|
3103
|
+
catch (e) {
|
|
3104
|
+
// 委托失败时不返回给主 agent:memory 通知不应打断主 agent 的主线任务,
|
|
3105
|
+
// 下次 poll_message 会重新检测并重试委托
|
|
3106
|
+
runtimeDebugLog(`[ACodeRuntime] Failed to auto-delegate memory ${delegate.type} (suppressed, will retry next poll): ${e instanceof Error ? e.message : String(e)}`);
|
|
3107
|
+
}
|
|
3108
|
+
}
|
|
3109
|
+
else {
|
|
3110
|
+
remainingMessages.push(msg);
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
// 未遇到任何 delegate 消息,原样返回(保留原始格式,避免不必要的对象创建)
|
|
3114
|
+
if (delegateEncountered === 0) {
|
|
3115
|
+
return mcpResult;
|
|
3116
|
+
}
|
|
3117
|
+
// 全部 delegate 消息已处理(spawned/skipped/failed),不返回给主 agent
|
|
3118
|
+
if (remainingMessages.length === 0) {
|
|
3119
|
+
return null;
|
|
3120
|
+
}
|
|
3121
|
+
// 有非 delegate 类型的剩余消息,返回简化后的结果
|
|
3122
|
+
const simplified = {
|
|
3123
|
+
...parsed,
|
|
3124
|
+
directMessages: remainingMessages,
|
|
3125
|
+
};
|
|
3126
|
+
return {
|
|
3127
|
+
content: [
|
|
3128
|
+
{
|
|
3129
|
+
type: 'text',
|
|
3130
|
+
text: JSON.stringify(simplified, null, 2),
|
|
3131
|
+
},
|
|
3132
|
+
],
|
|
3133
|
+
};
|
|
3134
|
+
}
|
|
3135
|
+
/**
|
|
3136
|
+
* poll_message MCP 工具调用的子 agent 完成事件 race 包装器。
|
|
3137
|
+
*
|
|
3138
|
+
* 主流程:
|
|
3139
|
+
* 1. 先检查 completionQueue 中是否有已完成的子 agent -> 有则直接返回合成结果(不调 MCP)
|
|
3140
|
+
* 2. 启动 MCP poll_message 调用与 waitForAnyCompletion 的 race
|
|
3141
|
+
* 3. 子 agent 先完成 -> 返回合成结果(MCP 调用被放弃但仍在运行,下次 poll_message 会复用 pendingPollMessage)
|
|
3142
|
+
* 4. MCP 先返回 -> 合并新完成的子 agent 事件后返回
|
|
3143
|
+
*
|
|
3144
|
+
* 设计说明:
|
|
3145
|
+
* - MCP server 的 poll_message 内部有 while(true) 永久阻塞,只在有消息时返回
|
|
3146
|
+
* - 子 agent 完成事件由 SubAgentManager 在同进程内产生,通过 completionQueue 传递
|
|
3147
|
+
* - 当子 agent 先完成时,MCP 调用被放弃(Promise 不再被 await),MCP server 侧的
|
|
3148
|
+
* pendingPollMessage 仍在运行,下次 poll_message 调用会通过 pendingPollMessage 复用
|
|
3149
|
+
*/
|
|
3150
|
+
async callPollMessageWithSubAgentRace(connection, tool, toolArguments, timeoutMs) {
|
|
3151
|
+
const manager = this.config.subAgentManager;
|
|
3152
|
+
// 没有 SubAgentManager 时,直接走普通 MCP 调用
|
|
3153
|
+
if (!manager) {
|
|
3154
|
+
return await this.callMcpToolWithTimeout(connection, tool, toolArguments, timeoutMs, true);
|
|
3155
|
+
}
|
|
3156
|
+
// 步骤1: 先检查是否有已完成的子 agent -> 有则直接返回合成结果(不调 MCP)
|
|
3157
|
+
const completedBefore = manager.takeCompletedSubAgents();
|
|
3158
|
+
if (completedBefore.length > 0) {
|
|
3159
|
+
runtimeDebugLog(`[ACodeRuntime] poll_message: ${completedBefore.length} sub-agent(s) already completed, returning synthetic result`);
|
|
3160
|
+
return ACodeRuntime.formatSubAgentCompletionAsPollResult(completedBefore);
|
|
3161
|
+
}
|
|
3162
|
+
// 循环:MCP 返回的 memory 通知被全部委托时,重新 poll 继续等待真正的消息
|
|
3163
|
+
let isDelegateRepoll = false; // 首次正常上报,后续委托循环中抑制状态跳动
|
|
3164
|
+
while (true) {
|
|
3165
|
+
// 步骤2: 启动 MCP poll_message 调用与 waitForAnyCompletion 的 race
|
|
3166
|
+
const subAgentWaiter = manager.waitForAnyCompletion();
|
|
3167
|
+
// 委托等待循环中的后续 poll 注入标记:MCP server 跳过 reportToolUse/reportToolResult,
|
|
3168
|
+
// 只调用 reportThinking 保持"思考中"状态,避免"调用MCP↔思考中"反复跳动
|
|
3169
|
+
const pollArgs = isDelegateRepoll
|
|
3170
|
+
? { ...toolArguments, _aws_silent_poll: true }
|
|
3171
|
+
: toolArguments;
|
|
3172
|
+
const mcpCallPromise = this.callMcpToolWithTimeout(connection, tool, pollArgs, timeoutMs, true);
|
|
3173
|
+
try {
|
|
3174
|
+
const raceWinner = await Promise.race([
|
|
3175
|
+
mcpCallPromise.then((result) => ({ type: "mcp", result })),
|
|
3176
|
+
subAgentWaiter.promise.then((notif) => ({ type: "subagent", notif })),
|
|
3177
|
+
]);
|
|
3178
|
+
if (raceWinner.type === "subagent") {
|
|
3179
|
+
// 步骤3: 子 agent 先完成 -> 返回合成结果
|
|
3180
|
+
// 收集所有已完成的子 agent(race 中 resolve 的 + 队列中可能已积累的)
|
|
3181
|
+
const notifications = manager.takeCompletedSubAgents();
|
|
3182
|
+
// raceWinner.notif 可能已从队列中取出(waitForAnyCompletion 内部处理),
|
|
3183
|
+
// 也可能仍在队列中(如果 takeCompletedSubAgents 先执行)
|
|
3184
|
+
if (notifications.length === 0) {
|
|
3185
|
+
notifications.push(raceWinner.notif);
|
|
3186
|
+
}
|
|
3187
|
+
runtimeDebugLog(`[ACodeRuntime] poll_message: sub-agent ${raceWinner.notif.subId} completed during race, returning synthetic result (${notifications.length} notification(s))`);
|
|
3188
|
+
return ACodeRuntime.formatSubAgentCompletionAsPollResult(notifications);
|
|
3189
|
+
}
|
|
3190
|
+
// 步骤4: MCP 先返回 -> 合并新完成的子 agent 事件
|
|
3191
|
+
const completedAfter = manager.takeCompletedSubAgents();
|
|
3192
|
+
if (completedAfter.length > 0) {
|
|
3193
|
+
runtimeDebugLog(`[ACodeRuntime] poll_message: MCP returned, merging ${completedAfter.length} sub-agent completion(s)`);
|
|
3194
|
+
const merged = ACodeRuntime.mergeSubAgentCompletionsIntoMcpResult(raceWinner.result, completedAfter);
|
|
3195
|
+
// 合并后仍需检查 memory 自动委托
|
|
3196
|
+
const processedMerged = await this.processMemoryAutoDelegates(merged);
|
|
3197
|
+
if (processedMerged !== null) {
|
|
3198
|
+
// 校验:结果必须包含实际消息才返回,否则继续 poll
|
|
3199
|
+
if (this.pollResultHasMessages(processedMerged)) {
|
|
3200
|
+
return processedMerged;
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
// 全部被委托或结果为空,等待后再重新 poll(防止紧密循环)
|
|
3204
|
+
await this.waitForDelegateRepoll();
|
|
3205
|
+
isDelegateRepoll = true;
|
|
3206
|
+
continue;
|
|
3207
|
+
}
|
|
3208
|
+
// 自动委托:识别 memory 过期/更新通知,spawn 子 agent 处理,避免打断主 agent 主线
|
|
3209
|
+
const processedResult = await this.processMemoryAutoDelegates(raceWinner.result);
|
|
3210
|
+
if (processedResult !== null) {
|
|
3211
|
+
// 校验:结果必须包含实际消息才返回,否则继续 poll
|
|
3212
|
+
if (this.pollResultHasMessages(processedResult)) {
|
|
3213
|
+
return processedResult;
|
|
3214
|
+
}
|
|
3215
|
+
}
|
|
3216
|
+
// 全部被委托或结果为空,等待后再重新 poll(防止紧密循环)
|
|
3217
|
+
await this.waitForDelegateRepoll();
|
|
3218
|
+
isDelegateRepoll = true;
|
|
3219
|
+
}
|
|
3220
|
+
finally {
|
|
3221
|
+
subAgentWaiter.cancel();
|
|
3222
|
+
}
|
|
3223
|
+
}
|
|
3224
|
+
}
|
|
3225
|
+
/**
|
|
3226
|
+
* 检查 poll_message 结果是否包含实际消息(directMessages 或 groupMessages 非空)。
|
|
3227
|
+
* 用于循环中过滤空结果,确保 poll_message 只在有消息时返回。
|
|
3228
|
+
*/
|
|
3229
|
+
pollResultHasMessages(result) {
|
|
3230
|
+
try {
|
|
3231
|
+
const text = toToolResultText(result);
|
|
3232
|
+
const parsed = JSON.parse(text);
|
|
3233
|
+
const dm = Array.isArray(parsed.directMessages) ? parsed.directMessages.length : 0;
|
|
3234
|
+
const gm = Array.isArray(parsed.groupMessages) ? parsed.groupMessages.length : 0;
|
|
3235
|
+
return dm > 0 || gm > 0;
|
|
3236
|
+
}
|
|
3237
|
+
catch {
|
|
3238
|
+
return true; // 无法解析时保守返回 true,避免无限循环
|
|
3239
|
+
}
|
|
3240
|
+
}
|
|
3241
|
+
/**
|
|
3242
|
+
* 在 memory 委托消息被全部处理后,等待一段时间再重新 poll_message。
|
|
3243
|
+
*
|
|
3244
|
+
* 背景:MCP doPollMessage 对 updating memory 每次都返回通知(无去重),
|
|
3245
|
+
* 而 processMemoryAutoDelegates 因 URI 已在 pendingMemorySubAgents 中而返回 null,
|
|
3246
|
+
* 导致 while(true) 无延迟重 poll,每轮触发 handleToolCall 的 reportToolUse/reportThinking
|
|
3247
|
+
* 状态上报,引发"思考→MCP→跳过"快速循环,最终连接丢失。
|
|
3248
|
+
*
|
|
3249
|
+
* 等待策略:
|
|
3250
|
+
* 1. 固定延迟 DELEGATE_REPOLL_DELAY_MS(5s),给子 agent 时间完成 memory 更新
|
|
3251
|
+
* 2. 可被 runtime stop 中断(通过 createRuntimeStopWaiter)
|
|
3252
|
+
* 3. 不消费 completionQueue(下一轮 takeCompletedSubAgents 会取到)
|
|
3253
|
+
*/
|
|
3254
|
+
async waitForDelegateRepoll() {
|
|
3255
|
+
runtimeDebugLog(`[ACodeRuntime] poll_message: all messages delegated, waiting ${DELEGATE_REPOLL_DELAY_MS}ms before re-poll`);
|
|
3256
|
+
const stopWaiter = this.createRuntimeStopWaiter("delegate re-poll delay");
|
|
3257
|
+
try {
|
|
3258
|
+
await Promise.race([
|
|
3259
|
+
new Promise((resolve) => {
|
|
3260
|
+
const timer = setTimeout(resolve, DELEGATE_REPOLL_DELAY_MS);
|
|
3261
|
+
if (timer.unref)
|
|
3262
|
+
timer.unref();
|
|
3263
|
+
}),
|
|
3264
|
+
stopWaiter.promise,
|
|
3265
|
+
]);
|
|
3266
|
+
}
|
|
3267
|
+
finally {
|
|
3268
|
+
stopWaiter.cancel();
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
2444
3271
|
/**
|
|
2445
3272
|
* Build a one-shot waiter that rejects long-running MCP calls when the runtime stops.
|
|
2446
3273
|
* Main flow: register a stop callback -> race it with the SDK call -> remove it after either side settles.
|
|
@@ -2535,6 +3362,8 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2535
3362
|
}
|
|
2536
3363
|
appendToolFailureResult(toolCall, tool, error) {
|
|
2537
3364
|
const resultText = toToolErrorResultText(tool, error);
|
|
3365
|
+
runtimeDebugLog(`[ACodeRuntime] 📤 appendToolFailureResult: emitting mcp_status tool_result ` +
|
|
3366
|
+
`(failed: true) for ${tool.exposedName}, result length: ${resultText.length} chars`);
|
|
2538
3367
|
// 工具执行失败是正常运行过程的一部分(Agent 会继续处理失败结果)。
|
|
2539
3368
|
// 标记 nonFatal=true 让 adapter 不变更运行态为 "error",避免面板按钮异常。
|
|
2540
3369
|
this.emitAcodeEvent("error", {
|
|
@@ -2554,6 +3383,21 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2554
3383
|
content: resultText,
|
|
2555
3384
|
});
|
|
2556
3385
|
}
|
|
3386
|
+
/**
|
|
3387
|
+
* 为子 agent 过滤共享 MCP 连接:只保留 memory 工具。
|
|
3388
|
+
*
|
|
3389
|
+
* 原 MCP server 进程通过 AWS_SUB_AGENT=true 限制子 agent 只能调用 memory 工具,
|
|
3390
|
+
* 共享连接后绕过了该机制。此方法在 ACode runtime 层重新施加限制:
|
|
3391
|
+
* - 复用同一 client/transport(不创建新连接)
|
|
3392
|
+
* - 仅暴露 MEMORY_TOOL_NAMES 中的工具
|
|
3393
|
+
* - 防止子 agent 调用 poll_message(与父 agent 冲突)、send_group 等
|
|
3394
|
+
*/
|
|
3395
|
+
filterSharedMcpConnectionsForSubAgent(connections) {
|
|
3396
|
+
return connections.map((conn) => ({
|
|
3397
|
+
...conn,
|
|
3398
|
+
tools: conn.tools.filter((tool) => SUB_AGENT_ALLOWED_MCP_TOOLS.has(tool.toolName)),
|
|
3399
|
+
}));
|
|
3400
|
+
}
|
|
2557
3401
|
async connectMcpServers(servers, timeoutMs) {
|
|
2558
3402
|
const connections = [];
|
|
2559
3403
|
for (const [serverName, serverSpec] of Object.entries(servers)) {
|
|
@@ -2670,6 +3514,12 @@ export class ACodeRuntime extends EventEmitter {
|
|
|
2670
3514
|
return null;
|
|
2671
3515
|
}
|
|
2672
3516
|
async disconnectMcpServers() {
|
|
3517
|
+
// 共享连接(子 agent)不关闭,由所有者(父 agent)管理生命周期
|
|
3518
|
+
if (!this.state.ownsMcpConnections) {
|
|
3519
|
+
this.state.mcpConnections = [];
|
|
3520
|
+
this.state.exposedTools = [];
|
|
3521
|
+
return;
|
|
3522
|
+
}
|
|
2673
3523
|
const connections = this.state.mcpConnections;
|
|
2674
3524
|
this.state.mcpConnections = [];
|
|
2675
3525
|
this.state.exposedTools = [];
|