@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.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,
@@ -209,12 +213,15 @@ __export(graph_engine_exports, {
209
213
  MemoryEventStore: () => MemoryEventStore,
210
214
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
211
215
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
216
+ RunPauseRequested: () => RunPauseRequested,
217
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
212
218
  ToolNode: () => ToolNode,
213
219
  UserNode: () => UserNode,
214
220
  WaitUserNode: () => WaitUserNode,
215
221
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
216
222
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
217
223
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
224
+ isRunPauseSignal: () => isRunPauseSignal,
218
225
  isRuntimeFailureFact: () => isRuntimeFailureFact,
219
226
  readCheckpointContextUsage: () => readCheckpointContextUsage,
220
227
  requireEventStoreId: () => requireEventStoreId,
@@ -2583,6 +2590,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2583
2590
  "memory",
2584
2591
  "runtimeEventSink",
2585
2592
  "runtimeEventCommitPort",
2593
+ "commitExecutionBoundary",
2594
+ "toolRecoveryPort",
2586
2595
  "runtimeFailureFactSink",
2587
2596
  "signal",
2588
2597
  "summarizationCallbacks",
@@ -3133,6 +3142,7 @@ var GraphExecutor = class {
3133
3142
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3134
3143
  };
3135
3144
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3145
+ this.executionCheckpointPort = config.executionCheckpointPort;
3136
3146
  }
3137
3147
  checkpointer;
3138
3148
  nodes = /* @__PURE__ */ new Map();
@@ -3140,6 +3150,7 @@ var GraphExecutor = class {
3140
3150
  checkpointQueues = /* @__PURE__ */ new Map();
3141
3151
  config;
3142
3152
  telemetryPort;
3153
+ executionCheckpointPort;
3143
3154
  registerNode(node) {
3144
3155
  this.nodes.set(node.id, node);
3145
3156
  }
@@ -3148,6 +3159,7 @@ var GraphExecutor = class {
3148
3159
  }
3149
3160
  sanitize(state) {
3150
3161
  return {
3162
+ ...state,
3151
3163
  nodeId: state.nodeId,
3152
3164
  revision: state.revision ?? 0,
3153
3165
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3167,8 +3179,9 @@ var GraphExecutor = class {
3167
3179
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3168
3180
  }
3169
3181
  this.ephemeralLocals.set(checkpointKey, { ...local });
3170
- await this.checkpointer.save(checkpointKey, {
3182
+ await this.commitCheckpoint(checkpointKey, {
3171
3183
  nodeId,
3184
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3172
3185
  revision: 1,
3173
3186
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3174
3187
  local: sanitizeCheckpointLocal(local)
@@ -3179,6 +3192,33 @@ var GraphExecutor = class {
3179
3192
  );
3180
3193
  });
3181
3194
  }
3195
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3196
+ async continueSession(checkpointKey, input) {
3197
+ if (!this.executionCheckpointPort) {
3198
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3199
+ }
3200
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3201
+ const current = await this.checkpointer.load(checkpointKey);
3202
+ if (!current || current.revision !== input.expectedRevision) {
3203
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3204
+ }
3205
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3206
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3207
+ }
3208
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3209
+ return { checkpoint: current, events: [], stepCount: 0 };
3210
+ }
3211
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3212
+ try {
3213
+ return await this.runUntilYieldQueued(
3214
+ checkpointKey,
3215
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3216
+ );
3217
+ } finally {
3218
+ this.ephemeralLocals.delete(checkpointKey);
3219
+ }
3220
+ });
3221
+ }
3182
3222
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3183
3223
  async resumeSession(checkpointKey, input) {
3184
3224
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3199,17 +3239,21 @@ var GraphExecutor = class {
3199
3239
  );
3200
3240
  }
3201
3241
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3242
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3243
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3244
+ }
3202
3245
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3203
- await this.checkpointer.save(checkpointKey, {
3246
+ await this.commitCheckpoint(checkpointKey, {
3204
3247
  ...current,
3205
3248
  nodeId: input.nodeId ?? "llm",
3249
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3206
3250
  revision: currentRevision + 1,
3207
3251
  local: sanitizeCheckpointLocal(resumedLocal)
3208
3252
  });
3209
3253
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3210
3254
  return this.runUntilYieldQueued(
3211
3255
  checkpointKey,
3212
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3256
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3213
3257
  );
3214
3258
  });
