@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/index.js CHANGED
@@ -3,6 +3,7 @@ import { createParser } from 'eventsource-parser';
3
3
  import { get_encoding } from 'tiktoken';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
5
5
  import { createHash } from 'crypto';
6
+ import { isDeepStrictEqual } from 'util';
6
7
  import { mkdir, appendFile } from 'fs/promises';
7
8
  import { dirname } from 'path';
8
9
 
@@ -50,6 +51,8 @@ __export(runtime_kernel_exports, {
50
51
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
51
52
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
52
53
  REASONING_EFFORTS: () => REASONING_EFFORTS,
54
+ RunPauseRequested: () => RunPauseRequested,
55
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
53
56
  RuntimeEventSubRunTracePublisher: () => RuntimeEventSubRunTracePublisher,
54
57
  SYSTEM_REMINDER_RULES: () => SYSTEM_REMINDER_RULES,
55
58
  SystemReminderRegistry: () => SystemReminderRegistry,
@@ -107,6 +110,7 @@ __export(runtime_kernel_exports, {
107
110
  getToolContextRuntimeBinding: () => getToolContextRuntimeBinding,
108
111
  graph: () => graph_engine_exports,
109
112
  hostReminderTextTemplate: () => hostReminderTextTemplate,
113
+ isRunPauseSignal: () => isRunPauseSignal,
110
114
  isRuntimeFailureFact: () => isRuntimeFailureFact,
111
115
  isValidReasoningEffort: () => isValidReasoningEffort,
112
116
  lastStepsHintTemplate: () => lastStepsHintTemplate,
@@ -154,12 +158,15 @@ __export(graph_engine_exports, {
154
158
  MemoryEventStore: () => MemoryEventStore,
155
159
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
156
160
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
161
+ RunPauseRequested: () => RunPauseRequested,
162
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
157
163
  ToolNode: () => ToolNode,
158
164
  UserNode: () => UserNode,
159
165
  WaitUserNode: () => WaitUserNode,
160
166
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
161
167
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
162
168
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
169
+ isRunPauseSignal: () => isRunPauseSignal,
163
170
  isRuntimeFailureFact: () => isRuntimeFailureFact,
164
171
  readCheckpointContextUsage: () => readCheckpointContextUsage,
165
172
  requireEventStoreId: () => requireEventStoreId,
@@ -3383,6 +3390,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
3383
3390
  "memory",
3384
3391
  "runtimeEventSink",
3385
3392
  "runtimeEventCommitPort",
3393
+ "commitExecutionBoundary",
3394
+ "toolRecoveryPort",
3386
3395
  "runtimeFailureFactSink",
3387
3396
  "signal",
3388
3397
  "summarizationCallbacks",
@@ -3933,6 +3942,7 @@ var GraphExecutor = class {
3933
3942
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3934
3943
  };
3935
3944
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3945
+ this.executionCheckpointPort = config.executionCheckpointPort;
3936
3946
  }
3937
3947
  checkpointer;
3938
3948
  nodes = /* @__PURE__ */ new Map();
@@ -3940,6 +3950,7 @@ var GraphExecutor = class {
3940
3950
  checkpointQueues = /* @__PURE__ */ new Map();
3941
3951
  config;
3942
3952
  telemetryPort;
3953
+ executionCheckpointPort;
3943
3954
  registerNode(node) {
3944
3955
  this.nodes.set(node.id, node);
3945
3956
  }
@@ -3948,6 +3959,7 @@ var GraphExecutor = class {
3948
3959
  }
3949
3960
  sanitize(state) {
3950
3961
  return {
3962
+ ...state,
3951
3963
  nodeId: state.nodeId,
3952
3964
  revision: state.revision ?? 0,
3953
3965
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3967,8 +3979,9 @@ var GraphExecutor = class {
3967
3979
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3968
3980
  }
3969
3981
  this.ephemeralLocals.set(checkpointKey, { ...local });
3970
- await this.checkpointer.save(checkpointKey, {
3982
+ await this.commitCheckpoint(checkpointKey, {
3971
3983
  nodeId,
3984
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3972
3985
  revision: 1,
3973
3986
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3974
3987
  local: sanitizeCheckpointLocal(local)
@@ -3979,6 +3992,33 @@ var GraphExecutor = class {
3979
3992
  );
3980
3993
  });
3981
3994
  }
3995
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3996
+ async continueSession(checkpointKey, input) {
3997
+ if (!this.executionCheckpointPort) {
3998
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3999
+ }
4000
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
4001
+ const current = await this.checkpointer.load(checkpointKey);
4002
+ if (!current || current.revision !== input.expectedRevision) {
4003
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
4004
+ }
4005
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
4006
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
4007
+ }
4008
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
4009
+ return { checkpoint: current, events: [], stepCount: 0 };
4010
+ }
4011
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
4012
+ try {
4013
+ return await this.runUntilYieldQueued(
4014
+ checkpointKey,
4015
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
4016
+ );
4017
+ } finally {
4018
+ this.ephemeralLocals.delete(checkpointKey);
4019
+ }
4020
+ });
4021
+ }
3982
4022
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3983
4023
  async resumeSession(checkpointKey, input) {
3984
4024
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3999,17 +4039,21 @@ var GraphExecutor = class {
3999
4039
  );
4000
4040
  }
4001
4041
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
4042
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
4043
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
4044
+ }
4002
4045
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
4003
- await this.checkpointer.save(checkpointKey, {
4046
+ await this.commitCheckpoint(checkpointKey, {
4004
4047
  ...current,
4005
4048
  nodeId: input.nodeId ?? "llm",
4049
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
4006
4050
  revision: currentRevision + 1,
4007
4051
  local: sanitizeCheckpointLocal(resumedLocal)
4008
4052
  });
4009
4053
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
4010
4054
  return this.runUntilYieldQueued(
4011
4055
  checkpointKey,
4012
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
4056
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
4013
4057
  );
4014
4058
  });
4015
4059
  }
@@ -4104,9 +4148,16 @@ var GraphExecutor = class {
4104
4148
  ...state,
4105
4149
  revision: (state.revision ?? 0) + 1
4106
4150
  });
4107
- await this.checkpointer.save(checkpointKey, checkpoint);
4151
+ await this.commitCheckpoint(checkpointKey, checkpoint);
4108
4152
  return checkpoint;
4109
4153
  }
4154
+ async commitCheckpoint(checkpointKey, checkpoint) {
4155
+ if (this.executionCheckpointPort) {
4156
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
4157
+ } else {
4158
+ await this.checkpointer.save(checkpointKey, checkpoint);
4159
+ }
4160
+ }
4110
4161
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
4111
4162
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
4112
4163
  return { events, checkpoint, stepCount };
@@ -4119,6 +4170,15 @@ var GraphExecutor = class {
4119
4170
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
4120
4171
  local: { ...state.local || {}, ...ephemeral }
4121
4172
  };
4173
+ if (this.executionCheckpointPort) {
4174
+ state.local = {
4175
+ ...state.local,
4176
+ commitExecutionBoundary: async (boundary) => {
4177
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
4178
+ boundary.revision = saved.revision;
4179
+ }
4180
+ };
4181
+ }
4122
4182
  const isAbortSignal2 = (v) => {
4123
4183
  return v !== null && typeof v === "object" && "aborted" in v;
4124
4184
  };
@@ -4128,11 +4188,12 @@ var GraphExecutor = class {
4128
4188
  throw err;
4129
4189
  };
4130
4190
  let stepCount = 0;
4191
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
4131
4192
  let allEvents = [];
4132
4193
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
4133
4194
  maxSteps
4134
4195
  });
