coremind-runtime 0.2.0-beta.2 → 0.3.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.
Files changed (108) hide show
  1. package/README.md +12 -2
  2. package/dist/agent-factory.d.ts +4 -0
  3. package/dist/agent-factory.d.ts.map +1 -1
  4. package/dist/agent-factory.js +19 -7
  5. package/dist/agent-factory.js.map +1 -1
  6. package/dist/budget.d.ts.map +1 -1
  7. package/dist/budget.js +3 -2
  8. package/dist/budget.js.map +1 -1
  9. package/dist/checkpoint.d.ts +13 -1
  10. package/dist/checkpoint.d.ts.map +1 -1
  11. package/dist/checkpoint.js +76 -2
  12. package/dist/checkpoint.js.map +1 -1
  13. package/dist/coding/engineering-kernel.d.ts +159 -0
  14. package/dist/coding/engineering-kernel.d.ts.map +1 -0
  15. package/dist/coding/engineering-kernel.js +476 -0
  16. package/dist/coding/engineering-kernel.js.map +1 -0
  17. package/dist/context.d.ts +34 -1
  18. package/dist/context.d.ts.map +1 -1
  19. package/dist/context.js +110 -10
  20. package/dist/context.js.map +1 -1
  21. package/dist/dependency-adapter.d.ts +26 -0
  22. package/dist/dependency-adapter.d.ts.map +1 -0
  23. package/dist/dependency-adapter.js +30 -0
  24. package/dist/dependency-adapter.js.map +1 -0
  25. package/dist/evaluation-graders.d.ts +89 -0
  26. package/dist/evaluation-graders.d.ts.map +1 -0
  27. package/dist/evaluation-graders.js +481 -0
  28. package/dist/evaluation-graders.js.map +1 -0
  29. package/dist/evaluation.d.ts +13 -2
  30. package/dist/evaluation.d.ts.map +1 -1
  31. package/dist/evaluation.js +156 -37
  32. package/dist/evaluation.js.map +1 -1
  33. package/dist/events.d.ts +58 -0
  34. package/dist/events.d.ts.map +1 -1
  35. package/dist/events.js +10 -1
  36. package/dist/events.js.map +1 -1
  37. package/dist/experiment.d.ts +63 -0
  38. package/dist/experiment.d.ts.map +1 -0
  39. package/dist/experiment.js +96 -0
  40. package/dist/experiment.js.map +1 -0
  41. package/dist/index.d.ts +15 -5
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +12 -2
  44. package/dist/index.js.map +1 -1
  45. package/dist/lifecycle-extension.d.ts +74 -0
  46. package/dist/lifecycle-extension.d.ts.map +1 -0
  47. package/dist/lifecycle-extension.js +200 -0
  48. package/dist/lifecycle-extension.js.map +1 -0
  49. package/dist/loop-controller.d.ts +79 -0
  50. package/dist/loop-controller.d.ts.map +1 -0
  51. package/dist/loop-controller.js +372 -0
  52. package/dist/loop-controller.js.map +1 -0
  53. package/dist/loop-runner.d.ts +52 -0
  54. package/dist/loop-runner.d.ts.map +1 -0
  55. package/dist/loop-runner.js +213 -0
  56. package/dist/loop-runner.js.map +1 -0
  57. package/dist/operation-state.d.ts +62 -0
  58. package/dist/operation-state.d.ts.map +1 -0
  59. package/dist/operation-state.js +160 -0
  60. package/dist/operation-state.js.map +1 -0
  61. package/dist/orchestrator.d.ts.map +1 -1
  62. package/dist/orchestrator.js +3 -2
  63. package/dist/orchestrator.js.map +1 -1
  64. package/dist/provider.d.ts +2 -0
  65. package/dist/provider.d.ts.map +1 -1
  66. package/dist/provider.js +5 -2
  67. package/dist/provider.js.map +1 -1
  68. package/dist/public-tool.d.ts +2 -0
  69. package/dist/public-tool.d.ts.map +1 -1
  70. package/dist/public-tool.js +12 -0
  71. package/dist/public-tool.js.map +1 -1
  72. package/dist/result.d.ts +16 -1
  73. package/dist/result.d.ts.map +1 -1
  74. package/dist/result.js +46 -5
  75. package/dist/result.js.map +1 -1
  76. package/dist/retry-policy.d.ts +16 -0
  77. package/dist/retry-policy.d.ts.map +1 -0
  78. package/dist/retry-policy.js +112 -0
  79. package/dist/retry-policy.js.map +1 -0
  80. package/dist/run-state.d.ts +32 -2
  81. package/dist/run-state.d.ts.map +1 -1
  82. package/dist/run-state.js +211 -20
  83. package/dist/run-state.js.map +1 -1
  84. package/dist/run-terminalizer.d.ts +11 -0
  85. package/dist/run-terminalizer.d.ts.map +1 -0
  86. package/dist/run-terminalizer.js +39 -0
  87. package/dist/run-terminalizer.js.map +1 -0
  88. package/dist/runtime.d.ts +17 -1
  89. package/dist/runtime.d.ts.map +1 -1
  90. package/dist/runtime.js +469 -65
  91. package/dist/runtime.js.map +1 -1
  92. package/dist/session.d.ts +12 -2
  93. package/dist/session.d.ts.map +1 -1
  94. package/dist/session.js +455 -19
  95. package/dist/session.js.map +1 -1
  96. package/dist/snapshot.d.ts +25 -0
  97. package/dist/snapshot.d.ts.map +1 -0
  98. package/dist/snapshot.js +12 -0
  99. package/dist/snapshot.js.map +1 -0
  100. package/dist/tool-policy.d.ts +11 -2
  101. package/dist/tool-policy.d.ts.map +1 -1
  102. package/dist/tool-policy.js +112 -15
  103. package/dist/tool-policy.js.map +1 -1
  104. package/dist/trace.d.ts +2 -0
  105. package/dist/trace.d.ts.map +1 -1
  106. package/dist/trace.js +77 -1
  107. package/dist/trace.js.map +1 -1
  108. package/package.json +15 -8