3215
3259
  }
@@ -3304,9 +3348,16 @@ var GraphExecutor = class {
3304
3348
  ...state,
3305
3349
  revision: (state.revision ?? 0) + 1
3306
3350
  });
3307
- await this.checkpointer.save(checkpointKey, checkpoint);
3351
+ await this.commitCheckpoint(checkpointKey, checkpoint);
3308
3352
  return checkpoint;
3309
3353
  }
3354
+ async commitCheckpoint(checkpointKey, checkpoint) {
3355
+ if (this.executionCheckpointPort) {
3356
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3357
+ } else {
3358
+ await this.checkpointer.save(checkpointKey, checkpoint);
3359
+ }
3360
+ }
3310
3361
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3311
3362
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3312
3363
  return { events, checkpoint, stepCount };
@@ -3319,6 +3370,15 @@ var GraphExecutor = class {
3319
3370
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3320
3371
  local: { ...state.local || {}, ...ephemeral }
3321
3372
  };
3373
+ if (this.executionCheckpointPort) {
3374
+ state.local = {
3375
+ ...state.local,
3376
+ commitExecutionBoundary: async (boundary) => {
3377
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3378
+ boundary.revision = saved.revision;
3379
+ }
3380
+ };
3381
+ }
3322
3382
  const isAbortSignal2 = (v) => {
3323
3383
  return v !== null && typeof v === "object" && "aborted" in v;
3324
3384
  };
@@ -3328,11 +3388,12 @@ var GraphExecutor = class {
3328
3388
  throw err;
3329
3389
  };
3330
3390
  let stepCount = 0;
3391
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3331
3392
  let allEvents = [];
3332
3393
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3333
3394
  maxSteps
3334
3395
  });
3335
- while (stepCount < maxSteps) {
3396
+ while (previousSteps + stepCount < maxSteps) {
3336
3397
  stepCount += 1;
3337
3398
  reportStepsUsed(stepCount);
3338
3399
  const signalRaw = state.local?.signal;
@@ -3344,7 +3405,7 @@ var GraphExecutor = class {
3344
3405
  const stepPreparation = prepareGraphStep({
3345
3406
  state,
3346
3407
  maxSteps,
3347
- stepCount
3408
+ stepCount: previousSteps + stepCount
3348
3409
  });
3349
3410
  state = stepPreparation.state;
3350
3411
  const node = this.nodes.get(state.nodeId);
@@ -3353,6 +3414,7 @@ var GraphExecutor = class {
3353
3414
  maxSteps,
3354
3415
  stepCount
3355
3416
  });
3417
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3356
3418
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3357
3419
  this.ephemeralLocals.delete(checkpointKey);
3358
3420
  return result3;
@@ -3362,6 +3424,11 @@ var GraphExecutor = class {
3362
3424
  stepCount,
3363
3425
  nodeId: state.nodeId
3364
3426
  });
3427
+ if (this.executionCheckpointPort) {
3428
+ state.executionStatus = "executing";
3429
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3430
+ state.revision = saved.revision;
3431
+ }
3365
3432
  const result2 = await runGraphNodeWithTelemetry({
3366
3433
  node,
3367
3434
  state,
@@ -3386,10 +3453,13 @@ var GraphExecutor = class {
3386
3453
  fromNodeId: stepResolution.action.fromNodeId,
3387
3454
  nextNodeId: stepResolution.action.nextNodeId
3388
3455
  });
3389
- await this.saveCheckpoint(checkpointKey, state);
3456
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3457
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3458
+ state.revision = saved.revision;
3390
3459
  continue;
3391
3460
  }
3392
3461
  if (stepResolution.action.kind === "yield") {
3462
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3393
3463
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3394
3464
  maxSteps,
3395
3465
  stepCount
@@ -3400,6 +3470,7 @@ var GraphExecutor = class {
3400
3470
  maxSteps,
3401
3471
  stepCount
3402
3472
  });
3473
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3403
3474
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3404
3475
  }
3405
3476
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3420,6 +3491,7 @@ var GraphExecutor = class {
3420
3491
  },
3421
3492
  retryable: false
