@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
@@ -5,6 +5,7 @@ require('eventsource-parser');
5
5
  var tiktoken = require('tiktoken');
6
6
  var async_hooks = require('async_hooks');
7
7
  var crypto = require('crypto');
8
+ var util = require('util');
8
9
  var promises = require('fs/promises');
9
10
  var path = require('path');
10
11
 
@@ -25,12 +26,15 @@ __export(graph_engine_exports, {
25
26
  MemoryEventStore: () => MemoryEventStore,
26
27
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
27
28
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
29
+ RunPauseRequested: () => RunPauseRequested,
30
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
28
31
  ToolNode: () => ToolNode,
29
32
  UserNode: () => UserNode,
30
33
  WaitUserNode: () => WaitUserNode,
31
34
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
32
35
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
33
36
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
37
+ isRunPauseSignal: () => isRunPauseSignal,
34
38
  isRuntimeFailureFact: () => isRuntimeFailureFact,
35
39
  readCheckpointContextUsage: () => readCheckpointContextUsage,
36
40
  requireEventStoreId: () => requireEventStoreId,
@@ -2399,6 +2403,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2399
2403
  "memory",
2400
2404
  "runtimeEventSink",
2401
2405
  "runtimeEventCommitPort",
2406
+ "commitExecutionBoundary",
2407
+ "toolRecoveryPort",
2402
2408
  "runtimeFailureFactSink",
2403
2409
  "signal",
2404
2410
  "summarizationCallbacks",
@@ -2949,6 +2955,7 @@ var GraphExecutor = class {
2949
2955
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
2950
2956
  };
2951
2957
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
2958
+ this.executionCheckpointPort = config.executionCheckpointPort;
2952
2959
  }
2953
2960
  checkpointer;
2954
2961
  nodes = /* @__PURE__ */ new Map();
@@ -2956,6 +2963,7 @@ var GraphExecutor = class {
2956
2963
  checkpointQueues = /* @__PURE__ */ new Map();
2957
2964
  config;
2958
2965
  telemetryPort;
2966
+ executionCheckpointPort;
2959
2967
  registerNode(node) {
2960
2968
  this.nodes.set(node.id, node);
2961
2969
  }
@@ -2964,6 +2972,7 @@ var GraphExecutor = class {
2964
2972
  }
2965
2973
  sanitize(state) {
2966
2974
  return {
2975
+ ...state,
2967
2976
  nodeId: state.nodeId,
2968
2977
  revision: state.revision ?? 0,
2969
2978
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -2983,8 +2992,9 @@ var GraphExecutor = class {
2983
2992
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
2984
2993
  }
2985
2994
  this.ephemeralLocals.set(checkpointKey, { ...local });
2986
- await this.checkpointer.save(checkpointKey, {
2995
+ await this.commitCheckpoint(checkpointKey, {
2987
2996
  nodeId,
2997
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
2988
2998
  revision: 1,
2989
2999
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
2990
3000
  local: sanitizeCheckpointLocal(local)
@@ -2995,6 +3005,33 @@ var GraphExecutor = class {
2995
3005
  );
2996
3006
  });
2997
3007
  }
3008
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3009
+ async continueSession(checkpointKey, input) {
3010
+ if (!this.executionCheckpointPort) {
3011
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3012
+ }
3013
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3014
+ const current = await this.checkpointer.load(checkpointKey);
3015
+ if (!current || current.revision !== input.expectedRevision) {
3016
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3017
+ }
3018
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3019
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3020
+ }
3021
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3022
+ return { checkpoint: current, events: [], stepCount: 0 };
3023
+ }
3024
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3025
+ try {
3026
+ return await this.runUntilYieldQueued(
3027
+ checkpointKey,
3028
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3029
+ );
3030
+ } finally {
3031
+ this.ephemeralLocals.delete(checkpointKey);
3032
+ }
3033
+ });
3034
+ }
2998
3035
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
2999
3036
  async resumeSession(checkpointKey, input) {
3000
3037
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3015,17 +3052,21 @@ var GraphExecutor = class {
3015
3052
  );
3016
3053
  }
3017
3054
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3055
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3056
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3057
+ }
3018
3058
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3019
- await this.checkpointer.save(checkpointKey, {
3059
+ await this.commitCheckpoint(checkpointKey, {
3020
3060
  ...current,
3021
3061
  nodeId: input.nodeId ?? "llm",
3062
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3022
3063
  revision: currentRevision + 1,
3023
3064
  local: sanitizeCheckpointLocal(resumedLocal)
3024
3065
  });
3025
3066
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3026
3067
  return this.runUntilYieldQueued(
3027
3068
  checkpointKey,
3028
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3069
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3029
3070
  );
3030
3071
  });
