feat: v0.4.0 四阶段迭代 — 安全加固 + 工程基线 + 架构重构 + 双 Provider 扩展
P0 安全修复: - API Key 加密存储(safeStorage 密钥链,版本化前缀,历史明文平滑兼容) - 间接提示注入防护(SecurityScanHook 工具结果深扫描,网络工具脱敏/本地工具警示分级) - error:report IPC 断链修复(渲染进程错误上报落 electron-log + 审计) - abort 信号贯通工具层(run_command/dev-tools 子进程随会话中断终止) - run_command 沙箱加固(cd 系统目录/敏感文件读取拦截 + chcp 前缀剥离防解析退化) - .env 真实生效(dotenv 回退加载,应用内配置优先) P1 工程基础: - ESLint 9 flat config + 全部 34 条存量 warnings 清零(零容忍基线) - 测试基线 118 用例 11 文件(token/文件防护/权限/沙箱/注入/命令/引擎/注册表/审计链/摘要分层) - test:electron 双模式(ELECTRON_RUN_AS_NODE 跑 Electron ABI,SQLite 套件全执行) - SessionRecorder 多会话隔离 + 9 种 TRACE 事件补全(含最终轮 iteration_end) - Provider 故障转移(重试耗尽/不可重试一次性切换 fallback + 前端通知) - MCP 真就绪(等待全部连接完成再广播 tools:ready) - SLO/HealthChecker 真实接入(60s 巡检 + 托盘状态) - CONFIG_DEFAULTS 单一来源(消除 SEED 双源漂移) P2 架构升级: - handlers.ts 1940 行拆分为 13 个 IPC 域模块(防重入注册 + 多窗口广播) - AgentEngineManager 每会话独立引擎(LRU 30 + adapter 工厂隔离 abort 信号) - TaskOrchestrator EngineProvider 改造 + abortByParent 联动中断 SubAgent - 会话摘要分层上下文(session_summaries 滚动摘要 + 截断游标清理防因果污染) - 消息编辑重发/重新生成(truncateAfter IPC + store 动作 + UI) - Markdown 导出 / WebSearch 并行抓取(并发 3)/ 记忆 TF 缓存 / 版本构建期注入 P3 能力扩展: - OpenAI Adapter(o 系列推理模型 reasoning_effort/max_completion_tokens) - Anthropic Adapter(原生 Messages API:tool_use 块/角色合并/thinking budget/图片 base64/SSE 事件机) - 设置页/Onboarding 六 Provider 全链路接入
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* AgentLoopEngine 单元测试(P1-14 测试基线)
|
||||
* 覆盖:完成终止、死循环检测、最大迭代、Provider 故障转移(P1)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
vi.mock('electron-log', () => ({
|
||||
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
}));
|
||||
|
||||
import { AgentLoopEngine } from '../engine';
|
||||
import { AgentLoopState, TerminationReason } from '../types';
|
||||
import type { IMetonaProviderAdapter, MetonaResponse, MetonaStreamEvent } from '../../types';
|
||||
import { MetonaStreamEventType } from '../../types';
|
||||
|
||||
/** 构造 Mock Adapter:sendStream 按脚本产出事件 */
|
||||
function createMockAdapter(scripts: MetonaStreamEvent[][], opts?: { failWith?: Error }): IMetonaProviderAdapter {
|
||||
let call = 0;
|
||||
return {
|
||||
providerId: 'mock',
|
||||
supportedModels: ['mock-model'],
|
||||
supportsToolCalling: true,
|
||||
supportsThinking: false,
|
||||
getContextWindow: () => 1_000_000,
|
||||
send: vi.fn(async (): Promise<MetonaResponse> => ({
|
||||
meta: { requestId: 'r_test', provider: 'mock', model: 'mock-model', latencyMs: 1, timestamp: Date.now() },
|
||||
content: 'ok',
|
||||
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
|
||||
finishReason: 'stop' as never,
|
||||
})),
|
||||
sendStream: vi.fn(async function* (): AsyncIterable<MetonaStreamEvent> {
|
||||
if (opts?.failWith) throw opts.failWith;
|
||||
const script = scripts[call % scripts.length];
|
||||
call++;
|
||||
for (const ev of script) yield ev;
|
||||
}),
|
||||
setAbortSignal: vi.fn(),
|
||||
healthCheck: async () => true,
|
||||
};
|
||||
}
|
||||
|
||||
function textDoneEvent(text: string): MetonaStreamEvent[] {
|
||||
return [
|
||||
{ type: MetonaStreamEventType.TEXT_DELTA, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 0, timestamp: Date.now(), delta: text },
|
||||
{ type: MetonaStreamEventType.DONE, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 1, timestamp: Date.now() },
|
||||
];
|
||||
}
|
||||
|
||||
function toolCallEvent(name: string, args: Record<string, unknown>): MetonaStreamEvent[] {
|
||||
return [
|
||||
{
|
||||
type: MetonaStreamEventType.TOOL_CALL_COMPLETE,
|
||||
requestId: 'r1', sessionId: 's1', iteration: 1, seq: 0, timestamp: Date.now(),
|
||||
toolCall: { id: 'tc_test', name, args, iteration: 1, timestamp: Date.now() },
|
||||
},
|
||||
{ type: MetonaStreamEventType.DONE, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 1, timestamp: Date.now() },
|
||||
];
|
||||
}
|
||||
|
||||
const userMessage = { role: 'user' as const, content: 'hello', timestamp: Date.now() };
|
||||
const systemPrompt = { roleDefinition: '', outputConstraints: '', safetyGuidelines: '' };
|
||||
|
||||
describe('AgentLoopEngine', () => {
|
||||
it('无工具调用时正常完成(COMPLETED)', async () => {
|
||||
const adapter = createMockAdapter([textDoneEvent('final answer')]);
|
||||
const engine = new AgentLoopEngine({}, adapter);
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.COMPLETED);
|
||||
expect(output.finalAnswer).toBe('final answer');
|
||||
});
|
||||
|
||||
it('死循环检测:连续 3 轮相同工具调用触发 DEAD_LOOP', async () => {
|
||||
// 每轮都返回相同的工具调用(read_file + 相同参数)
|
||||
const adapter = createMockAdapter([toolCallEvent('read_file', { file_path: 'same.ts' })]);
|
||||
const engine = new AgentLoopEngine({ maxIterations: 10 }, adapter);
|
||||
const deadLoopEvents: unknown[] = [];
|
||||
engine.on('deadLoop', (d) => deadLoopEvents.push(d));
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.DEAD_LOOP);
|
||||
expect(deadLoopEvents.length).toBe(1);
|
||||
});
|
||||
|
||||
it('参数不同的相同工具不触发死循环(签名不同)', async () => {
|
||||
const scripts = [
|
||||
toolCallEvent('read_file', { file_path: 'a.ts' }),
|
||||
toolCallEvent('read_file', { file_path: 'b.ts' }),
|
||||
];
|
||||
const adapter = createMockAdapter(scripts);
|
||||
const engine = new AgentLoopEngine({ maxIterations: 3 }, adapter);
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
// 3 轮工具调用后达到 MAX_ITERATIONS(非 DEAD_LOOP)
|
||||
expect(output.terminationReason).toBe(TerminationReason.MAX_ITERATIONS);
|
||||
});
|
||||
|
||||
it('达到最大迭代次数触发 MAX_ITERATIONS', async () => {
|
||||
// 交替不同的工具调用避免死循环
|
||||
const scripts = [
|
||||
toolCallEvent('read_file', { file_path: 'a.ts' }),
|
||||
toolCallEvent('read_file', { file_path: 'b.ts' }),
|
||||
];
|
||||
const adapter = createMockAdapter(scripts);
|
||||
const engine = new AgentLoopEngine({ maxIterations: 2 }, adapter);
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.MAX_ITERATIONS);
|
||||
expect(output.iterations.length).toBe(2);
|
||||
});
|
||||
|
||||
it('状态机经过 THINKING → PARSING → OBSERVING', async () => {
|
||||
const adapter = createMockAdapter([textDoneEvent('answer')]);
|
||||
const engine = new AgentLoopEngine({}, adapter);
|
||||
const states: string[] = [];
|
||||
engine.on('stateChange', (d: { current?: string }) => {
|
||||
if (d.current) states.push(d.current);
|
||||
});
|
||||
await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(states).toContain(AgentLoopState.THINKING);
|
||||
expect(states).toContain(AgentLoopState.PARSING);
|
||||
expect(states).toContain(AgentLoopState.OBSERVING);
|
||||
expect(states[states.length - 1]).toBe(AgentLoopState.TERMINATED);
|
||||
});
|
||||
|
||||
it('不可重试错误直接 ERROR(无 fallback 时)', async () => {
|
||||
const adapter = createMockAdapter([], { failWith: Object.assign(new Error('401 unauthorized'), { status: 401 }) });
|
||||
const engine = new AgentLoopEngine({ retryCount: 0 }, adapter);
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.ERROR);
|
||||
});
|
||||
|
||||
it('P1 故障转移:主 Provider 失败后切换到 fallback Provider', async () => {
|
||||
// 主 adapter 每次都失败(401 不可重试)
|
||||
const primary = createMockAdapter([], { failWith: Object.assign(new Error('401 invalid key'), { status: 401 }) });
|
||||
// fallback 正常返回
|
||||
const fallback = createMockAdapter([textDoneEvent('fallback answer')]);
|
||||
|
||||
const engine = new AgentLoopEngine({ retryCount: 0 }, primary);
|
||||
engine.setFallbackAdapter(fallback);
|
||||
|
||||
const switchEvents: Array<{ from?: string; to?: string }> = [];
|
||||
engine.on('providerSwitched', (d) => switchEvents.push(d));
|
||||
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
|
||||
expect(output.terminationReason).toBe(TerminationReason.COMPLETED);
|
||||
expect(output.finalAnswer).toBe('fallback answer');
|
||||
expect(switchEvents.length).toBe(1);
|
||||
expect(switchEvents[0].from).toBe('mock');
|
||||
expect(switchEvents[0].to).toBe('mock');
|
||||
// fallback 的 sendStream 被调用
|
||||
expect(fallback.sendStream).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('P1 故障转移仅触发一次(fallback 也失败不回切)', async () => {
|
||||
const primary = createMockAdapter([], { failWith: Object.assign(new Error('401'), { status: 401 }) });
|
||||
const fallback = createMockAdapter([], { failWith: Object.assign(new Error('500'), { status: 500 }) });
|
||||
|
||||
const engine = new AgentLoopEngine({ retryCount: 0 }, primary);
|
||||
engine.setFallbackAdapter(fallback);
|
||||
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
// fallback 失败 → ERROR(不回切 primary)
|
||||
expect(output.terminationReason).toBe(TerminationReason.ERROR);
|
||||
});
|
||||
});
|
||||
@@ -18,14 +18,12 @@ import {
|
||||
AgentLoopState,
|
||||
TerminationReason,
|
||||
type IterationStep,
|
||||
type Thought,
|
||||
type AgentLoopConfig,
|
||||
type AgentLoopOutput,
|
||||
type TokenUsage,
|
||||
} from './types';
|
||||
import type {
|
||||
MetonaRequest,
|
||||
MetonaResponse,
|
||||
MetonaMessage,
|
||||
MetonaSystemPrompt,
|
||||
MetonaToolCall,
|
||||
@@ -34,7 +32,7 @@ import type {
|
||||
IMetonaProviderAdapter,
|
||||
MetonaToolDef,
|
||||
} from '../types';
|
||||
import { MetonaStreamEventType, MetonaFinishReason, MetonaErrorCode } from '../types';
|
||||
import { MetonaStreamEventType, MetonaErrorCode } from '../types';
|
||||
import { estimateMessagesTokens } from '../utils/token-estimator';
|
||||
import { ContentFilterError } from '../adapters/base-adapter';
|
||||
import log from 'electron-log';
|
||||
@@ -151,6 +149,16 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* P1: 故障转移 Provider(主 Provider 重试耗尽后切换,见 chatStreamWithRetry)
|
||||
* 由 AgentEngineManager 在创建引擎时注入;null 表示未配置故障转移。
|
||||
*/
|
||||
private fallbackAdapter: IMetonaProviderAdapter | null = null;
|
||||
|
||||
setFallbackAdapter(adapter: IMetonaProviderAdapter | null): void {
|
||||
this.fallbackAdapter = adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 热更新 Engine 配置(设置变更时调用)
|
||||
*
|
||||
@@ -331,18 +339,6 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
return this.adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* #4 修复: 恢复 adapter 的 abort signal
|
||||
*
|
||||
* SubEngine 共享主 Engine 的 adapter 时,SubEngine 会覆盖 adapter 的 abort signal。
|
||||
* SubEngine 完成后,主 Engine 需调用此方法恢复自己的 signal,否则后续 fetch 无法被中断。
|
||||
*/
|
||||
restoreAbortSignal(): void {
|
||||
if (this.abortController && this.adapter.setAbortSignal) {
|
||||
this.adapter.setAbortSignal(this.abortController.signal);
|
||||
}
|
||||
}
|
||||
|
||||
/** 获取工作空间路径(供 SubAgent 继承) */
|
||||
getWorkspacePath(): string {
|
||||
return this.workspacePath;
|
||||
@@ -805,6 +801,8 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
workspacePath: this.workspacePath,
|
||||
iteration: this.currentIteration,
|
||||
requestId: this.currentRequestId,
|
||||
// P0-4: 引擎级 abort 信号透传——用户中断时工具内部(如 run_command 子进程)可自行终止
|
||||
signal: this.abortController?.signal,
|
||||
}),
|
||||
new Promise<MetonaToolResult>((_, reject) => {
|
||||
engineTimer = setTimeout(
|
||||
@@ -823,22 +821,26 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
durationMs: 0,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
// 仍执行 post-hook
|
||||
// 仍执行 post-hook(P0-2: 错误结果同样过安全扫描/审计;钩子可返回修改后的结果)
|
||||
let errorResult = toolResult;
|
||||
for (const hook of this.postToolHooks) {
|
||||
await hook.afterExecute(toolCall, toolResult, this.currentSessionId);
|
||||
const modified = await hook.afterExecute(toolCall, errorResult, this.currentSessionId);
|
||||
if (modified) errorResult = modified;
|
||||
}
|
||||
return toolResult;
|
||||
return errorResult;
|
||||
} finally {
|
||||
// M-16 修复: 清理未触发的 timeout timer
|
||||
if (engineTimer) clearTimeout(engineTimer);
|
||||
}
|
||||
|
||||
// 后置 Hook 管道
|
||||
// 后置 Hook 管道(P0-2: 钩子可返回修改后的结果——如 SecurityScanHook 对网页内容脱敏)
|
||||
let finalResult = toolResult;
|
||||
for (const hook of this.postToolHooks) {
|
||||
await hook.afterExecute(toolCall, toolResult, this.currentSessionId);
|
||||
const modified = await hook.afterExecute(toolCall, finalResult, this.currentSessionId);
|
||||
if (modified) finalResult = modified;
|
||||
}
|
||||
|
||||
return toolResult;
|
||||
return finalResult;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -874,79 +876,123 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 带重试的流式调用(v0.2.0: 指数退避)
|
||||
* 带重试的流式调用(v0.2.0: 指数退避;P1: Provider 故障转移)
|
||||
*
|
||||
* 如果 adapter 抛出错误,在 retryCount 次数内重试。
|
||||
* v0.2.0: 使用指数退避替代固定 1 秒等待
|
||||
* 等待时间 = baseDelay * 2^attempt(1s, 2s, 4s, 8s...)
|
||||
* 上限 30 秒,加上 ±20% 随机抖动(jitter)避免惊群效应
|
||||
* 重试策略:
|
||||
* 1. 可重试错误(429/5xx/网络)→ 指数退避重试(1s/2s/4s...,上限 30s,±20% jitter)
|
||||
* 2. 重试耗尽或不可重试错误 → 若配置了 fallbackAdapter,切换 Provider 重发本次请求
|
||||
* 3. 故障转移仅触发一次(防止主/备 Provider 间乒乓切换)
|
||||
*
|
||||
* 故障转移后 this.adapter 切换为 fallback,本 run 内后续迭代均使用备用 Provider,
|
||||
* 并通过 'providerSwitched' 事件通知上层(IPC → 前端系统消息 + Toast)。
|
||||
*/
|
||||
private async *chatStreamWithRetry(request: MetonaRequest): AsyncIterable<MetonaStreamEvent> {
|
||||
let lastError: unknown;
|
||||
const baseDelayMs = 1_000;
|
||||
const maxDelayMs = 30_000;
|
||||
let attempt = 0;
|
||||
let currentAdapter = this.adapter;
|
||||
let failoverUsed = false;
|
||||
|
||||
for (let attempt = 0; attempt <= this.config.retryCount; attempt++) {
|
||||
while (true) {
|
||||
try {
|
||||
// 首次尝试直接 yield
|
||||
if (attempt === 0) {
|
||||
yield* this.adapter.sendStream(request);
|
||||
return;
|
||||
if (attempt > 0) {
|
||||
// 重试时:先发送一个 retry 事件,让 UI 清空已接收的 delta
|
||||
yield {
|
||||
type: MetonaStreamEventType.ERROR,
|
||||
requestId: request.meta.requestId,
|
||||
sessionId: request.meta.sessionId,
|
||||
iteration: request.meta.iteration,
|
||||
seq: 0,
|
||||
timestamp: Date.now(),
|
||||
error: {
|
||||
code: MetonaErrorCode.RETRY,
|
||||
message: `Retrying after error (attempt ${attempt}/${this.config.retryCount})`,
|
||||
retryable: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
// 重试时:先发送一个 retry 事件,让 UI 清空已接收的 delta
|
||||
// H-11 修复: 使用 MetonaErrorCode.RETRY 替代 'RETRY' as never,移除不安全的类型断言
|
||||
yield {
|
||||
type: MetonaStreamEventType.ERROR,
|
||||
requestId: request.meta.requestId,
|
||||
sessionId: request.meta.sessionId,
|
||||
iteration: request.meta.iteration,
|
||||
seq: 0,
|
||||
timestamp: Date.now(),
|
||||
error: {
|
||||
code: MetonaErrorCode.RETRY,
|
||||
message: `Retrying after error (attempt ${attempt + 1}/${this.config.retryCount + 1})`,
|
||||
retryable: true,
|
||||
},
|
||||
};
|
||||
yield* this.adapter.sendStream(request);
|
||||
yield* currentAdapter.sendStream(request);
|
||||
return;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (this.aborted) throw error;
|
||||
if (attempt < this.config.retryCount) {
|
||||
// 检查是否为可重试错误
|
||||
if (!this.isRetryableError(error)) throw error;
|
||||
// 指数退避 + 抖动
|
||||
const delay = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));
|
||||
const jitter = delay * 0.2 * (Math.random() * 2 - 1); // ±20% jitter
|
||||
const waitMs = Math.max(500, delay + jitter);
|
||||
log.warn(`[AgentLoop] Retry ${attempt + 1}/${this.config.retryCount} after ${Math.round(waitMs)}ms: ${(error as Error).message}`);
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
// v0.3.0 修复: timer 先触发时移除 abort 监听器,避免监听器堆积
|
||||
if (onAbort && signal) signal.removeEventListener('abort', onAbort);
|
||||
resolve(undefined);
|
||||
}, waitMs);
|
||||
// 支持 abort 中断等待
|
||||
const signal = this.abortController?.signal;
|
||||
let onAbort: (() => void) | null = null;
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('Aborted'));
|
||||
return;
|
||||
}
|
||||
onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('Aborted'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
const retryable = this.isRetryableError(error);
|
||||
|
||||
// P1: 故障转移 — 重试耗尽或不可重试错误(如 401 密钥失效)时切换备用 Provider
|
||||
if (
|
||||
!failoverUsed &&
|
||||
this.fallbackAdapter &&
|
||||
this.fallbackAdapter !== currentAdapter &&
|
||||
(!retryable || attempt >= this.config.retryCount)
|
||||
) {
|
||||
failoverUsed = true;
|
||||
const fromId = currentAdapter.providerId;
|
||||
this.adapter = this.fallbackAdapter; // 本 run 内后续迭代均使用 fallback
|
||||
currentAdapter = this.fallbackAdapter;
|
||||
this.syncContextWindow();
|
||||
// 故障转移后重新注入 abort 信号(新 adapter 实例需要关联引擎的中断控制器)
|
||||
if (this.abortController && currentAdapter.setAbortSignal) {
|
||||
currentAdapter.setAbortSignal(this.abortController.signal);
|
||||
}
|
||||
log.warn(
|
||||
`[AgentLoop] Provider failover: ${fromId} → ${currentAdapter.providerId} (${(error as Error).message})`,
|
||||
);
|
||||
this.emit('providerSwitched', {
|
||||
from: fromId,
|
||||
to: currentAdapter.providerId,
|
||||
sessionId: this.currentSessionId,
|
||||
reason: 'failover',
|
||||
});
|
||||
attempt = 0;
|
||||
yield {
|
||||
type: MetonaStreamEventType.ERROR,
|
||||
requestId: request.meta.requestId,
|
||||
sessionId: request.meta.sessionId,
|
||||
iteration: request.meta.iteration,
|
||||
seq: 0,
|
||||
timestamp: Date.now(),
|
||||
error: {
|
||||
code: MetonaErrorCode.RETRY,
|
||||
message: `Primary provider failed, switching to fallback (${currentAdapter.providerId})`,
|
||||
retryable: true,
|
||||
},
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!retryable || attempt >= this.config.retryCount) throw error;
|
||||
attempt++;
|
||||
|
||||
// 指数退避 + 抖动
|
||||
const delay = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt - 1));
|
||||
const jitter = delay * 0.2 * (Math.random() * 2 - 1); // ±20% jitter
|
||||
const waitMs = Math.max(500, delay + jitter);
|
||||
log.warn(
|
||||
`[AgentLoop] Retry ${attempt}/${this.config.retryCount} after ${Math.round(waitMs)}ms: ${(error as Error).message}`,
|
||||
);
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
// v0.3.0 修复: timer 先触发时移除 abort 监听器,避免监听器堆积
|
||||
if (onAbort && signal) signal.removeEventListener('abort', onAbort);
|
||||
resolve(undefined);
|
||||
}, waitMs);
|
||||
// 支持 abort 中断等待
|
||||
const signal = this.abortController?.signal;
|
||||
let onAbort: (() => void) | null = null;
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('Aborted'));
|
||||
return;
|
||||
}
|
||||
onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('Aborted'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
/** 判断错误是否可重试 */
|
||||
|
||||
Reference in New Issue
Block a user