4135
- while (stepCount < maxSteps) {
4196
+ while (previousSteps + stepCount < maxSteps) {
4136
4197
  stepCount += 1;
4137
4198
  reportStepsUsed(stepCount);
4138
4199
  const signalRaw = state.local?.signal;
@@ -4144,7 +4205,7 @@ var GraphExecutor = class {
4144
4205
  const stepPreparation = prepareGraphStep({
4145
4206
  state,
4146
4207
  maxSteps,
4147
- stepCount
4208
+ stepCount: previousSteps + stepCount
4148
4209
  });
4149
4210
  state = stepPreparation.state;
4150
4211
  const node = this.nodes.get(state.nodeId);
@@ -4153,6 +4214,7 @@ var GraphExecutor = class {
4153
4214
  maxSteps,
4154
4215
  stepCount
4155
4216
  });
4217
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
4156
4218
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
4157
4219
  this.ephemeralLocals.delete(checkpointKey);
4158
4220
  return result3;
@@ -4162,6 +4224,11 @@ var GraphExecutor = class {
4162
4224
  stepCount,
4163
4225
  nodeId: state.nodeId
4164
4226
  });
4227
+ if (this.executionCheckpointPort) {
4228
+ state.executionStatus = "executing";
4229
+ const saved = await this.saveCheckpoint(checkpointKey, state);
4230
+ state.revision = saved.revision;
4231
+ }
4165
4232
  const result2 = await runGraphNodeWithTelemetry({
4166
4233
  node,
4167
4234
  state,
@@ -4186,10 +4253,13 @@ var GraphExecutor = class {
4186
4253
  fromNodeId: stepResolution.action.fromNodeId,
4187
4254
  nextNodeId: stepResolution.action.nextNodeId
4188
4255
  });
4189
- await this.saveCheckpoint(checkpointKey, state);
4256
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
4257
+ const saved = await this.saveCheckpoint(checkpointKey, state);
4258
+ state.revision = saved.revision;
4190
4259
  continue;
4191
4260
  }
4192
4261
  if (stepResolution.action.kind === "yield") {
4262
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
4193
4263
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
4194
4264
  maxSteps,
4195
4265
  stepCount
@@ -4200,6 +4270,7 @@ var GraphExecutor = class {
4200
4270
  maxSteps,
4201
4271
  stepCount
4202
4272
  });
4273
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
4203
4274
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
4204
4275
  }