package/dist/runtime.js CHANGED
@@ -1,19 +1,25 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import path from "node:path";
3
3
  import { loadDirectorySkills, resolveSkills, SKILLS } from "coremind-templates";
4
- import { buildTools } from "coremind-tools";
4
+ import { ArtifactStore, buildTools, extractArtifactRecord, wrapToolWithArtifactCapture, } from "coremind-tools";
5
5
  import { buildAgent } from "./agent-factory.js";
6
6
  import { RunBudgetController, resolveRuntimeLimits } from "./budget.js";
7
7
  import { CheckpointManager, inspectCheckpoint as inspectStoredCheckpoint, restoreCheckpoint as restoreStoredCheckpoint, } from "./checkpoint.js";
8
8
  import { ContextProtector } from "./context.js";
9
9
  import { CoreMindError } from "./errors.js";
10
10
  import { extractAgentError, extractText } from "./events.js";
11
+ import { LifecycleExtensionHost, } from "./lifecycle-extension.js";
12
+ import { LoopRunner } from "./loop-runner.js";
13
+ import { DurableOperation, restoreDurableOperation, } from "./operation-state.js";
11
14
  import { Orchestrator } from "./orchestrator.js";
12
15
  import { buildProviderRuntime } from "./provider.js";
13
16
  import { adaptCoreMindTool } from "./public-tool.js";
14
17
  import { analyzeRunMetrics, assessReleaseReadiness, createEvaluationReport, } from "./result.js";
18
+ import { classifyRetry, runWithTransientRetry } from "./retry-policy.js";
15
19
  import { FileRunStore, fingerprintRunConfig, prepareRunResume, RunStateJournal, } from "./run-state.js";
20
+ import { RunTerminalizer } from "./run-terminalizer.js";
16
21
  import { CoreMindSession } from "./session.js";
22
+ import { createRunSnapshot } from "./snapshot.js";
17
23
  import { ToolPolicy } from "./tool-policy.js";
18
24
  import { TraceRecorder } from "./trace.js";
19
25
  /**
@@ -24,6 +30,7 @@ export class CoreMindRuntime {
24
30
  config;
25
31
  agentConfigs;
26
32
  toolsByAgent;
33
+ toolEffectsByAgent;
27
34
  providerRuntime;
28
35
  options;
29
36
  /** 最近创建的每个 agent 实例(收集最终消息/落盘用) */
