@linnlabs/linnkit 0.32.2 → 0.33.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 (78) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/cli.cjs +312 -50
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +312 -50
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +1 -0
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +1 -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 +32 -32
  13. package/dist/contracts/audit.d.ts +32 -32
  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 +968 -968
  17. package/dist/contracts/events.d.ts +968 -968
  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 +204 -204
  21. package/dist/contracts/messages.d.ts +204 -204
  22. package/dist/contracts/sse.d.cts +891 -891
  23. package/dist/contracts/sse.d.ts +891 -891
  24. package/dist/contracts/sub-run-trace-payload.d.cts +26 -26
  25. package/dist/contracts/sub-run-trace-payload.d.ts +26 -26
  26. package/dist/contracts/token-accounting.d.cts +28 -28
  27. package/dist/contracts/token-accounting.d.ts +28 -28
  28. package/dist/index.cjs +383 -66
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.js +383 -66
  31. package/dist/index.js.map +1 -1
  32. package/dist/quickstart/toolRuntime.d.cts +1 -1
  33. package/dist/quickstart/toolRuntime.d.ts +1 -1
  34. package/dist/quickstart/types.d.cts +1 -1
  35. package/dist/quickstart/types.d.ts +1 -1
  36. package/dist/quickstart.cjs +312 -50
  37. package/dist/quickstart.cjs.map +1 -1
  38. package/dist/quickstart.js +312 -50
  39. package/dist/quickstart.js.map +1 -1
  40. package/dist/runtime-kernel/child-runs/childRunInvoker.d.cts +11 -0
  41. package/dist/runtime-kernel/child-runs/childRunInvoker.d.ts +11 -0
  42. package/dist/runtime-kernel/events/agentEvents.d.cts +98 -98
  43. package/dist/runtime-kernel/events/agentEvents.d.ts +98 -98
  44. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.cts +15 -1
  45. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.ts +15 -1
  46. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.cts +34 -0
  47. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.ts +34 -0
  48. package/dist/runtime-kernel/graph-engine/engine.d.cts +13 -2
  49. package/dist/runtime-kernel/graph-engine/engine.d.ts +13 -2
  50. package/dist/runtime-kernel/graph-engine/index.d.cts +2 -1
  51. package/dist/runtime-kernel/graph-engine/index.d.ts +2 -1
  52. package/dist/runtime-kernel/graph-engine/types.d.cts +8 -0
  53. package/dist/runtime-kernel/graph-engine/types.d.ts +8 -0
  54. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +14 -2
  55. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +14 -2
  56. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.cts +1 -0
  57. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.ts +1 -0
  58. package/dist/runtime-kernel/run-supervisor/runHandle.d.cts +9 -5
  59. package/dist/runtime-kernel/run-supervisor/runHandle.d.ts +9 -5
  60. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.cts +2 -0
  61. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.ts +2 -0
  62. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +7 -1
  63. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +7 -1
  64. package/dist/runtime-kernel.cjs +383 -66
  65. package/dist/runtime-kernel.cjs.map +1 -1
  66. package/dist/runtime-kernel.d.cts +2 -1
  67. package/dist/runtime-kernel.d.ts +2 -1
  68. package/dist/runtime-kernel.js +381 -67
  69. package/dist/runtime-kernel.js.map +1 -1
  70. package/dist/testkit.cjs +383 -66
  71. package/dist/testkit.cjs.map +1 -1
  72. package/dist/testkit.js +383 -66
  73. package/dist/testkit.js.map +1 -1
  74. package/docs/integration/01-installation.md +1 -1
  75. package/docs/integration/child-runs.md +12 -0
  76. package/docs/integration/persistence.md +23 -0
  77. package/docs/integration/run-supervisor.md +12 -2
  78. package/package.json +4 -4
package/dist/testkit.js CHANGED
@@ -4,6 +4,7 @@ import 'eventsource-parser';
4
4
  import { get_encoding } from 'tiktoken';
5
5
  import { AsyncLocalStorage } from 'async_hooks';
6
6
  import { createHash } from 'crypto';
7
+ import { isDeepStrictEqual } from 'util';
7
8
  import { mkdir, appendFile } from 'fs/promises';
8
9
  import { dirname } from 'path';
9
10
 