3031
3072
  }
@@ -3120,9 +3161,16 @@ var GraphExecutor = class {
3120
3161
  ...state,
3121
3162
  revision: (state.revision ?? 0) + 1
3122
3163
  });
3123
- await this.checkpointer.save(checkpointKey, checkpoint);
3164
+ await this.commitCheckpoint(checkpointKey, checkpoint);
3124
3165
  return checkpoint;
3125
3166
  }
3167
+ async commitCheckpoint(checkpointKey, checkpoint) {
3168
+ if (this.executionCheckpointPort) {
3169
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3170
+ } else {
3171
+ await this.checkpointer.save(checkpointKey, checkpoint);
3172
+ }
3173
+ }
3126
3174
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3127
3175
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3128
3176
  return { events, checkpoint, stepCount };
@@ -3135,6 +3183,15 @@ var GraphExecutor = class {
3135
3183
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3136
3184
  local: { ...state.local || {}, ...ephemeral }
3137
3185
  };
3186
+ if (this.executionCheckpointPort) {
3187
+ state.local = {
3188
+ ...state.local,
3189
+ commitExecutionBoundary: async (boundary) => {
3190
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3191
+ boundary.revision = saved.revision;
3192
+ }
3193
+ };
3194
+ }
3138
3195
  const isAbortSignal2 = (v) => {
3139
3196
  return v !== null && typeof v === "object" && "aborted" in v;
3140
3197
  };
@@ -3144,11 +3201,12 @@ var GraphExecutor = class {
3144
3201
  throw err;
3145
3202
  };
3146
3203
  let stepCount = 0;
3204
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3147
3205
  let allEvents = [];
3148
3206
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3149
3207
  maxSteps
3150
3208
  });
3151
- while (stepCount < maxSteps) {
3209
+ while (previousSteps + stepCount < maxSteps) {
3152
3210
  stepCount += 1;
3153
3211
  reportStepsUsed(stepCount);
3154
3212
  const signalRaw = state.local?.signal;
@@ -3160,7 +3218,7 @@ var GraphExecutor = class {
3160
3218
  const stepPreparation = prepareGraphStep({
3161
3219
  state,
3162
3220
  maxSteps,
3163
- stepCount
3221
+ stepCount: previousSteps + stepCount
3164
3222
  });
3165
3223
  state = stepPreparation.state;
3166
3224
  const node = this.nodes.get(state.nodeId);
@@ -3169,6 +3227,7 @@ var GraphExecutor = class {
3169
3227
  maxSteps,
3170
3228
  stepCount
3171
3229
  });
3230
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3172
3231
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3173
3232
  this.ephemeralLocals.delete(checkpointKey);
3174
3233
  return result3;
@@ -3178,6 +3237,11 @@ var GraphExecutor = class {
3178
3237
  stepCount,
3179
3238
  nodeId: state.nodeId
3180
3239
  });
3240
+ if (this.executionCheckpointPort) {
3241
+ state.executionStatus = "executing";
3242
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3243
+ state.revision = saved.revision;
3244
+ }
3181
3245
  const result2 = await runGraphNodeWithTelemetry({
3182
3246
  node,
3183
3247
  state,
@@ -3202,10 +3266,13 @@ var GraphExecutor = class {
3202
3266
  fromNodeId: stepResolution.action.fromNodeId,
3203
3267
  nextNodeId: stepResolution.action.nextNodeId
3204
3268
  });
3205
- await this.saveCheckpoint(checkpointKey, state);
3269
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3270
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3271
+ state.revision = saved.revision;
3206
3272
  continue;
3207
3273
  }
3208
3274
  if (stepResolution.action.kind === "yield") {
3275
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3209
3276
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3210
3277
  maxSteps,
3211
3278
  stepCount
@@ -3216,6 +3283,7 @@ var GraphExecutor = class {
3216
3283
  maxSteps,
3217
3284
  stepCount
3218
3285
  });
3286
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3219
3287
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3220
3288
  }
3221
3289
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3236,6 +3304,7 @@ var GraphExecutor = class {
3236
3304
  },
3237
3305
  retryable: false
3238
3306
  }), "GraphExecutor.engine_budget_exhausted"));
3307
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3239
3308
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3240
3309
  this.ephemeralLocals.delete(checkpointKey);
3241
3310
  return result;
@@ -7129,10 +7198,11 @@ var LlmNode = class {
7129
7198
  bridge.handle
7130
7199
  );
7131
7200
  } catch (error) {
7132
- bridge.finalizePartialAnswer();
7201
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7133
7202
  throw error;
7134
7203
  }
