@linnlabs/linnkit 0.32.3 → 0.34.0

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 (83) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/cli.cjs +458 -70
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +458 -70
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +55 -0
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +55 -0
  9. package/dist/context-manager.js.map +1 -1
  10. package/dist/contracts/agentSpec.d.cts +30 -30
  11. package/dist/contracts/agentSpec.d.ts +30 -30
  12. package/dist/contracts/audit.d.cts +24 -24
  13. package/dist/contracts/audit.d.ts +24 -24
  14. package/dist/contracts/contextPolicy.d.cts +36 -36
  15. package/dist/contracts/contextPolicy.d.ts +36 -36
  16. package/dist/contracts/events.d.cts +1083 -1083
  17. package/dist/contracts/events.d.ts +1083 -1083
  18. package/dist/contracts/execution.d.cts +8 -8
  19. package/dist/contracts/execution.d.ts +8 -8
  20. package/dist/contracts/messages.d.cts +1178 -1178
  21. package/dist/contracts/messages.d.ts +1178 -1178
  22. package/dist/contracts/provider-continuation.d.cts +28 -28
  23. package/dist/contracts/provider-continuation.d.ts +28 -28
  24. package/dist/contracts/sse.d.cts +899 -899
  25. package/dist/contracts/sse.d.ts +899 -899
  26. package/dist/contracts/sub-run-trace-payload.d.cts +26 -26
  27. package/dist/contracts/sub-run-trace-payload.d.ts +26 -26
  28. package/dist/contracts/token-accounting.d.cts +30 -30
  29. package/dist/contracts/token-accounting.d.ts +30 -30
  30. package/dist/index.cjs +538 -94
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.js +538 -94
  33. package/dist/index.js.map +1 -1
  34. package/dist/quickstart/toolRuntime.d.cts +1 -1
  35. package/dist/quickstart/toolRuntime.d.ts +1 -1
  36. package/dist/quickstart/types.d.cts +1 -1
  37. package/dist/quickstart/types.d.ts +1 -1
  38. package/dist/quickstart.cjs +458 -70
  39. package/dist/quickstart.cjs.map +1 -1
  40. package/dist/quickstart.js +458 -70
  41. package/dist/quickstart.js.map +1 -1
  42. package/dist/runtime-kernel/child-runs/childRunInvoker.d.cts +11 -0
  43. package/dist/runtime-kernel/child-runs/childRunInvoker.d.ts +11 -0
  44. package/dist/runtime-kernel/events/agentEvents.d.cts +172 -172
  45. package/dist/runtime-kernel/events/agentEvents.d.ts +172 -172
  46. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.cts +15 -1
  47. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.ts +15 -1
  48. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.cts +34 -0
  49. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.ts +34 -0
  50. package/dist/runtime-kernel/graph-engine/engine.d.cts +13 -2
  51. package/dist/runtime-kernel/graph-engine/engine.d.ts +13 -2
  52. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.cts +6 -0
  53. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.ts +6 -0
  54. package/dist/runtime-kernel/graph-engine/index.d.cts +3 -1
  55. package/dist/runtime-kernel/graph-engine/index.d.ts +3 -1
  56. package/dist/runtime-kernel/graph-engine/types.d.cts +8 -0
  57. package/dist/runtime-kernel/graph-engine/types.d.ts +8 -0
  58. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +35 -6
  59. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +35 -6
  60. package/dist/runtime-kernel/run-supervisor/index.d.cts +1 -1
  61. package/dist/runtime-kernel/run-supervisor/index.d.ts +1 -1
  62. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.cts +1 -0
  63. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.ts +1 -0
  64. package/dist/runtime-kernel/run-supervisor/runHandle.d.cts +9 -5
  65. package/dist/runtime-kernel/run-supervisor/runHandle.d.ts +9 -5
  66. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.cts +2 -0
  67. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.ts +2 -0
  68. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +9 -2
  69. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +9 -2
  70. package/dist/runtime-kernel.cjs +535 -91
  71. package/dist/runtime-kernel.cjs.map +1 -1
  72. package/dist/runtime-kernel.d.cts +3 -1
  73. package/dist/runtime-kernel.d.ts +3 -1
  74. package/dist/runtime-kernel.js +532 -92
  75. package/dist/runtime-kernel.js.map +1 -1
  76. package/dist/testkit.cjs +535 -91
  77. package/dist/testkit.cjs.map +1 -1
  78. package/dist/testkit.js +535 -91
  79. package/dist/testkit.js.map +1 -1
  80. package/docs/integration/child-runs.md +12 -0
  81. package/docs/integration/persistence.md +24 -0
  82. package/docs/integration/run-supervisor.md +15 -2
  83. package/package.json +2 -2
package/dist/testkit.cjs CHANGED
@@ -6,6 +6,7 @@ require('eventsource-parser');
6
6
  var tiktoken = require('tiktoken');
7
7
  var async_hooks = require('async_hooks');
8
8
  var crypto = require('crypto');
9
+ var util = require('util');
9
10
  var promises = require('fs/promises');
10
11
  var path = require('path');
11
12
 