@@ -103,6 +104,8 @@ __export(runtime_kernel_exports, {
103
104
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
104
105
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
105
106
  REASONING_EFFORTS: () => REASONING_EFFORTS,
107
+ RunPauseRequested: () => RunPauseRequested,
108
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
106
109
  RuntimeEventSubRunTracePublisher: () => RuntimeEventSubRunTracePublisher,
107
110
  SYSTEM_REMINDER_RULES: () => SYSTEM_REMINDER_RULES,
108
111
  SystemReminderRegistry: () => SystemReminderRegistry,
@@ -160,6 +163,7 @@ __export(runtime_kernel_exports, {
160
163
  getToolContextRuntimeBinding: () => getToolContextRuntimeBinding,
161
164
  graph: () => graph_engine_exports,
162
165
  hostReminderTextTemplate: () => hostReminderTextTemplate,
166
+ isRunPauseSignal: () => isRunPauseSignal,
163
167
  isRuntimeFailureFact: () => isRuntimeFailureFact,
164
168
  isValidReasoningEffort: () => isValidReasoningEffort,
165
169
  lastStepsHintTemplate: () => lastStepsHintTemplate,
@@ -207,12 +211,15 @@ __export(graph_engine_exports, {
207
211
  MemoryEventStore: () => MemoryEventStore,
208
212
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
209
213
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
214
+ RunPauseRequested: () => RunPauseRequested,
215
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
210
216
  ToolNode: () => ToolNode,
211
217
  UserNode: () => UserNode,
212
218
  WaitUserNode: () => WaitUserNode,
213
219
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
214
220
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
215
221
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
222
+ isRunPauseSignal: () => isRunPauseSignal,
216
223
  isRuntimeFailureFact: () => isRuntimeFailureFact,
217
224
  readCheckpointContextUsage: () => readCheckpointContextUsage,
218
225
  requireEventStoreId: () => requireEventStoreId,
@@ -2581,6 +2588,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2581
2588
  "memory",
2582
2589
  "runtimeEventSink",
2583
2590
  "runtimeEventCommitPort",
2591
+ "commitExecutionBoundary",
2592
+ "toolRecoveryPort",
2584
2593
  "runtimeFailureFactSink",
2585
2594
  "signal",
2586
2595
  "summarizationCallbacks",
@@ -3131,6 +3140,7 @@ var GraphExecutor = class {
3131
3140
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3132
3141
  };
3133
3142
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3143
+ this.executionCheckpointPort = config.executionCheckpointPort;
3134
3144
  }
3135
3145
  checkpointer;
3136
3146
  nodes = /* @__PURE__ */ new Map();
@@ -3138,6 +3148,7 @@ var GraphExecutor = class {
3138
3148
  checkpointQueues = /* @__PURE__ */ new Map();
3139
3149
  config;
3140
3150
  telemetryPort;
3151
+ executionCheckpointPort;
3141
3152
  registerNode(node) {
3142
3153
  this.nodes.set(node.id, node);
3143
3154
  }
@@ -3146,6 +3157,7 @@ var GraphExecutor = class {
3146
3157
  }
3147
3158
  sanitize(state) {
3148
3159
  return {
3160
+ ...state,
3149
3161
  nodeId: state.nodeId,
3150
3162
  revision: state.revision ?? 0,
3151
3163
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3165,8 +3177,9 @@ var GraphExecutor = class {
3165
3177
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3166
3178
  }
3167
3179
  this.ephemeralLocals.set(checkpointKey, { ...local });
3168
- await this.checkpointer.save(checkpointKey, {
3180
+ await this.commitCheckpoint(checkpointKey, {
3169
3181
  nodeId,
3182
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3170
3183
  revision: 1,
3171
3184
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3172
3185
  local: sanitizeCheckpointLocal(local)
@@ -3177,6 +3190,33 @@ var GraphExecutor = class {
3177
3190
  );
3178
3191
  });
3179
3192
  }
3193
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3194
+ async continueSession(checkpointKey, input) {
3195
+ if (!this.executionCheckpointPort) {
3196
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3197
+ }
3198
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3199
+ const current = await this.checkpointer.load(checkpointKey);
3200
+ if (!current || current.revision !== input.expectedRevision) {
3201
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3202
+ }
3203
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3204
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3205
+ }
3206
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3207
+ return { checkpoint: current, events: [], stepCount: 0 };
3208
+ }
3209
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3210
+ try {
3211
+ return await this.runUntilYieldQueued(
3212
+ checkpointKey,
3213
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3214
+ );
3215
+ } finally {
3216
+ this.ephemeralLocals.delete(checkpointKey);
3217
+ }
3218
+ });
3219
+ }
3180
3220
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3181
3221
  async resumeSession(checkpointKey, input) {
3182
3222
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3197,17 +3237,21 @@ var GraphExecutor = class {
3197
3237
  );
3198
3238
  }
3199
3239
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3240
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3241
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3242
+ }
3200
3243
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3201
- await this.checkpointer.save(checkpointKey, {
3244
+ await this.commitCheckpoint(checkpointKey, {
3202
3245
  ...current,
3203
3246
  nodeId: input.nodeId ?? "llm",
3247
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3204
3248
  revision: currentRevision + 1,
3205
3249
  local: sanitizeCheckpointLocal(resumedLocal)
3206
3250
  });
3207
3251
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3208
3252
  return this.runUntilYieldQueued(
3209
3253
  checkpointKey,
3210
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3254
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3211
3255
  );
3212
3256
  });
3213
3257
  }
@@ -3302,9 +3346,16 @@ var GraphExecutor = class {
3302
3346
  ...state,
3303
3347
  revision: (state.revision ?? 0) + 1
3304
3348
  });
3305
- await this.checkpointer.save(checkpointKey, checkpoint);
3349
+ await this.commitCheckpoint(checkpointKey, checkpoint);
3306
3350
  return checkpoint;
3307
3351
  }
3352
+ async commitCheckpoint(checkpointKey, checkpoint) {
3353
+ if (this.executionCheckpointPort) {
3354
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3355
+ } else {
3356
+ await this.checkpointer.save(checkpointKey, checkpoint);
3357
+ }
3358
+ }
3308
3359
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3309
3360
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3310
3361
  return { events, checkpoint, stepCount };
@@ -3317,6 +3368,15 @@ var GraphExecutor = class {
3317
3368
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3318
3369
  local: { ...state.local || {}, ...ephemeral }
3319
3370
  };
3371
+ if (this.executionCheckpointPort) {
3372
+ state.local = {
3373
+ ...state.local,
3374
+ commitExecutionBoundary: async (boundary) => {
3375
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3376
+ boundary.revision = saved.revision;
3377
+ }
3378
+ };
3379
+ }
3320
3380
  const isAbortSignal2 = (v) => {
3321
3381
  return v !== null && typeof v === "object" && "aborted" in v;
3322
3382
  };
@@ -3326,11 +3386,12 @@ var GraphExecutor = class {
3326
3386
  throw err;
3327
3387
  };
3328
3388
  let stepCount = 0;
3389
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3329
3390
  let allEvents = [];
3330
3391
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3331
3392
  maxSteps
3332
3393
  });