@@ -37,10 +44,11 @@ export class CoreMindRuntime {
37
44
  /** agent 名 → 注入的技能内容 */
38
45
  skillsByAgent;
39
46
  activeHarnessFactory;
40
- constructor(config, agentConfigs, toolsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent) {
47
+ constructor(config, agentConfigs, toolsByAgent, toolEffectsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent) {
41
48
  this.config = config;
42
49
  this.agentConfigs = agentConfigs;
43
50
  this.toolsByAgent = toolsByAgent;
51
+ this.toolEffectsByAgent = toolEffectsByAgent;
44
52
  this.providerRuntime = providerRuntime;
45
53
  this.options = options;
46
54
  this.sessionMessages = sessionMessages;
@@ -62,18 +70,29 @@ export class CoreMindRuntime {
62
70
  // 2. 每个 agent:构建工具与技能(Agent 实例按需创建,避免并发冲突)
63
71
  const agentConfigs = new Map();
64
72
  const toolsByAgent = new Map();
73
+ const toolEffectsByAgent = new Map();
65
74
  const skillsByAgent = new Map();
66
- const externalTools = (options.toolDefinitions ?? []).map(adaptCoreMindTool);
75
+ const artifactStore = new ArtifactStore({ cwd });
76
+ const externalTools = (options.toolDefinitions ?? []).map((definition) => wrapToolWithArtifactCapture(adaptCoreMindTool(definition), artifactStore));
67
77
  // 自定义技能(生态机制):配置文件所在目录的 skills/ 下,每个子目录的 README.md 即一个技能
68
78
  const customSkills = await loadDirectorySkills(path.join(configDir, "skills"));
69
79
  for (const [name, agentCfg] of Object.entries(config.agents)) {
70
80
  const toolConfigs = (agentCfg.tools?.length ?? 0) > 0 ? agentCfg.tools : config.tools;
71
- const { tools, warnings } = await buildTools(toolConfigs ?? [], { cwd, configDir, env });
81
+ const { tools, warnings, effects } = await buildTools(toolConfigs ?? [], {
82
+ cwd,
83
+ configDir,
84
+ env,
85
+ artifactStore,
86
+ });
72
87
  for (const warning of warnings) {
73
88
  emit({ type: "error", message: warning, fatal: false });
74
89
  }
75
90
  agentConfigs.set(name, agentCfg);
76
91
  toolsByAgent.set(name, [...tools, ...externalTools]);
92
+ toolEffectsByAgent.set(name, new Map([
93
+ ...effects,
94
+ ...(options.toolDefinitions ?? []).map((definition) => [definition.name, definition.effect]),
95
+ ]));
77
96
  // 技能:内置优先,未命中的查自定义目录,仍缺失才告警(不阻断)
78
97
  const { contents, missing } = resolveSkills(agentCfg.skills ?? []);
79
98
  const allContents = [...contents];
@@ -112,13 +131,14 @@ export class CoreMindRuntime {
112
131
  throw new CoreMindError("session_restore_failed", `会话 ${options.sessionId} 恢复失败:${detail}`);
113
132
  }
114
133
  }
115
- return new CoreMindRuntime(config, agentConfigs, toolsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent);
134
+ return new CoreMindRuntime(config, agentConfigs, toolsByAgent, toolEffectsByAgent, providerRuntime, options, sessionMessages, resumedContextLength, skillsByAgent);
116
135
  }
117
136
  /** 按名字创建独立 Agent 实例(每次新实例,消息历史独立) */
118
- createAgent(name, onEvent = this.options.events ?? (() => { })) {
137
+ createAgent(name, onEvent = this.options.events ?? (() => { }), stepId) {
119
138
  const agentCfg = this.agentConfigs.get(name);
120
139
  if (!agentCfg)
121
140
  return undefined;
141
+ const harness = this.activeHarnessFactory?.(name, stepId);
122
142
  const agent = buildAgent(agentCfg, {
123
143
  models: this.providerRuntime.models,
124
144
  model: this.providerRuntime.model,
@@ -129,8 +149,23 @@ export class CoreMindRuntime {
129
149
  // 恢复视图只注入主 agent(会话归属者)
130
150
  sessionMessages: name === this.mainAgentName ? this.sessionMessages : undefined,
131
151
  skillsContent: this.skillsByAgent.get(name),
132
- harness: this.activeHarnessFactory?.(name),
152
+ stableFacts: {
153
+ provider: this.providerRuntime.model.provider,
154
+ model: this.providerRuntime.model.id,
155
+ contextWindow: this.providerRuntime.model.contextWindow,
156
+ },
157
+ promptCacheStatus: this.providerRuntime.promptCacheStatus,
158
+ harness,
133
159
  });
160
+ // 该停止钩子只属于 Runtime 内部 Harness,不扩大公开 AgentBuildContext 合同。
161
+ agent.shouldStopAfterTurn = harness?.shouldStopAfterTurn;
162
+ if (harness?.throwIfDenied) {
163
+ const waitForIdle = agent.waitForIdle.bind(agent);
164
+ agent.waitForIdle = async () => {
165
+ await waitForIdle();
166
+ harness.throwIfDenied?.();
167
+ };
168
+ }
134
169
  this.lastAgents.set(name, agent);
135
170
  return agent;
136
171
  }
@@ -152,7 +187,7 @@ export class CoreMindRuntime {
152
187
  }
153
188
  const turnConfig = { ...this.config, defaultAgent: agentName };
154
189
  delete turnConfig.workflow;
155
- const turnRuntime = new CoreMindRuntime(turnConfig, this.agentConfigs, this.toolsByAgent, this.providerRuntime, {
190
+ const turnRuntime = new CoreMindRuntime(turnConfig, this.agentConfigs, this.toolsByAgent, this.toolEffectsByAgent, this.providerRuntime, {
156
191
  ...this.options,
157
192
  config: turnConfig,
158
193
  initialPrompt: message,
@@ -170,6 +205,9 @@ export class CoreMindRuntime {
170
205
  /** 执行:有 workflow 走编排,否则单 agent 直答。返回结果含质量摘要 */
171
206
  async run() {
172
207
  const started = performance.now();
208
+ const lifecycleHost = this.options.lifecycleExtensions
209
+ ? new LifecycleExtensionHost(this.options.lifecycleExtensions)
210
+ : undefined;
173
211
  const runStore = this.options.runStore ??
174
212
  new FileRunStore(path.join(this.options.configDir, ".coremind", "runs"));
175
213
  const configFingerprint = fingerprintRunConfig(this.config);
@@ -179,12 +217,30 @@ export class CoreMindRuntime {
179
217
  const runId = resumePlan?.runId ?? randomUUID();
180
218
  const effectiveInitialPrompt = resumePlan?.initialPrompt ?? this.options.initialPrompt;
181
219
  const journal = new RunStateJournal(runId, runStore, resumePlan?.nextJournalSequence ?? 0);
220
+ const operation = resumePlan && resumePlan.operationRecords.length > 0
221
+ ? restoreDurableOperation(resumePlan.operationRecords)
222
+ : DurableOperation.create({
223
+ runId,
224
+ operationId: randomUUID(),
225
+ eventId: randomUUID(),
226
+ });
227
+ const persistOperation = (event) => {
228
+ const transition = operation.transition(event);
229
+ if (transition.record)
230
+ journal.operation(transition.record);
231
+ };
232
+ const initialOperationState = operation.snapshot().state;
233
+ if (resumePlan &&
234
+ initialOperationState !== "accepted" &&
235
+ initialOperationState !== "running" &&
236
+ initialOperationState !== "paused") {
237
+ throw new CoreMindError("operation_not_resumable", `操作 ${operation.snapshot().operationId} 处于 ${initialOperationState},不能继续执行`);
238
+ }
182
239
  if (resumePlan) {
183
240
  journal.resume({
184
241
  completedStepIds: [...resumePlan.completedSteps.keys()],
185
242
  resumedAt: new Date().toISOString(),
186
243
  });
187
- await journal.flush();
188
244
  }
189
245
  else {
190
246
  await journal.start({
@@ -193,23 +249,94 @@ export class CoreMindRuntime {
193
249
  configFingerprint,
194
250
  initialPrompt: this.options.initialPrompt,
195
251
  sessionId: this.options.sessionId,
252
+ operationId: operation.snapshot().operationId,
196
253
  });
197
254
  }
255
+ if (!resumePlan || resumePlan.operationRecords.length === 0) {
256
+ journal.operation(operation.records()[0]);
257
+ }
258
+ if (operation.snapshot().state === "running") {
259
+ persistOperation({
260
+ eventId: randomUUID(),
261
+ type: "PAUSE",
262
+ reason: "process_interrupted",
263
+ });
264
+ }
265
+ if (operation.snapshot().state === "accepted") {
266
+ persistOperation({ eventId: randomUUID(), type: "START" });
267
+ }
268
+ else if (operation.snapshot().state === "paused") {
269
+ persistOperation({ eventId: randomUUID(), type: "RESUME" });
270
+ }
271
+ else {
272
+ throw new CoreMindError("operation_not_resumable", `操作 ${operation.snapshot().operationId} 处于 ${operation.snapshot().state},不能继续执行`);
273
+ }
274
+ await journal.flush();
198
275
  const trace = new TraceRecorder(runId, (entry) => {
199
276
  journal.event(entry);
200
277
  this.options.trace?.(entry);
201
278
  }, resumePlan?.previousTrace);
202
279
  const collected = resumePlan?.previousTrace.map((entry) => entry.event) ?? [];
203
280
  const userEvents = this.options.events ?? (() => { });
281
+ const extensionReceipts = [];
282
+ const activeToolEffects = new Map();
283
+ const recordEvent = (event) => {
284
+ collected.push(event);
285
+ trace.record(event);
286
+ userEvents(event);
287
+ };
204
288
  const emit = (event) => {
205
- const enriched = event.type === "tool_call" && event.callId && !event.idempotencyKey
206
- ? { ...event, idempotencyKey: `${runId}:${event.callId}` }
289
+ const enriched = (event.type === "tool_call" || event.type === "tool_result") &&
290
+ event.callId &&
291
+ !event.idempotencyKey
292
+ ? { ...event, idempotencyKey: effectIdempotencyKey(runId, event.stepId, event.callId) }
207
293
  : event;
208
- collected.push(enriched);
209
- trace.record(enriched);
210
- userEvents(enriched);
294
+ recordEvent(enriched);
295
+ if (enriched.type === "tool_call" && enriched.callId && enriched.idempotencyKey) {
296
+ const effect = {
297
+ idempotencyKey: enriched.idempotencyKey,
298
+ tool: enriched.tool,
299
+ ...(enriched.stepId ? { stepId: enriched.stepId } : {}),
300
+ };
301
+ activeToolEffects.set(effectCallKey(enriched.stepId, enriched.callId), effect);
302
+ recordEvent({ type: "effect_receipt", ...effect, status: "started" });
303
+ }
304
+ if (enriched.type === "tool_result" && enriched.callId) {
305
+ const callKey = effectCallKey(enriched.stepId, enriched.callId);
306
+ const effect = activeToolEffects.get(callKey) ?? {
307
+ idempotencyKey: effectIdempotencyKey(runId, enriched.stepId, enriched.callId),
308
+ tool: enriched.tool,
309
+ ...(enriched.stepId ? { stepId: enriched.stepId } : {}),
310
+ };
311
+ activeToolEffects.delete(callKey);
312
+ recordEvent({
313
+ type: "effect_receipt",
314
+ ...effect,
315
+ status: enriched.isError ? "unknown" : "committed",
316
+ });
317
+ }
318
+ };
319
+ const dispatchLifecycle = async (lifecycle, payload) => {
320
+ if (!lifecycleHost)
321
+ return undefined;
322
+ const result = await lifecycleHost.dispatch(lifecycle, payload);
323
+ for (const receipt of result.receipts) {
324
+ extensionReceipts.push(receipt);
325
+ emit({
326
+ type: "extension_lifecycle",
327
+ extensionId: receipt.extensionId,
328
+ extensionVersion: receipt.extensionVersion,
329
+ lifecycle: receipt.event,
330
+ status: receipt.status,
331
+ durationMs: receipt.durationMs,
332
+ error: receipt.error,
333
+ denied: receipt.denied,
334
+ });
335
+ }
336
+ return result;
211
337
  };
212
338
  const workflow = this.config.workflow;
339
+ const loop = this.config.loop;
213
340
  const limits = resolveRuntimeLimits(this.config.runtime, {
214
341
  maxSteps: this.options.maxSteps,
215
342
  stepTimeoutMs: this.options.stepTimeoutMs,
@@ -223,6 +350,8 @@ export class CoreMindRuntime {
223
350
  runId: trace.runId,
224
351
  });
225
352
  let checkpointFailure;
353
+ const artifacts = [];
354
+ const checkpointByCallId = new Map();
226
355
  const contextWindow = this.providerRuntime.model.contextWindow;
227
356
  const contextProtector = new ContextProtector({
228
357
  contextWindow,
@@ -233,6 +362,13 @@ export class CoreMindRuntime {
233
362
  beforeTokens: result.beforeTokens,
234
363
  afterTokens: result.afterTokens,
235
364
  removedMessages: result.removedMessages,
365
+ strategy: "deterministic-v1",
366
+ reason: "threshold",
367
+ summaryFingerprint: result.summaryFingerprint,
368
+ }), (failure) => emit({
369
+ type: "context_compaction_failed",
370
+ message: failure.message,
371
+ preservedMessages: failure.preservedMessages,
236
372
  }));
237
373
  const policy = new ToolPolicy({
238
374
  permissions: this.config.permissions,
@@ -248,6 +384,7 @@ export class CoreMindRuntime {
248
384
  tool: request.tool,
249
385
  args: request.args,
250
386
  risk: request.risk,
387
+ effect: request.effect,
251
388
  }),
252
389
  onApprovalResolved: (request, decision) => emit({
253
390
  type: "approval_resolved",
@@ -256,31 +393,76 @@ export class CoreMindRuntime {
256
393
  decision,
257
394
  }),
258
395
  });
259
- this.activeHarnessFactory = (agentName) => ({
260
- maxRetries: limits.maxRetries,
261
- transformContext: async (messages) => contextProtector.transform(messages),
396
+ const deniedAgents = new Set();
397
+ this.activeHarnessFactory = (agentName, stepId) => ({
398
+ maxRetries: loop ? 0 : limits.maxRetries,
399
+ transformContext: async (messages) => {
400
+ await dispatchLifecycle("before-model", {
401
+ runId,
402
+ agent: agentName,
403
+ stepId,
404
+ messageCount: messages.length,
405
+ });
406
+ return contextProtector.transform(messages);
407
+ },
262
408
  beforeToolCall: async (context) => {
409
+ if (deniedAgents.has(agentName)) {
410
+ return {
411
+ block: true,
412
+ reason: "同一工具批次已有请求被拒绝",
413
+ terminate: true,
414
+ };
415
+ }
263
416
  const blockedByBudget = budget.beforeToolCall();
264
417
  if (blockedByBudget)
265
418
  return blockedByBudget;
266
- const decision = await policy.authorize(agentName, context.toolCall.name, context.args);
419
+ const decision = await policy.authorize(agentName, context.toolCall.name, context.args, this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.name));
267
420
  if (!decision.allowed) {
421
+ deniedAgents.add(agentName);
268
422
  emit({
269
423
  type: "policy_denied",
270
424
  agent: agentName,
271
425
  tool: context.toolCall.name,
272
426
  reason: decision.reason,
273
427
  });
274
- return { block: true, reason: decision.reason };
428
+ return { block: true, reason: decision.reason, terminate: true };
429
+ }
430
+ const extensionDecision = await dispatchLifecycle("before-tool", {
431
+ runId,
432
+ agent: agentName,
433
+ stepId,
434
+ tool: context.toolCall.name,
435
+ callId: context.toolCall.id,
436
+ args: context.args,
437
+ approvalAllowed: true,
438
+ });
439
+ if (extensionDecision?.denied) {
440
+ deniedAgents.add(agentName);
441
+ const reason = extensionDecision.denied.reason;
442
+ emit({
443
+ type: "policy_denied",
444
+ agent: agentName,
445
+ tool: context.toolCall.name,
446
+ reason,
447
+ });
448
+ return { block: true, reason, terminate: true };
275
449
  }
276
450
  try {
277
- const checkpoint = await checkpointManager.capture(context.toolCall.name, context.args);
451
+ const idempotencyKey = effectIdempotencyKey(runId, stepId, context.toolCall.id);
452
+ const checkpoint = await checkpointManager.capture(context.toolCall.name, context.args, {
453
+ operationId: operation.snapshot().operationId,
454
+ toolCallId: context.toolCall.id,
455
+ idempotencyKey,
456
+ });
278
457
  if (checkpoint) {
458
+ checkpointByCallId.set(context.toolCall.id, checkpoint.checkpointId);
279
459
  journal.checkpoint(checkpoint);
280
460
  emit({
281
461
  type: "checkpoint_created",
282
462
  checkpointId: checkpoint.checkpointId,
283
463
  tool: checkpoint.tool,
464
+ callId: context.toolCall.id,
465
+ idempotencyKey,
284
466
  targetPath: checkpoint.targetPath,
285
467
  reversible: checkpoint.reversible,
286
468
  });
@@ -296,26 +478,117 @@ export class CoreMindRuntime {
296
478
  }
297
479
  return undefined;
298
480
  },
299
- afterToolCall: async (context) => budget.afterToolCall(context.isError),
481
+ afterToolCall: async (context) => {
482
+ const artifact = extractArtifactRecord(context.result.details);
483
+ if (artifact) {
484
+ artifacts.push(artifact);
485
+ emit({
486
+ type: "artifact_created",
487
+ artifactId: artifact.artifactId,
488
+ status: artifact.status,
489
+ sizeBytes: artifact.sizeBytes,
490
+ relativePath: artifact.relativePath,
491
+ sha256: artifact.sha256,
492
+ mediaType: artifact.mediaType,
493
+ redaction: artifact.redaction,
494
+ tool: context.toolCall.name,
495
+ callId: context.toolCall.id,
496
+ });
497
+ }
498
+ const checkpointId = checkpointByCallId.get(context.toolCall.id);
499
+ checkpointByCallId.delete(context.toolCall.id);
500
+ if (checkpointId) {
501
+ try {
502
+ await checkpointManager.markApplied(checkpointId);
503
+ }
504
+ catch (error) {
505
+ checkpointFailure =
506
+ error instanceof CoreMindError
507
+ ? error
508
+ : new CoreMindError("checkpoint_failed", error instanceof Error ? error.message : String(error));
509
+ emit({ type: "error", message: checkpointFailure.message, fatal: true });
510
+ }
511
+ }
512
+ const budgetResult = budget.afterToolCall(context.isError);
513
+ await dispatchLifecycle("after-tool", {
514
+ runId,
515
+ agent: agentName,
516
+ stepId,
517
+ tool: context.toolCall.name,
518
+ callId: context.toolCall.id,
519
+ isError: context.isError,
520
+ checkpointId,
521
+ artifactId: artifact?.artifactId,
522
+ });
523
+ return checkpointFailure ? { terminate: true } : budgetResult;
524
+ },
525
+ shouldStopAfterTurn: () => deniedAgents.has(agentName),
526
+ throwIfDenied: () => {
527
+ if (deniedAgents.has(agentName)) {
528
+ throw new CoreMindError("loop_paused", stepId ? `步骤 ${stepId} 的工具请求未获批准` : `Agent ${agentName} 的工具请求未获批准`);
529
+ }
530
+ },
300
531
  onAgentEvent: (event, agent) => {
301
532
  if (budget.observeAgentEvent(event))
302
533
  agent.abort();
303
534
  },
304
535
  });
305
- let outputs;
306
- let transcript;
536
+ let outputs = new Map();
537
+ let transcript = "";
538
+ let terminalError;
539
+ let loopSnapshot = resumePlan?.loopSnapshot;
540
+ let activeLoopRunner;
307
541
  try {
308
542
  ({ outputs, transcript } = await this.runWithGuard(limits.runTimeoutMs, async () => {
543
+ if (loop) {
544
+ let retryCount = resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry" && entry.event.scope === "provider").length ?? 0;
545
+ const runner = new LoopRunner({
546
+ runId,
547
+ configFingerprint,
548
+ initialPrompt: effectiveInitialPrompt,
549
+ loop,
550
+ completedSteps: resumePlan?.completedSteps,
551
+ restoredSnapshot: resumePlan?.loopSnapshot,
552
+ emit,
553
+ persistSnapshot: async (snapshot) => {
554
+ loopSnapshot = snapshot;
555
+ journal.loop(snapshot);
556
+ await journal.flush();
557
+ },
558
+ executeStep: (request) => runWithTransientRetry(() => this.executeLoopStep(request, emit, limits.stepTimeoutMs, collected), {
559
+ maxRetries: Math.max(0, limits.maxRetries - retryCount),
560
+ signal: this.options.signal,
561
+ onRetry: () => {
562
+ retryCount += 1;
563
+ emit({
564
+ type: "retry",
565
+ scope: "provider",
566
+ attempt: retryCount,
567
+ stepId: request.stepId,
568
+ });
569
+ },
570
+ }),
571
+ });
572
+ activeLoopRunner = runner;
573
+ const loopResult = await runner.run();
574
+ outputs = loopResult.outputs;
575
+ transcript = loopResult.transcript;
576
+ loopSnapshot = loopResult.snapshot;
577
+ if (loopResult.error !== undefined)
578
+ throw loopResult.error;
579
+ return { outputs, transcript };
580
+ }
309
581
  if (workflow && workflow.length > 0) {
310
582
  const orchestrator = new Orchestrator(workflow, {
311
- createAgent: (name, stepId) => this.createAgent(name, (event) => emit(stepId ? { ...event, stepId } : event)),
583
+ createAgent: (name, stepId) => this.createAgent(name, (event) => emit(stepId ? { ...event, stepId } : event), stepId),
312
584
  events: emit,
313
585
  initialPrompt: effectiveInitialPrompt,
314
586
  signal: this.options.signal,
315
587
  maxSteps: limits.maxSteps,
316
588
  stepTimeoutMs: limits.stepTimeoutMs,
317
589
  maxRetries: limits.maxRetries,
318
- initialRetryCount: resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry").length ?? 0,
590
+ initialRetryCount: resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry").length ??
591
+ 0,
319
592
  completedSteps: resumePlan?.completedSteps,
320
593
  });
321
594
  const workflowOutputs = await orchestrator.run();
@@ -342,56 +615,125 @@ export class CoreMindRuntime {
342
615
  }
343
616
  transcript = extractText(agent.state.messages.slice(messageCursor));
344
617
  return { outputs: new Map(), transcript };
345
- }));
618
+ }, (error) => activeLoopRunner?.interrupt(error)));
346
619
  if (checkpointFailure)
347
620
  throw checkpointFailure;
348
621
  budget.throwIfExceeded();
349
622
  }
350
623
  catch (error) {
351
- let runError = error;
352
- if (checkpointFailure)
353
- runError = checkpointFailure;
624
+ terminalError = checkpointFailure ?? error;
354
625
  try {
355
626
  if (!checkpointFailure)
356
627
  budget.throwIfExceeded();
357
628
  }
358
629
  catch (budgetError) {
359
- runError = budgetError;
630
+ terminalError = budgetError;
360
631
  }
361
- journal.finish(failedRunPayload(runError));
362
- await journal.flush();
363
- throw runError;
364
632
  }
365
633
  finally {
366
634
  this.activeHarnessFactory = undefined;
367
635
  }
368
636
  let sessionFile;
369
- try {
370
- sessionFile = await this.persistSession();
371
- }
372
- catch (error) {
373
- journal.finish(failedRunPayload(error));
374
- await journal.flush();
375
- throw error;
637
+ if (terminalError === undefined) {
638
+ try {
639
+ sessionFile = await this.persistSession();
640
+ }
641
+ catch (error) {
642
+ terminalError = error;
643
+ }
376
644
  }
377
645
  const allMessages = [...this.collectMessages().values()].flat();
646
+ if (terminalError !== undefined && transcript.length === 0) {
647
+ transcript = extractText(allMessages);
648
+ }
378
649
  const metrics = analyzeRunMetrics(collected, allMessages, performance.now() - started, transcript.length);
379
- const allToolRequestsDenied = collected.some((event) => event.type === "policy_denied") &&
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" };
650
+ const outcome = new RunTerminalizer().terminalize(collected, terminalError);
384
651
  const evaluation = createEvaluationReport(this.config.quality, metrics);
385
- for (const checkpoint of checkpointManager.records) {
386
- if (!checkpoint.reversible) {
387
- evaluation.securityFindings.push(`工具 ${checkpoint.tool} 的副作用不可自动回退`);
652
+ const releaseReadiness = assessReleaseReadiness(outcome, evaluation);
653
+ const irreversibleTools = [
654
+ ...new Set(checkpointManager.records
655
+ .filter((checkpoint) => !checkpoint.reversible)
656
+ .map((checkpoint) => checkpoint.tool)),
657
+ ];
658
+ if (irreversibleTools.length > 0) {
659
+ releaseReadiness.warnings.push(`存在不可自动回退的工具执行:${irreversibleTools.join("、")};请结合 Trace 和外部系统记录复核`);
660
+ }
661
+ if (outcome.status === "paused") {
662
+ persistOperation({
663
+ eventId: randomUUID(),
664
+ type: "PAUSE",
665
+ reason: outcome.finishReason,
666
+ });
667
+ }
668
+ else {
669
+ if (outcome.status === "aborted") {
670
+ persistOperation({
671
+ eventId: randomUUID(),
672
+ type: "REQUEST_ABORT",
673
+ reason: outcome.finishReason,
674
+ });
675
+ persistOperation({
676
+ eventId: randomUUID(),
677
+ type: "FAIL",
678
+ reason: outcome.finishReason,
679
+ });
680
+ }
681
+ else if (outcome.status === "succeeded") {
682
+ persistOperation({ eventId: randomUUID(), type: "COMPLETE" });
683
+ }
684
+ else {
685
+ persistOperation({
686
+ eventId: randomUUID(),
687
+ type: "FAIL",
688
+ reason: outcome.finishReason,
689
+ });
388
690
  }
389
691
  }
390
- const releaseReadiness = assessReleaseReadiness(outcome, evaluation);
391
- journal.finish({ outcome, metrics, evaluation, releaseReadiness });
692
+ await dispatchLifecycle("run-finished", {
693
+ runId,
694
+ operation: operation.snapshot(),
695
+ outcome,
696
+ metrics,
697
+ evaluation,
698
+ releaseReadiness,
699
+ checkpointCount: checkpointManager.records.length,
700
+ artifactCount: artifacts.length,
701
+ });
702
+ if (outcome.status === "paused") {
703
+ journal.pause({
704
+ operation: operation.snapshot(),
705
+ outcome,
706
+ metrics,
707
+ evaluation,
708
+ releaseReadiness,
709
+ ...(loopSnapshot ? { loopSnapshot } : {}),
710
+ });
711
+ }
712
+ else {
713
+ journal.finish({
714
+ operation: operation.snapshot(),
715
+ outcome,
716
+ metrics,
717
+ evaluation,
718
+ releaseReadiness,
719
+ });
720
+ }
392
721
  await journal.flush();
722
+ const snapshot = createRunSnapshot({
723
+ runId: trace.runId,
724
+ operation: operation.snapshot(),
725
+ outcome,
726
+ metrics,
727
+ evaluation,
728
+ releaseReadiness,
729
+ trace: trace.entries,
730
+ checkpoints: checkpointManager.records,
731
+ artifacts,
732
+ extensions: extensionReceipts,
733
+ });
393
734
  return {
394
735
  runId: trace.runId,
736
+ operation: operation.snapshot(),
395
737
  outcome,
396
738
  metrics,
397
739
  evaluation,
@@ -403,27 +745,41 @@ export class CoreMindRuntime {
403
745
  messages: this.collectMessages(),
404
746
  transcript,
405
747
  sessionFile,
748
+ artifacts,
749
+ extensions: extensionReceipts,
750
+ snapshot,
406
751
  };
407
752
  }
408
- async runWithGuard(timeoutMs, operation) {
753
+ async runWithGuard(timeoutMs, operation, onGuardError) {
409
754
  const signal = this.options.signal;
410
755
  if (signal?.aborted)
411
756
  throw new CoreMindError("aborted", "执行已中止");
412
757
  let timer;
413
758
  let rejectAbort;
759
+ let guardTriggered = false;
414
760
  const aborted = new Promise((_resolve, reject) => {
415
761
  rejectAbort = reject;
416
762
  });
763
+ const triggerGuard = (error, reject) => {
764
+ if (guardTriggered)
765
+ return;
766
+ guardTriggered = true;
767
+ void Promise.resolve(onGuardError?.(error))
768
+ .catch(() => undefined)
769
+ .then(() => {
770
+ reject(error);
771
+ this.abortAll();
772
+ });
773
+ };
417
774
  const onAbort = () => {
418
- this.abortAll();
419
- rejectAbort?.(new CoreMindError("aborted", "执行已中止"));
775
+ if (rejectAbort)
776
+ triggerGuard(new CoreMindError("aborted", "执行已中止"), rejectAbort);
420
777
  };
421
778
  signal?.addEventListener("abort", onAbort, { once: true });
422
779
  const timedOut = timeoutMs > 0
423
780
  ? new Promise((_resolve, reject) => {
424
781
  timer = setTimeout(() => {
425
- this.abortAll();
426
- reject(new CoreMindError("run_timeout", `运行超时(${timeoutMs}ms),已中止`));
782
+ triggerGuard(new CoreMindError("run_timeout", `运行超时(${timeoutMs}ms),已中止`), reject);
427
783
  }, timeoutMs);
428
784
  })
429
785
  : new Promise(() => { });
@@ -436,6 +792,59 @@ export class CoreMindRuntime {
436
792
  signal?.removeEventListener("abort", onAbort);
437
793
  }
438
794
  }
795
+ async executeLoopStep(request, emit, timeoutMs, collected) {
796
+ const eventCursor = collected.length;
797
+ const agent = this.createAgent(request.agent, (event) => emit({ ...event, stepId: request.stepId }), request.stepId);
798
+ if (!agent) {
799
+ throw new CoreMindError("unknown_agent", `Loop 引用了未定义的 agent:${request.agent}(${request.stepId})`);
800
+ }
801
+ const messageCursor = agent.state.messages.length;
802
+ let timer;
803
+ const operation = (async () => {
804
+ await agent.prompt(request.input);
805
+ await agent.waitForIdle();
806
+ })();
807
+ try {
808
+ if (timeoutMs > 0) {
809
+ await Promise.race([
810
+ operation,
811
+ new Promise((_resolve, reject) => {
812
+ timer = setTimeout(() => {
813
+ agent.abort();
814
+ reject(new CoreMindError("step_timeout", `步骤 ${request.stepId} 执行超时(${timeoutMs}ms),已中止`));
815
+ }, timeoutMs);
816
+ }),
817
+ ]);
818
+ }
819
+ else {
820
+ await operation;
821
+ }
822
+ }
823
+ finally {
824
+ if (timer)
825
+ clearTimeout(timer);
826
+ }
827
+ const stepEvents = collected.slice(eventCursor);
828
+ const budgetExceeded = stepEvents.find((event) => event.type === "budget_exceeded");
829
+ if (budgetExceeded?.type === "budget_exceeded") {
830
+ throw new CoreMindError("budget_exceeded", budgetExceeded.message);
831
+ }
832
+ if (stepEvents.some((event) => event.type === "policy_denied")) {
833
+ throw new CoreMindError("loop_paused", `步骤 ${request.stepId} 的工具请求未获批准`);
834
+ }
835
+ const lastAssistant = [...agent.state.messages]
836
+ .reverse()
837
+ .find((message) => message.role === "assistant");
838
+ if (lastAssistant?.stopReason === "aborted") {
839
+ throw new CoreMindError("aborted", `步骤 ${request.stepId} 已中止`);
840
+ }
841
+ if (lastAssistant?.stopReason === "error") {
842
+ const agentError = lastAssistant.errorMessage ?? "模型执行失败,但未提供错误详情";
843
+ const code = classifyRetry(lastAssistant).retryable ? "provider_transient" : "agent_failed";
844
+ throw new CoreMindError(code, `步骤 ${request.stepId} 的 Agent 执行失败:${agentError}`);
845
+ }
846
+ return extractText(agent.state.messages.slice(messageCursor));
847
+ }
439
848
  abortAll() {
440
849
  for (const agent of this.lastAgents.values())
441
850
  agent.abort();
@@ -485,15 +894,10 @@ function lastOutputText(outputs) {
485
894
  function firstKey(record) {
486
895
  return Object.keys(record)[0];
487
896
  }
488
- function failedRunPayload(error) {
489
- const code = error instanceof CoreMindError ? error.code : "unknown";
490
- const message = error instanceof Error ? error.message : String(error);
491
- return {
492
- outcome: {
493
- status: code === "aborted" || code === "run_timeout" ? "aborted" : "failed",
494
- finishReason: code,
495
- error: { code, message },
496
- },
497
- };
897
+ function effectCallKey(stepId, callId) {
898
+ return `${stepId ?? "agent"}:${callId}`;
899
+ }
900
+ function effectIdempotencyKey(runId, stepId, callId) {
901
+ return stepId ? `${runId}:${stepId}:${callId}` : `${runId}:${callId}`;
498
902
  }
499
903
  //# sourceMappingURL=runtime.js.map