@@ -105,6 +106,8 @@ __export(runtime_kernel_exports, {
105
106
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
106
107
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
107
108
  REASONING_EFFORTS: () => REASONING_EFFORTS,
109
+ RunPauseRequested: () => RunPauseRequested,
110
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
108
111
  RuntimeEventSubRunTracePublisher: () => RuntimeEventSubRunTracePublisher,
109
112
  SYSTEM_REMINDER_RULES: () => SYSTEM_REMINDER_RULES,
110
113
  SystemReminderRegistry: () => SystemReminderRegistry,
@@ -162,6 +165,7 @@ __export(runtime_kernel_exports, {
162
165
  getToolContextRuntimeBinding: () => getToolContextRuntimeBinding,
163
166
  graph: () => graph_engine_exports,
164
167
  hostReminderTextTemplate: () => hostReminderTextTemplate,
168
+ isRunPauseSignal: () => isRunPauseSignal,
165
169
  isRuntimeFailureFact: () => isRuntimeFailureFact,
166
170
  isValidReasoningEffort: () => isValidReasoningEffort,
167
171
  lastStepsHintTemplate: () => lastStepsHintTemplate,
@@ -170,6 +174,7 @@ __export(runtime_kernel_exports, {
170
174
  maxStepsForceFinalAnswerTemplate: () => maxStepsForceFinalAnswerTemplate,
171
175
  noopAudit: () => noopAudit,
172
176
  normalizeToolArgs: () => normalizeToolArgs,
177
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
173
178
  parseToolModelInputDeclaration: () => parseToolModelInputDeclaration,
174
179
  periodicProgressReflectionTemplate: () => periodicProgressReflectionTemplate,
175
180
  phaseEqualsTrigger: () => phaseEqualsTrigger,
@@ -209,13 +214,17 @@ __export(graph_engine_exports, {
209
214
  MemoryEventStore: () => MemoryEventStore,
210
215
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
211
216
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
217
+ RunPauseRequested: () => RunPauseRequested,
218
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
212
219
  ToolNode: () => ToolNode,
213
220
  UserNode: () => UserNode,
214
221
  WaitUserNode: () => WaitUserNode,
215
222
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
216
223
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
217
224
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
225
+ isRunPauseSignal: () => isRunPauseSignal,
218
226
  isRuntimeFailureFact: () => isRuntimeFailureFact,
227
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
219
228
  readCheckpointContextUsage: () => readCheckpointContextUsage,
220
229
  requireEventStoreId: () => requireEventStoreId,
221
230
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -2583,6 +2592,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2583
2592
  "memory",
2584
2593
  "runtimeEventSink",
2585
2594
  "runtimeEventCommitPort",
2595
+ "commitExecutionBoundary",
2596
+ "toolRecoveryPort",
2586
2597
  "runtimeFailureFactSink",
2587
2598
  "signal",
2588
2599
  "summarizationCallbacks",
@@ -3133,6 +3144,7 @@ var GraphExecutor = class {
3133
3144
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3134
3145
  };
3135
3146
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3147
+ this.executionCheckpointPort = config.executionCheckpointPort;
3136
3148
  }
3137
3149
  checkpointer;
3138
3150
  nodes = /* @__PURE__ */ new Map();
@@ -3140,6 +3152,7 @@ var GraphExecutor = class {
3140
3152
  checkpointQueues = /* @__PURE__ */ new Map();
3141
3153
  config;
3142
3154
  telemetryPort;
3155
+ executionCheckpointPort;
3143
3156
  registerNode(node) {
3144
3157
  this.nodes.set(node.id, node);
3145
3158
  }
@@ -3148,6 +3161,7 @@ var GraphExecutor = class {
3148
3161
  }
3149
3162
  sanitize(state) {
3150
3163
  return {
3164
+ ...state,
3151
3165
  nodeId: state.nodeId,
3152
3166
  revision: state.revision ?? 0,
3153
3167
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3167,8 +3181,9 @@ var GraphExecutor = class {
3167
3181
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3168
3182
  }
3169
3183
  this.ephemeralLocals.set(checkpointKey, { ...local });
3170
- await this.checkpointer.save(checkpointKey, {
3184
+ await this.commitCheckpoint(checkpointKey, {
3171
3185
  nodeId,
3186
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3172
3187
  revision: 1,
3173
3188
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3174
3189
  local: sanitizeCheckpointLocal(local)
@@ -3179,6 +3194,33 @@ var GraphExecutor = class {
3179
3194
  );
3180
3195
  });
3181
3196
  }
3197
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3198
+ async continueSession(checkpointKey, input) {
3199
+ if (!this.executionCheckpointPort) {
3200
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3201
+ }
3202
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3203
+ const current = await this.checkpointer.load(checkpointKey);
3204
+ if (!current || current.revision !== input.expectedRevision) {
3205
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3206
+ }
3207
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3208
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3209
+ }
3210
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3211
+ return { checkpoint: current, events: [], stepCount: 0 };
3212
+ }
3213
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3214
+ try {
3215
+ return await this.runUntilYieldQueued(
3216
+ checkpointKey,
3217
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3218
+ );
3219
+ } finally {
3220
+ this.ephemeralLocals.delete(checkpointKey);
3221
+ }
3222
+ });
3223
+ }
3182
3224
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3183
3225
  async resumeSession(checkpointKey, input) {
3184
3226
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3199,17 +3241,21 @@ var GraphExecutor = class {
3199
3241
  );
3200
3242
  }
3201
3243
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3244
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3245
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3246
+ }
3202
3247
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3203
- await this.checkpointer.save(checkpointKey, {
3248
+ await this.commitCheckpoint(checkpointKey, {
3204
3249
  ...current,
3205
3250
  nodeId: input.nodeId ?? "llm",
3251
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3206
3252
  revision: currentRevision + 1,
3207
3253
  local: sanitizeCheckpointLocal(resumedLocal)
3208
3254
  });
3209
3255
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3210
3256
  return this.runUntilYieldQueued(
3211
3257
  checkpointKey,
3212
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3258
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3213
3259
  );
3214
3260
  });
3215
3261
  }
@@ -3300,16 +3346,23 @@ var GraphExecutor = class {
3300
3346
  };
3301
3347
  }
3302
3348
  async saveCheckpoint(checkpointKey, state) {
3303
- const checkpoint = this.sanitize({
3349
+ const checkpoint2 = this.sanitize({
3304
3350
  ...state,
3305
3351
  revision: (state.revision ?? 0) + 1
3306
3352
  });
3307
- await this.checkpointer.save(checkpointKey, checkpoint);
3308
- return checkpoint;
3353
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3354
+ return checkpoint2;
3355
+ }
3356
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3357
+ if (this.executionCheckpointPort) {
3358
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3359
+ } else {
3360
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3361
+ }
3309
3362
  }
3310
3363
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3311
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3312
- return { events, checkpoint, stepCount };
3364
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3365
+ return { events, checkpoint: checkpoint2, stepCount };
3313
3366
  }
3314
3367
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3315
3368
  let state = initialState;
@@ -3319,6 +3372,15 @@ var GraphExecutor = class {
3319
3372
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3320
3373
  local: { ...state.local || {}, ...ephemeral }
3321
3374
  };
3375
+ if (this.executionCheckpointPort) {
3376
+ state.local = {
3377
+ ...state.local,
3378
+ commitExecutionBoundary: async (boundary) => {
3379
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3380
+ boundary.revision = saved.revision;
3381
+ }
3382
+ };
3383
+ }
3322
3384
  const isAbortSignal2 = (v) => {
3323
3385
  return v !== null && typeof v === "object" && "aborted" in v;
3324
3386
  };
@@ -3328,11 +3390,12 @@ var GraphExecutor = class {
3328
3390
  throw err;
3329
3391
  };
3330
3392
  let stepCount = 0;
3393
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3331
3394
  let allEvents = [];
3332
3395
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3333
3396
  maxSteps
3334
3397
  });
3335
- while (stepCount < maxSteps) {
3398
+ while (previousSteps + stepCount < maxSteps) {
3336
3399
  stepCount += 1;
3337
3400
  reportStepsUsed(stepCount);
3338
3401
  const signalRaw = state.local?.signal;
@@ -3344,7 +3407,7 @@ var GraphExecutor = class {
3344
3407
  const stepPreparation = prepareGraphStep({
3345
3408
  state,
3346
3409
  maxSteps,
3347
- stepCount
3410
+ stepCount: previousSteps + stepCount
3348
3411
  });
3349
3412
  state = stepPreparation.state;
3350
3413
  const node = this.nodes.get(state.nodeId);
@@ -3353,6 +3416,7 @@ var GraphExecutor = class {
3353
3416
  maxSteps,
3354
3417
  stepCount
3355
3418
  });
3419
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3356
3420
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3357
3421
  this.ephemeralLocals.delete(checkpointKey);
3358
3422
  return result3;
@@ -3362,6 +3426,11 @@ var GraphExecutor = class {
3362
3426
  stepCount,
3363
3427
  nodeId: state.nodeId
3364
3428
  });
3429
+ if (this.executionCheckpointPort) {
3430
+ state.executionStatus = "executing";
3431
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3432
+ state.revision = saved.revision;
3433
+ }
3365
3434
  const result2 = await runGraphNodeWithTelemetry({
3366
3435
  node,
3367
3436
  state,
@@ -3386,10 +3455,13 @@ var GraphExecutor = class {
3386
3455
  fromNodeId: stepResolution.action.fromNodeId,
3387
3456
  nextNodeId: stepResolution.action.nextNodeId
3388
3457
  });
3389
- await this.saveCheckpoint(checkpointKey, state);
3458
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3459
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3460
+ state.revision = saved.revision;
3390
3461
  continue;
3391
3462
  }
3392
3463
  if (stepResolution.action.kind === "yield") {
3464
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3393
3465
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3394
3466
  maxSteps,
3395
3467
  stepCount
@@ -3400,6 +3472,7 @@ var GraphExecutor = class {
3400
3472
  maxSteps,
3401
3473
  stepCount
3402
3474
  });
3475
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3403
3476
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3404
3477
  }
3405
3478
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3420,6 +3493,7 @@ var GraphExecutor = class {
3420
3493
  },
3421
3494
  retryable: false
3422
3495
  }), "GraphExecutor.engine_budget_exhausted"));