3333
- while (stepCount < maxSteps) {
3394
+ while (previousSteps + stepCount < maxSteps) {
3334
3395
  stepCount += 1;
3335
3396
  reportStepsUsed(stepCount);
3336
3397
  const signalRaw = state.local?.signal;
@@ -3342,7 +3403,7 @@ var GraphExecutor = class {
3342
3403
  const stepPreparation = prepareGraphStep({
3343
3404
  state,
3344
3405
  maxSteps,
3345
- stepCount
3406
+ stepCount: previousSteps + stepCount
3346
3407
  });
3347
3408
  state = stepPreparation.state;
3348
3409
  const node = this.nodes.get(state.nodeId);
@@ -3351,6 +3412,7 @@ var GraphExecutor = class {
3351
3412
  maxSteps,
3352
3413
  stepCount
3353
3414
  });
3415
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3354
3416
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3355
3417
  this.ephemeralLocals.delete(checkpointKey);
3356
3418
  return result3;
@@ -3360,6 +3422,11 @@ var GraphExecutor = class {
3360
3422
  stepCount,
3361
3423
  nodeId: state.nodeId
3362
3424
  });
3425
+ if (this.executionCheckpointPort) {
3426
+ state.executionStatus = "executing";
3427
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3428
+ state.revision = saved.revision;
3429
+ }
3363
3430
  const result2 = await runGraphNodeWithTelemetry({
3364
3431
  node,
3365
3432
  state,
@@ -3384,10 +3451,13 @@ var GraphExecutor = class {
3384
3451
  fromNodeId: stepResolution.action.fromNodeId,
3385
3452
  nextNodeId: stepResolution.action.nextNodeId
3386
3453
  });
3387
- await this.saveCheckpoint(checkpointKey, state);
3454
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3455
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3456
+ state.revision = saved.revision;
3388
3457
  continue;
3389
3458
  }
3390
3459
  if (stepResolution.action.kind === "yield") {
3460
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3391
3461
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3392
3462
  maxSteps,
3393
3463
  stepCount
@@ -3398,6 +3468,7 @@ var GraphExecutor = class {
3398
3468
  maxSteps,
3399
3469
  stepCount
3400
3470
  });
3471
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3401
3472
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3402
3473
  }
3403
3474
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3418,6 +3489,7 @@ var GraphExecutor = class {
3418
3489
  },
3419
3490
  retryable: false
3420
3491
  }), "GraphExecutor.engine_budget_exhausted"));
3492
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3421
3493
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3422
3494
  this.ephemeralLocals.delete(checkpointKey);
3423
3495
  return result;
@@ -7311,10 +7383,11 @@ var LlmNode = class {
7311
7383
  bridge.handle
7312
7384
  );
7313
7385
  } catch (error) {
7314
- bridge.finalizePartialAnswer();
7386
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7315
7387
  throw error;
7316
7388
  }