4205
4276
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -4220,6 +4291,7 @@ var GraphExecutor = class {
4220
4291
  },
4221
4292
  retryable: false
4222
4293
  }), "GraphExecutor.engine_budget_exhausted"));
4294
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
4223
4295
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
4224
4296
  this.ephemeralLocals.delete(checkpointKey);
4225
4297
  return result;
@@ -8123,10 +8195,11 @@ var LlmNode = class {
8123
8195
  bridge.handle
8124
8196
  );
8125
8197
  } catch (error) {
8126
- bridge.finalizePartialAnswer();
8198
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
8127
8199
  throw error;
8128
8200
  }
8129
8201
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
8202
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
8130
8203
  switch (decision.kind) {
8131
8204
  case "tool_calls": {
8132
8205
  if (forceFinalAnswer) {
@@ -9401,6 +9474,58 @@ function recordToolProtocolError(params) {
9401
9474
  recorder?.recordToolProtocolError?.(params);
9402
9475
  }
9403
9476
 
9477
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
9478
+ var RunRecoveryBlockedError = class extends Error {
9479
+ code = "RUN_RECOVERY_BLOCKED";
9480
+ constructor(message) {
9481
+ super(message);
9482
+ this.name = "RunRecoveryBlockedError";
9483
+ }
9484
+ };
9485
+ var RunPauseRequested = class extends Error {
9486
+ code = "RUN_PAUSE_REQUESTED";
9487
+ constructor(message = "Run paused by user") {
9488
+ super(message);
9489
+ this.name = "RunPauseRequested";
9490
+ }
9491
+ };
9492
+ function isRunPauseSignal(signal) {
9493
+ const reason = signal?.reason;
9494
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
9495
+ }
9496
+
9497
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
9498
+ async function executeRecoverableTool(input) {
9499
+ const local = input.state.local;
9500
+ if (!local?.commitExecutionBoundary) return input.execute();
9501
+ if (local.executingToolCallId) {
9502
+ if (local.executingToolCallId !== input.call.id) {
9503
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
9504
+ }
9505
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
9506
+ if (!decision || decision.kind === "blocked") {
9507
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
9508
+ }
9509
+ if (decision.kind === "settled") return decision.result;
9510
+ }
9511
+ local.executingToolCallId = input.call.id;
9512
+ await local.commitExecutionBoundary(input.state);
9513
+ const result = await input.execute();
9514
+ if (!result.success && isRunPauseSignal(local.signal)) {
9515
+ const error = new Error("Tool execution paused before its outcome was confirmed");
9516
+ error.name = "AbortError";
9517
+ throw error;
9518
+ }
9519
+ return result;
9520
+ }
9521
+ async function commitToolBoundary(state, result) {
9522
+ if (!state.local?.commitExecutionBoundary) return;
9523
+ delete state.local.executingToolCallId;
9524
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
9525
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
9526
+ await state.local.commitExecutionBoundary(state);
9527
+ }
9528
+
9404
9529
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
9405
9530
  var logger11 = new Logger("ToolNode");
9406
9531
  function isAbortSignal(value) {
@@ -9571,6 +9696,7 @@ var ToolNode = class {
9571
9696
  const events = [];
9572
9697
  while (true) {
9573
9698
  const result = await this.runNextPendingToolCall(state);
9699
+ await commitToolBoundary(state, result);
9574
9700
  if (Array.isArray(result.events) && result.events.length > 0) {
9575
9701
  events.push(...result.events);
9576
9702
  }
@@ -9587,11 +9713,9 @@ var ToolNode = class {
9587
9713
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
9588
9714
  const signalRaw = state.local?.signal;
9589
9715
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
9590
- settlePendingToolCallsAfterAbort({
9591
- state,
9592
- calls,
9593
- toolCatalog: this.toolRuntime
9594
- });
9716
+ if (!isRunPauseSignal(signalRaw)) {
9717
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
9718
+ }
9595
9719
  const abortError = new Error("The user aborted a request.");
9596
9720
  abortError.name = "AbortError";
9597
9721
  throw abortError;
@@ -9730,16 +9854,21 @@ var ToolNode = class {
9730
9854
  tool_calls: [call]
9731
9855
  });
9732
9856
  try {
9733
- const exec = await executeToolWithIdempotency({
9734
- idempotencyKey: execution.idempotencyKey,
9735
- inFlight: this.idempotencyInFlight,
9736
- history: readHistoryEvents(prepared.local),
9737
- toolName: execution.toolName,
9738
- execute: () => this.toolRuntime.executeTool(
9739
- execution.toolName,
9740
- execution.toolArgs,
9741
- prepared.toolContext
9742
- )
9857
+ const exec = await executeRecoverableTool({
9858
+ state,
9859
+ call,
9860
+ context: prepared.toolContext,
9861
+ execute: () => executeToolWithIdempotency({
9862
+ idempotencyKey: execution.idempotencyKey,
9863
+ inFlight: this.idempotencyInFlight,
9864
+ history: readHistoryEvents(prepared.local),
9865
+ toolName: execution.toolName,
9866
+ execute: () => this.toolRuntime.executeTool(
9867
+ execution.toolName,
9868
+ execution.toolArgs,
9869
+ prepared.toolContext
9870
+ )
9871
+ })
9743
9872
  });
9744
9873
  if (exec.success) {
9745
9874
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -9819,7 +9948,7 @@ var ToolNode = class {
9819
9948
  bridge: execution.bridge
9820
9949
  });
9821
9950
  } catch (error) {
9822
- if (isToolExecutionAbort(error)) {
9951
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
9823
9952
  settleToolCallsAfterExecutionAbort({
9824
9953
  state,
9825
9954
  remainingCalls: calls.slice(1),
@@ -9879,7 +10008,7 @@ var ToolNode = class {
9879
10008
  {
9880
10009
  attachments: context.attachments,
9881
10010
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
9882
- ephemeral: context.exec.idempotency?.cacheHit === true,
10011
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
9883
10012
  durationMs: context.exec.durationMs
9884
10013
  }
9885
10014
  );
@@ -9936,6 +10065,9 @@ var ToolNode = class {
9936
10065
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
9937
10066
  }
9938
10067
  async handleError(context) {
10068
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
10069
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
10070
+ }
9939
10071
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
9940
10072
  await this.emitToolDecisionAudit({
9941
10073
  action: "tool.deny",
@@ -11044,12 +11176,33 @@ var RuntimeEventPublisher = class {
11044
11176
  var EventBusEventPersistence = class {
11045
11177
  constructor(options) {
11046
11178
  this.options = options;
11179
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
11047
11180
  }
11048
11181
  options;
11049
11182
  scheduledEventIds = /* @__PURE__ */ new Set();
11050
11183
  writeTail = Promise.resolve();
11051
11184
  firstWriteError;
11052
11185
  connected = false;
11186
+ checkpointWritesActive;
11187
+ checkpointEvents = [];
11188
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
11189
+ async commitCheckpoint(checkpointKey, checkpoint) {
11190
+ const writer = this.options.checkpointWriter;
11191
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
11192
+ const events = this.checkpointEvents;
11193
+ this.checkpointEvents = [];
11194
+ await this.enqueueWrite(() => writer({
11195
+ checkpointKey,
11196
+ checkpoint,
11197
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
11198
+ }));
11199
+ }
11200
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
11201
+ finishCheckpointWrites() {
11202
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
11203
+ this.checkpointEvents = [];
11204
+ this.checkpointWritesActive = false;
11205
+ }
11053
11206
  connect() {
11054
11207
  if (this.connected) {
11055
11208
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -11096,14 +11249,22 @@ var EventBusEventPersistence = class {
11096
11249
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
11097
11250
  return;
11098
11251
  }
11252
+ if (this.checkpointWritesActive) {
11253
+ this.scheduledEventIds.add(event.id);
11254
+ this.checkpointEvents.push(event);
11255
+ return;
11256
+ }
11099
11257
  void this.scheduleWrite(event).catch(() => void 0);
11100
11258
  };
11101
11259
  scheduleWrite(event) {
11102
11260
  this.scheduledEventIds.add(event.id);
11103
- const eventStoreId = this.options.nextEventStoreId();
11104
- const write = this.writeTail.then(async () => {
11105
- await this.options.eventStore.append({ eventStoreId, event });
11106
- });
11261
+ return this.enqueueWrite(() => this.options.eventStore.append({
11262
+ eventStoreId: this.options.nextEventStoreId(),
11263
+ event
11264
+ }));
11265
+ }
11266
+ enqueueWrite(operation) {
11267
+ const write = this.writeTail.then(operation);
11107
11268
  this.writeTail = write;
11108
11269
  void write.catch((error) => {
11109
11270
  this.firstWriteError ??= error;
@@ -12824,6 +12985,9 @@ var ChildRunInvoker = class {
12824
12985
  explicitConversationId: conversationId,
12825
12986
  parentToolContext
12826
12987
  });
12988
+ if (config.persistence?.expectedRevision !== void 0) {
12989
+ return this.continueChild(config, childRunId, runtimeConversationId);
12990
+ }
12827
12991
  const turnId = generateTurnId();
12828
12992
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
12829
12993
  conversationId: runtimeConversationId,
@@ -12831,21 +12995,8 @@ var ChildRunInvoker = class {
12831
12995
  maxSteps,
12832
12996
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
12833
12997
  });
12834
- const checkpointer = new MemoryCheckpointer();
12835
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
12836
- const llmNode = this.createLlmNode();
12837
- const toolNode = new ToolNode({
12838
- toolRuntime: this.toolRuntime,
12839
- observationPreview: this.observationPreview,
12840
- telemetryPort: this.telemetryPort,
12841
- auditPort: this.auditPort,
12842
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12843
- modelInputResolver: this.modelInputResolver
12844
- });
12845
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
12846
- graphExecutor.registerNode(llmNode);
12847
- graphExecutor.registerNode(toolNode);
12848
- graphExecutor.registerNode(waitUserNode);
12998
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
12999
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
12849
13000
  const childUserInput = createChildRunUserInput({
12850
13001
  id: generateRuntimeEventId(),
12851
13002
  conversationId: runtimeConversationId,
@@ -12925,6 +13076,7 @@ var ChildRunInvoker = class {
12925
13076
  ...abortSignal ? { signal: abortSignal } : {},
12926
13077
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
12927
13078
  runtimeEventSink,
13079
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
12928
13080
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
12929
13081
  systemPrompt
12930
13082
  };
@@ -12965,6 +13117,7 @@ var ChildRunInvoker = class {
12965
13117
  eventToMessageConverter: this.eventToMessageConverter
12966
13118
  });
12967
13119
  } catch (err) {
13120
+ if (config.persistence) throw err;
12968
13121
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
12969
13122
  checkpointer,
12970
13123
  checkpointKey: internalCheckpointKey,
@@ -13003,7 +13156,7 @@ var ChildRunInvoker = class {
13003
13156
  events: allEvents,
13004
13157
  eventToMessageConverter: this.eventToMessageConverter
13005
13158
  });
13006
- await checkpointer.clear(internalCheckpointKey);
13159
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
13007
13160
  return {
13008
13161
  success: !error && !cancelled,
13009
13162
  runId: childRunId,
@@ -13020,6 +13173,66 @@ var ChildRunInvoker = class {
13020
13173
  error
13021
13174
  };
13022
13175
  }
13176
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
13177
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
13178
+ graph.registerNode(this.createLlmNode());
13179
+ graph.registerNode(new ToolNode({
13180
+ toolRuntime: this.toolRuntime,
13181
+ observationPreview: this.observationPreview,
13182
+ telemetryPort: this.telemetryPort,
13183
+ auditPort: this.auditPort,
13184
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
13185
+ modelInputResolver: this.modelInputResolver
13186
+ }));
13187
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
13188
+ return graph;
13189
+ }
13190
+ async continueChild(config, runId, conversationId) {
13191
+ const persistence = config.persistence;
13192
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
13193
+ const checkpoint = await persistence.checkpointer.load(runId);
13194
+ if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
13195
+ const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
13196
+ const request = local.request;
13197
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
13198
+ const context = createChildRunToolContext({
13199
+ parentToolContext: config.parentToolContext,
13200
+ conversationId,
13201
+ turnId: local.turnId,
13202
+ runId,
13203
+ parentRunId: config.parentRunId,
13204
+ userQuery: request.query,
13205
+ modelId: request.model_id,
13206
+ seedHistory: local.history,
13207
+ abortSignal: config.abortSignal
13208
+ });
13209
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
13210
+ const result = await graph.continueSession(runId, {
13211
+ expectedRevision: persistence.expectedRevision,
13212
+ capabilities: {
13213
+ toolContext: context,
13214
+ signal: config.abortSignal,
13215
+ runtimeEventSink: config.runtimeEventSink,
13216
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
13217
+ toolRecoveryPort: persistence.toolRecoveryPort
13218
+ }
13219
+ });
13220
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
13221
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
13222
+ const finalAnswer = extractFinalAnswer(events);
13223
+ return {
13224
+ runId,
13225
+ parentRunId: config.parentRunId,
13226
+ subrunId: runId,
13227
+ success: true,
13228
+ events,
13229
+ finalAnswer,
13230
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
13231
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
13232
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
13233
+ toolset: { availableTools: request.availableTools }
13234
+ };
13235
+ }
13023
13236
  };
13024
13237
  function isAbortError2(error) {
13025
13238
  return error instanceof Error && error.name === "AbortError";
@@ -13421,8 +13634,6 @@ __export(run_supervisor_exports, {
13421
13634
  RunNotFoundError: () => RunNotFoundError,
13422
13635
  runMetaFromRecord: () => runMetaFromRecord
13423
13636
  });
13424
-
13425
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
13426
13637
  function cloneRunRecord(record) {
13427
13638
  return {
13428
13639
  ...record,
@@ -13442,6 +13653,11 @@ function matchesStatus(candidate, filter) {
13442
13653
  }
13443
13654
  var MemoryRunRegistryStore = class {
13444
13655
  store = /* @__PURE__ */ new Map();
13656
+ async compareAndSwap(previous, next) {
13657
+ if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
13658
+ this.store.set(next.runId, cloneRunRecord(next));
13659
+ return true;
13660
+ }
13445
13661
  async save(record) {
13446
13662
  this.store.set(record.runId, cloneRunRecord(record));
13447
13663
  }
@@ -13589,6 +13805,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
13589
13805
  }
13590
13806
  };
13591
13807
 
13808
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
13809
+ async function persistRunTransition(store, previous, next) {
13810
+ if (store.compareAndSwap) {
13811
+ if (!await store.compareAndSwap(previous, next)) {
13812
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
13813
+ }
13814
+ } else {
13815
+ await store.save(next);
13816
+ }
13817
+ }
13818
+
13592
13819
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
13593
13820
  function isRunTerminalStatus(status) {
13594
13821
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -13644,6 +13871,7 @@ var DefaultRunHandle = class {
13644
13871
  parentRunId;
13645
13872
  runRecord;
13646
13873
  abortController;
13874
+ executionId;
13647
13875
  agentSpecSnapshot;
13648
13876
  requestSnapshot;
13649
13877
  transportEventBus;
@@ -13659,6 +13887,9 @@ var DefaultRunHandle = class {
13659
13887
  this.runId = options.runRecord.runId;
13660
13888
  this.parentRunId = options.runRecord.parentRunId;
13661
13889
  this.abortController = options.abortController;
13890
+ const executionId = options.runRecord.metadata?.executionId;
13891
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
13892
+ this.executionId = executionId;
13662
13893
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
13663
13894
  this.requestSnapshot = cloneRequest(options.request);
13664
13895
  this.transportEventBus = options.eventBus;
@@ -13678,8 +13909,9 @@ var DefaultRunHandle = class {
13678
13909
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
13679
13910
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
13680
13911
  */
13681
- replaceExecutionAbortController(controller) {
13912
+ replaceExecutionAbortController(controller, executionId) {
13682
13913
  this.abortController = controller;
13914
+ this.executionId = executionId;
13683
13915
  }
13684
13916
  async spec() {
13685
13917
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -13699,6 +13931,7 @@ var DefaultRunHandle = class {
13699
13931
  this.abortController.abort(opts.reason);
13700
13932
  const latestRecord = await this.registryStore.load(this.runId);
13701
13933
  const baseRecord = latestRecord ?? this.runRecord;
13934
+ this.assertExecutionOwner(baseRecord);
13702
13935
  const transition = decideRunLifecycleTransition(baseRecord.status);
13703
13936
  if (transition.kind === "skip_terminal") {
13704
13937
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -13708,7 +13941,7 @@ var DefaultRunHandle = class {
13708
13941
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13709
13942
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
13710
13943
  };
13711
- await this.registryStore.save(settledRecord);
13944
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
13712
13945
  this.runRecord = { ...settledRecord };
13713
13946
  return;
13714
13947
  }
@@ -13735,7 +13968,7 @@ var DefaultRunHandle = class {
13735
13968
  }
13736
13969
  }
13737
13970
  };
13738
- await this.registryStore.save(nextRecord);
13971
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13739
13972
  this.runRecord = { ...nextRecord };
13740
13973
  await this.auditPort.emit({
13741
13974
  envelopeId: generateAuditEnvelopeId(),
@@ -13843,21 +14076,35 @@ var DefaultRunHandle = class {
13843
14076
  async markFailed(error, patch = {}) {
13844
14077
  await this.saveLifecycleStatus("failed", patch, error);
13845
14078
  }
13846
- async pause(_reason) {
13847
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
14079
+ async pause(reason = "Run paused by user") {
14080
+ const latest = await this.registryStore.load(this.runId);
14081
+ if (latest) this.assertExecutionOwner(latest);
14082
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
14083
+ const next = {
14084
+ ...latest,
14085
+ status: "paused",
14086
+ updatedAt: Date.now(),
14087
+ pauseReason: reason,
14088
+ pausedAt: void 0
14089
+ };
14090
+ await persistRunTransition(this.registryStore, latest, next);
14091
+ this.runRecord = next;
14092
+ this.abortController.abort(new RunPauseRequested(reason));
13848
14093
  }
13849
- async resume() {
13850
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
14094
+ async markPaused(patch = {}) {
14095
+ await this.saveLifecycleStatus("paused", patch);
13851
14096
  }
13852
14097
  async saveLifecycleStatus(status, patch, errorIfAny) {
13853
14098
  const latestRecord = await this.registryStore.load(this.runId);
13854
14099
  const baseRecord = latestRecord ?? this.runRecord;
13855
14100
  const transition = decideRunLifecycleTransition(baseRecord.status);
14101
+ this.assertExecutionOwner(baseRecord);
14102
+ if (status === "running" && baseRecord.status === "paused") return;
13856
14103
  if (transition.kind === "skip_terminal") {
13857
14104
  this.runRecord = { ...baseRecord };
13858
14105
  return;
13859
14106
  }
13860
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
14107
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
13861
14108
  const updatedAt = Date.now();
13862
14109
  const nextRecord = {
13863
14110
  ...baseRecord,
@@ -13865,8 +14112,8 @@ var DefaultRunHandle = class {
13865
14112
  updatedAt,
13866
14113
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13867
14114
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
13868
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13869
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
14115
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
14116
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
13870
14117
  errorIfAny,
13871
14118
  metadata: awaitingUserPatch?.eventId ? {
13872
14119
  ...baseRecord.metadata ?? {},
@@ -13877,7 +14124,7 @@ var DefaultRunHandle = class {
13877
14124
  }
13878
14125
  } : baseRecord.metadata
13879
14126
  };
13880
- await this.registryStore.save(nextRecord);
14127
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13881
14128
  this.runRecord = { ...nextRecord };
13882
14129
  if (status === "completed" || status === "failed") {
13883
14130
  this.closeObservationChannel();
@@ -13887,6 +14134,11 @@ var DefaultRunHandle = class {
13887
14134
  forwardTransportEvent = (envelope) => {
13888
14135
  this.observationEventBus.emit("event", envelope);
13889
14136
  };
14137
+ assertExecutionOwner(record) {
14138
+ if (record.metadata?.executionId !== this.executionId) {
14139
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
14140
+ }
14141
+ }
13890
14142
  forwardTransportError = (error) => {
13891
14143
  this.observationEventBus.emit("error", error);
13892
14144
  };
@@ -14268,6 +14520,24 @@ async function recoverRunsOnBoot(options) {
14268
14520
  const outcomes = [];
14269
14521
  for (const record of activeRecords) {
14270
14522
  const updatedAt = options.now();
14523
+ if (await options.canRestoreRun?.(record)) {
14524
+ const metadata = { ...record.metadata };
14525
+ const awaitingUser = metadata.awaitingUser;
14526
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
14527
+ const restored = { ...awaitingUser };
14528
+ Reflect.deleteProperty(restored, "resumeClaim");
14529
+ metadata.awaitingUser = restored;
14530
+ }
14531
+ await persistRunTransition(options.registryStore, record, {
14532
+ ...record,
14533
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
14534
+ pausedAt: record.pausedAt ?? updatedAt,
14535
+ pauseReason: record.pauseReason ?? options.reason,
14536
+ updatedAt,
14537
+ metadata
14538
+ });
14539
+ continue;
14540
+ }
14271
14541
  const nextRecord = {
14272
14542
  ...record,
14273
14543
  status: "failed",
@@ -14285,7 +14555,7 @@ async function recoverRunsOnBoot(options) {
14285
14555
  }
14286
14556
  }
14287
14557
  };
14288
- await options.registryStore.save(nextRecord);
14558
+ await persistRunTransition(options.registryStore, record, nextRecord);
14289
14559
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
14290
14560
  options.notifyTerminal(outcome);
14291
14561
  outcomes.push(outcome);
@@ -14409,8 +14679,13 @@ var DefaultRunSupervisor = class {
14409
14679
  inFlight = /* @__PURE__ */ new Map();
14410
14680
  eventWatchDisposers = /* @__PURE__ */ new Map();
14411
14681
  controlOperations = /* @__PURE__ */ new Map();
14682
+ canRestoreRun;
14412
14683
  constructor(options) {
14684
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
14685
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
14686
+ }
14413
14687
  this.registryStore = options.registryStore;
14688
+ this.canRestoreRun = options.canRestoreRun;
14414
14689
  this.auditPort = options.auditPort;
14415
14690
  this.executor = options.executor;
14416
14691
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -14458,6 +14733,23 @@ var DefaultRunSupervisor = class {
14458
14733
  this.releaseRunAdmission(runId);
14459
14734
  throw error;
14460
14735
  }
14736
+ return this.attachRun(record, spec, controller);
14737
+ }
14738
+ async restoreRun(spec) {
14739
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
14740
+ return this.withRunControlLock(spec.runId, async () => {
14741
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
14742
+ const record = await this.registryStore.load(spec.runId);
14743
+ if (!record) throw new RunNotFoundError(spec.runId);
14744
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
14745
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
14746
+ }
14747
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
14748
+ return this.attachRun(record, spec, new AbortController());
14749
+ });
14750
+ }
14751
+ attachRun(record, spec, controller) {
14752
+ const runId = record.runId;
14461
14753
  try {
14462
14754
  const handle = new DefaultRunHandle({
14463
14755
  runRecord: record,
@@ -14555,11 +14847,36 @@ var DefaultRunSupervisor = class {
14555
14847
  registryStore: this.registryStore,
14556
14848
  reason,
14557
14849
  now: this.now,
14558
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
14850
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
14851
+ canRestoreRun: this.canRestoreRun
14559
14852
  });
14560
14853
  }
14561
- async pause(_runId, _reason) {
14562
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
14854
+ async pause(runId, reason) {
14855
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
14856
+ }
14857
+ async resumePausedRun(input) {
14858
+ return this.withRunControlLock(input.runId, async () => {
14859
+ const handle = this.getHandle(input.runId);
14860
+ const record = await this.registryStore.load(input.runId);
14861
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
14862
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
14863
+ }
14864
+ await persistRunTransition(this.registryStore, record, {
14865
+ ...record,
14866
+ status: "running",
14867
+ updatedAt: this.now(),
14868
+ pausedAt: void 0,
14869
+ pauseReason: void 0,
14870
+ errorIfAny: void 0,
14871
+ metadata: { ...record.metadata, executionId: input.executionId }
14872
+ });
14873
+ const controller = new AbortController();
14874
+ handle.replaceExecutionAbortController(controller, input.executionId);
14875
+ handle.attachTransportEventBus(input.eventBus);
14876
+ this.controllers.set(input.runId, controller);
14877
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
14878
+ return handle;
14879
+ });
14563
14880
  }
14564
14881
  async claimResume(runId, interaction, eventBus, parentSignal) {
14565
14882
  return this.withRunControlLock(runId, async () => {
@@ -14594,7 +14911,7 @@ var DefaultRunSupervisor = class {
14594
14911
  throw new RunNotFoundError(runId);
14595
14912
  }
14596
14913
  const claimId = generateRunResumeClaimId();
14597
- await this.registryStore.save({
14914
+ await persistRunTransition(this.registryStore, record, {
14598
14915
  ...record,
14599
14916
  updatedAt: this.now(),
14600
14917
  metadata: {
@@ -14682,7 +14999,7 @@ var DefaultRunSupervisor = class {
14682
14999
  }
14683
15000
  const awaitingUserWithoutClaim = { ...awaitingUser };
14684
15001
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
14685
- await this.registryStore.save({
15002
+ await persistRunTransition(this.registryStore, record, {
14686
15003
  ...record,
14687
15004
  status: "running",
14688
15005
  updatedAt: this.now(),
@@ -14703,7 +15020,7 @@ var DefaultRunSupervisor = class {
14703
15020
  });
14704
15021
  const executionController = new AbortController();
14705
15022
  forwardParentAbortSignal(executionController, parentSignal);
14706
- handle.replaceExecutionAbortController(executionController);
15023
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
14707
15024
  this.controllers.set(runId, executionController);
14708
15025
  return handle;
14709
15026
  });
@@ -14721,7 +15038,7 @@ var DefaultRunSupervisor = class {
14721
15038
  }
14722
15039
  const awaitingUserWithoutClaim = { ...awaitingUser };
14723
15040
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
14724
- await this.registryStore.save({
15041
+ await persistRunTransition(this.registryStore, record, {
14725
15042
  ...record,
14726
15043
  updatedAt: this.now(),
14727
15044
  metadata: {