3496
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3423
3497
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3424
3498
  this.ephemeralLocals.delete(checkpointKey);
3425
3499
  return result;
@@ -7313,10 +7387,11 @@ var LlmNode = class {
7313
7387
  bridge.handle
7314
7388
  );
7315
7389
  } catch (error) {
7316
- bridge.finalizePartialAnswer();
7390
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7317
7391
  throw error;
7318
7392
  }
7319
7393
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7394
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7320
7395
  switch (decision.kind) {
7321
7396
  case "tool_calls": {
7322
7397
  if (forceFinalAnswer) {
@@ -8584,6 +8659,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8584
8659
  function recordToolProtocolError(params) {
8585
8660
  }
8586
8661
 
8662
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8663
+ var RunRecoveryBlockedError = class extends Error {
8664
+ code = "RUN_RECOVERY_BLOCKED";
8665
+ constructor(message) {
8666
+ super(message);
8667
+ this.name = "RunRecoveryBlockedError";
8668
+ }
8669
+ };
8670
+ var RunPauseRequested = class extends Error {
8671
+ code = "RUN_PAUSE_REQUESTED";
8672
+ constructor(message = "Run paused by user") {
8673
+ super(message);
8674
+ this.name = "RunPauseRequested";
8675
+ }
8676
+ };
8677
+ function isRunPauseSignal(signal) {
8678
+ const reason = signal?.reason;
8679
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8680
+ }
8681
+
8682
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8683
+ async function executeRecoverableTool(input) {
8684
+ const local = input.state.local;
8685
+ if (!local?.commitExecutionBoundary) return input.execute();
8686
+ if (local.executingToolCallId) {
8687
+ if (local.executingToolCallId !== input.call.id) {
8688
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8689
+ }
8690
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8691
+ if (!decision || decision.kind === "blocked") {
8692
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8693
+ }
8694
+ if (decision.kind === "settled") return decision.result;
8695
+ }
8696
+ local.executingToolCallId = input.call.id;
8697
+ await local.commitExecutionBoundary(input.state);
8698
+ const result = await input.execute();
8699
+ if (!result.success && isRunPauseSignal(local.signal)) {
8700
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8701
+ error.name = "AbortError";
8702
+ throw error;
8703
+ }
8704
+ return result;
8705
+ }
8706
+ async function commitToolBoundary(state, result) {
8707
+ if (!state.local?.commitExecutionBoundary) return;
8708
+ delete state.local.executingToolCallId;
8709
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8710
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8711
+ await state.local.commitExecutionBoundary(state);
8712
+ }
8713
+
8587
8714
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8588
8715
  var logger11 = new Logger("ToolNode");
8589
8716
  function isAbortSignal(value) {
@@ -8754,6 +8881,7 @@ var ToolNode = class {
8754
8881
  const events = [];
8755
8882
  while (true) {
8756
8883
  const result = await this.runNextPendingToolCall(state);
8884
+ await commitToolBoundary(state, result);
8757
8885
  if (Array.isArray(result.events) && result.events.length > 0) {
8758
8886
  events.push(...result.events);
8759
8887
  }
@@ -8770,11 +8898,9 @@ var ToolNode = class {
8770
8898
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8771
8899
  const signalRaw = state.local?.signal;
8772
8900
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8773
- settlePendingToolCallsAfterAbort({
8774
- state,
8775
- calls,
8776
- toolCatalog: this.toolRuntime
8777
- });
8901
+ if (!isRunPauseSignal(signalRaw)) {
8902
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8903
+ }
8778
8904
  const abortError = new Error("The user aborted a request.");
8779
8905
  abortError.name = "AbortError";
8780
8906
  throw abortError;
@@ -8913,16 +9039,21 @@ var ToolNode = class {
8913
9039
  tool_calls: [call]
8914
9040
  });
8915
9041
  try {
8916
- const exec = await executeToolWithIdempotency({
8917
- idempotencyKey: execution.idempotencyKey,
8918
- inFlight: this.idempotencyInFlight,
8919
- history: readHistoryEvents(prepared.local),
8920
- toolName: execution.toolName,
8921
- execute: () => this.toolRuntime.executeTool(
8922
- execution.toolName,
8923
- execution.toolArgs,
8924
- prepared.toolContext
8925
- )
9042
+ const exec = await executeRecoverableTool({
9043
+ state,
9044
+ call,
9045
+ context: prepared.toolContext,
9046
+ execute: () => executeToolWithIdempotency({
9047
+ idempotencyKey: execution.idempotencyKey,
9048
+ inFlight: this.idempotencyInFlight,
9049
+ history: readHistoryEvents(prepared.local),
9050
+ toolName: execution.toolName,
9051
+ execute: () => this.toolRuntime.executeTool(
9052
+ execution.toolName,
9053
+ execution.toolArgs,
9054
+ prepared.toolContext
9055
+ )
9056
+ })
8926
9057
  });
8927
9058
  if (exec.success) {
8928
9059
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -9002,7 +9133,7 @@ var ToolNode = class {
9002
9133
  bridge: execution.bridge
9003
9134
  });
9004
9135
  } catch (error) {
9005
- if (isToolExecutionAbort(error)) {
9136
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
9006
9137
  settleToolCallsAfterExecutionAbort({
9007
9138
  state,
9008
9139
  remainingCalls: calls.slice(1),
@@ -9062,7 +9193,7 @@ var ToolNode = class {
9062
9193
  {
9063
9194
  attachments: context.attachments,
9064
9195
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
9065
- ephemeral: context.exec.idempotency?.cacheHit === true,
9196
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
9066
9197
  durationMs: context.exec.durationMs
9067
9198
  }
9068
9199
  );
@@ -9119,6 +9250,9 @@ var ToolNode = class {
9119
9250
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
9120
9251
  }
9121
9252
  async handleError(context) {
9253
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9254
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9255
+ }
9122
9256
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
9123
9257
  await this.emitToolDecisionAudit({
9124
9258
  action: "tool.deny",
@@ -9355,16 +9489,16 @@ function requireEventStoreId(eventStoreId) {
9355
9489
  }
9356
9490
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9357
9491
  let lastTimestamp = 0;
9358
- let counter = 0;
9492
+ let counter2 = 0;
9359
9493
  return () => {
9360
9494
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9361
9495
  if (timestamp === lastTimestamp) {
9362
- counter += 1;
9496
+ counter2 += 1;
9363
9497
  } else {
9364
9498
  lastTimestamp = timestamp;
9365
- counter = 0;
9499
+ counter2 = 0;
9366
9500
  }
9367
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9501
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9368
9502
  };
9369
9503
  }
9370
9504
 
@@ -9776,6 +9910,76 @@ function assertNonNegativeSafeInteger(value, field) {
9776
9910
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9777
9911
  }
9778
9912
  }
9913
+ var counter = zod.z.number().int().nonnegative();
9914
+ var executor = zod.z.object({
9915
+ stepCount: counter,
9916
+ phase: zod.z.string().optional(),
9917
+ maxSteps: counter.optional(),
9918
+ remainingSteps: zod.z.number().int().optional(),
9919
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
9920
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
9921
+ lastStepsHintThreshold: counter.optional(),
9922
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9923
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9924
+ runLockedModelId: zod.z.string().optional(),
9925
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
9926
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
9927
+ llmInvocationCount: counter.optional(),
9928
+ lockRequestedModelId: zod.z.boolean().optional(),
9929
+ contextCompaction: zod.z.object({
9930
+ attemptCount: counter,
9931
+ committedCount: counter,
9932
+ lastCommittedFingerprint: zod.z.string().optional()
9933
+ }).strict().optional()
9934
+ }).strict();
9935
+ var checkpoint = zod.z.object({
9936
+ nodeId: zod.z.string().min(1),
9937
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9938
+ revision: counter.optional(),
9939
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9940
+ local: zod.z.object({
9941
+ runId: RunIdSchema.optional(),
9942
+ parentRunId: RunIdSchema.optional(),
9943
+ conversationId: zod.z.string().optional(),
9944
+ turnId: zod.z.string().optional(),
9945
+ request: SerializableJsonRecord.optional(),
9946
+ history: zod.z.array(RuntimeEvent).optional(),
9947
+ newEvents: zod.z.array(RuntimeEvent).optional(),
9948
+ executorLocal: executor.optional(),
9949
+ pendingToolCalls: zod.z.array(zod.z.object({
9950
+ id: ToolCallIdSchema,
9951
+ type: zod.z.literal("function"),
9952
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
9953
+ }).strict()).optional(),
9954
+ executingToolCallId: ToolCallIdSchema.optional(),
9955
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9956
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9957
+ lastToolResult: SerializableJsonRecord.optional(),
9958
+ finalAnswer: zod.z.string().optional(),
9959
+ answerId: zod.z.string().optional(),
9960
+ chunkSeq: counter.optional(),
9961
+ contextUsage: ContextUsageSnapshot.optional()
9962
+ }).passthrough().optional()
9963
+ }).strict();
9964
+ function parseEngineCheckpoint(value) {
9965
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9966
+ for (const key of [
9967
+ "memory",
9968
+ "signal",
9969
+ "toolContext",
9970
+ "runtimeEventSink",
9971
+ "runtimeEventCommitPort",
9972
+ "runtimeFailureFactSink",
9973
+ "summarizationCallbacks",
9974
+ "commitExecutionBoundary",
9975
+ "toolRecoveryPort"
9976
+ ]) {
9977
+ if (result.local && Object.hasOwn(result.local, key)) {
9978
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9979
+ }
9980
+ }
9981
+ return result;
9982
+ }
9779
9983
 
9780
9984
  // src/runtime-kernel/tools/index.ts
9781
9985
  var tools_exports = {};
@@ -10227,12 +10431,33 @@ var RuntimeEventPublisher = class {
10227
10431
  var EventBusEventPersistence = class {
10228
10432
  constructor(options) {
10229
10433
  this.options = options;
10434
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10230
10435
  }
10231
10436
  options;
10232
10437
  scheduledEventIds = /* @__PURE__ */ new Set();
10233
10438
  writeTail = Promise.resolve();
10234
10439
  firstWriteError;
10235
10440
  connected = false;
10441
+ checkpointWritesActive;
10442
+ checkpointEvents = [];
10443
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10444
+ async commitCheckpoint(checkpointKey, checkpoint2) {
10445
+ const writer = this.options.checkpointWriter;
10446
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10447
+ const events = this.checkpointEvents;
10448
+ this.checkpointEvents = [];
10449
+ await this.enqueueWrite(() => writer({
10450
+ checkpointKey,
10451
+ checkpoint: checkpoint2,
10452
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10453
+ }));
10454
+ }
10455
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10456
+ finishCheckpointWrites() {
10457
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10458
+ this.checkpointEvents = [];
10459
+ this.checkpointWritesActive = false;
10460
+ }
10236
10461
  connect() {
10237
10462
  if (this.connected) {
10238
10463
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10279,14 +10504,22 @@ var EventBusEventPersistence = class {
10279
10504
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10280
10505
  return;
10281
10506
  }
10507
+ if (this.checkpointWritesActive) {
10508
+ this.scheduledEventIds.add(event.id);
10509
+ this.checkpointEvents.push(event);
10510
+ return;
10511
+ }
10282
10512
  void this.scheduleWrite(event).catch(() => void 0);
10283
10513
  };
10284
10514
  scheduleWrite(event) {
10285
10515
  this.scheduledEventIds.add(event.id);
10286
- const eventStoreId = this.options.nextEventStoreId();
10287
- const write = this.writeTail.then(async () => {
10288
- await this.options.eventStore.append({ eventStoreId, event });
10289
- });
10516
+ return this.enqueueWrite(() => this.options.eventStore.append({
10517
+ eventStoreId: this.options.nextEventStoreId(),
10518
+ event
10519
+ }));
10520
+ }
10521
+ enqueueWrite(operation) {
10522
+ const write = this.writeTail.then(operation);
10290
10523
  this.writeTail = write;
10291
10524
  void write.catch((error) => {
10292
10525
  this.firstWriteError ??= error;
@@ -11908,15 +12141,15 @@ function hasSeedHistoryPrefix(history, seedHistory) {
11908
12141
  }
11909
12142
  return true;
11910
12143
  }
11911
- function readCheckpointHistory(checkpoint) {
11912
- if (!checkpoint?.local) return [];
11913
- const history = checkpoint.local.history;
12144
+ function readCheckpointHistory(checkpoint2) {
12145
+ if (!checkpoint2?.local) return [];
12146
+ const history = checkpoint2.local.history;
11914
12147
  if (!Array.isArray(history)) return [];
11915
12148
  return parseRuntimeEvents(history);
11916
12149
  }
11917
12150
  async function recoverChildRunEventsFromCheckpoint(params) {
11918
- const checkpoint = await params.checkpointer.load(params.checkpointKey);
11919
- const history = readCheckpointHistory(checkpoint);
12151
+ const checkpoint2 = await params.checkpointer.load(params.checkpointKey);
12152
+ const history = readCheckpointHistory(checkpoint2);
11920
12153
  if (history.length === 0) {
11921
12154
  return [];
11922
12155
  }
@@ -12007,6 +12240,9 @@ var ChildRunInvoker = class {
12007
12240
  explicitConversationId: conversationId,
12008
12241
  parentToolContext
12009
12242
  });
12243
+ if (config.persistence?.expectedRevision !== void 0) {
12244
+ return this.continueChild(config, childRunId, runtimeConversationId);
12245
+ }
12010
12246
  const turnId = generateTurnId();
12011
12247
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
12012
12248
  conversationId: runtimeConversationId,
@@ -12014,21 +12250,8 @@ var ChildRunInvoker = class {
12014
12250
  maxSteps,
12015
12251
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
12016
12252
  });
12017
- const checkpointer = new MemoryCheckpointer();
12018
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
12019
- const llmNode = this.createLlmNode();
12020
- const toolNode = new ToolNode({
12021
- toolRuntime: this.toolRuntime,
12022
- observationPreview: this.observationPreview,
12023
- telemetryPort: this.telemetryPort,
12024
- auditPort: this.auditPort,
12025
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12026
- modelInputResolver: this.modelInputResolver
12027
- });
12028
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
12029
- graphExecutor.registerNode(llmNode);
12030
- graphExecutor.registerNode(toolNode);
12031
- graphExecutor.registerNode(waitUserNode);
12253
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
12254
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
12032
12255
  const childUserInput = createChildRunUserInput({
12033
12256
  id: generateRuntimeEventId(),
12034
12257
  conversationId: runtimeConversationId,
@@ -12108,6 +12331,7 @@ var ChildRunInvoker = class {
12108
12331
  ...abortSignal ? { signal: abortSignal } : {},
12109
12332
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
12110
12333
  runtimeEventSink,
12334
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
12111
12335
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
12112
12336
  systemPrompt
12113
12337
  };
@@ -12148,6 +12372,7 @@ var ChildRunInvoker = class {
12148
12372
  eventToMessageConverter: this.eventToMessageConverter
12149
12373
  });
12150
12374
  } catch (err) {
12375
+ if (config.persistence) throw err;
12151
12376
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
12152
12377
  checkpointer,
12153
12378
  checkpointKey: internalCheckpointKey,
@@ -12186,7 +12411,7 @@ var ChildRunInvoker = class {
12186
12411
  events: allEvents,
12187
12412
  eventToMessageConverter: this.eventToMessageConverter
12188
12413
  });
12189
- await checkpointer.clear(internalCheckpointKey);
12414
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12190
12415
  return {
12191
12416
  success: !error && !cancelled,
12192
12417
  runId: childRunId,
@@ -12203,6 +12428,66 @@ var ChildRunInvoker = class {
12203
12428
  error
12204
12429
  };
12205
12430
  }
12431
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12432
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12433
+ graph.registerNode(this.createLlmNode());
12434
+ graph.registerNode(new ToolNode({
12435
+ toolRuntime: this.toolRuntime,
12436
+ observationPreview: this.observationPreview,
12437
+ telemetryPort: this.telemetryPort,
12438
+ auditPort: this.auditPort,
12439
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12440
+ modelInputResolver: this.modelInputResolver
12441
+ }));
12442
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12443
+ return graph;
12444
+ }
12445
+ async continueChild(config, runId, conversationId) {
12446
+ const persistence = config.persistence;
12447
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12448
+ const checkpoint2 = await persistence.checkpointer.load(runId);
12449
+ if (!checkpoint2 || checkpoint2.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12450
+ const local = readGraphAgentLocal({ ...checkpoint2.local, runtimeEventSink: config.runtimeEventSink });
12451
+ const request = local.request;
12452
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12453
+ const context = createChildRunToolContext({
12454
+ parentToolContext: config.parentToolContext,
12455
+ conversationId,
12456
+ turnId: local.turnId,
12457
+ runId,
12458
+ parentRunId: config.parentRunId,
12459
+ userQuery: request.query,
12460
+ modelId: request.model_id,
12461
+ seedHistory: local.history,
12462
+ abortSignal: config.abortSignal
12463
+ });
12464
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12465
+ const result = await graph.continueSession(runId, {
12466
+ expectedRevision: persistence.expectedRevision,
12467
+ capabilities: {
12468
+ toolContext: context,
12469
+ signal: config.abortSignal,
12470
+ runtimeEventSink: config.runtimeEventSink,
12471
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12472
+ toolRecoveryPort: persistence.toolRecoveryPort
12473
+ }
12474
+ });
12475
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12476
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12477
+ const finalAnswer = extractFinalAnswer(events);
12478
+ return {
12479
+ runId,
12480
+ parentRunId: config.parentRunId,
12481
+ subrunId: runId,
12482
+ success: true,
12483
+ events,
12484
+ finalAnswer,
12485
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12486
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12487
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12488
+ toolset: { availableTools: request.availableTools }
12489
+ };
12490
+ }
12206
12491
  };
12207
12492
  function isAbortError2(error) {
12208
12493
  return error instanceof Error && error.name === "AbortError";
@@ -12604,8 +12889,6 @@ __export(run_supervisor_exports, {
12604
12889
  RunNotFoundError: () => RunNotFoundError,
12605
12890
  runMetaFromRecord: () => runMetaFromRecord
12606
12891
  });
12607
-
12608
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12609
12892
  function cloneRunRecord(record) {
12610
12893
  return {
12611
12894
  ...record,
@@ -12625,6 +12908,11 @@ function matchesStatus(candidate, filter) {
12625
12908
  }
12626
12909
  var MemoryRunRegistryStore = class {
12627
12910
  store = /* @__PURE__ */ new Map();
12911
+ async compareAndSwap(previous, next) {
12912
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12913
+ this.store.set(next.runId, cloneRunRecord(next));
12914
+ return true;
12915
+ }
12628
12916
  async save(record) {
12629
12917
  this.store.set(record.runId, cloneRunRecord(record));
12630
12918
  }
@@ -12772,6 +13060,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12772
13060
  }
12773
13061
  };
12774
13062
 
13063
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
13064
+ async function persistRunTransition(store, previous, next) {
13065
+ if (store.compareAndSwap) {
13066
+ if (!await store.compareAndSwap(previous, next)) {
13067
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
13068
+ }
13069
+ } else {
13070
+ await store.save(next);
13071
+ }
13072
+ }
13073
+
12775
13074
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12776
13075
  function isRunTerminalStatus(status) {
12777
13076
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12827,6 +13126,7 @@ var DefaultRunHandle = class {
12827
13126
  parentRunId;
12828
13127
  runRecord;
12829
13128
  abortController;
13129
+ executionId;
12830
13130
  agentSpecSnapshot;
12831
13131
  requestSnapshot;
12832
13132
  transportEventBus;
@@ -12842,6 +13142,9 @@ var DefaultRunHandle = class {
12842
13142
  this.runId = options.runRecord.runId;
12843
13143
  this.parentRunId = options.runRecord.parentRunId;
12844
13144
  this.abortController = options.abortController;
13145
+ const executionId = options.runRecord.metadata?.executionId;
13146
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
13147
+ this.executionId = executionId;
12845
13148
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12846
13149
  this.requestSnapshot = cloneRequest(options.request);
12847
13150
  this.transportEventBus = options.eventBus;
@@ -12861,8 +13164,9 @@ var DefaultRunHandle = class {
12861
13164
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12862
13165
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12863
13166
  */
12864
- replaceExecutionAbortController(controller) {
13167
+ replaceExecutionAbortController(controller, executionId) {
12865
13168
  this.abortController = controller;
13169
+ this.executionId = executionId;
12866
13170
  }
12867
13171
  async spec() {
12868
13172
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12882,6 +13186,7 @@ var DefaultRunHandle = class {
12882
13186
  this.abortController.abort(opts.reason);
12883
13187
  const latestRecord = await this.registryStore.load(this.runId);
12884
13188
  const baseRecord = latestRecord ?? this.runRecord;
13189
+ this.assertExecutionOwner(baseRecord);
12885
13190
  const transition = decideRunLifecycleTransition(baseRecord.status);
12886
13191
  if (transition.kind === "skip_terminal") {
12887
13192
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12891,7 +13196,7 @@ var DefaultRunHandle = class {
12891
13196
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12892
13197
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12893
13198
  };
12894
- await this.registryStore.save(settledRecord);
13199
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12895
13200
  this.runRecord = { ...settledRecord };
12896
13201
  return;
12897
13202
  }
@@ -12918,7 +13223,7 @@ var DefaultRunHandle = class {
12918
13223
  }
12919
13224
  }
12920
13225
  };
12921
- await this.registryStore.save(nextRecord);
13226
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12922
13227
  this.runRecord = { ...nextRecord };
12923
13228
  await this.auditPort.emit({
12924
13229
  envelopeId: generateAuditEnvelopeId(),
@@ -13026,21 +13331,35 @@ var DefaultRunHandle = class {
13026
13331
  async markFailed(error, patch = {}) {
13027
13332
  await this.saveLifecycleStatus("failed", patch, error);
13028
13333
  }
13029
- async pause(_reason) {
13030
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13334
+ async pause(reason = "Run paused by user") {
13335
+ const latest = await this.registryStore.load(this.runId);
13336
+ if (latest) this.assertExecutionOwner(latest);
13337
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13338
+ const next = {
13339
+ ...latest,
13340
+ status: "paused",
13341
+ updatedAt: Date.now(),
13342
+ pauseReason: reason,
13343
+ pausedAt: void 0
13344
+ };
13345
+ await persistRunTransition(this.registryStore, latest, next);
13346
+ this.runRecord = next;
13347
+ this.abortController.abort(new RunPauseRequested(reason));
13031
13348
  }
13032
- async resume() {
13033
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13349
+ async markPaused(patch = {}) {
13350
+ await this.saveLifecycleStatus("paused", patch);
13034
13351
  }
13035
13352
  async saveLifecycleStatus(status, patch, errorIfAny) {
13036
13353
  const latestRecord = await this.registryStore.load(this.runId);
13037
13354
  const baseRecord = latestRecord ?? this.runRecord;
13038
13355
  const transition = decideRunLifecycleTransition(baseRecord.status);
13356
+ this.assertExecutionOwner(baseRecord);
13357
+ if (status === "running" && baseRecord.status === "paused") return;
13039
13358
  if (transition.kind === "skip_terminal") {
13040
13359
  this.runRecord = { ...baseRecord };
13041
13360
  return;
13042
13361
  }
13043
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13362
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
13044
13363
  const updatedAt = Date.now();
13045
13364
  const nextRecord = {
13046
13365
  ...baseRecord,
@@ -13048,8 +13367,8 @@ var DefaultRunHandle = class {
13048
13367
  updatedAt,
13049
13368
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13050
13369
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
13051
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13052
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13370
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13371
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
13053
13372
  errorIfAny,
13054
13373
  metadata: awaitingUserPatch?.eventId ? {
13055
13374
  ...baseRecord.metadata ?? {},
@@ -13060,7 +13379,7 @@ var DefaultRunHandle = class {
13060
13379
  }
13061
13380
  } : baseRecord.metadata
13062
13381
  };
13063
- await this.registryStore.save(nextRecord);
13382
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13064
13383
  this.runRecord = { ...nextRecord };
13065
13384
  if (status === "completed" || status === "failed") {
13066
13385
  this.closeObservationChannel();
@@ -13070,6 +13389,11 @@ var DefaultRunHandle = class {
13070
13389
  forwardTransportEvent = (envelope) => {
13071
13390
  this.observationEventBus.emit("event", envelope);
13072
13391
  };
13392
+ assertExecutionOwner(record) {
13393
+ if (record.metadata?.executionId !== this.executionId) {
13394
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13395
+ }
13396
+ }
13073
13397
  forwardTransportError = (error) => {
13074
13398
  this.observationEventBus.emit("error", error);
13075
13399
  };
@@ -13400,7 +13724,15 @@ function createRunConcurrencyKeyRegistry() {
13400
13724
  runIdByKey.delete(concurrencyKey);
13401
13725
  }
13402
13726
  }
13403
- return { acquire, release };
13727
+ function transfer(previous, next, concurrencyKey) {
13728
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
13729
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
13730
+ }
13731
+ keyByRunId.delete(previous);
13732
+ keyByRunId.set(next, concurrencyKey);
13733
+ runIdByKey.set(concurrencyKey, next);
13734
+ }
13735
+ return { acquire, release, transfer };
13404
13736
  }
13405
13737
 
13406
13738
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -13451,6 +13783,24 @@ async function recoverRunsOnBoot(options) {
13451
13783
  const outcomes = [];
13452
13784
  for (const record of activeRecords) {
13453
13785
  const updatedAt = options.now();
13786
+ if (await options.canRestoreRun?.(record)) {
13787
+ const metadata = { ...record.metadata };
13788
+ const awaitingUser = metadata.awaitingUser;
13789
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13790
+ const restored = { ...awaitingUser };
13791
+ Reflect.deleteProperty(restored, "resumeClaim");
13792
+ metadata.awaitingUser = restored;
13793
+ }
13794
+ await persistRunTransition(options.registryStore, record, {
13795
+ ...record,
13796
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13797
+ pausedAt: record.pausedAt ?? updatedAt,
13798
+ pauseReason: record.pauseReason ?? options.reason,
13799
+ updatedAt,
13800
+ metadata
13801
+ });
13802
+ continue;
13803
+ }
13454
13804
  const nextRecord = {
13455
13805
  ...record,
13456
13806
  status: "failed",
@@ -13468,7 +13818,7 @@ async function recoverRunsOnBoot(options) {
13468
13818
  }
13469
13819
  }
13470
13820
  };
13471
- await options.registryStore.save(nextRecord);
13821
+ await persistRunTransition(options.registryStore, record, nextRecord);
13472
13822
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13473
13823
  options.notifyTerminal(outcome);
13474
13824
  outcomes.push(outcome);
@@ -13592,8 +13942,13 @@ var DefaultRunSupervisor = class {
13592
13942
  inFlight = /* @__PURE__ */ new Map();
13593
13943
  eventWatchDisposers = /* @__PURE__ */ new Map();
13594
13944
  controlOperations = /* @__PURE__ */ new Map();
13945
+ canRestoreRun;
13595
13946
  constructor(options) {
13947
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13948
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13949
+ }
13596
13950
  this.registryStore = options.registryStore;
13951
+ this.canRestoreRun = options.canRestoreRun;
13597
13952
  this.auditPort = options.auditPort;
13598
13953
  this.executor = options.executor;
13599
13954
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13626,6 +13981,9 @@ var DefaultRunSupervisor = class {
13626
13981
  });
13627
13982
  }
13628
13983
  async registerRun(spec) {
13984
+ if (spec.replacesPausedRun) {
13985
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
13986
+ }
13629
13987
  const runId = spec.runId ?? this.runIdFactory();
13630
13988
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
13631
13989
  throw new RunAlreadyRegisteredError(runId);
@@ -13636,11 +13994,66 @@ var DefaultRunSupervisor = class {
13636
13994
  forwardParentAbortSignal(controller, spec.parentSignal);
13637
13995
  const record = createInitialRunRecord({ runId, spec, startedAt });
13638
13996
  try {
13639
- await this.registryStore.save(record);
13997
+ if (spec.admissionCommit) await spec.admissionCommit(record);
13998
+ else await this.registryStore.save(record);
13640
13999
  } catch (error) {
13641
14000
  this.releaseRunAdmission(runId);
13642
14001
  throw error;
13643
14002
  }
14003
+ return this.attachRun(record, spec, controller);
14004
+ }
14005
+ async registerPausedReplacement(spec) {
14006
+ const target = spec.replacesPausedRun;
14007
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
14008
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
14009
+ }
14010
+ this.getHandle(target.runId);
14011
+ const previous = await this.registryStore.load(target.runId);
14012
+ if (!previous || previous.status !== "paused" || previous.pausedAt === void 0 || previous.updatedAt !== target.expectedUpdatedAt || previous.metadata?.executionId !== target.expectedExecutionId || previous.conversationId !== spec.conversationId || previous.parentRunId !== spec.parentRunId) {
14013
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
14014
+ }
14015
+ const runId = spec.runId ?? this.runIdFactory();
14016
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
14017
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
14018
+ this.runSlotLimiter.release(previous.runId);
14019
+ this.runSlotLimiter.acquire(runId);
14020
+ const now = this.now();
14021
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
14022
+ const next = {
14023
+ ...previous,
14024
+ status: "cancelled",
14025
+ updatedAt: now,
14026
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
14027
+ };
14028
+ try {
14029
+ await spec.admissionCommit(record, { previous, next });
14030
+ } catch (error) {
14031
+ this.runSlotLimiter.release(runId);
14032
+ this.runSlotLimiter.acquire(previous.runId);
14033
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
14034
+ throw error;
14035
+ }
14036
+ this.cleanupRunResources(previous.runId);
14037
+ this.notifyTerminalWaiters(previous.runId);
14038
+ const controller = new AbortController();
14039
+ forwardParentAbortSignal(controller, spec.parentSignal);
14040
+ return this.attachRun(record, spec, controller);
14041
+ }
14042
+ async restoreRun(spec) {
14043
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
14044
+ return this.withRunControlLock(spec.runId, async () => {
14045
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
14046
+ const record = await this.registryStore.load(spec.runId);
14047
+ if (!record) throw new RunNotFoundError(spec.runId);
14048
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
14049
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
14050
+ }
14051
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
14052
+ return this.attachRun(record, spec, new AbortController());
14053
+ });
14054
+ }
14055
+ attachRun(record, spec, controller) {
14056
+ const runId = record.runId;
13644
14057
  try {
13645
14058
  const handle = new DefaultRunHandle({
13646
14059
  runRecord: record,
@@ -13738,11 +14151,36 @@ var DefaultRunSupervisor = class {
13738
14151
  registryStore: this.registryStore,
13739
14152
  reason,
13740
14153
  now: this.now,
13741
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
14154
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
14155
+ canRestoreRun: this.canRestoreRun
13742
14156
  });
13743
14157
  }
13744
- async pause(_runId, _reason) {
13745
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
14158
+ async pause(runId, reason) {
14159
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
14160
+ }
14161
+ async resumePausedRun(input) {
14162
+ return this.withRunControlLock(input.runId, async () => {
14163
+ const handle = this.getHandle(input.runId);
14164
+ const record = await this.registryStore.load(input.runId);
14165
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
14166
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
14167
+ }
14168
+ await persistRunTransition(this.registryStore, record, {
14169
+ ...record,
14170
+ status: "running",
14171
+ updatedAt: this.now(),
14172
+ pausedAt: void 0,
14173
+ pauseReason: void 0,
14174
+ errorIfAny: void 0,
14175
+ metadata: { ...record.metadata, executionId: input.executionId }
14176
+ });
14177
+ const controller = new AbortController();
14178
+ handle.replaceExecutionAbortController(controller, input.executionId);
14179
+ handle.attachTransportEventBus(input.eventBus);
14180
+ this.controllers.set(input.runId, controller);
14181
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
14182
+ return handle;
14183
+ });
13746
14184
  }
13747
14185
  async claimResume(runId, interaction, eventBus, parentSignal) {
13748
14186
  return this.withRunControlLock(runId, async () => {
@@ -13777,7 +14215,7 @@ var DefaultRunSupervisor = class {
13777
14215
  throw new RunNotFoundError(runId);
13778
14216
  }
13779
14217
  const claimId = generateRunResumeClaimId();
13780
- await this.registryStore.save({
14218
+ await persistRunTransition(this.registryStore, record, {
13781
14219
  ...record,
13782
14220
  updatedAt: this.now(),
13783
14221
  metadata: {
@@ -13865,7 +14303,7 @@ var DefaultRunSupervisor = class {
13865
14303
  }
13866
14304
  const awaitingUserWithoutClaim = { ...awaitingUser };
13867
14305
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13868
- await this.registryStore.save({
14306
+ const nextRecord = {
13869
14307
  ...record,
13870
14308
  status: "running",
13871
14309
  updatedAt: this.now(),
@@ -13875,6 +14313,10 @@ var DefaultRunSupervisor = class {
13875
14313
  metadata: {
13876
14314
  ...record.metadata ?? {},
13877
14315
  ...execution ? { executionId: execution.executionId } : {},
14316
+ ...execution?.inputEventIds ? { resumeInputs: {
14317
+ eventIds: [...execution.inputEventIds],
14318
+ checkpointRevision: pendingInteraction.checkpointRevision
14319
+ } } : {},
13878
14320
  awaitingUser: {
13879
14321
  ...awaitingUserWithoutClaim,
13880
14322
  interaction: {
@@ -13883,10 +14325,12 @@ var DefaultRunSupervisor = class {
13883
14325
  }
13884
14326
  }
13885
14327
  }
13886
- });
14328
+ };
14329
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
14330
+ else await persistRunTransition(this.registryStore, record, nextRecord);
13887
14331
  const executionController = new AbortController();
13888
14332
  forwardParentAbortSignal(executionController, parentSignal);
13889
- handle.replaceExecutionAbortController(executionController);
14333
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13890
14334
  this.controllers.set(runId, executionController);
13891
14335
  return handle;
13892
14336
  });
@@ -13904,7 +14348,7 @@ var DefaultRunSupervisor = class {
13904
14348
  }
13905
14349
  const awaitingUserWithoutClaim = { ...awaitingUser };
13906
14350
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13907
- await this.registryStore.save({
14351
+ await persistRunTransition(this.registryStore, record, {
13908
14352
  ...record,
13909
14353
  updatedAt: this.now(),
13910
14354
  metadata: {
@@ -14049,13 +14493,13 @@ __export(system_reminder_exports, {
14049
14493
 
14050
14494
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
14051
14495
  function createDefaultGraphExecutor(options) {
14052
- const executor = new GraphExecutor(
14496
+ const executor2 = new GraphExecutor(
14053
14497
  options.checkpointer ?? new MemoryCheckpointer(),
14054
14498
  { maxSteps: options.maxSteps ?? 8 }
14055
14499
  );
14056
- executor.registerNode(new UserNode());
14057
- executor.registerNode(options.llmNode);
14058
- executor.registerNode(new ToolNode({
14500
+ executor2.registerNode(new UserNode());
14501
+ executor2.registerNode(options.llmNode);
14502
+ executor2.registerNode(new ToolNode({
14059
14503
  toolRuntime: options.toolRuntime,
14060
14504
  observationPreview: options.observationPreview,
14061
14505
  auditPort: options.auditPort,
@@ -14063,8 +14507,8 @@ function createDefaultGraphExecutor(options) {
14063
14507
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
14064
14508
  modelInputResolver: options.modelInputResolver
14065
14509
  }));
14066
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14067
- return executor;
14510
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14511
+ return executor2;
14068
14512
  }
14069
14513
 
14070
14514
  // src/runtime-kernel/testkit/graphLoopHarness.ts
@@ -14089,7 +14533,7 @@ function createGraphLoopHarness(options) {
14089
14533
  return {
14090
14534
  async run() {
14091
14535
  const checkpointKey = options.runId ?? options.turnId;
14092
- const executor = createDefaultGraphExecutor({
14536
+ const executor2 = createDefaultGraphExecutor({
14093
14537
  llmNode: options.createLlmNode({
14094
14538
  llmCaller: options.llmCaller,
14095
14539
  toolRuntime: options.toolRuntime
@@ -14119,8 +14563,8 @@ function createGraphLoopHarness(options) {
14119
14563
  signal: options.signal ?? options.toolContext.abortSignal,
14120
14564
  executorLocal
14121
14565
  };
14122
- await executor.prime(checkpointKey, local, "user");
14123
- const result = await executor.runUntilYield(checkpointKey);
14566
+ await executor2.prime(checkpointKey, local, "user");
14567
+ const result = await executor2.runUntilYield(checkpointKey);
14124
14568
  return {
14125
14569
  checkpointNodeId: result.checkpoint.nodeId,
14126
14570
  stepCount: result.stepCount,