7317
7389
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7390
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7318
7391
  switch (decision.kind) {
7319
7392
  case "tool_calls": {
7320
7393
  if (forceFinalAnswer) {
@@ -8582,6 +8655,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8582
8655
  function recordToolProtocolError(params) {
8583
8656
  }
8584
8657
 
8658
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8659
+ var RunRecoveryBlockedError = class extends Error {
8660
+ code = "RUN_RECOVERY_BLOCKED";
8661
+ constructor(message) {
8662
+ super(message);
8663
+ this.name = "RunRecoveryBlockedError";
8664
+ }
8665
+ };
8666
+ var RunPauseRequested = class extends Error {
8667
+ code = "RUN_PAUSE_REQUESTED";
8668
+ constructor(message = "Run paused by user") {
8669
+ super(message);
8670
+ this.name = "RunPauseRequested";
8671
+ }
8672
+ };
8673
+ function isRunPauseSignal(signal) {
8674
+ const reason = signal?.reason;
8675
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8676
+ }
8677
+
8678
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8679
+ async function executeRecoverableTool(input) {
8680
+ const local = input.state.local;
8681
+ if (!local?.commitExecutionBoundary) return input.execute();
8682
+ if (local.executingToolCallId) {
8683
+ if (local.executingToolCallId !== input.call.id) {
8684
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8685
+ }
8686
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8687
+ if (!decision || decision.kind === "blocked") {
8688
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8689
+ }
8690
+ if (decision.kind === "settled") return decision.result;
8691
+ }
8692
+ local.executingToolCallId = input.call.id;
8693
+ await local.commitExecutionBoundary(input.state);
8694
+ const result = await input.execute();
8695
+ if (!result.success && isRunPauseSignal(local.signal)) {
8696
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8697
+ error.name = "AbortError";
8698
+ throw error;
8699
+ }
8700
+ return result;
8701
+ }
8702
+ async function commitToolBoundary(state, result) {
8703
+ if (!state.local?.commitExecutionBoundary) return;
8704
+ delete state.local.executingToolCallId;
8705
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8706
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8707
+ await state.local.commitExecutionBoundary(state);
8708
+ }
8709
+
8585
8710
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8586
8711
  var logger11 = new Logger("ToolNode");
8587
8712
  function isAbortSignal(value) {
@@ -8752,6 +8877,7 @@ var ToolNode = class {
8752
8877
  const events = [];
8753
8878
  while (true) {
8754
8879
  const result = await this.runNextPendingToolCall(state);
8880
+ await commitToolBoundary(state, result);
8755
8881
  if (Array.isArray(result.events) && result.events.length > 0) {
8756
8882
  events.push(...result.events);
8757
8883
  }
@@ -8768,11 +8894,9 @@ var ToolNode = class {
8768
8894
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8769
8895
  const signalRaw = state.local?.signal;
8770
8896
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8771
- settlePendingToolCallsAfterAbort({
8772
- state,
8773
- calls,
8774
- toolCatalog: this.toolRuntime
8775
- });
8897
+ if (!isRunPauseSignal(signalRaw)) {
8898
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8899
+ }
8776
8900
  const abortError = new Error("The user aborted a request.");
8777
8901
  abortError.name = "AbortError";
8778
8902
  throw abortError;
@@ -8911,16 +9035,21 @@ var ToolNode = class {
8911
9035
  tool_calls: [call]
8912
9036
  });
8913
9037
  try {
8914
- const exec = await executeToolWithIdempotency({
8915
- idempotencyKey: execution.idempotencyKey,
8916
- inFlight: this.idempotencyInFlight,
8917
- history: readHistoryEvents(prepared.local),
8918
- toolName: execution.toolName,
8919
- execute: () => this.toolRuntime.executeTool(
8920
- execution.toolName,
8921
- execution.toolArgs,
8922
- prepared.toolContext
8923
- )
9038
+ const exec = await executeRecoverableTool({
9039
+ state,
9040
+ call,
9041
+ context: prepared.toolContext,
9042
+ execute: () => executeToolWithIdempotency({
9043
+ idempotencyKey: execution.idempotencyKey,
9044
+ inFlight: this.idempotencyInFlight,
9045
+ history: readHistoryEvents(prepared.local),
9046
+ toolName: execution.toolName,
9047
+ execute: () => this.toolRuntime.executeTool(
9048
+ execution.toolName,
9049
+ execution.toolArgs,
9050
+ prepared.toolContext
9051
+ )
9052
+ })
8924
9053
  });
8925
9054
  if (exec.success) {
8926
9055
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -9000,7 +9129,7 @@ var ToolNode = class {
9000
9129
  bridge: execution.bridge
9001
9130
  });
9002
9131
  } catch (error) {
9003
- if (isToolExecutionAbort(error)) {
9132
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
9004
9133
  settleToolCallsAfterExecutionAbort({
9005
9134
  state,
9006
9135
  remainingCalls: calls.slice(1),
@@ -9060,7 +9189,7 @@ var ToolNode = class {
9060
9189
  {
9061
9190
  attachments: context.attachments,
9062
9191
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
9063
- ephemeral: context.exec.idempotency?.cacheHit === true,
9192
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
9064
9193
  durationMs: context.exec.durationMs
9065
9194
  }
9066
9195
  );
@@ -9117,6 +9246,9 @@ var ToolNode = class {
9117
9246
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
9118
9247
  }
9119
9248
  async handleError(context) {
9249
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9250
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9251
+ }
9120
9252
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
9121
9253
  await this.emitToolDecisionAudit({
9122
9254
  action: "tool.deny",
@@ -10225,12 +10357,33 @@ var RuntimeEventPublisher = class {
10225
10357
  var EventBusEventPersistence = class {
10226
10358
  constructor(options) {
10227
10359
  this.options = options;
10360
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10228
10361
  }
10229
10362
  options;
10230
10363
  scheduledEventIds = /* @__PURE__ */ new Set();
10231
10364
  writeTail = Promise.resolve();
10232
10365
  firstWriteError;
10233
10366
  connected = false;
10367
+ checkpointWritesActive;
10368
+ checkpointEvents = [];
10369
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10370
+ async commitCheckpoint(checkpointKey, checkpoint) {
10371
+ const writer = this.options.checkpointWriter;
10372
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10373
+ const events = this.checkpointEvents;
10374
+ this.checkpointEvents = [];
10375
+ await this.enqueueWrite(() => writer({
10376
+ checkpointKey,
10377
+ checkpoint,
10378
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10379
+ }));
10380
+ }
10381
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10382
+ finishCheckpointWrites() {
10383
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10384
+ this.checkpointEvents = [];
10385
+ this.checkpointWritesActive = false;
10386
+ }
10234
10387
  connect() {
10235
10388
  if (this.connected) {
10236
10389
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10277,14 +10430,22 @@ var EventBusEventPersistence = class {
10277
10430
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10278
10431
  return;
10279
10432
  }
10433
+ if (this.checkpointWritesActive) {
10434
+ this.scheduledEventIds.add(event.id);
10435
+ this.checkpointEvents.push(event);
10436
+ return;
10437
+ }
10280
10438
  void this.scheduleWrite(event).catch(() => void 0);
10281
10439
  };
10282
10440
  scheduleWrite(event) {
10283
10441
  this.scheduledEventIds.add(event.id);
10284
- const eventStoreId = this.options.nextEventStoreId();
10285
- const write = this.writeTail.then(async () => {
10286
- await this.options.eventStore.append({ eventStoreId, event });
10287
- });
10442
+ return this.enqueueWrite(() => this.options.eventStore.append({
10443
+ eventStoreId: this.options.nextEventStoreId(),
10444
+ event
10445
+ }));
10446
+ }
10447
+ enqueueWrite(operation) {
10448
+ const write = this.writeTail.then(operation);
10288
10449
  this.writeTail = write;
10289
10450
  void write.catch((error) => {
10290
10451
  this.firstWriteError ??= error;
@@ -12005,6 +12166,9 @@ var ChildRunInvoker = class {
12005
12166
  explicitConversationId: conversationId,
12006
12167
  parentToolContext
12007
12168
  });
12169
+ if (config.persistence?.expectedRevision !== void 0) {
12170
+ return this.continueChild(config, childRunId, runtimeConversationId);
12171
+ }
12008
12172
  const turnId = generateTurnId();
12009
12173
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
12010
12174
  conversationId: runtimeConversationId,
@@ -12012,21 +12176,8 @@ var ChildRunInvoker = class {
12012
12176
  maxSteps,
12013
12177
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
12014
12178
  });
12015
- const checkpointer = new MemoryCheckpointer();
12016
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
12017
- const llmNode = this.createLlmNode();
12018
- const toolNode = new ToolNode({
12019
- toolRuntime: this.toolRuntime,
12020
- observationPreview: this.observationPreview,
12021
- telemetryPort: this.telemetryPort,
12022
- auditPort: this.auditPort,
12023
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12024
- modelInputResolver: this.modelInputResolver
12025
- });
12026
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
12027
- graphExecutor.registerNode(llmNode);
12028
- graphExecutor.registerNode(toolNode);
12029
- graphExecutor.registerNode(waitUserNode);
12179
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
12180
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
12030
12181
  const childUserInput = createChildRunUserInput({
12031
12182
  id: generateRuntimeEventId(),
12032
12183
  conversationId: runtimeConversationId,
@@ -12106,6 +12257,7 @@ var ChildRunInvoker = class {
12106
12257
  ...abortSignal ? { signal: abortSignal } : {},
12107
12258
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
12108
12259
  runtimeEventSink,
12260
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
12109
12261
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
12110
12262
  systemPrompt
12111
12263
  };
@@ -12146,6 +12298,7 @@ var ChildRunInvoker = class {
12146
12298
  eventToMessageConverter: this.eventToMessageConverter
12147
12299
  });
12148
12300
  } catch (err) {
12301
+ if (config.persistence) throw err;
12149
12302
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
12150
12303
  checkpointer,
12151
12304
  checkpointKey: internalCheckpointKey,
@@ -12184,7 +12337,7 @@ var ChildRunInvoker = class {
12184
12337
  events: allEvents,
12185
12338
  eventToMessageConverter: this.eventToMessageConverter
12186
12339
  });
12187
- await checkpointer.clear(internalCheckpointKey);
12340
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12188
12341
  return {
12189
12342
  success: !error && !cancelled,
12190
12343
  runId: childRunId,
@@ -12201,6 +12354,66 @@ var ChildRunInvoker = class {
12201
12354
  error
12202
12355
  };
12203
12356
  }
12357
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12358
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12359
+ graph.registerNode(this.createLlmNode());
12360
+ graph.registerNode(new ToolNode({
12361
+ toolRuntime: this.toolRuntime,
12362
+ observationPreview: this.observationPreview,
12363
+ telemetryPort: this.telemetryPort,
12364
+ auditPort: this.auditPort,
12365
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12366
+ modelInputResolver: this.modelInputResolver
12367
+ }));
12368
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12369
+ return graph;
12370
+ }
12371
+ async continueChild(config, runId, conversationId) {
12372
+ const persistence = config.persistence;
12373
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12374
+ const checkpoint = await persistence.checkpointer.load(runId);
12375
+ if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12376
+ const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
12377
+ const request = local.request;
12378
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12379
+ const context = createChildRunToolContext({
12380
+ parentToolContext: config.parentToolContext,
12381
+ conversationId,
12382
+ turnId: local.turnId,
12383
+ runId,
12384
+ parentRunId: config.parentRunId,
12385
+ userQuery: request.query,
12386
+ modelId: request.model_id,
12387
+ seedHistory: local.history,
12388
+ abortSignal: config.abortSignal
12389
+ });
12390
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12391
+ const result = await graph.continueSession(runId, {
12392
+ expectedRevision: persistence.expectedRevision,
12393
+ capabilities: {
12394
+ toolContext: context,
12395
+ signal: config.abortSignal,
12396
+ runtimeEventSink: config.runtimeEventSink,
12397
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12398
+ toolRecoveryPort: persistence.toolRecoveryPort
12399
+ }
12400
+ });
12401
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12402
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12403
+ const finalAnswer = extractFinalAnswer(events);
12404
+ return {
12405
+ runId,
12406
+ parentRunId: config.parentRunId,
12407
+ subrunId: runId,
12408
+ success: true,
12409
+ events,
12410
+ finalAnswer,
12411
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12412
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12413
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12414
+ toolset: { availableTools: request.availableTools }
12415
+ };
12416
+ }
12204
12417
  };
12205
12418
  function isAbortError2(error) {
12206
12419
  return error instanceof Error && error.name === "AbortError";
@@ -12602,8 +12815,6 @@ __export(run_supervisor_exports, {
12602
12815
  RunNotFoundError: () => RunNotFoundError,
12603
12816
  runMetaFromRecord: () => runMetaFromRecord
12604
12817
  });
12605
-
12606
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12607
12818
  function cloneRunRecord(record) {
12608
12819
  return {
12609
12820
  ...record,
@@ -12623,6 +12834,11 @@ function matchesStatus(candidate, filter) {
12623
12834
  }
12624
12835
  var MemoryRunRegistryStore = class {
12625
12836
  store = /* @__PURE__ */ new Map();
12837
+ async compareAndSwap(previous, next) {
12838
+ if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12839
+ this.store.set(next.runId, cloneRunRecord(next));
12840
+ return true;
12841
+ }
12626
12842
  async save(record) {
12627
12843
  this.store.set(record.runId, cloneRunRecord(record));
12628
12844
  }
@@ -12770,6 +12986,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12770
12986
  }
12771
12987
  };
12772
12988
 
12989
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
12990
+ async function persistRunTransition(store, previous, next) {
12991
+ if (store.compareAndSwap) {
12992
+ if (!await store.compareAndSwap(previous, next)) {
12993
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
12994
+ }
12995
+ } else {
12996
+ await store.save(next);
12997
+ }
12998
+ }
12999
+
12773
13000
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12774
13001
  function isRunTerminalStatus(status) {
12775
13002
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12825,6 +13052,7 @@ var DefaultRunHandle = class {
12825
13052
  parentRunId;
12826
13053
  runRecord;
12827
13054
  abortController;
13055
+ executionId;
12828
13056
  agentSpecSnapshot;
12829
13057
  requestSnapshot;
12830
13058
  transportEventBus;
@@ -12840,6 +13068,9 @@ var DefaultRunHandle = class {
12840
13068
  this.runId = options.runRecord.runId;
12841
13069
  this.parentRunId = options.runRecord.parentRunId;
12842
13070
  this.abortController = options.abortController;
13071
+ const executionId = options.runRecord.metadata?.executionId;
13072
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
13073
+ this.executionId = executionId;
12843
13074
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12844
13075
  this.requestSnapshot = cloneRequest(options.request);
12845
13076
  this.transportEventBus = options.eventBus;
@@ -12859,8 +13090,9 @@ var DefaultRunHandle = class {
12859
13090
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12860
13091
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12861
13092
  */
12862
- replaceExecutionAbortController(controller) {
13093
+ replaceExecutionAbortController(controller, executionId) {
12863
13094
  this.abortController = controller;
13095
+ this.executionId = executionId;
12864
13096
  }
12865
13097
  async spec() {
12866
13098
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12880,6 +13112,7 @@ var DefaultRunHandle = class {
12880
13112
  this.abortController.abort(opts.reason);
12881
13113
  const latestRecord = await this.registryStore.load(this.runId);
12882
13114
  const baseRecord = latestRecord ?? this.runRecord;
13115
+ this.assertExecutionOwner(baseRecord);
12883
13116
  const transition = decideRunLifecycleTransition(baseRecord.status);
12884
13117
  if (transition.kind === "skip_terminal") {
12885
13118
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12889,7 +13122,7 @@ var DefaultRunHandle = class {
12889
13122
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12890
13123
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12891
13124
  };
12892
- await this.registryStore.save(settledRecord);
13125
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12893
13126
  this.runRecord = { ...settledRecord };
12894
13127
  return;
12895
13128
  }
@@ -12916,7 +13149,7 @@ var DefaultRunHandle = class {
12916
13149
  }
12917
13150
  }
12918
13151
  };
12919
- await this.registryStore.save(nextRecord);
13152
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12920
13153
  this.runRecord = { ...nextRecord };
12921
13154
  await this.auditPort.emit({
12922
13155
  envelopeId: generateAuditEnvelopeId(),
@@ -13024,21 +13257,35 @@ var DefaultRunHandle = class {
13024
13257
  async markFailed(error, patch = {}) {
13025
13258
  await this.saveLifecycleStatus("failed", patch, error);
13026
13259
  }
13027
- async pause(_reason) {
13028
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13260
+ async pause(reason = "Run paused by user") {
13261
+ const latest = await this.registryStore.load(this.runId);
13262
+ if (latest) this.assertExecutionOwner(latest);
13263
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13264
+ const next = {
13265
+ ...latest,
13266
+ status: "paused",
13267
+ updatedAt: Date.now(),
13268
+ pauseReason: reason,
13269
+ pausedAt: void 0
13270
+ };
13271
+ await persistRunTransition(this.registryStore, latest, next);
13272
+ this.runRecord = next;
13273
+ this.abortController.abort(new RunPauseRequested(reason));
13029
13274
  }
13030
- async resume() {
13031
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13275
+ async markPaused(patch = {}) {
13276
+ await this.saveLifecycleStatus("paused", patch);
13032
13277
  }
13033
13278
  async saveLifecycleStatus(status, patch, errorIfAny) {
13034
13279
  const latestRecord = await this.registryStore.load(this.runId);
13035
13280
  const baseRecord = latestRecord ?? this.runRecord;
13036
13281
  const transition = decideRunLifecycleTransition(baseRecord.status);
13282
+ this.assertExecutionOwner(baseRecord);
13283
+ if (status === "running" && baseRecord.status === "paused") return;
13037
13284
  if (transition.kind === "skip_terminal") {
13038
13285
  this.runRecord = { ...baseRecord };
13039
13286
  return;
13040
13287
  }
13041
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13288
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
13042
13289
  const updatedAt = Date.now();
13043
13290
  const nextRecord = {
13044
13291
  ...baseRecord,
@@ -13046,8 +13293,8 @@ var DefaultRunHandle = class {
13046
13293
  updatedAt,
13047
13294
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13048
13295
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
13049
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13050
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13296
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13297
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
13051
13298
  errorIfAny,
13052
13299
  metadata: awaitingUserPatch?.eventId ? {
13053
13300
  ...baseRecord.metadata ?? {},
@@ -13058,7 +13305,7 @@ var DefaultRunHandle = class {
13058
13305
  }
13059
13306
  } : baseRecord.metadata
13060
13307
  };
13061
- await this.registryStore.save(nextRecord);
13308
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13062
13309
  this.runRecord = { ...nextRecord };
13063
13310
  if (status === "completed" || status === "failed") {
13064
13311
  this.closeObservationChannel();
@@ -13068,6 +13315,11 @@ var DefaultRunHandle = class {
13068
13315
  forwardTransportEvent = (envelope) => {
13069
13316
  this.observationEventBus.emit("event", envelope);
13070
13317
  };
13318
+ assertExecutionOwner(record) {
13319
+ if (record.metadata?.executionId !== this.executionId) {
13320
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13321
+ }
13322
+ }
13071
13323
  forwardTransportError = (error) => {
13072
13324
  this.observationEventBus.emit("error", error);
13073
13325
  };
@@ -13449,6 +13701,24 @@ async function recoverRunsOnBoot(options) {
13449
13701
  const outcomes = [];
13450
13702
  for (const record of activeRecords) {
13451
13703
  const updatedAt = options.now();
13704
+ if (await options.canRestoreRun?.(record)) {
13705
+ const metadata = { ...record.metadata };
13706
+ const awaitingUser = metadata.awaitingUser;
13707
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13708
+ const restored = { ...awaitingUser };
13709
+ Reflect.deleteProperty(restored, "resumeClaim");
13710
+ metadata.awaitingUser = restored;
13711
+ }
13712
+ await persistRunTransition(options.registryStore, record, {
13713
+ ...record,
13714
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13715
+ pausedAt: record.pausedAt ?? updatedAt,
13716
+ pauseReason: record.pauseReason ?? options.reason,
13717
+ updatedAt,
13718
+ metadata
13719
+ });
13720
+ continue;
13721
+ }
13452
13722
  const nextRecord = {
13453
13723
  ...record,
13454
13724
  status: "failed",
@@ -13466,7 +13736,7 @@ async function recoverRunsOnBoot(options) {
13466
13736
  }
13467
13737
  }
13468
13738
  };
13469
- await options.registryStore.save(nextRecord);
13739
+ await persistRunTransition(options.registryStore, record, nextRecord);
13470
13740
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13471
13741
  options.notifyTerminal(outcome);
13472
13742
  outcomes.push(outcome);
@@ -13590,8 +13860,13 @@ var DefaultRunSupervisor = class {
13590
13860
  inFlight = /* @__PURE__ */ new Map();
13591
13861
  eventWatchDisposers = /* @__PURE__ */ new Map();
13592
13862
  controlOperations = /* @__PURE__ */ new Map();
13863
+ canRestoreRun;
13593
13864
  constructor(options) {
13865
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13866
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13867
+ }
13594
13868
  this.registryStore = options.registryStore;
13869
+ this.canRestoreRun = options.canRestoreRun;
13595
13870
  this.auditPort = options.auditPort;
13596
13871
  this.executor = options.executor;
13597
13872
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13639,6 +13914,23 @@ var DefaultRunSupervisor = class {
13639
13914
  this.releaseRunAdmission(runId);
13640
13915
  throw error;
13641
13916
  }
13917
+ return this.attachRun(record, spec, controller);
13918
+ }
13919
+ async restoreRun(spec) {
13920
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13921
+ return this.withRunControlLock(spec.runId, async () => {
13922
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
13923
+ const record = await this.registryStore.load(spec.runId);
13924
+ if (!record) throw new RunNotFoundError(spec.runId);
13925
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
13926
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
13927
+ }
13928
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
13929
+ return this.attachRun(record, spec, new AbortController());
13930
+ });
13931
+ }
13932
+ attachRun(record, spec, controller) {
13933
+ const runId = record.runId;
13642
13934
  try {
13643
13935
  const handle = new DefaultRunHandle({
13644
13936
  runRecord: record,
@@ -13736,11 +14028,36 @@ var DefaultRunSupervisor = class {
13736
14028
  registryStore: this.registryStore,
13737
14029
  reason,
13738
14030
  now: this.now,
13739
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
14031
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
14032
+ canRestoreRun: this.canRestoreRun
13740
14033
  });
13741
14034
  }
13742
- async pause(_runId, _reason) {
13743
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
14035
+ async pause(runId, reason) {
14036
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
14037
+ }
14038
+ async resumePausedRun(input) {
14039
+ return this.withRunControlLock(input.runId, async () => {
14040
+ const handle = this.getHandle(input.runId);
14041
+ const record = await this.registryStore.load(input.runId);
14042
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
14043
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
14044
+ }
14045
+ await persistRunTransition(this.registryStore, record, {
14046
+ ...record,
14047
+ status: "running",
14048
+ updatedAt: this.now(),
14049
+ pausedAt: void 0,
14050
+ pauseReason: void 0,
14051
+ errorIfAny: void 0,
14052
+ metadata: { ...record.metadata, executionId: input.executionId }
14053
+ });
14054
+ const controller = new AbortController();
14055
+ handle.replaceExecutionAbortController(controller, input.executionId);
14056
+ handle.attachTransportEventBus(input.eventBus);
14057
+ this.controllers.set(input.runId, controller);
14058
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
14059
+ return handle;
14060
+ });
13744
14061
  }
13745
14062
  async claimResume(runId, interaction, eventBus, parentSignal) {
13746
14063
  return this.withRunControlLock(runId, async () => {
@@ -13775,7 +14092,7 @@ var DefaultRunSupervisor = class {
13775
14092
  throw new RunNotFoundError(runId);
13776
14093
  }
13777
14094
  const claimId = generateRunResumeClaimId();
13778
- await this.registryStore.save({
14095
+ await persistRunTransition(this.registryStore, record, {
13779
14096
  ...record,
13780
14097
  updatedAt: this.now(),
13781
14098
  metadata: {
@@ -13863,7 +14180,7 @@ var DefaultRunSupervisor = class {
13863
14180
  }
13864
14181
  const awaitingUserWithoutClaim = { ...awaitingUser };
13865
14182
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13866
- await this.registryStore.save({
14183
+ await persistRunTransition(this.registryStore, record, {
13867
14184
  ...record,
13868
14185
  status: "running",
13869
14186
  updatedAt: this.now(),
@@ -13884,7 +14201,7 @@ var DefaultRunSupervisor = class {
13884
14201
  });
13885
14202
  const executionController = new AbortController();
13886
14203
  forwardParentAbortSignal(executionController, parentSignal);
13887
- handle.replaceExecutionAbortController(executionController);
14204
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13888
14205
  this.controllers.set(runId, executionController);
13889
14206
  return handle;
13890
14207
  });
@@ -13902,7 +14219,7 @@ var DefaultRunSupervisor = class {
13902
14219
  }
13903
14220
  const awaitingUserWithoutClaim = { ...awaitingUser };
13904
14221
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13905
- await this.registryStore.save({
14222
+ await persistRunTransition(this.registryStore, record, {
13906
14223
  ...record,
13907
14224
  updatedAt: this.now(),
13908
14225
  metadata: {