3422
3493
  }), "GraphExecutor.engine_budget_exhausted"));
3494
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3423
3495
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3424
3496
  this.ephemeralLocals.delete(checkpointKey);
3425
3497
  return result;
@@ -7313,10 +7385,11 @@ var LlmNode = class {
7313
7385
  bridge.handle
7314
7386
  );
7315
7387
  } catch (error) {
7316
- bridge.finalizePartialAnswer();
7388
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7317
7389
  throw error;
7318
7390
  }
7319
7391
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7392
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7320
7393
  switch (decision.kind) {
7321
7394
  case "tool_calls": {
7322
7395
  if (forceFinalAnswer) {
@@ -8584,6 +8657,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8584
8657
  function recordToolProtocolError(params) {
8585
8658
  }
8586
8659
 
8660
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8661
+ var RunRecoveryBlockedError = class extends Error {
8662
+ code = "RUN_RECOVERY_BLOCKED";
8663
+ constructor(message) {
8664
+ super(message);
8665
+ this.name = "RunRecoveryBlockedError";
8666
+ }
8667
+ };
8668
+ var RunPauseRequested = class extends Error {
8669
+ code = "RUN_PAUSE_REQUESTED";
8670
+ constructor(message = "Run paused by user") {
8671
+ super(message);
8672
+ this.name = "RunPauseRequested";
8673
+ }
8674
+ };
8675
+ function isRunPauseSignal(signal) {
8676
+ const reason = signal?.reason;
8677
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8678
+ }
8679
+
8680
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8681
+ async function executeRecoverableTool(input) {
8682
+ const local = input.state.local;
8683
+ if (!local?.commitExecutionBoundary) return input.execute();
8684
+ if (local.executingToolCallId) {
8685
+ if (local.executingToolCallId !== input.call.id) {
8686
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8687
+ }
8688
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8689
+ if (!decision || decision.kind === "blocked") {
8690
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8691
+ }
8692
+ if (decision.kind === "settled") return decision.result;
8693
+ }
8694
+ local.executingToolCallId = input.call.id;
8695
+ await local.commitExecutionBoundary(input.state);
8696
+ const result = await input.execute();
8697
+ if (!result.success && isRunPauseSignal(local.signal)) {
8698
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8699
+ error.name = "AbortError";
8700
+ throw error;
8701
+ }
8702
+ return result;
8703
+ }
8704
+ async function commitToolBoundary(state, result) {
8705
+ if (!state.local?.commitExecutionBoundary) return;
8706
+ delete state.local.executingToolCallId;
8707
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8708
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8709
+ await state.local.commitExecutionBoundary(state);
8710
+ }
8711
+
8587
8712
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8588
8713
  var logger11 = new Logger("ToolNode");
8589
8714
  function isAbortSignal(value) {
@@ -8754,6 +8879,7 @@ var ToolNode = class {
8754
8879
  const events = [];
8755
8880
  while (true) {
8756
8881
  const result = await this.runNextPendingToolCall(state);
8882
+ await commitToolBoundary(state, result);
8757
8883
  if (Array.isArray(result.events) && result.events.length > 0) {
8758
8884
  events.push(...result.events);
8759
8885
  }
@@ -8770,11 +8896,9 @@ var ToolNode = class {
8770
8896
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8771
8897
  const signalRaw = state.local?.signal;
8772
8898
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8773
- settlePendingToolCallsAfterAbort({
8774
- state,
8775
- calls,
8776
- toolCatalog: this.toolRuntime
8777
- });
8899
+ if (!isRunPauseSignal(signalRaw)) {
8900
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8901
+ }
8778
8902
  const abortError = new Error("The user aborted a request.");
8779
8903
  abortError.name = "AbortError";
8780
8904
  throw abortError;
@@ -8913,16 +9037,21 @@ var ToolNode = class {
8913
9037
  tool_calls: [call]
8914
9038
  });
8915
9039
  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
- )
9040
+ const exec = await executeRecoverableTool({
9041
+ state,
9042
+ call,
9043
+ context: prepared.toolContext,
9044
+ execute: () => executeToolWithIdempotency({
9045
+ idempotencyKey: execution.idempotencyKey,
9046
+ inFlight: this.idempotencyInFlight,
9047
+ history: readHistoryEvents(prepared.local),
9048
+ toolName: execution.toolName,
9049
+ execute: () => this.toolRuntime.executeTool(
9050
+ execution.toolName,
9051
+ execution.toolArgs,
9052
+ prepared.toolContext
9053
+ )
9054
+ })
8926
9055
  });
8927
9056
  if (exec.success) {
8928
9057
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -9002,7 +9131,7 @@ var ToolNode = class {
9002
9131
  bridge: execution.bridge
9003
9132
  });
9004
9133
  } catch (error) {
9005
- if (isToolExecutionAbort(error)) {
9134
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
9006
9135
  settleToolCallsAfterExecutionAbort({
9007
9136
  state,
9008
9137
  remainingCalls: calls.slice(1),
@@ -9062,7 +9191,7 @@ var ToolNode = class {
9062
9191
  {
9063
9192
  attachments: context.attachments,
9064
9193
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
9065
- ephemeral: context.exec.idempotency?.cacheHit === true,
9194
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
9066
9195
  durationMs: context.exec.durationMs
9067
9196
  }
9068
9197
  );
@@ -9119,6 +9248,9 @@ var ToolNode = class {
9119
9248
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
9120
9249
  }
9121
9250
  async handleError(context) {
9251
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9252
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9253
+ }
9122
9254
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
9123
9255
  await this.emitToolDecisionAudit({
9124
9256
  action: "tool.deny",
@@ -10227,12 +10359,33 @@ var RuntimeEventPublisher = class {
10227
10359
  var EventBusEventPersistence = class {
10228
10360
  constructor(options) {
10229
10361
  this.options = options;
10362
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10230
10363
  }
10231
10364
  options;
10232
10365
  scheduledEventIds = /* @__PURE__ */ new Set();
10233
10366
  writeTail = Promise.resolve();
10234
10367
  firstWriteError;
10235
10368
  connected = false;
10369
+ checkpointWritesActive;
10370
+ checkpointEvents = [];
10371
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10372
+ async commitCheckpoint(checkpointKey, checkpoint) {
10373
+ const writer = this.options.checkpointWriter;
10374
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10375
+ const events = this.checkpointEvents;
10376
+ this.checkpointEvents = [];
10377
+ await this.enqueueWrite(() => writer({
10378
+ checkpointKey,
10379
+ checkpoint,
10380
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10381
+ }));
10382
+ }
10383
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10384
+ finishCheckpointWrites() {
10385
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10386
+ this.checkpointEvents = [];
10387
+ this.checkpointWritesActive = false;
10388
+ }
10236
10389
  connect() {
10237
10390
  if (this.connected) {
10238
10391
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10279,14 +10432,22 @@ var EventBusEventPersistence = class {
10279
10432
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10280
10433
  return;
10281
10434
  }
10435
+ if (this.checkpointWritesActive) {
10436
+ this.scheduledEventIds.add(event.id);
10437
+ this.checkpointEvents.push(event);
10438
+ return;
10439
+ }
10282
10440
  void this.scheduleWrite(event).catch(() => void 0);
10283
10441
  };
10284
10442
  scheduleWrite(event) {
10285
10443
  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
- });
10444
+ return this.enqueueWrite(() => this.options.eventStore.append({
10445
+ eventStoreId: this.options.nextEventStoreId(),
10446
+ event
10447
+ }));
10448
+ }
10449
+ enqueueWrite(operation) {
10450
+ const write = this.writeTail.then(operation);
10290
10451
  this.writeTail = write;
10291
10452
  void write.catch((error) => {
10292
10453
  this.firstWriteError ??= error;
@@ -12007,6 +12168,9 @@ var ChildRunInvoker = class {
12007
12168
  explicitConversationId: conversationId,
12008
12169
  parentToolContext
12009
12170
  });
12171
+ if (config.persistence?.expectedRevision !== void 0) {
12172
+ return this.continueChild(config, childRunId, runtimeConversationId);
12173
+ }
12010
12174
  const turnId = generateTurnId();
12011
12175
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
12012
12176
  conversationId: runtimeConversationId,
@@ -12014,21 +12178,8 @@ var ChildRunInvoker = class {
12014
12178
  maxSteps,
12015
12179
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
12016
12180
  });
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);
12181
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
12182
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
12032
12183
  const childUserInput = createChildRunUserInput({
12033
12184
  id: generateRuntimeEventId(),
12034
12185
  conversationId: runtimeConversationId,
@@ -12108,6 +12259,7 @@ var ChildRunInvoker = class {
12108
12259
  ...abortSignal ? { signal: abortSignal } : {},
12109
12260
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
12110
12261
  runtimeEventSink,
12262
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
12111
12263
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
12112
12264
  systemPrompt
12113
12265
  };
@@ -12148,6 +12300,7 @@ var ChildRunInvoker = class {
12148
12300
  eventToMessageConverter: this.eventToMessageConverter
12149
12301
  });
12150
12302
  } catch (err) {
12303
+ if (config.persistence) throw err;
12151
12304
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
12152
12305
  checkpointer,
12153
12306
  checkpointKey: internalCheckpointKey,
@@ -12186,7 +12339,7 @@ var ChildRunInvoker = class {
12186
12339
  events: allEvents,
12187
12340
  eventToMessageConverter: this.eventToMessageConverter
12188
12341
  });
12189
- await checkpointer.clear(internalCheckpointKey);
12342
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12190
12343
  return {
12191
12344
  success: !error && !cancelled,
12192
12345
  runId: childRunId,
@@ -12203,6 +12356,66 @@ var ChildRunInvoker = class {
12203
12356
  error
12204
12357
  };
12205
12358
  }
12359
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12360
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12361
+ graph.registerNode(this.createLlmNode());
12362
+ graph.registerNode(new ToolNode({
12363
+ toolRuntime: this.toolRuntime,
12364
+ observationPreview: this.observationPreview,
12365
+ telemetryPort: this.telemetryPort,
12366
+ auditPort: this.auditPort,
12367
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12368
+ modelInputResolver: this.modelInputResolver
12369
+ }));
12370
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12371
+ return graph;
12372
+ }
12373
+ async continueChild(config, runId, conversationId) {
12374
+ const persistence = config.persistence;
12375
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12376
+ const checkpoint = await persistence.checkpointer.load(runId);
12377
+ if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12378
+ const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
12379
+ const request = local.request;
12380
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12381
+ const context = createChildRunToolContext({
12382
+ parentToolContext: config.parentToolContext,
12383
+ conversationId,
12384
+ turnId: local.turnId,
12385
+ runId,
12386
+ parentRunId: config.parentRunId,
12387
+ userQuery: request.query,
12388
+ modelId: request.model_id,
12389
+ seedHistory: local.history,
12390
+ abortSignal: config.abortSignal
12391
+ });
12392
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12393
+ const result = await graph.continueSession(runId, {
12394
+ expectedRevision: persistence.expectedRevision,
12395
+ capabilities: {
12396
+ toolContext: context,
12397
+ signal: config.abortSignal,
12398
+ runtimeEventSink: config.runtimeEventSink,
12399
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12400
+ toolRecoveryPort: persistence.toolRecoveryPort
12401
+ }
12402
+ });
12403
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12404
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12405
+ const finalAnswer = extractFinalAnswer(events);
12406
+ return {
12407
+ runId,
12408
+ parentRunId: config.parentRunId,
12409
+ subrunId: runId,
12410
+ success: true,
12411
+ events,
12412
+ finalAnswer,
12413
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12414
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12415
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12416
+ toolset: { availableTools: request.availableTools }
12417
+ };
12418
+ }
12206
12419
  };
12207
12420
  function isAbortError2(error) {
12208
12421
  return error instanceof Error && error.name === "AbortError";
@@ -12604,8 +12817,6 @@ __export(run_supervisor_exports, {
12604
12817
  RunNotFoundError: () => RunNotFoundError,
12605
12818
  runMetaFromRecord: () => runMetaFromRecord
12606
12819
  });
12607
-
12608
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12609
12820
  function cloneRunRecord(record) {
12610
12821
  return {
12611
12822
  ...record,
@@ -12625,6 +12836,11 @@ function matchesStatus(candidate, filter) {
12625
12836
  }
12626
12837
  var MemoryRunRegistryStore = class {
12627
12838
  store = /* @__PURE__ */ new Map();
12839
+ async compareAndSwap(previous, next) {
12840
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12841
+ this.store.set(next.runId, cloneRunRecord(next));
12842
+ return true;
12843
+ }
12628
12844
  async save(record) {
12629
12845
  this.store.set(record.runId, cloneRunRecord(record));
12630
12846
  }
@@ -12772,6 +12988,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12772
12988
  }
12773
12989
  };
12774
12990
 
12991
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
12992
+ async function persistRunTransition(store, previous, next) {
12993
+ if (store.compareAndSwap) {
12994
+ if (!await store.compareAndSwap(previous, next)) {
12995
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
12996
+ }
12997
+ } else {
12998
+ await store.save(next);
12999
+ }
13000
+ }
13001
+
12775
13002
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12776
13003
  function isRunTerminalStatus(status) {
12777
13004
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12827,6 +13054,7 @@ var DefaultRunHandle = class {
12827
13054
  parentRunId;
12828
13055
  runRecord;
12829
13056
  abortController;
13057
+ executionId;
12830
13058
  agentSpecSnapshot;
12831
13059
  requestSnapshot;
12832
13060
  transportEventBus;
@@ -12842,6 +13070,9 @@ var DefaultRunHandle = class {
12842
13070
  this.runId = options.runRecord.runId;
12843
13071
  this.parentRunId = options.runRecord.parentRunId;
12844
13072
  this.abortController = options.abortController;
13073
+ const executionId = options.runRecord.metadata?.executionId;
13074
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
13075
+ this.executionId = executionId;
12845
13076
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12846
13077
  this.requestSnapshot = cloneRequest(options.request);
12847
13078
  this.transportEventBus = options.eventBus;
@@ -12861,8 +13092,9 @@ var DefaultRunHandle = class {
12861
13092
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12862
13093
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12863
13094
  */
12864
- replaceExecutionAbortController(controller) {
13095
+ replaceExecutionAbortController(controller, executionId) {
12865
13096
  this.abortController = controller;
13097
+ this.executionId = executionId;
12866
13098
  }
12867
13099
  async spec() {
12868
13100
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12882,6 +13114,7 @@ var DefaultRunHandle = class {
12882
13114
  this.abortController.abort(opts.reason);
12883
13115
  const latestRecord = await this.registryStore.load(this.runId);
12884
13116
  const baseRecord = latestRecord ?? this.runRecord;
13117
+ this.assertExecutionOwner(baseRecord);
12885
13118
  const transition = decideRunLifecycleTransition(baseRecord.status);
12886
13119
  if (transition.kind === "skip_terminal") {
12887
13120
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12891,7 +13124,7 @@ var DefaultRunHandle = class {
12891
13124
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12892
13125
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12893
13126
  };
12894
- await this.registryStore.save(settledRecord);
13127
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12895
13128
  this.runRecord = { ...settledRecord };
12896
13129
  return;
12897
13130
  }
@@ -12918,7 +13151,7 @@ var DefaultRunHandle = class {
12918
13151
  }
12919
13152
  }
12920
13153
  };
12921
- await this.registryStore.save(nextRecord);
13154
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12922
13155
  this.runRecord = { ...nextRecord };
12923
13156
  await this.auditPort.emit({
12924
13157
  envelopeId: generateAuditEnvelopeId(),
@@ -13026,21 +13259,35 @@ var DefaultRunHandle = class {
13026
13259
  async markFailed(error, patch = {}) {
13027
13260
  await this.saveLifecycleStatus("failed", patch, error);
13028
13261
  }
13029
- async pause(_reason) {
13030
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13262
+ async pause(reason = "Run paused by user") {
13263
+ const latest = await this.registryStore.load(this.runId);
13264
+ if (latest) this.assertExecutionOwner(latest);
13265
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13266
+ const next = {
13267
+ ...latest,
13268
+ status: "paused",
13269
+ updatedAt: Date.now(),
13270
+ pauseReason: reason,
13271
+ pausedAt: void 0
13272
+ };
13273
+ await persistRunTransition(this.registryStore, latest, next);
13274
+ this.runRecord = next;
13275
+ this.abortController.abort(new RunPauseRequested(reason));
13031
13276
  }
13032
- async resume() {
13033
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13277
+ async markPaused(patch = {}) {
13278
+ await this.saveLifecycleStatus("paused", patch);
13034
13279
  }
13035
13280
  async saveLifecycleStatus(status, patch, errorIfAny) {
13036
13281
  const latestRecord = await this.registryStore.load(this.runId);
13037
13282
  const baseRecord = latestRecord ?? this.runRecord;
13038
13283
  const transition = decideRunLifecycleTransition(baseRecord.status);
13284
+ this.assertExecutionOwner(baseRecord);
13285
+ if (status === "running" && baseRecord.status === "paused") return;
13039
13286
  if (transition.kind === "skip_terminal") {
13040
13287
  this.runRecord = { ...baseRecord };
13041
13288
  return;
13042
13289
  }
13043
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13290
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
13044
13291
  const updatedAt = Date.now();
13045
13292
  const nextRecord = {
13046
13293
  ...baseRecord,
@@ -13048,8 +13295,8 @@ var DefaultRunHandle = class {
13048
13295
  updatedAt,
13049
13296
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13050
13297
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
13051
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13052
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13298
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13299
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
13053
13300
  errorIfAny,
13054
13301
  metadata: awaitingUserPatch?.eventId ? {
13055
13302
  ...baseRecord.metadata ?? {},
@@ -13060,7 +13307,7 @@ var DefaultRunHandle = class {
13060
13307
  }
13061
13308
  } : baseRecord.metadata
13062
13309
  };
13063
- await this.registryStore.save(nextRecord);
13310
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13064
13311
  this.runRecord = { ...nextRecord };
13065
13312
  if (status === "completed" || status === "failed") {
13066
13313
  this.closeObservationChannel();
@@ -13070,6 +13317,11 @@ var DefaultRunHandle = class {
13070
13317
  forwardTransportEvent = (envelope) => {
13071
13318
  this.observationEventBus.emit("event", envelope);
13072
13319
  };
13320
+ assertExecutionOwner(record) {
13321
+ if (record.metadata?.executionId !== this.executionId) {
13322
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13323
+ }
13324
+ }
13073
13325
  forwardTransportError = (error) => {
13074
13326
  this.observationEventBus.emit("error", error);
13075
13327
  };
@@ -13451,6 +13703,24 @@ async function recoverRunsOnBoot(options) {
13451
13703
  const outcomes = [];
13452
13704
  for (const record of activeRecords) {
13453
13705
  const updatedAt = options.now();
13706
+ if (await options.canRestoreRun?.(record)) {
13707
+ const metadata = { ...record.metadata };
13708
+ const awaitingUser = metadata.awaitingUser;
13709
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13710
+ const restored = { ...awaitingUser };
13711
+ Reflect.deleteProperty(restored, "resumeClaim");
13712
+ metadata.awaitingUser = restored;
13713
+ }
13714
+ await persistRunTransition(options.registryStore, record, {
13715
+ ...record,
13716
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13717
+ pausedAt: record.pausedAt ?? updatedAt,
13718
+ pauseReason: record.pauseReason ?? options.reason,
13719
+ updatedAt,
13720
+ metadata
13721
+ });
13722
+ continue;
13723
+ }
13454
13724
  const nextRecord = {
13455
13725
  ...record,
13456
13726
  status: "failed",
@@ -13468,7 +13738,7 @@ async function recoverRunsOnBoot(options) {
13468
13738
  }
13469
13739
  }
13470
13740
  };
13471
- await options.registryStore.save(nextRecord);
13741
+ await persistRunTransition(options.registryStore, record, nextRecord);
13472
13742
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13473
13743
  options.notifyTerminal(outcome);
13474
13744
  outcomes.push(outcome);
@@ -13592,8 +13862,13 @@ var DefaultRunSupervisor = class {
13592
13862
  inFlight = /* @__PURE__ */ new Map();
13593
13863
  eventWatchDisposers = /* @__PURE__ */ new Map();
13594
13864
  controlOperations = /* @__PURE__ */ new Map();
13865
+ canRestoreRun;
13595
13866
  constructor(options) {
13867
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13868
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13869
+ }
13596
13870
  this.registryStore = options.registryStore;
13871
+ this.canRestoreRun = options.canRestoreRun;
13597
13872
  this.auditPort = options.auditPort;
13598
13873
  this.executor = options.executor;
13599
13874
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13641,6 +13916,23 @@ var DefaultRunSupervisor = class {
13641
13916
  this.releaseRunAdmission(runId);
13642
13917
  throw error;
13643
13918
  }
13919
+ return this.attachRun(record, spec, controller);
13920
+ }
13921
+ async restoreRun(spec) {
13922
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13923
+ return this.withRunControlLock(spec.runId, async () => {
13924
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
13925
+ const record = await this.registryStore.load(spec.runId);
13926
+ if (!record) throw new RunNotFoundError(spec.runId);
13927
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
13928
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
13929
+ }
13930
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
13931
+ return this.attachRun(record, spec, new AbortController());
13932
+ });
13933
+ }
13934
+ attachRun(record, spec, controller) {
13935
+ const runId = record.runId;
13644
13936
  try {
13645
13937
  const handle = new DefaultRunHandle({
13646
13938
  runRecord: record,
@@ -13738,11 +14030,36 @@ var DefaultRunSupervisor = class {
13738
14030
  registryStore: this.registryStore,
13739
14031
  reason,
13740
14032
  now: this.now,
13741
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
14033
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
14034
+ canRestoreRun: this.canRestoreRun
13742
14035
  });
13743
14036
  }
13744
- async pause(_runId, _reason) {
13745
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
14037
+ async pause(runId, reason) {
14038
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
14039
+ }
14040
+ async resumePausedRun(input) {
14041
+ return this.withRunControlLock(input.runId, async () => {
14042
+ const handle = this.getHandle(input.runId);
14043
+ const record = await this.registryStore.load(input.runId);
14044
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
14045
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
14046
+ }
14047
+ await persistRunTransition(this.registryStore, record, {
14048
+ ...record,
14049
+ status: "running",
14050
+ updatedAt: this.now(),
14051
+ pausedAt: void 0,
14052
+ pauseReason: void 0,
14053
+ errorIfAny: void 0,
14054
+ metadata: { ...record.metadata, executionId: input.executionId }
14055
+ });
14056
+ const controller = new AbortController();
14057
+ handle.replaceExecutionAbortController(controller, input.executionId);
14058
+ handle.attachTransportEventBus(input.eventBus);
14059
+ this.controllers.set(input.runId, controller);
14060
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
14061
+ return handle;
14062
+ });
13746
14063
  }
13747
14064
  async claimResume(runId, interaction, eventBus, parentSignal) {
13748
14065
  return this.withRunControlLock(runId, async () => {
@@ -13777,7 +14094,7 @@ var DefaultRunSupervisor = class {
13777
14094
  throw new RunNotFoundError(runId);
13778
14095
  }
13779
14096
  const claimId = generateRunResumeClaimId();
13780
- await this.registryStore.save({
14097
+ await persistRunTransition(this.registryStore, record, {
13781
14098
  ...record,
13782
14099
  updatedAt: this.now(),
13783
14100
  metadata: {
@@ -13865,7 +14182,7 @@ var DefaultRunSupervisor = class {
13865
14182
  }
13866
14183
  const awaitingUserWithoutClaim = { ...awaitingUser };
13867
14184
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13868
- await this.registryStore.save({
14185
+ await persistRunTransition(this.registryStore, record, {
13869
14186
  ...record,
13870
14187
  status: "running",
13871
14188
  updatedAt: this.now(),
@@ -13886,7 +14203,7 @@ var DefaultRunSupervisor = class {
13886
14203
  });
13887
14204
  const executionController = new AbortController();
13888
14205
  forwardParentAbortSignal(executionController, parentSignal);
13889
- handle.replaceExecutionAbortController(executionController);
14206
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13890
14207
  this.controllers.set(runId, executionController);
13891
14208
  return handle;
13892
14209
  });
@@ -13904,7 +14221,7 @@ var DefaultRunSupervisor = class {
13904
14221
  }
13905
14222
  const awaitingUserWithoutClaim = { ...awaitingUser };
13906
14223
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13907
- await this.registryStore.save({
14224
+ await persistRunTransition(this.registryStore, record, {
13908
14225
  ...record,
13909
14226
  updatedAt: this.now(),
13910
14227
  metadata: {