coremind-runtime 0.2.0-beta.2 → 0.2.0-rc.1
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/README.md +10 -2
- package/dist/checkpoint.d.ts +5 -0
- package/dist/checkpoint.d.ts.map +1 -1
- package/dist/checkpoint.js +73 -1
- package/dist/checkpoint.js.map +1 -1
- package/dist/context.d.ts +6 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +48 -9
- package/dist/context.js.map +1 -1
- package/dist/evaluation-graders.d.ts +89 -0
- package/dist/evaluation-graders.d.ts.map +1 -0
- package/dist/evaluation-graders.js +481 -0
- package/dist/evaluation-graders.js.map +1 -0
- package/dist/evaluation.d.ts +13 -2
- package/dist/evaluation.d.ts.map +1 -1
- package/dist/evaluation.js +118 -37
- package/dist/evaluation.js.map +1 -1
- package/dist/events.d.ts +22 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/loop-controller.d.ts +79 -0
- package/dist/loop-controller.d.ts.map +1 -0
- package/dist/loop-controller.js +372 -0
- package/dist/loop-controller.js.map +1 -0
- package/dist/loop-runner.d.ts +52 -0
- package/dist/loop-runner.d.ts.map +1 -0
- package/dist/loop-runner.js +213 -0
- package/dist/loop-runner.js.map +1 -0
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +3 -2
- package/dist/orchestrator.js.map +1 -1
- package/dist/public-tool.d.ts +2 -0
- package/dist/public-tool.d.ts.map +1 -1
- package/dist/public-tool.js +12 -0
- package/dist/public-tool.js.map +1 -1
- package/dist/result.d.ts +1 -1
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js.map +1 -1
- package/dist/retry-policy.d.ts +16 -0
- package/dist/retry-policy.d.ts.map +1 -0
- package/dist/retry-policy.js +112 -0
- package/dist/retry-policy.js.map +1 -0
- package/dist/run-state.d.ts +12 -1
- package/dist/run-state.d.ts.map +1 -1
- package/dist/run-state.js +72 -3
- package/dist/run-state.js.map +1 -1
- package/dist/run-terminalizer.d.ts +11 -0
- package/dist/run-terminalizer.d.ts.map +1 -0
- package/dist/run-terminalizer.js +38 -0
- package/dist/run-terminalizer.js.map +1 -0
- package/dist/runtime.d.ts +2 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +230 -55
- package/dist/runtime.js.map +1 -1
- package/dist/tool-policy.d.ts +11 -2
- package/dist/tool-policy.d.ts.map +1 -1
- package/dist/tool-policy.js +112 -15
- package/dist/tool-policy.js.map +1 -1
- package/dist/trace.d.ts +2 -0
- package/dist/trace.d.ts.map +1 -1
- package/dist/trace.js +77 -1
- package/dist/trace.js.map +1 -1
- package/package.json +13 -6
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { CoreMindError } from "./errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* 把一次运行的所有结束路径收敛为稳定终态。
|
|
4
|
+
*
|
|
5
|
+
* 调用方只需要判断 RunOutcome,不需要同时处理“返回值”和“抛异常”两套协议。
|
|
6
|
+
*/
|
|
7
|
+
export class RunTerminalizer {
|
|
8
|
+
terminalize(events, error) {
|
|
9
|
+
if (error !== undefined)
|
|
10
|
+
return outcomeFromError(error);
|
|
11
|
+
if (events.some((event) => event.type === "policy_denied")) {
|
|
12
|
+
return { status: "paused", finishReason: "tool_approval_denied" };
|
|
13
|
+
}
|
|
14
|
+
return { status: "succeeded", finishReason: "completed" };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function outcomeFromError(error) {
|
|
18
|
+
const code = error instanceof CoreMindError ? error.code : "unknown";
|
|
19
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
20
|
+
return {
|
|
21
|
+
status: statusFromCode(code),
|
|
22
|
+
finishReason: code,
|
|
23
|
+
error: { code, message },
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function statusFromCode(code) {
|
|
27
|
+
if (code === "loop_paused")
|
|
28
|
+
return "paused";
|
|
29
|
+
if (code === "aborted")
|
|
30
|
+
return "aborted";
|
|
31
|
+
if (code === "run_timeout" || code === "step_timeout")
|
|
32
|
+
return "timeout";
|
|
33
|
+
if (code === "budget_exceeded" || code === "retry_limit" || code === "step_limit") {
|
|
34
|
+
return "budget_exceeded";
|
|
35
|
+
}
|
|
36
|
+
return "failed";
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=run-terminalizer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-terminalizer.js","sourceRoot":"","sources":["../src/run-terminalizer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAI5C;;;;GAIG;AACH,MAAM,OAAO,eAAe;IAC1B,WAAW,CAAC,MAAuB,EAAE,KAAe;QAClD,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,gBAAgB,CAAC,KAAK,CAAC,CAAC;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,eAAe,CAAC,EAAE,CAAC;YAC3D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,sBAAsB,EAAE,CAAC;QACpE,CAAC;QACD,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC;IAC5D,CAAC;CACF;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,MAAM,IAAI,GAAG,KAAK,YAAY,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACrE,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,OAAO;QACL,MAAM,EAAE,cAAc,CAAC,IAAI,CAAC;QAC5B,YAAY,EAAE,IAAI;QAClB,KAAK,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;KACzB,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,IAAY;IAClC,IAAI,IAAI,KAAK,aAAa;QAAE,OAAO,QAAQ,CAAC;IAC5C,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACzC,IAAI,IAAI,KAAK,aAAa,IAAI,IAAI,KAAK,cAAc;QAAE,OAAO,SAAS,CAAC;IACxE,IAAI,IAAI,KAAK,iBAAiB,IAAI,IAAI,KAAK,aAAa,IAAI,IAAI,KAAK,YAAY,EAAE,CAAC;QAClF,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -65,6 +65,7 @@ export declare class CoreMindRuntime {
|
|
|
65
65
|
private readonly config;
|
|
66
66
|
private readonly agentConfigs;
|
|
67
67
|
private readonly toolsByAgent;
|
|
68
|
+
private readonly toolEffectsByAgent;
|
|
68
69
|
private readonly providerRuntime;
|
|
69
70
|
private readonly options;
|
|
70
71
|
/** 最近创建的每个 agent 实例(收集最终消息/落盘用) */
|
|
@@ -97,6 +98,7 @@ export declare class CoreMindRuntime {
|
|
|
97
98
|
/** 执行:有 workflow 走编排,否则单 agent 直答。返回结果含质量摘要 */
|
|
98
99
|
run(): Promise<RunResult>;
|
|
99
100
|
private runWithGuard;
|
|
101
|
+
private executeLoopStep;
|
|
100
102
|
private abortAll;
|
|
101
103
|
private collectMessages;
|
|
102
104
|
/** 会话配置开启时,把主 agent 本轮新增消息追加落盘(返回会话文件路径) */
|
package/dist/runtime.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,KAAK,EACL,YAAY,EAGb,MAAM,+BAA+B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;IAkE7B,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,eAAe;IAMvB,4CAA4C;IACtC,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;CAuBpD;AAED,wBAAwB;AACxB,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC,CAE1B"}
|
package/dist/runtime.js
CHANGED
|
@@ -8,11 +8,14 @@ import { CheckpointManager, inspectCheckpoint as inspectStoredCheckpoint, restor
|
|
|
8
8
|
import { ContextProtector } from "./context.js";
|
|
9
9
|
import { CoreMindError } from "./errors.js";
|
|
10
10
|
import { extractAgentError, extractText } from "./events.js";
|
|
11
|
+
import { LoopRunner } from "./loop-runner.js";
|
|
11
12
|
import { Orchestrator } from "./orchestrator.js";
|
|
12
13
|
import { buildProviderRuntime } from "./provider.js";
|
|
13
14
|
import { adaptCoreMindTool } from "./public-tool.js";
|
|
14
15
|
import { analyzeRunMetrics, assessReleaseReadiness, createEvaluationReport, } from "./result.js";
|
|
16
|
+
import { classifyRetry, runWithTransientRetry } from "./retry-policy.js";
|
|
15
17
|
import { FileRunStore, fingerprintRunConfig, prepareRunResume, RunStateJournal, } from "./run-state.js";
|
|
18
|
+
import { RunTerminalizer } from "./run-terminalizer.js";
|
|
16
19
|
import { CoreMindSession } from "./session.js";
|
|
17
20
|
import { ToolPolicy } from "./tool-policy.js";
|
|
18
21
|
import { TraceRecorder } from "./trace.js";
|
|
@@ -24,6 +27,7 @@ export class CoreMindRuntime {
|
|
|
24
27
|
config;
|
|
25
28
|
agentConfigs;
|
|
26
29
|
toolsByAgent;
|
|
30
|
+
toolEffectsByAgent;
|
|
27
31
|
providerRuntime;
|
|
28
32
|
options;
|
|
29
33
|
/** 最近创建的每个 agent 实例(收集最终消息/落盘用) */
|
|
@@ -37,10 +41,11 @@ export class CoreMindRuntime {
|
|
|
37
41
|
/** agent 名 → 注入的技能内容 */
|
|
38
42
|
skillsByAgent;
|
|
39
43
|
activeHarnessFactory;
|
|
40
|
-
constructor(config, agentConfigs, toolsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent) {
|
|
44
|
+
constructor(config, agentConfigs, toolsByAgent, toolEffectsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent) {
|
|
41
45
|
this.config = config;
|
|
42
46
|
this.agentConfigs = agentConfigs;
|
|
43
47
|
this.toolsByAgent = toolsByAgent;
|
|
48
|
+
this.toolEffectsByAgent = toolEffectsByAgent;
|
|
44
49
|
this.providerRuntime = providerRuntime;
|
|
45
50
|
this.options = options;
|
|
46
51
|
this.sessionMessages = sessionMessages;
|
|
@@ -62,18 +67,27 @@ export class CoreMindRuntime {
|
|
|
62
67
|
// 2. 每个 agent:构建工具与技能(Agent 实例按需创建,避免并发冲突)
|
|
63
68
|
const agentConfigs = new Map();
|
|
64
69
|
const toolsByAgent = new Map();
|
|
70
|
+
const toolEffectsByAgent = new Map();
|
|
65
71
|
const skillsByAgent = new Map();
|
|
66
72
|
const externalTools = (options.toolDefinitions ?? []).map(adaptCoreMindTool);
|
|
67
73
|
// 自定义技能(生态机制):配置文件所在目录的 skills/ 下,每个子目录的 README.md 即一个技能
|
|
68
74
|
const customSkills = await loadDirectorySkills(path.join(configDir, "skills"));
|
|
69
75
|
for (const [name, agentCfg] of Object.entries(config.agents)) {
|
|
70
76
|
const toolConfigs = (agentCfg.tools?.length ?? 0) > 0 ? agentCfg.tools : config.tools;
|
|
71
|
-
const { tools, warnings } = await buildTools(toolConfigs ?? [], {
|
|
77
|
+
const { tools, warnings, effects } = await buildTools(toolConfigs ?? [], {
|
|
78
|
+
cwd,
|
|
79
|
+
configDir,
|
|
80
|
+
env,
|
|
81
|
+
});
|
|
72
82
|
for (const warning of warnings) {
|
|
73
83
|
emit({ type: "error", message: warning, fatal: false });
|
|
74
84
|
}
|
|
75
85
|
agentConfigs.set(name, agentCfg);
|
|
76
86
|
toolsByAgent.set(name, [...tools, ...externalTools]);
|
|
87
|
+
toolEffectsByAgent.set(name, new Map([
|
|
88
|
+
...effects,
|
|
89
|
+
...(options.toolDefinitions ?? []).map((definition) => [definition.name, definition.effect]),
|
|
90
|
+
]));
|
|
77
91
|
// 技能:内置优先,未命中的查自定义目录,仍缺失才告警(不阻断)
|
|
78
92
|
const { contents, missing } = resolveSkills(agentCfg.skills ?? []);
|
|
79
93
|
const allContents = [...contents];
|
|
@@ -112,7 +126,7 @@ export class CoreMindRuntime {
|
|
|
112
126
|
throw new CoreMindError("session_restore_failed", `会话 ${options.sessionId} 恢复失败:${detail}`);
|
|
113
127
|
}
|
|
114
128
|
}
|
|
115
|
-
return new CoreMindRuntime(config, agentConfigs, toolsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent);
|
|
129
|
+
return new CoreMindRuntime(config, agentConfigs, toolsByAgent, toolEffectsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent);
|
|
116
130
|
}
|
|
117
131
|
/** 按名字创建独立 Agent 实例(每次新实例,消息历史独立) */
|
|
118
132
|
createAgent(name, onEvent = this.options.events ?? (() => { })) {
|
|
@@ -152,7 +166,7 @@ export class CoreMindRuntime {
|
|
|
152
166
|
}
|
|
153
167
|
const turnConfig = { ...this.config, defaultAgent: agentName };
|
|
154
168
|
delete turnConfig.workflow;
|
|
155
|
-
const turnRuntime = new CoreMindRuntime(turnConfig, this.agentConfigs, this.toolsByAgent, this.providerRuntime, {
|
|
169
|
+
const turnRuntime = new CoreMindRuntime(turnConfig, this.agentConfigs, this.toolsByAgent, this.toolEffectsByAgent, this.providerRuntime, {
|
|
156
170
|
...this.options,
|
|
157
171
|
config: turnConfig,
|
|
158
172
|
initialPrompt: message,
|
|
@@ -201,15 +215,43 @@ export class CoreMindRuntime {
|
|
|
201
215
|
}, resumePlan?.previousTrace);
|
|
202
216
|
const collected = resumePlan?.previousTrace.map((entry) => entry.event) ?? [];
|
|
203
217
|
const userEvents = this.options.events ?? (() => { });
|
|
218
|
+
const activeToolEffects = new Map();
|
|
219
|
+
const recordEvent = (event) => {
|
|
220
|
+
collected.push(event);
|
|
221
|
+
trace.record(event);
|
|
222
|
+
userEvents(event);
|
|
223
|
+
};
|
|
204
224
|
const emit = (event) => {
|
|
205
225
|
const enriched = event.type === "tool_call" && event.callId && !event.idempotencyKey
|
|
206
|
-
? { ...event, idempotencyKey:
|
|
226
|
+
? { ...event, idempotencyKey: effectIdempotencyKey(runId, event.stepId, event.callId) }
|
|
207
227
|
: event;
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
228
|
+
recordEvent(enriched);
|
|
229
|
+
if (enriched.type === "tool_call" && enriched.callId && enriched.idempotencyKey) {
|
|
230
|
+
const effect = {
|
|
231
|
+
idempotencyKey: enriched.idempotencyKey,
|
|
232
|
+
tool: enriched.tool,
|
|
233
|
+
...(enriched.stepId ? { stepId: enriched.stepId } : {}),
|
|
234
|
+
};
|
|
235
|
+
activeToolEffects.set(effectCallKey(enriched.stepId, enriched.callId), effect);
|
|
236
|
+
recordEvent({ type: "effect_receipt", ...effect, status: "started" });
|
|
237
|
+
}
|
|
238
|
+
if (enriched.type === "tool_result" && enriched.callId) {
|
|
239
|
+
const callKey = effectCallKey(enriched.stepId, enriched.callId);
|
|
240
|
+
const effect = activeToolEffects.get(callKey) ?? {
|
|
241
|
+
idempotencyKey: effectIdempotencyKey(runId, enriched.stepId, enriched.callId),
|
|
242
|
+
tool: enriched.tool,
|
|
243
|
+
...(enriched.stepId ? { stepId: enriched.stepId } : {}),
|
|
244
|
+
};
|
|
245
|
+
activeToolEffects.delete(callKey);
|
|
246
|
+
recordEvent({
|
|
247
|
+
type: "effect_receipt",
|
|
248
|
+
...effect,
|
|
249
|
+
status: enriched.isError ? "unknown" : "committed",
|
|
250
|
+
});
|
|
251
|
+
}
|
|
211
252
|
};
|
|
212
253
|
const workflow = this.config.workflow;
|
|
254
|
+
const loop = this.config.loop;
|
|
213
255
|
const limits = resolveRuntimeLimits(this.config.runtime, {
|
|
214
256
|
maxSteps: this.options.maxSteps,
|
|
215
257
|
stepTimeoutMs: this.options.stepTimeoutMs,
|
|
@@ -223,6 +265,7 @@ export class CoreMindRuntime {
|
|
|
223
265
|
runId: trace.runId,
|
|
224
266
|
});
|
|
225
267
|
let checkpointFailure;
|
|
268
|
+
const checkpointByCallId = new Map();
|
|
226
269
|
const contextWindow = this.providerRuntime.model.contextWindow;
|
|
227
270
|
const contextProtector = new ContextProtector({
|
|
228
271
|
contextWindow,
|
|
@@ -233,6 +276,10 @@ export class CoreMindRuntime {
|
|
|
233
276
|
beforeTokens: result.beforeTokens,
|
|
234
277
|
afterTokens: result.afterTokens,
|
|
235
278
|
removedMessages: result.removedMessages,
|
|
279
|
+
}), (failure) => emit({
|
|
280
|
+
type: "context_compaction_failed",
|
|
281
|
+
message: failure.message,
|
|
282
|
+
preservedMessages: failure.preservedMessages,
|
|
236
283
|
}));
|
|
237
284
|
const policy = new ToolPolicy({
|
|
238
285
|
permissions: this.config.permissions,
|
|
@@ -248,6 +295,7 @@ export class CoreMindRuntime {
|
|
|
248
295
|
tool: request.tool,
|
|
249
296
|
args: request.args,
|
|
250
297
|
risk: request.risk,
|
|
298
|
+
effect: request.effect,
|
|
251
299
|
}),
|
|
252
300
|
onApprovalResolved: (request, decision) => emit({
|
|
253
301
|
type: "approval_resolved",
|
|
@@ -257,13 +305,13 @@ export class CoreMindRuntime {
|
|
|
257
305
|
}),
|
|
258
306
|
});
|
|
259
307
|
this.activeHarnessFactory = (agentName) => ({
|
|
260
|
-
maxRetries: limits.maxRetries,
|
|
308
|
+
maxRetries: loop ? 0 : limits.maxRetries,
|
|
261
309
|
transformContext: async (messages) => contextProtector.transform(messages),
|
|
262
310
|
beforeToolCall: async (context) => {
|
|
263
311
|
const blockedByBudget = budget.beforeToolCall();
|
|
264
312
|
if (blockedByBudget)
|
|
265
313
|
return blockedByBudget;
|
|
266
|
-
const decision = await policy.authorize(agentName, context.toolCall.name, context.args);
|
|
314
|
+
const decision = await policy.authorize(agentName, context.toolCall.name, context.args, this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.name));
|
|
267
315
|
if (!decision.allowed) {
|
|
268
316
|
emit({
|
|
269
317
|
type: "policy_denied",
|
|
@@ -276,6 +324,7 @@ export class CoreMindRuntime {
|
|
|
276
324
|
try {
|
|
277
325
|
const checkpoint = await checkpointManager.capture(context.toolCall.name, context.args);
|
|
278
326
|
if (checkpoint) {
|
|
327
|
+
checkpointByCallId.set(context.toolCall.id, checkpoint.checkpointId);
|
|
279
328
|
journal.checkpoint(checkpoint);
|
|
280
329
|
emit({
|
|
281
330
|
type: "checkpoint_created",
|
|
@@ -296,16 +345,74 @@ export class CoreMindRuntime {
|
|
|
296
345
|
}
|
|
297
346
|
return undefined;
|
|
298
347
|
},
|
|
299
|
-
afterToolCall: async (context) =>
|
|
348
|
+
afterToolCall: async (context) => {
|
|
349
|
+
const checkpointId = checkpointByCallId.get(context.toolCall.id);
|
|
350
|
+
checkpointByCallId.delete(context.toolCall.id);
|
|
351
|
+
if (checkpointId) {
|
|
352
|
+
try {
|
|
353
|
+
await checkpointManager.markApplied(checkpointId);
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
checkpointFailure =
|
|
357
|
+
error instanceof CoreMindError
|
|
358
|
+
? error
|
|
359
|
+
: new CoreMindError("checkpoint_failed", error instanceof Error ? error.message : String(error));
|
|
360
|
+
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const budgetResult = budget.afterToolCall(context.isError);
|
|
364
|
+
return checkpointFailure ? { terminate: true } : budgetResult;
|
|
365
|
+
},
|
|
300
366
|
onAgentEvent: (event, agent) => {
|
|
301
367
|
if (budget.observeAgentEvent(event))
|
|
302
368
|
agent.abort();
|
|
303
369
|
},
|
|
304
370
|
});
|
|
305
|
-
let outputs;
|
|
306
|
-
let transcript;
|
|
371
|
+
let outputs = new Map();
|
|
372
|
+
let transcript = "";
|
|
373
|
+
let terminalError;
|
|
374
|
+
let loopSnapshot = resumePlan?.loopSnapshot;
|
|
375
|
+
let activeLoopRunner;
|
|
307
376
|
try {
|
|
308
377
|
({ outputs, transcript } = await this.runWithGuard(limits.runTimeoutMs, async () => {
|
|
378
|
+
if (loop) {
|
|
379
|
+
let retryCount = resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry" && entry.event.scope === "provider").length ?? 0;
|
|
380
|
+
const runner = new LoopRunner({
|
|
381
|
+
runId,
|
|
382
|
+
configFingerprint,
|
|
383
|
+
initialPrompt: effectiveInitialPrompt,
|
|
384
|
+
loop,
|
|
385
|
+
completedSteps: resumePlan?.completedSteps,
|
|
386
|
+
restoredSnapshot: resumePlan?.loopSnapshot,
|
|
387
|
+
emit,
|
|
388
|
+
persistSnapshot: async (snapshot) => {
|
|
389
|
+
loopSnapshot = snapshot;
|
|
390
|
+
journal.loop(snapshot);
|
|
391
|
+
await journal.flush();
|
|
392
|
+
},
|
|
393
|
+
executeStep: (request) => runWithTransientRetry(() => this.executeLoopStep(request, emit, limits.stepTimeoutMs, collected), {
|
|
394
|
+
maxRetries: Math.max(0, limits.maxRetries - retryCount),
|
|
395
|
+
signal: this.options.signal,
|
|
396
|
+
onRetry: () => {
|
|
397
|
+
retryCount += 1;
|
|
398
|
+
emit({
|
|
399
|
+
type: "retry",
|
|
400
|
+
scope: "provider",
|
|
401
|
+
attempt: retryCount,
|
|
402
|
+
stepId: request.stepId,
|
|
403
|
+
});
|
|
404
|
+
},
|
|
405
|
+
}),
|
|
406
|
+
});
|
|
407
|
+
activeLoopRunner = runner;
|
|
408
|
+
const loopResult = await runner.run();
|
|
409
|
+
outputs = loopResult.outputs;
|
|
410
|
+
transcript = loopResult.transcript;
|
|
411
|
+
loopSnapshot = loopResult.snapshot;
|
|
412
|
+
if (loopResult.error !== undefined)
|
|
413
|
+
throw loopResult.error;
|
|
414
|
+
return { outputs, transcript };
|
|
415
|
+
}
|
|
309
416
|
if (workflow && workflow.length > 0) {
|
|
310
417
|
const orchestrator = new Orchestrator(workflow, {
|
|
311
418
|
createAgent: (name, stepId) => this.createAgent(name, (event) => emit(stepId ? { ...event, stepId } : event)),
|
|
@@ -315,7 +422,8 @@ export class CoreMindRuntime {
|
|
|
315
422
|
maxSteps: limits.maxSteps,
|
|
316
423
|
stepTimeoutMs: limits.stepTimeoutMs,
|
|
317
424
|
maxRetries: limits.maxRetries,
|
|
318
|
-
initialRetryCount: resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry").length ??
|
|
425
|
+
initialRetryCount: resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry").length ??
|
|
426
|
+
0,
|
|
319
427
|
completedSteps: resumePlan?.completedSteps,
|
|
320
428
|
});
|
|
321
429
|
const workflowOutputs = await orchestrator.run();
|
|
@@ -342,53 +450,61 @@ export class CoreMindRuntime {
|
|
|
342
450
|
}
|
|
343
451
|
transcript = extractText(agent.state.messages.slice(messageCursor));
|
|
344
452
|
return { outputs: new Map(), transcript };
|
|
345
|
-
}));
|
|
453
|
+
}, (error) => activeLoopRunner?.interrupt(error)));
|
|
346
454
|
if (checkpointFailure)
|
|
347
455
|
throw checkpointFailure;
|
|
348
456
|
budget.throwIfExceeded();
|
|
349
457
|
}
|
|
350
458
|
catch (error) {
|
|
351
|
-
|
|
352
|
-
if (checkpointFailure)
|
|
353
|
-
runError = checkpointFailure;
|
|
459
|
+
terminalError = checkpointFailure ?? error;
|
|
354
460
|
try {
|
|
355
461
|
if (!checkpointFailure)
|
|
356
462
|
budget.throwIfExceeded();
|
|
357
463
|
}
|
|
358
464
|
catch (budgetError) {
|
|
359
|
-
|
|
465
|
+
terminalError = budgetError;
|
|
360
466
|
}
|
|
361
|
-
journal.finish(failedRunPayload(runError));
|
|
362
|
-
await journal.flush();
|
|
363
|
-
throw runError;
|
|
364
467
|
}
|
|
365
468
|
finally {
|
|
366
469
|
this.activeHarnessFactory = undefined;
|
|
367
470
|
}
|
|
368
471
|
let sessionFile;
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
472
|
+
if (terminalError === undefined) {
|
|
473
|
+
try {
|
|
474
|
+
sessionFile = await this.persistSession();
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
terminalError = error;
|
|
478
|
+
}
|
|
376
479
|
}
|
|
377
480
|
const allMessages = [...this.collectMessages().values()].flat();
|
|
481
|
+
if (terminalError !== undefined && transcript.length === 0) {
|
|
482
|
+
transcript = extractText(allMessages);
|
|
483
|
+
}
|
|
378
484
|
const metrics = analyzeRunMetrics(collected, allMessages, performance.now() - started, transcript.length);
|
|
379
|
-
const
|
|
380
|
-
!collected.some((event) => event.type === "tool_result" && !event.isError);
|
|
381
|
-
const outcome = allToolRequestsDenied
|
|
382
|
-
? { status: "paused", finishReason: "tool_approval_denied" }
|
|
383
|
-
: { status: "succeeded", finishReason: "completed" };
|
|
485
|
+
const outcome = new RunTerminalizer().terminalize(collected, terminalError);
|
|
384
486
|
const evaluation = createEvaluationReport(this.config.quality, metrics);
|
|
385
|
-
for (const checkpoint of checkpointManager.records) {
|
|
386
|
-
if (!checkpoint.reversible) {
|
|
387
|
-
evaluation.securityFindings.push(`工具 ${checkpoint.tool} 的副作用不可自动回退`);
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
487
|
const releaseReadiness = assessReleaseReadiness(outcome, evaluation);
|
|
391
|
-
|
|
488
|
+
const irreversibleTools = [
|
|
489
|
+
...new Set(checkpointManager.records
|
|
490
|
+
.filter((checkpoint) => !checkpoint.reversible)
|
|
491
|
+
.map((checkpoint) => checkpoint.tool)),
|
|
492
|
+
];
|
|
493
|
+
if (irreversibleTools.length > 0) {
|
|
494
|
+
releaseReadiness.warnings.push(`存在不可自动回退的工具执行:${irreversibleTools.join("、")};请结合 Trace 和外部系统记录复核`);
|
|
495
|
+
}
|
|
496
|
+
if (outcome.status === "paused") {
|
|
497
|
+
journal.pause({
|
|
498
|
+
outcome,
|
|
499
|
+
metrics,
|
|
500
|
+
evaluation,
|
|
501
|
+
releaseReadiness,
|
|
502
|
+
...(loopSnapshot ? { loopSnapshot } : {}),
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
journal.finish({ outcome, metrics, evaluation, releaseReadiness });
|
|
507
|
+
}
|
|
392
508
|
await journal.flush();
|
|
393
509
|
return {
|
|
394
510
|
runId: trace.runId,
|
|
@@ -405,25 +521,36 @@ export class CoreMindRuntime {
|
|
|
405
521
|
sessionFile,
|
|
406
522
|
};
|
|
407
523
|
}
|
|
408
|
-
async runWithGuard(timeoutMs, operation) {
|
|
524
|
+
async runWithGuard(timeoutMs, operation, onGuardError) {
|
|
409
525
|
const signal = this.options.signal;
|
|
410
526
|
if (signal?.aborted)
|
|
411
527
|
throw new CoreMindError("aborted", "执行已中止");
|
|
412
528
|
let timer;
|
|
413
529
|
let rejectAbort;
|
|
530
|
+
let guardTriggered = false;
|
|
414
531
|
const aborted = new Promise((_resolve, reject) => {
|
|
415
532
|
rejectAbort = reject;
|
|
416
533
|
});
|
|
534
|
+
const triggerGuard = (error, reject) => {
|
|
535
|
+
if (guardTriggered)
|
|
536
|
+
return;
|
|
537
|
+
guardTriggered = true;
|
|
538
|
+
void Promise.resolve(onGuardError?.(error))
|
|
539
|
+
.catch(() => undefined)
|
|
540
|
+
.then(() => {
|
|
541
|
+
reject(error);
|
|
542
|
+
this.abortAll();
|
|
543
|
+
});
|
|
544
|
+
};
|
|
417
545
|
const onAbort = () => {
|
|
418
|
-
|
|
419
|
-
|
|
546
|
+
if (rejectAbort)
|
|
547
|
+
triggerGuard(new CoreMindError("aborted", "执行已中止"), rejectAbort);
|
|
420
548
|
};
|
|
421
549
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
422
550
|
const timedOut = timeoutMs > 0
|
|
423
551
|
? new Promise((_resolve, reject) => {
|
|
424
552
|
timer = setTimeout(() => {
|
|
425
|
-
|
|
426
|
-
reject(new CoreMindError("run_timeout", `运行超时(${timeoutMs}ms),已中止`));
|
|
553
|
+
triggerGuard(new CoreMindError("run_timeout", `运行超时(${timeoutMs}ms),已中止`), reject);
|
|
427
554
|
}, timeoutMs);
|
|
428
555
|
})
|
|
429
556
|
: new Promise(() => { });
|
|
@@ -436,6 +563,59 @@ export class CoreMindRuntime {
|
|
|
436
563
|
signal?.removeEventListener("abort", onAbort);
|
|
437
564
|
}
|
|
438
565
|
}
|
|
566
|
+
async executeLoopStep(request, emit, timeoutMs, collected) {
|
|
567
|
+
const eventCursor = collected.length;
|
|
568
|
+
const agent = this.createAgent(request.agent, (event) => emit({ ...event, stepId: request.stepId }));
|
|
569
|
+
if (!agent) {
|
|
570
|
+
throw new CoreMindError("unknown_agent", `Loop 引用了未定义的 agent:${request.agent}(${request.stepId})`);
|
|
571
|
+
}
|
|
572
|
+
const messageCursor = agent.state.messages.length;
|
|
573
|
+
let timer;
|
|
574
|
+
const operation = (async () => {
|
|
575
|
+
await agent.prompt(request.input);
|
|
576
|
+
await agent.waitForIdle();
|
|
577
|
+
})();
|
|
578
|
+
try {
|
|
579
|
+
if (timeoutMs > 0) {
|
|
580
|
+
await Promise.race([
|
|
581
|
+
operation,
|
|
582
|
+
new Promise((_resolve, reject) => {
|
|
583
|
+
timer = setTimeout(() => {
|
|
584
|
+
agent.abort();
|
|
585
|
+
reject(new CoreMindError("step_timeout", `步骤 ${request.stepId} 执行超时(${timeoutMs}ms),已中止`));
|
|
586
|
+
}, timeoutMs);
|
|
587
|
+
}),
|
|
588
|
+
]);
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
await operation;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
finally {
|
|
595
|
+
if (timer)
|
|
596
|
+
clearTimeout(timer);
|
|
597
|
+
}
|
|
598
|
+
const stepEvents = collected.slice(eventCursor);
|
|
599
|
+
const budgetExceeded = stepEvents.find((event) => event.type === "budget_exceeded");
|
|
600
|
+
if (budgetExceeded?.type === "budget_exceeded") {
|
|
601
|
+
throw new CoreMindError("budget_exceeded", budgetExceeded.message);
|
|
602
|
+
}
|
|
603
|
+
if (stepEvents.some((event) => event.type === "policy_denied")) {
|
|
604
|
+
throw new CoreMindError("loop_paused", `步骤 ${request.stepId} 的工具请求未获批准`);
|
|
605
|
+
}
|
|
606
|
+
const lastAssistant = [...agent.state.messages]
|
|
607
|
+
.reverse()
|
|
608
|
+
.find((message) => message.role === "assistant");
|
|
609
|
+
if (lastAssistant?.stopReason === "aborted") {
|
|
610
|
+
throw new CoreMindError("aborted", `步骤 ${request.stepId} 已中止`);
|
|
611
|
+
}
|
|
612
|
+
if (lastAssistant?.stopReason === "error") {
|
|
613
|
+
const agentError = lastAssistant.errorMessage ?? "模型执行失败,但未提供错误详情";
|
|
614
|
+
const code = classifyRetry(lastAssistant).retryable ? "provider_transient" : "agent_failed";
|
|
615
|
+
throw new CoreMindError(code, `步骤 ${request.stepId} 的 Agent 执行失败:${agentError}`);
|
|
616
|
+
}
|
|
617
|
+
return extractText(agent.state.messages.slice(messageCursor));
|
|
618
|
+
}
|
|
439
619
|
abortAll() {
|
|
440
620
|
for (const agent of this.lastAgents.values())
|
|
441
621
|
agent.abort();
|
|
@@ -485,15 +665,10 @@ function lastOutputText(outputs) {
|
|
|
485
665
|
function firstKey(record) {
|
|
486
666
|
return Object.keys(record)[0];
|
|
487
667
|
}
|
|
488
|
-
function
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
status: code === "aborted" || code === "run_timeout" ? "aborted" : "failed",
|
|
494
|
-
finishReason: code,
|
|
495
|
-
error: { code, message },
|
|
496
|
-
},
|
|
497
|
-
};
|
|
668
|
+
function effectCallKey(stepId, callId) {
|
|
669
|
+
return `${stepId ?? "agent"}:${callId}`;
|
|
670
|
+
}
|
|
671
|
+
function effectIdempotencyKey(runId, stepId, callId) {
|
|
672
|
+
return stepId ? `${runId}:${stepId}:${callId}` : `${runId}:${callId}`;
|
|
498
673
|
}
|
|
499
674
|
//# sourceMappingURL=runtime.js.map
|