7135
7204
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7205
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7136
7206
  switch (decision.kind) {
7137
7207
  case "tool_calls": {
7138
7208
  if (forceFinalAnswer) {
@@ -8400,6 +8470,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8400
8470
  function recordToolProtocolError(params) {
8401
8471
  }
8402
8472
 
8473
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8474
+ var RunRecoveryBlockedError = class extends Error {
8475
+ code = "RUN_RECOVERY_BLOCKED";
8476
+ constructor(message) {
8477
+ super(message);
8478
+ this.name = "RunRecoveryBlockedError";
8479
+ }
8480
+ };
8481
+ var RunPauseRequested = class extends Error {
8482
+ code = "RUN_PAUSE_REQUESTED";
8483
+ constructor(message = "Run paused by user") {
8484
+ super(message);
8485
+ this.name = "RunPauseRequested";
8486
+ }
8487
+ };
8488
+ function isRunPauseSignal(signal) {
8489
+ const reason = signal?.reason;
8490
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8491
+ }
8492
+
8493
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8494
+ async function executeRecoverableTool(input) {
8495
+ const local = input.state.local;
8496
+ if (!local?.commitExecutionBoundary) return input.execute();
8497
+ if (local.executingToolCallId) {
8498
+ if (local.executingToolCallId !== input.call.id) {
8499
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8500
+ }
8501
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8502
+ if (!decision || decision.kind === "blocked") {
8503
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8504
+ }
8505
+ if (decision.kind === "settled") return decision.result;
8506
+ }
8507
+ local.executingToolCallId = input.call.id;
8508
+ await local.commitExecutionBoundary(input.state);
8509
+ const result = await input.execute();
8510
+ if (!result.success && isRunPauseSignal(local.signal)) {
8511
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8512
+ error.name = "AbortError";
8513
+ throw error;
8514
+ }
8515
+ return result;
8516
+ }
8517
+ async function commitToolBoundary(state, result) {
8518
+ if (!state.local?.commitExecutionBoundary) return;
8519
+ delete state.local.executingToolCallId;
8520
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8521
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8522
+ await state.local.commitExecutionBoundary(state);
8523
+ }
8524
+
8403
8525
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8404
8526
  var logger11 = new Logger("ToolNode");
8405
8527
  function isAbortSignal(value) {
@@ -8570,6 +8692,7 @@ var ToolNode = class {
8570
8692
  const events = [];
8571
8693
  while (true) {
8572
8694
  const result = await this.runNextPendingToolCall(state);
8695
+ await commitToolBoundary(state, result);
8573
8696
  if (Array.isArray(result.events) && result.events.length > 0) {
8574
8697
  events.push(...result.events);
8575
8698
  }
@@ -8586,11 +8709,9 @@ var ToolNode = class {
8586
8709
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8587
8710
  const signalRaw = state.local?.signal;
8588
8711
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8589
- settlePendingToolCallsAfterAbort({
8590
- state,
8591
- calls,
8592
- toolCatalog: this.toolRuntime
8593
- });
8712
+ if (!isRunPauseSignal(signalRaw)) {
8713
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8714
+ }
8594
8715
  const abortError = new Error("The user aborted a request.");
8595
8716
  abortError.name = "AbortError";
8596
8717
  throw abortError;
@@ -8729,16 +8850,21 @@ var ToolNode = class {
8729
8850
  tool_calls: [call]
8730
8851
  });
8731
8852
  try {
8732
- const exec = await executeToolWithIdempotency({
8733
- idempotencyKey: execution.idempotencyKey,
8734
- inFlight: this.idempotencyInFlight,
8735
- history: readHistoryEvents(prepared.local),
8736
- toolName: execution.toolName,
8737
- execute: () => this.toolRuntime.executeTool(
8738
- execution.toolName,
8739
- execution.toolArgs,
8740
- prepared.toolContext
8741
- )
8853
+ const exec = await executeRecoverableTool({
8854
+ state,
8855
+ call,
8856
+ context: prepared.toolContext,
8857
+ execute: () => executeToolWithIdempotency({
8858
+ idempotencyKey: execution.idempotencyKey,
8859
+ inFlight: this.idempotencyInFlight,
8860
+ history: readHistoryEvents(prepared.local),
8861
+ toolName: execution.toolName,
8862
+ execute: () => this.toolRuntime.executeTool(
8863
+ execution.toolName,
8864
+ execution.toolArgs,
8865
+ prepared.toolContext
8866
+ )
8867
+ })
8742
8868
  });
8743
8869
  if (exec.success) {
8744
8870
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8818,7 +8944,7 @@ var ToolNode = class {
8818
8944
  bridge: execution.bridge
8819
8945
  });
8820
8946
  } catch (error) {
8821
- if (isToolExecutionAbort(error)) {
8947
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8822
8948
  settleToolCallsAfterExecutionAbort({
8823
8949
  state,
8824
8950
  remainingCalls: calls.slice(1),
@@ -8878,7 +9004,7 @@ var ToolNode = class {
8878
9004
  {
8879
9005
  attachments: context.attachments,
8880
9006
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8881
- ephemeral: context.exec.idempotency?.cacheHit === true,
9007
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8882
9008
  durationMs: context.exec.durationMs
8883
9009
  }
8884
9010
  );
@@ -8935,6 +9061,9 @@ var ToolNode = class {
8935
9061
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8936
9062
  }
8937
9063
  async handleError(context) {
9064
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9065
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9066
+ }
8938
9067
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8939
9068
  await this.emitToolDecisionAudit({
8940
9069
  action: "tool.deny",
@@ -10043,12 +10172,33 @@ var RuntimeEventPublisher = class {
10043
10172
  var EventBusEventPersistence = class {
10044
10173
  constructor(options) {
10045
10174
  this.options = options;
10175
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10046
10176
  }
10047
10177
  options;
10048
10178
  scheduledEventIds = /* @__PURE__ */ new Set();
10049
10179
  writeTail = Promise.resolve();
10050
10180
  firstWriteError;
10051
10181
  connected = false;
10182
+ checkpointWritesActive;
10183
+ checkpointEvents = [];
10184
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10185
+ async commitCheckpoint(checkpointKey, checkpoint) {
10186
+ const writer = this.options.checkpointWriter;
10187
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10188
+ const events = this.checkpointEvents;
10189
+ this.checkpointEvents = [];
10190
+ await this.enqueueWrite(() => writer({
10191
+ checkpointKey,
10192
+ checkpoint,
10193
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10194
+ }));
10195
+ }
10196
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10197
+ finishCheckpointWrites() {
10198
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10199
+ this.checkpointEvents = [];
10200
+ this.checkpointWritesActive = false;
10201
+ }
10052
10202
  connect() {
10053
10203
  if (this.connected) {
10054
10204
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10095,14 +10245,22 @@ var EventBusEventPersistence = class {
10095
10245
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10096
10246
  return;
10097
10247
  }
10248
+ if (this.checkpointWritesActive) {
10249
+ this.scheduledEventIds.add(event.id);
10250
+ this.checkpointEvents.push(event);
10251
+ return;
10252
+ }
10098
10253
  void this.scheduleWrite(event).catch(() => void 0);
10099
10254
  };
10100
10255
  scheduleWrite(event) {
10101
10256
  this.scheduledEventIds.add(event.id);
10102
- const eventStoreId = this.options.nextEventStoreId();
10103
- const write = this.writeTail.then(async () => {
10104
- await this.options.eventStore.append({ eventStoreId, event });
10105
- });
10257
+ return this.enqueueWrite(() => this.options.eventStore.append({
10258
+ eventStoreId: this.options.nextEventStoreId(),
10259
+ event
10260
+ }));
10261
+ }
10262
+ enqueueWrite(operation) {
10263
+ const write = this.writeTail.then(operation);
10106
10264
  this.writeTail = write;
10107
10265
  void write.catch((error) => {
10108
10266
  this.firstWriteError ??= error;
@@ -11823,6 +11981,9 @@ var ChildRunInvoker = class {
11823
11981
  explicitConversationId: conversationId,
11824
11982
  parentToolContext
11825
11983
  });
11984
+ if (config.persistence?.expectedRevision !== void 0) {
11985
+ return this.continueChild(config, childRunId, runtimeConversationId);
11986
+ }
11826
11987
  const turnId = generateTurnId();
11827
11988
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
11828
11989
  conversationId: runtimeConversationId,
@@ -11830,21 +11991,8 @@ var ChildRunInvoker = class {
11830
11991
  maxSteps,
11831
11992
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
11832
11993
  });
11833
- const checkpointer = new MemoryCheckpointer();
11834
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
11835
- const llmNode = this.createLlmNode();
11836
- const toolNode = new ToolNode({
11837
- toolRuntime: this.toolRuntime,
11838
- observationPreview: this.observationPreview,
11839
- telemetryPort: this.telemetryPort,
11840
- auditPort: this.auditPort,
11841
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
11842
- modelInputResolver: this.modelInputResolver
11843
- });
11844
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
11845
- graphExecutor.registerNode(llmNode);
11846
- graphExecutor.registerNode(toolNode);
11847
- graphExecutor.registerNode(waitUserNode);
11994
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
11995
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
11848
11996
  const childUserInput = createChildRunUserInput({
11849
11997
  id: generateRuntimeEventId(),
11850
11998
  conversationId: runtimeConversationId,
@@ -11924,6 +12072,7 @@ var ChildRunInvoker = class {
11924
12072
  ...abortSignal ? { signal: abortSignal } : {},
11925
12073
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
11926
12074
  runtimeEventSink,
12075
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
11927
12076
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
11928
12077
  systemPrompt
11929
12078
  };
@@ -11964,6 +12113,7 @@ var ChildRunInvoker = class {
11964
12113
  eventToMessageConverter: this.eventToMessageConverter
11965
12114
  });
11966
12115
  } catch (err) {
12116
+ if (config.persistence) throw err;
11967
12117
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
11968
12118
  checkpointer,
11969
12119
  checkpointKey: internalCheckpointKey,
@@ -12002,7 +12152,7 @@ var ChildRunInvoker = class {
12002
12152
  events: allEvents,
12003
12153
  eventToMessageConverter: this.eventToMessageConverter
12004
12154
  });
12005
- await checkpointer.clear(internalCheckpointKey);
12155
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12006
12156
  return {
12007
12157
  success: !error && !cancelled,
12008
12158
  runId: childRunId,
@@ -12019,6 +12169,66 @@ var ChildRunInvoker = class {
12019
12169
  error
12020
12170
  };
12021
12171
  }
12172
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12173
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12174
+ graph.registerNode(this.createLlmNode());
12175
+ graph.registerNode(new ToolNode({
12176
+ toolRuntime: this.toolRuntime,
12177
+ observationPreview: this.observationPreview,
12178
+ telemetryPort: this.telemetryPort,
12179
+ auditPort: this.auditPort,
12180
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12181
+ modelInputResolver: this.modelInputResolver
12182
+ }));
12183
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12184
+ return graph;
12185
+ }
12186
+ async continueChild(config, runId, conversationId) {
12187
+ const persistence = config.persistence;
12188
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12189
+ const checkpoint = await persistence.checkpointer.load(runId);
12190
+ if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12191
+ const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
12192
+ const request = local.request;
12193
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12194
+ const context = createChildRunToolContext({
12195
+ parentToolContext: config.parentToolContext,
12196
+ conversationId,
12197
+ turnId: local.turnId,
12198
+ runId,
12199
+ parentRunId: config.parentRunId,
12200
+ userQuery: request.query,
12201
+ modelId: request.model_id,
12202
+ seedHistory: local.history,
12203
+ abortSignal: config.abortSignal
12204
+ });
12205
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12206
+ const result = await graph.continueSession(runId, {
12207
+ expectedRevision: persistence.expectedRevision,
12208
+ capabilities: {
12209
+ toolContext: context,
12210
+ signal: config.abortSignal,
12211
+ runtimeEventSink: config.runtimeEventSink,
12212
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12213
+ toolRecoveryPort: persistence.toolRecoveryPort
12214
+ }
12215
+ });
12216
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12217
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12218
+ const finalAnswer = extractFinalAnswer(events);
12219
+ return {
12220
+ runId,
12221
+ parentRunId: config.parentRunId,
12222
+ subrunId: runId,
12223
+ success: true,
12224
+ events,
12225
+ finalAnswer,
12226
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12227
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12228
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12229
+ toolset: { availableTools: request.availableTools }
12230
+ };
12231
+ }
12022
12232
  };
12023
12233
  function isAbortError2(error) {
12024
12234
  return error instanceof Error && error.name === "AbortError";
@@ -12420,8 +12630,6 @@ __export(run_supervisor_exports, {
12420
12630
  RunNotFoundError: () => RunNotFoundError,
12421
12631
  runMetaFromRecord: () => runMetaFromRecord
12422
12632
  });
12423
-
12424
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12425
12633
  function cloneRunRecord(record) {
12426
12634
  return {
12427
12635
  ...record,
@@ -12441,6 +12649,11 @@ function matchesStatus(candidate, filter) {
12441
12649
  }
12442
12650
  var MemoryRunRegistryStore = class {
12443
12651
  store = /* @__PURE__ */ new Map();
12652
+ async compareAndSwap(previous, next) {
12653
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12654
+ this.store.set(next.runId, cloneRunRecord(next));
12655
+ return true;
12656
+ }
12444
12657
  async save(record) {
12445
12658
  this.store.set(record.runId, cloneRunRecord(record));
12446
12659
  }
@@ -12588,6 +12801,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12588
12801
  }
12589
12802
  };
12590
12803
 
12804
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
12805
+ async function persistRunTransition(store, previous, next) {
12806
+ if (store.compareAndSwap) {
12807
+ if (!await store.compareAndSwap(previous, next)) {
12808
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
12809
+ }
12810
+ } else {
12811
+ await store.save(next);
12812
+ }
12813
+ }
12814
+
12591
12815
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12592
12816
  function isRunTerminalStatus(status) {
12593
12817
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12643,6 +12867,7 @@ var DefaultRunHandle = class {
12643
12867
  parentRunId;
12644
12868
  runRecord;
12645
12869
  abortController;
12870
+ executionId;
12646
12871
  agentSpecSnapshot;
12647
12872
  requestSnapshot;
12648
12873
  transportEventBus;
@@ -12658,6 +12883,9 @@ var DefaultRunHandle = class {
12658
12883
  this.runId = options.runRecord.runId;
12659
12884
  this.parentRunId = options.runRecord.parentRunId;
12660
12885
  this.abortController = options.abortController;
12886
+ const executionId = options.runRecord.metadata?.executionId;
12887
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
12888
+ this.executionId = executionId;
12661
12889
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12662
12890
  this.requestSnapshot = cloneRequest(options.request);
12663
12891
  this.transportEventBus = options.eventBus;
@@ -12677,8 +12905,9 @@ var DefaultRunHandle = class {
12677
12905
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12678
12906
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12679
12907
  */
12680
- replaceExecutionAbortController(controller) {
12908
+ replaceExecutionAbortController(controller, executionId) {
12681
12909
  this.abortController = controller;
12910
+ this.executionId = executionId;
12682
12911
  }
12683
12912
  async spec() {
12684
12913
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12698,6 +12927,7 @@ var DefaultRunHandle = class {
12698
12927
  this.abortController.abort(opts.reason);
12699
12928
  const latestRecord = await this.registryStore.load(this.runId);
12700
12929
  const baseRecord = latestRecord ?? this.runRecord;
12930
+ this.assertExecutionOwner(baseRecord);
12701
12931
  const transition = decideRunLifecycleTransition(baseRecord.status);
12702
12932
  if (transition.kind === "skip_terminal") {
12703
12933
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12707,7 +12937,7 @@ var DefaultRunHandle = class {
12707
12937
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12708
12938
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12709
12939
  };
12710
- await this.registryStore.save(settledRecord);
12940
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12711
12941
  this.runRecord = { ...settledRecord };
12712
12942
  return;
12713
12943
  }
@@ -12734,7 +12964,7 @@ var DefaultRunHandle = class {
12734
12964
  }
12735
12965
  }
12736
12966
  };
12737
- await this.registryStore.save(nextRecord);
12967
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12738
12968
  this.runRecord = { ...nextRecord };
12739
12969
  await this.auditPort.emit({
12740
12970
  envelopeId: generateAuditEnvelopeId(),
@@ -12842,21 +13072,35 @@ var DefaultRunHandle = class {
12842
13072
  async markFailed(error, patch = {}) {
12843
13073
  await this.saveLifecycleStatus("failed", patch, error);
12844
13074
  }
12845
- async pause(_reason) {
12846
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13075
+ async pause(reason = "Run paused by user") {
13076
+ const latest = await this.registryStore.load(this.runId);
13077
+ if (latest) this.assertExecutionOwner(latest);
13078
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13079
+ const next = {
13080
+ ...latest,
13081
+ status: "paused",
13082
+ updatedAt: Date.now(),
13083
+ pauseReason: reason,
13084
+ pausedAt: void 0
13085
+ };
13086
+ await persistRunTransition(this.registryStore, latest, next);
13087
+ this.runRecord = next;
13088
+ this.abortController.abort(new RunPauseRequested(reason));
12847
13089
  }
12848
- async resume() {
12849
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13090
+ async markPaused(patch = {}) {
13091
+ await this.saveLifecycleStatus("paused", patch);
12850
13092
  }
12851
13093
  async saveLifecycleStatus(status, patch, errorIfAny) {
12852
13094
  const latestRecord = await this.registryStore.load(this.runId);
12853
13095
  const baseRecord = latestRecord ?? this.runRecord;
12854
13096
  const transition = decideRunLifecycleTransition(baseRecord.status);
13097
+ this.assertExecutionOwner(baseRecord);
13098
+ if (status === "running" && baseRecord.status === "paused") return;
12855
13099
  if (transition.kind === "skip_terminal") {
12856
13100
  this.runRecord = { ...baseRecord };
12857
13101
  return;
12858
13102
  }
12859
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13103
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
12860
13104
  const updatedAt = Date.now();
12861
13105
  const nextRecord = {
12862
13106
  ...baseRecord,
@@ -12864,8 +13108,8 @@ var DefaultRunHandle = class {
12864
13108
  updatedAt,
12865
13109
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12866
13110
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
12867
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
12868
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13111
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13112
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
12869
13113
  errorIfAny,
12870
13114
  metadata: awaitingUserPatch?.eventId ? {
12871
13115
  ...baseRecord.metadata ?? {},
@@ -12876,7 +13120,7 @@ var DefaultRunHandle = class {
12876
13120
  }
12877
13121
  } : baseRecord.metadata
12878
13122
  };
12879
- await this.registryStore.save(nextRecord);
13123
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12880
13124
  this.runRecord = { ...nextRecord };
12881
13125
  if (status === "completed" || status === "failed") {
12882
13126
  this.closeObservationChannel();
@@ -12886,6 +13130,11 @@ var DefaultRunHandle = class {
12886
13130
  forwardTransportEvent = (envelope) => {
12887
13131
  this.observationEventBus.emit("event", envelope);
12888
13132
  };
13133
+ assertExecutionOwner(record) {
13134
+ if (record.metadata?.executionId !== this.executionId) {
13135
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13136
+ }
13137
+ }
12889
13138
  forwardTransportError = (error) => {
12890
13139
  this.observationEventBus.emit("error", error);
12891
13140
  };
@@ -13267,6 +13516,24 @@ async function recoverRunsOnBoot(options) {
13267
13516
  const outcomes = [];
13268
13517
  for (const record of activeRecords) {
13269
13518
  const updatedAt = options.now();
13519
+ if (await options.canRestoreRun?.(record)) {
13520
+ const metadata = { ...record.metadata };
13521
+ const awaitingUser = metadata.awaitingUser;
13522
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13523
+ const restored = { ...awaitingUser };
13524
+ Reflect.deleteProperty(restored, "resumeClaim");
13525
+ metadata.awaitingUser = restored;
13526
+ }
13527
+ await persistRunTransition(options.registryStore, record, {
13528
+ ...record,
13529
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13530
+ pausedAt: record.pausedAt ?? updatedAt,
13531
+ pauseReason: record.pauseReason ?? options.reason,
13532
+ updatedAt,
13533
+ metadata
13534
+ });
13535
+ continue;
13536
+ }
13270
13537
  const nextRecord = {
13271
13538
  ...record,
13272
13539
  status: "failed",
@@ -13284,7 +13551,7 @@ async function recoverRunsOnBoot(options) {
13284
13551
  }
13285
13552
  }
13286
13553
  };
13287
- await options.registryStore.save(nextRecord);
13554
+ await persistRunTransition(options.registryStore, record, nextRecord);
13288
13555
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13289
13556
  options.notifyTerminal(outcome);
13290
13557
  outcomes.push(outcome);
@@ -13408,8 +13675,13 @@ var DefaultRunSupervisor = class {
13408
13675
  inFlight = /* @__PURE__ */ new Map();
13409
13676
  eventWatchDisposers = /* @__PURE__ */ new Map();
13410
13677
  controlOperations = /* @__PURE__ */ new Map();
13678
+ canRestoreRun;
13411
13679
  constructor(options) {
13680
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13681
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13682
+ }
13412
13683
  this.registryStore = options.registryStore;
13684
+ this.canRestoreRun = options.canRestoreRun;
13413
13685
  this.auditPort = options.auditPort;
13414
13686
  this.executor = options.executor;
13415
13687
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13457,6 +13729,23 @@ var DefaultRunSupervisor = class {
13457
13729
  this.releaseRunAdmission(runId);
13458
13730
  throw error;
13459
13731
  }
13732
+ return this.attachRun(record, spec, controller);
13733
+ }
13734
+ async restoreRun(spec) {
13735
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13736
+ return this.withRunControlLock(spec.runId, async () => {
13737
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
13738
+ const record = await this.registryStore.load(spec.runId);
13739
+ if (!record) throw new RunNotFoundError(spec.runId);
13740
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
13741
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
13742
+ }
13743
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
13744
+ return this.attachRun(record, spec, new AbortController());
13745
+ });
13746
+ }
13747
+ attachRun(record, spec, controller) {
13748
+ const runId = record.runId;
13460
13749
  try {
13461
13750
  const handle = new DefaultRunHandle({
13462
13751
  runRecord: record,
@@ -13554,11 +13843,36 @@ var DefaultRunSupervisor = class {
13554
13843
  registryStore: this.registryStore,
13555
13844
  reason,
13556
13845
  now: this.now,
13557
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
13846
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
13847
+ canRestoreRun: this.canRestoreRun
13558
13848
  });
13559
13849
  }
13560
- async pause(_runId, _reason) {
13561
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
13850
+ async pause(runId, reason) {
13851
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
13852
+ }
13853
+ async resumePausedRun(input) {
13854
+ return this.withRunControlLock(input.runId, async () => {
13855
+ const handle = this.getHandle(input.runId);
13856
+ const record = await this.registryStore.load(input.runId);
13857
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
13858
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
13859
+ }
13860
+ await persistRunTransition(this.registryStore, record, {
13861
+ ...record,
13862
+ status: "running",
13863
+ updatedAt: this.now(),
13864
+ pausedAt: void 0,
13865
+ pauseReason: void 0,
13866
+ errorIfAny: void 0,
13867
+ metadata: { ...record.metadata, executionId: input.executionId }
13868
+ });
13869
+ const controller = new AbortController();
13870
+ handle.replaceExecutionAbortController(controller, input.executionId);
13871
+ handle.attachTransportEventBus(input.eventBus);
13872
+ this.controllers.set(input.runId, controller);
13873
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
13874
+ return handle;
13875
+ });
13562
13876
  }
13563
13877
  async claimResume(runId, interaction, eventBus, parentSignal) {
13564
13878
  return this.withRunControlLock(runId, async () => {
@@ -13593,7 +13907,7 @@ var DefaultRunSupervisor = class {
13593
13907
  throw new RunNotFoundError(runId);
13594
13908
  }
13595
13909
  const claimId = generateRunResumeClaimId();
13596
- await this.registryStore.save({
13910
+ await persistRunTransition(this.registryStore, record, {
13597
13911
  ...record,
13598
13912
  updatedAt: this.now(),
13599
13913
  metadata: {
@@ -13681,7 +13995,7 @@ var DefaultRunSupervisor = class {
13681
13995
  }
13682
13996
  const awaitingUserWithoutClaim = { ...awaitingUser };
13683
13997
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13684
- await this.registryStore.save({
13998
+ await persistRunTransition(this.registryStore, record, {
13685
13999
  ...record,
13686
14000
  status: "running",
13687
14001
  updatedAt: this.now(),
@@ -13702,7 +14016,7 @@ var DefaultRunSupervisor = class {
13702
14016
  });
13703
14017
  const executionController = new AbortController();
13704
14018
  forwardParentAbortSignal(executionController, parentSignal);
13705
- handle.replaceExecutionAbortController(executionController);
14019
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13706
14020
  this.controllers.set(runId, executionController);
13707
14021
  return handle;
13708
14022
  });
@@ -13720,7 +14034,7 @@ var DefaultRunSupervisor = class {
13720
14034
  }
13721
14035
  const awaitingUserWithoutClaim = { ...awaitingUser };
13722
14036
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13723
- await this.registryStore.save({
14037
+ await persistRunTransition(this.registryStore, record, {
13724
14038
  ...record,
13725
14039
  updatedAt: this.now(),
13726
14040
  metadata: {
@@ -13978,6 +14292,8 @@ exports.ModelResolver = ModelResolver;
13978
14292
  exports.PRIMARY_PROMPT_CAPACITY_ERROR_CODE = PRIMARY_PROMPT_CAPACITY_ERROR_CODE;
13979
14293
  exports.PrimaryPromptCapacityError = PrimaryPromptCapacityError;
13980
14294
  exports.REASONING_EFFORTS = REASONING_EFFORTS;
14295
+ exports.RunPauseRequested = RunPauseRequested;
14296
+ exports.RunRecoveryBlockedError = RunRecoveryBlockedError;
13981
14297
  exports.RuntimeEventSubRunTracePublisher = RuntimeEventSubRunTracePublisher;
13982
14298
  exports.SYSTEM_REMINDER_RULES = SYSTEM_REMINDER_RULES;
13983
14299
  exports.SystemReminderRegistry = SystemReminderRegistry;
@@ -14035,6 +14351,7 @@ exports.findCachedToolOutputByIdempotencyKey = findCachedToolOutputByIdempotency
14035
14351
  exports.getToolContextRuntimeBinding = getToolContextRuntimeBinding;
14036
14352
  exports.graph = graph_engine_exports;
14037
14353
  exports.hostReminderTextTemplate = hostReminderTextTemplate;
14354
+ exports.isRunPauseSignal = isRunPauseSignal;
14038
14355
  exports.isRuntimeFailureFact = isRuntimeFailureFact;
14039
14356
  exports.isValidReasoningEffort = isValidReasoningEffort;
14040
14357
  exports.lastStepsHintTemplate = lastStepsHintTemplate;