@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
@@ -3,6 +3,7 @@ import '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
 
@@ -23,12 +24,15 @@ __export(graph_engine_exports, {
23
24
  MemoryEventStore: () => MemoryEventStore,
24
25
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
25
26
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
27
+ RunPauseRequested: () => RunPauseRequested,
28
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
26
29
  ToolNode: () => ToolNode,
27
30
  UserNode: () => UserNode,
28
31
  WaitUserNode: () => WaitUserNode,
29
32
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
30
33
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
31
34
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
35
+ isRunPauseSignal: () => isRunPauseSignal,
32
36
  isRuntimeFailureFact: () => isRuntimeFailureFact,
33
37
  readCheckpointContextUsage: () => readCheckpointContextUsage,
34
38
  requireEventStoreId: () => requireEventStoreId,
@@ -2397,6 +2401,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2397
2401
  "memory",
2398
2402
  "runtimeEventSink",
2399
2403
  "runtimeEventCommitPort",
2404
+ "commitExecutionBoundary",
2405
+ "toolRecoveryPort",
2400
2406
  "runtimeFailureFactSink",
2401
2407
  "signal",
2402
2408
  "summarizationCallbacks",
@@ -2947,6 +2953,7 @@ var GraphExecutor = class {
2947
2953
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
2948
2954
  };
2949
2955
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
2956
+ this.executionCheckpointPort = config.executionCheckpointPort;
2950
2957
  }
2951
2958
  checkpointer;
2952
2959
  nodes = /* @__PURE__ */ new Map();
@@ -2954,6 +2961,7 @@ var GraphExecutor = class {
2954
2961
  checkpointQueues = /* @__PURE__ */ new Map();
2955
2962
  config;
2956
2963
  telemetryPort;
2964
+ executionCheckpointPort;
2957
2965
  registerNode(node) {
2958
2966
  this.nodes.set(node.id, node);
2959
2967
  }
@@ -2962,6 +2970,7 @@ var GraphExecutor = class {
2962
2970
  }
2963
2971
  sanitize(state) {
2964
2972
  return {
2973
+ ...state,
2965
2974
  nodeId: state.nodeId,
2966
2975
  revision: state.revision ?? 0,
2967
2976
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -2981,8 +2990,9 @@ var GraphExecutor = class {
2981
2990
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
2982
2991
  }
2983
2992
  this.ephemeralLocals.set(checkpointKey, { ...local });
2984
- await this.checkpointer.save(checkpointKey, {
2993
+ await this.commitCheckpoint(checkpointKey, {
2985
2994
  nodeId,
2995
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
2986
2996
  revision: 1,
2987
2997
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
2988
2998
  local: sanitizeCheckpointLocal(local)
@@ -2993,6 +3003,33 @@ var GraphExecutor = class {
2993
3003
  );
2994
3004
  });
2995
3005
  }
3006
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3007
+ async continueSession(checkpointKey, input) {
3008
+ if (!this.executionCheckpointPort) {
3009
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3010
+ }
3011
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3012
+ const current = await this.checkpointer.load(checkpointKey);
3013
+ if (!current || current.revision !== input.expectedRevision) {
3014
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3015
+ }
3016
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3017
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3018
+ }
3019
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3020
+ return { checkpoint: current, events: [], stepCount: 0 };
3021
+ }
3022
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3023
+ try {
3024
+ return await this.runUntilYieldQueued(
3025
+ checkpointKey,
3026
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3027
+ );
3028
+ } finally {
3029
+ this.ephemeralLocals.delete(checkpointKey);
3030
+ }
3031
+ });
3032
+ }
2996
3033
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
2997
3034
  async resumeSession(checkpointKey, input) {
2998
3035
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3013,17 +3050,21 @@ var GraphExecutor = class {
3013
3050
  );
3014
3051
  }
3015
3052
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3053
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3054
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3055
+ }
3016
3056
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3017
- await this.checkpointer.save(checkpointKey, {
3057
+ await this.commitCheckpoint(checkpointKey, {
3018
3058
  ...current,
3019
3059
  nodeId: input.nodeId ?? "llm",
3060
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3020
3061
  revision: currentRevision + 1,
3021
3062
  local: sanitizeCheckpointLocal(resumedLocal)
3022
3063
  });
3023
3064
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3024
3065
  return this.runUntilYieldQueued(
3025
3066
  checkpointKey,
3026
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3067
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3027
3068
  );
3028
3069
  });
3029
3070
  }
@@ -3118,9 +3159,16 @@ var GraphExecutor = class {
3118
3159
  ...state,
3119
3160
  revision: (state.revision ?? 0) + 1
3120
3161
  });
3121
- await this.checkpointer.save(checkpointKey, checkpoint);
3162
+ await this.commitCheckpoint(checkpointKey, checkpoint);
3122
3163
  return checkpoint;
3123
3164
  }
3165
+ async commitCheckpoint(checkpointKey, checkpoint) {
3166
+ if (this.executionCheckpointPort) {
3167
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3168
+ } else {
3169
+ await this.checkpointer.save(checkpointKey, checkpoint);
3170
+ }
3171
+ }
3124
3172
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3125
3173
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3126
3174
  return { events, checkpoint, stepCount };
@@ -3133,6 +3181,15 @@ var GraphExecutor = class {
3133
3181
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3134
3182
  local: { ...state.local || {}, ...ephemeral }
3135
3183
  };
3184
+ if (this.executionCheckpointPort) {
3185
+ state.local = {
3186
+ ...state.local,
3187
+ commitExecutionBoundary: async (boundary) => {
3188
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3189
+ boundary.revision = saved.revision;
3190
+ }
3191
+ };
3192
+ }
3136
3193
  const isAbortSignal2 = (v) => {
3137
3194
  return v !== null && typeof v === "object" && "aborted" in v;
3138
3195
  };
@@ -3142,11 +3199,12 @@ var GraphExecutor = class {
3142
3199
  throw err;
3143
3200
  };
3144
3201
  let stepCount = 0;
3202
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3145
3203
  let allEvents = [];
3146
3204
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3147
3205
  maxSteps
3148
3206
  });
3149
- while (stepCount < maxSteps) {
3207
+ while (previousSteps + stepCount < maxSteps) {
3150
3208
  stepCount += 1;
3151
3209
  reportStepsUsed(stepCount);
3152
3210
  const signalRaw = state.local?.signal;
@@ -3158,7 +3216,7 @@ var GraphExecutor = class {
3158
3216
  const stepPreparation = prepareGraphStep({
3159
3217
  state,
3160
3218
  maxSteps,
3161
- stepCount
3219
+ stepCount: previousSteps + stepCount
3162
3220
  });
3163
3221
  state = stepPreparation.state;
3164
3222
  const node = this.nodes.get(state.nodeId);
@@ -3167,6 +3225,7 @@ var GraphExecutor = class {
3167
3225
  maxSteps,
3168
3226
  stepCount
3169
3227
  });
3228
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3170
3229
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3171
3230
  this.ephemeralLocals.delete(checkpointKey);
3172
3231
  return result3;
@@ -3176,6 +3235,11 @@ var GraphExecutor = class {
3176
3235
  stepCount,
3177
3236
  nodeId: state.nodeId
3178
3237
  });
3238
+ if (this.executionCheckpointPort) {
3239
+ state.executionStatus = "executing";
3240
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3241
+ state.revision = saved.revision;
3242
+ }
3179
3243
  const result2 = await runGraphNodeWithTelemetry({
3180
3244
  node,
3181
3245
  state,
@@ -3200,10 +3264,13 @@ var GraphExecutor = class {
3200
3264
  fromNodeId: stepResolution.action.fromNodeId,
3201
3265
  nextNodeId: stepResolution.action.nextNodeId
3202
3266
  });
3203
- await this.saveCheckpoint(checkpointKey, state);
3267
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3268
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3269
+ state.revision = saved.revision;
3204
3270
  continue;
3205
3271
  }
3206
3272
  if (stepResolution.action.kind === "yield") {
3273
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3207
3274
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3208
3275
  maxSteps,
3209
3276
  stepCount
@@ -3214,6 +3281,7 @@ var GraphExecutor = class {
3214
3281
  maxSteps,
3215
3282
  stepCount
3216
3283
  });
3284
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3217
3285
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3218
3286
  }
3219
3287
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3234,6 +3302,7 @@ var GraphExecutor = class {
3234
3302
  },
3235
3303
  retryable: false
3236
3304
  }), "GraphExecutor.engine_budget_exhausted"));
3305
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3237
3306
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3238
3307
  this.ephemeralLocals.delete(checkpointKey);
3239
3308
  return result;
@@ -7127,10 +7196,11 @@ var LlmNode = class {
7127
7196
  bridge.handle
7128
7197
  );
7129
7198
  } catch (error) {
7130
- bridge.finalizePartialAnswer();
7199
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7131
7200
  throw error;
7132
7201
  }
7133
7202
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7203
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7134
7204
  switch (decision.kind) {
7135
7205
  case "tool_calls": {
7136
7206
  if (forceFinalAnswer) {
@@ -8398,6 +8468,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8398
8468
  function recordToolProtocolError(params) {
8399
8469
  }
8400
8470
 
8471
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8472
+ var RunRecoveryBlockedError = class extends Error {
8473
+ code = "RUN_RECOVERY_BLOCKED";
8474
+ constructor(message) {
8475
+ super(message);
8476
+ this.name = "RunRecoveryBlockedError";
8477
+ }
8478
+ };
8479
+ var RunPauseRequested = class extends Error {
8480
+ code = "RUN_PAUSE_REQUESTED";
8481
+ constructor(message = "Run paused by user") {
8482
+ super(message);
8483
+ this.name = "RunPauseRequested";
8484
+ }
8485
+ };
8486
+ function isRunPauseSignal(signal) {
8487
+ const reason = signal?.reason;
8488
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8489
+ }
8490
+
8491
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8492
+ async function executeRecoverableTool(input) {
8493
+ const local = input.state.local;
8494
+ if (!local?.commitExecutionBoundary) return input.execute();
8495
+ if (local.executingToolCallId) {
8496
+ if (local.executingToolCallId !== input.call.id) {
8497
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8498
+ }
8499
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8500
+ if (!decision || decision.kind === "blocked") {
8501
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8502
+ }
8503
+ if (decision.kind === "settled") return decision.result;
8504
+ }
8505
+ local.executingToolCallId = input.call.id;
8506
+ await local.commitExecutionBoundary(input.state);
8507
+ const result = await input.execute();
8508
+ if (!result.success && isRunPauseSignal(local.signal)) {
8509
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8510
+ error.name = "AbortError";
8511
+ throw error;
8512
+ }
8513
+ return result;
8514
+ }
8515
+ async function commitToolBoundary(state, result) {
8516
+ if (!state.local?.commitExecutionBoundary) return;
8517
+ delete state.local.executingToolCallId;
8518
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8519
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8520
+ await state.local.commitExecutionBoundary(state);
8521
+ }
8522
+
8401
8523
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8402
8524
  var logger11 = new Logger("ToolNode");
8403
8525
  function isAbortSignal(value) {
@@ -8568,6 +8690,7 @@ var ToolNode = class {
8568
8690
  const events = [];
8569
8691
  while (true) {
8570
8692
  const result = await this.runNextPendingToolCall(state);
8693
+ await commitToolBoundary(state, result);
8571
8694
  if (Array.isArray(result.events) && result.events.length > 0) {
8572
8695
  events.push(...result.events);
8573
8696
  }
@@ -8584,11 +8707,9 @@ var ToolNode = class {
8584
8707
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8585
8708
  const signalRaw = state.local?.signal;
8586
8709
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8587
- settlePendingToolCallsAfterAbort({
8588
- state,
8589
- calls,
8590
- toolCatalog: this.toolRuntime
8591
- });
8710
+ if (!isRunPauseSignal(signalRaw)) {
8711
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8712
+ }
8592
8713
  const abortError = new Error("The user aborted a request.");
8593
8714
  abortError.name = "AbortError";
8594
8715
  throw abortError;
@@ -8727,16 +8848,21 @@ var ToolNode = class {
8727
8848
  tool_calls: [call]
8728
8849
  });
8729
8850
  try {
8730
- const exec = await executeToolWithIdempotency({
8731
- idempotencyKey: execution.idempotencyKey,
8732
- inFlight: this.idempotencyInFlight,
8733
- history: readHistoryEvents(prepared.local),
8734
- toolName: execution.toolName,
8735
- execute: () => this.toolRuntime.executeTool(
8736
- execution.toolName,
8737
- execution.toolArgs,
8738
- prepared.toolContext
8739
- )
8851
+ const exec = await executeRecoverableTool({
8852
+ state,
8853
+ call,
8854
+ context: prepared.toolContext,
8855
+ execute: () => executeToolWithIdempotency({
8856
+ idempotencyKey: execution.idempotencyKey,
8857
+ inFlight: this.idempotencyInFlight,
8858
+ history: readHistoryEvents(prepared.local),
8859
+ toolName: execution.toolName,
8860
+ execute: () => this.toolRuntime.executeTool(
8861
+ execution.toolName,
8862
+ execution.toolArgs,
8863
+ prepared.toolContext
8864
+ )
8865
+ })
8740
8866
  });
8741
8867
  if (exec.success) {
8742
8868
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8816,7 +8942,7 @@ var ToolNode = class {
8816
8942
  bridge: execution.bridge
8817
8943
  });
8818
8944
  } catch (error) {
8819
- if (isToolExecutionAbort(error)) {
8945
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8820
8946
  settleToolCallsAfterExecutionAbort({
8821
8947
  state,
8822
8948
  remainingCalls: calls.slice(1),
@@ -8876,7 +9002,7 @@ var ToolNode = class {
8876
9002
  {
8877
9003
  attachments: context.attachments,
8878
9004
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8879
- ephemeral: context.exec.idempotency?.cacheHit === true,
9005
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8880
9006
  durationMs: context.exec.durationMs
8881
9007
  }
8882
9008
  );
@@ -8933,6 +9059,9 @@ var ToolNode = class {
8933
9059
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8934
9060
  }
8935
9061
  async handleError(context) {
9062
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9063
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9064
+ }
8936
9065
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8937
9066
  await this.emitToolDecisionAudit({
8938
9067
  action: "tool.deny",
@@ -10041,12 +10170,33 @@ var RuntimeEventPublisher = class {
10041
10170
  var EventBusEventPersistence = class {
10042
10171
  constructor(options) {
10043
10172
  this.options = options;
10173
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10044
10174
  }
10045
10175
  options;
10046
10176
  scheduledEventIds = /* @__PURE__ */ new Set();
10047
10177
  writeTail = Promise.resolve();
10048
10178
  firstWriteError;
10049
10179
  connected = false;
10180
+ checkpointWritesActive;
10181
+ checkpointEvents = [];
10182
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10183
+ async commitCheckpoint(checkpointKey, checkpoint) {
10184
+ const writer = this.options.checkpointWriter;
10185
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10186
+ const events = this.checkpointEvents;
10187
+ this.checkpointEvents = [];
10188
+ await this.enqueueWrite(() => writer({
10189
+ checkpointKey,
10190
+ checkpoint,
10191
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10192
+ }));
10193
+ }
10194
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10195
+ finishCheckpointWrites() {
10196
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10197
+ this.checkpointEvents = [];
10198
+ this.checkpointWritesActive = false;
10199
+ }
10050
10200
  connect() {
10051
10201
  if (this.connected) {
10052
10202
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10093,14 +10243,22 @@ var EventBusEventPersistence = class {
10093
10243
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10094
10244
  return;
10095
10245
  }
10246
+ if (this.checkpointWritesActive) {
10247
+ this.scheduledEventIds.add(event.id);
10248
+ this.checkpointEvents.push(event);
10249
+ return;
10250
+ }
10096
10251
  void this.scheduleWrite(event).catch(() => void 0);
10097
10252
  };
10098
10253
  scheduleWrite(event) {
10099
10254
  this.scheduledEventIds.add(event.id);
10100
- const eventStoreId = this.options.nextEventStoreId();
10101
- const write = this.writeTail.then(async () => {
10102
- await this.options.eventStore.append({ eventStoreId, event });
10103
- });
10255
+ return this.enqueueWrite(() => this.options.eventStore.append({
10256
+ eventStoreId: this.options.nextEventStoreId(),
10257
+ event
10258
+ }));
10259
+ }
10260
+ enqueueWrite(operation) {
10261
+ const write = this.writeTail.then(operation);
10104
10262
  this.writeTail = write;
10105
10263
  void write.catch((error) => {
10106
10264
  this.firstWriteError ??= error;
@@ -11821,6 +11979,9 @@ var ChildRunInvoker = class {
11821
11979
  explicitConversationId: conversationId,
11822
11980
  parentToolContext
11823
11981
  });
11982
+ if (config.persistence?.expectedRevision !== void 0) {
11983
+ return this.continueChild(config, childRunId, runtimeConversationId);
11984
+ }
11824
11985
  const turnId = generateTurnId();
11825
11986
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
11826
11987
  conversationId: runtimeConversationId,
@@ -11828,21 +11989,8 @@ var ChildRunInvoker = class {
11828
11989
  maxSteps,
11829
11990
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
11830
11991
  });
11831
- const checkpointer = new MemoryCheckpointer();
11832
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
11833
- const llmNode = this.createLlmNode();
11834
- const toolNode = new ToolNode({
11835
- toolRuntime: this.toolRuntime,
11836
- observationPreview: this.observationPreview,
11837
- telemetryPort: this.telemetryPort,
11838
- auditPort: this.auditPort,
11839
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
11840
- modelInputResolver: this.modelInputResolver
11841
- });
11842
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
11843
- graphExecutor.registerNode(llmNode);
11844
- graphExecutor.registerNode(toolNode);
11845
- graphExecutor.registerNode(waitUserNode);
11992
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
11993
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
11846
11994
  const childUserInput = createChildRunUserInput({
11847
11995
  id: generateRuntimeEventId(),
11848
11996
  conversationId: runtimeConversationId,
@@ -11922,6 +12070,7 @@ var ChildRunInvoker = class {
11922
12070
  ...abortSignal ? { signal: abortSignal } : {},
11923
12071
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
11924
12072
  runtimeEventSink,
12073
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
11925
12074
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
11926
12075
  systemPrompt
11927
12076
  };
@@ -11962,6 +12111,7 @@ var ChildRunInvoker = class {
11962
12111
  eventToMessageConverter: this.eventToMessageConverter
11963
12112
  });
11964
12113
  } catch (err) {
12114
+ if (config.persistence) throw err;
11965
12115
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
11966
12116
  checkpointer,
11967
12117
  checkpointKey: internalCheckpointKey,
@@ -12000,7 +12150,7 @@ var ChildRunInvoker = class {
12000
12150
  events: allEvents,
12001
12151
  eventToMessageConverter: this.eventToMessageConverter
12002
12152
  });
12003
- await checkpointer.clear(internalCheckpointKey);
12153
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12004
12154
  return {
12005
12155
  success: !error && !cancelled,
12006
12156
  runId: childRunId,
@@ -12017,6 +12167,66 @@ var ChildRunInvoker = class {
12017
12167
  error
12018
12168
  };
12019
12169
  }
12170
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12171
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12172
+ graph.registerNode(this.createLlmNode());
12173
+ graph.registerNode(new ToolNode({
12174
+ toolRuntime: this.toolRuntime,
12175
+ observationPreview: this.observationPreview,
12176
+ telemetryPort: this.telemetryPort,
12177
+ auditPort: this.auditPort,
12178
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12179
+ modelInputResolver: this.modelInputResolver
12180
+ }));
12181
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12182
+ return graph;
12183
+ }
12184
+ async continueChild(config, runId, conversationId) {
12185
+ const persistence = config.persistence;
12186
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12187
+ const checkpoint = await persistence.checkpointer.load(runId);
12188
+ if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12189
+ const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
12190
+ const request = local.request;
12191
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12192
+ const context = createChildRunToolContext({
12193
+ parentToolContext: config.parentToolContext,
12194
+ conversationId,
12195
+ turnId: local.turnId,
12196
+ runId,
12197
+ parentRunId: config.parentRunId,
12198
+ userQuery: request.query,
12199
+ modelId: request.model_id,
12200
+ seedHistory: local.history,
12201
+ abortSignal: config.abortSignal
12202
+ });
12203
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12204
+ const result = await graph.continueSession(runId, {
12205
+ expectedRevision: persistence.expectedRevision,
12206
+ capabilities: {
12207
+ toolContext: context,
12208
+ signal: config.abortSignal,
12209
+ runtimeEventSink: config.runtimeEventSink,
12210
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12211
+ toolRecoveryPort: persistence.toolRecoveryPort
12212
+ }
12213
+ });
12214
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12215
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12216
+ const finalAnswer = extractFinalAnswer(events);
12217
+ return {
12218
+ runId,
12219
+ parentRunId: config.parentRunId,
12220
+ subrunId: runId,
12221
+ success: true,
12222
+ events,
12223
+ finalAnswer,
12224
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12225
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12226
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12227
+ toolset: { availableTools: request.availableTools }
12228
+ };
12229
+ }
12020
12230
  };
12021
12231
  function isAbortError2(error) {
12022
12232
  return error instanceof Error && error.name === "AbortError";
@@ -12418,8 +12628,6 @@ __export(run_supervisor_exports, {
12418
12628
  RunNotFoundError: () => RunNotFoundError,
12419
12629
  runMetaFromRecord: () => runMetaFromRecord
12420
12630
  });
12421
-
12422
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12423
12631
  function cloneRunRecord(record) {
12424
12632
  return {
12425
12633
  ...record,
@@ -12439,6 +12647,11 @@ function matchesStatus(candidate, filter) {
12439
12647
  }
12440
12648
  var MemoryRunRegistryStore = class {
12441
12649
  store = /* @__PURE__ */ new Map();
12650
+ async compareAndSwap(previous, next) {
12651
+ if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12652
+ this.store.set(next.runId, cloneRunRecord(next));
12653
+ return true;
12654
+ }
12442
12655
  async save(record) {
12443
12656
  this.store.set(record.runId, cloneRunRecord(record));
12444
12657
  }
@@ -12586,6 +12799,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12586
12799
  }
12587
12800
  };
12588
12801
 
12802
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
12803
+ async function persistRunTransition(store, previous, next) {
12804
+ if (store.compareAndSwap) {
12805
+ if (!await store.compareAndSwap(previous, next)) {
12806
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
12807
+ }
12808
+ } else {
12809
+ await store.save(next);
12810
+ }
12811
+ }
12812
+
12589
12813
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12590
12814
  function isRunTerminalStatus(status) {
12591
12815
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12641,6 +12865,7 @@ var DefaultRunHandle = class {
12641
12865
  parentRunId;
12642
12866
  runRecord;
12643
12867
  abortController;
12868
+ executionId;
12644
12869
  agentSpecSnapshot;
12645
12870
  requestSnapshot;
12646
12871
  transportEventBus;
@@ -12656,6 +12881,9 @@ var DefaultRunHandle = class {
12656
12881
  this.runId = options.runRecord.runId;
12657
12882
  this.parentRunId = options.runRecord.parentRunId;
12658
12883
  this.abortController = options.abortController;
12884
+ const executionId = options.runRecord.metadata?.executionId;
12885
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
12886
+ this.executionId = executionId;
12659
12887
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12660
12888
  this.requestSnapshot = cloneRequest(options.request);
12661
12889
  this.transportEventBus = options.eventBus;
@@ -12675,8 +12903,9 @@ var DefaultRunHandle = class {
12675
12903
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12676
12904
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12677
12905
  */
12678
- replaceExecutionAbortController(controller) {
12906
+ replaceExecutionAbortController(controller, executionId) {
12679
12907
  this.abortController = controller;
12908
+ this.executionId = executionId;
12680
12909
  }
12681
12910
  async spec() {
12682
12911
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12696,6 +12925,7 @@ var DefaultRunHandle = class {
12696
12925
  this.abortController.abort(opts.reason);
12697
12926
  const latestRecord = await this.registryStore.load(this.runId);
12698
12927
  const baseRecord = latestRecord ?? this.runRecord;
12928
+ this.assertExecutionOwner(baseRecord);
12699
12929
  const transition = decideRunLifecycleTransition(baseRecord.status);
12700
12930
  if (transition.kind === "skip_terminal") {
12701
12931
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12705,7 +12935,7 @@ var DefaultRunHandle = class {
12705
12935
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12706
12936
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12707
12937
  };
12708
- await this.registryStore.save(settledRecord);
12938
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12709
12939
  this.runRecord = { ...settledRecord };
12710
12940
  return;
12711
12941
  }
@@ -12732,7 +12962,7 @@ var DefaultRunHandle = class {
12732
12962
  }
12733
12963
  }
12734
12964
  };
12735
- await this.registryStore.save(nextRecord);
12965
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12736
12966
  this.runRecord = { ...nextRecord };
12737
12967
  await this.auditPort.emit({
12738
12968
  envelopeId: generateAuditEnvelopeId(),
@@ -12840,21 +13070,35 @@ var DefaultRunHandle = class {
12840
13070
  async markFailed(error, patch = {}) {
12841
13071
  await this.saveLifecycleStatus("failed", patch, error);
12842
13072
  }
12843
- async pause(_reason) {
12844
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13073
+ async pause(reason = "Run paused by user") {
13074
+ const latest = await this.registryStore.load(this.runId);
13075
+ if (latest) this.assertExecutionOwner(latest);
13076
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13077
+ const next = {
13078
+ ...latest,
13079
+ status: "paused",
13080
+ updatedAt: Date.now(),
13081
+ pauseReason: reason,
13082
+ pausedAt: void 0
13083
+ };
13084
+ await persistRunTransition(this.registryStore, latest, next);
13085
+ this.runRecord = next;
13086
+ this.abortController.abort(new RunPauseRequested(reason));
12845
13087
  }
12846
- async resume() {
12847
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13088
+ async markPaused(patch = {}) {
13089
+ await this.saveLifecycleStatus("paused", patch);
12848
13090
  }
12849
13091
  async saveLifecycleStatus(status, patch, errorIfAny) {
12850
13092
  const latestRecord = await this.registryStore.load(this.runId);
12851
13093
  const baseRecord = latestRecord ?? this.runRecord;
12852
13094
  const transition = decideRunLifecycleTransition(baseRecord.status);
13095
+ this.assertExecutionOwner(baseRecord);
13096
+ if (status === "running" && baseRecord.status === "paused") return;
12853
13097
  if (transition.kind === "skip_terminal") {
12854
13098
  this.runRecord = { ...baseRecord };
12855
13099
  return;
12856
13100
  }
12857
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13101
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
12858
13102
  const updatedAt = Date.now();
12859
13103
  const nextRecord = {
12860
13104
  ...baseRecord,
@@ -12862,8 +13106,8 @@ var DefaultRunHandle = class {
12862
13106
  updatedAt,
12863
13107
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12864
13108
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
12865
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
12866
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13109
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13110
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
12867
13111
  errorIfAny,
12868
13112
  metadata: awaitingUserPatch?.eventId ? {
12869
13113
  ...baseRecord.metadata ?? {},
@@ -12874,7 +13118,7 @@ var DefaultRunHandle = class {
12874
13118
  }
12875
13119
  } : baseRecord.metadata
12876
13120
  };
12877
- await this.registryStore.save(nextRecord);
13121
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12878
13122
  this.runRecord = { ...nextRecord };
12879
13123
  if (status === "completed" || status === "failed") {
12880
13124
  this.closeObservationChannel();
@@ -12884,6 +13128,11 @@ var DefaultRunHandle = class {
12884
13128
  forwardTransportEvent = (envelope) => {
12885
13129
  this.observationEventBus.emit("event", envelope);
12886
13130
  };
13131
+ assertExecutionOwner(record) {
13132
+ if (record.metadata?.executionId !== this.executionId) {
13133
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13134
+ }
13135
+ }
12887
13136
  forwardTransportError = (error) => {
12888
13137
  this.observationEventBus.emit("error", error);
12889
13138
  };
@@ -13265,6 +13514,24 @@ async function recoverRunsOnBoot(options) {
13265
13514
  const outcomes = [];
13266
13515
  for (const record of activeRecords) {
13267
13516
  const updatedAt = options.now();
13517
+ if (await options.canRestoreRun?.(record)) {
13518
+ const metadata = { ...record.metadata };
13519
+ const awaitingUser = metadata.awaitingUser;
13520
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13521
+ const restored = { ...awaitingUser };
13522
+ Reflect.deleteProperty(restored, "resumeClaim");
13523
+ metadata.awaitingUser = restored;
13524
+ }
13525
+ await persistRunTransition(options.registryStore, record, {
13526
+ ...record,
13527
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13528
+ pausedAt: record.pausedAt ?? updatedAt,
13529
+ pauseReason: record.pauseReason ?? options.reason,
13530
+ updatedAt,
13531
+ metadata
13532
+ });
13533
+ continue;
13534
+ }
13268
13535
  const nextRecord = {
13269
13536
  ...record,
13270
13537
  status: "failed",
@@ -13282,7 +13549,7 @@ async function recoverRunsOnBoot(options) {
13282
13549
  }
13283
13550
  }
13284
13551
  };
13285
- await options.registryStore.save(nextRecord);
13552
+ await persistRunTransition(options.registryStore, record, nextRecord);
13286
13553
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13287
13554
  options.notifyTerminal(outcome);
13288
13555
  outcomes.push(outcome);
@@ -13406,8 +13673,13 @@ var DefaultRunSupervisor = class {
13406
13673
  inFlight = /* @__PURE__ */ new Map();
13407
13674
  eventWatchDisposers = /* @__PURE__ */ new Map();
13408
13675
  controlOperations = /* @__PURE__ */ new Map();
13676
+ canRestoreRun;
13409
13677
  constructor(options) {
13678
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13679
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13680
+ }
13410
13681
  this.registryStore = options.registryStore;
13682
+ this.canRestoreRun = options.canRestoreRun;
13411
13683
  this.auditPort = options.auditPort;
13412
13684
  this.executor = options.executor;
13413
13685
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13455,6 +13727,23 @@ var DefaultRunSupervisor = class {
13455
13727
  this.releaseRunAdmission(runId);
13456
13728
  throw error;
13457
13729
  }
13730
+ return this.attachRun(record, spec, controller);
13731
+ }
13732
+ async restoreRun(spec) {
13733
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13734
+ return this.withRunControlLock(spec.runId, async () => {
13735
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
13736
+ const record = await this.registryStore.load(spec.runId);
13737
+ if (!record) throw new RunNotFoundError(spec.runId);
13738
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
13739
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
13740
+ }
13741
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
13742
+ return this.attachRun(record, spec, new AbortController());
13743
+ });
13744
+ }
13745
+ attachRun(record, spec, controller) {
13746
+ const runId = record.runId;
13458
13747
  try {
13459
13748
  const handle = new DefaultRunHandle({
13460
13749
  runRecord: record,
@@ -13552,11 +13841,36 @@ var DefaultRunSupervisor = class {
13552
13841
  registryStore: this.registryStore,
13553
13842
  reason,
13554
13843
  now: this.now,
13555
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
13844
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
13845
+ canRestoreRun: this.canRestoreRun
13556
13846
  });
13557
13847
  }
13558
- async pause(_runId, _reason) {
13559
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
13848
+ async pause(runId, reason) {
13849
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
13850
+ }
13851
+ async resumePausedRun(input) {
13852
+ return this.withRunControlLock(input.runId, async () => {
13853
+ const handle = this.getHandle(input.runId);
13854
+ const record = await this.registryStore.load(input.runId);
13855
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
13856
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
13857
+ }
13858
+ await persistRunTransition(this.registryStore, record, {
13859
+ ...record,
13860
+ status: "running",
13861
+ updatedAt: this.now(),
13862
+ pausedAt: void 0,
13863
+ pauseReason: void 0,
13864
+ errorIfAny: void 0,
13865
+ metadata: { ...record.metadata, executionId: input.executionId }
13866
+ });
13867
+ const controller = new AbortController();
13868
+ handle.replaceExecutionAbortController(controller, input.executionId);
13869
+ handle.attachTransportEventBus(input.eventBus);
13870
+ this.controllers.set(input.runId, controller);
13871
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
13872
+ return handle;
13873
+ });
13560
13874
  }
13561
13875
  async claimResume(runId, interaction, eventBus, parentSignal) {
13562
13876
  return this.withRunControlLock(runId, async () => {
@@ -13591,7 +13905,7 @@ var DefaultRunSupervisor = class {
13591
13905
  throw new RunNotFoundError(runId);
13592
13906
  }
13593
13907
  const claimId = generateRunResumeClaimId();
13594
- await this.registryStore.save({
13908
+ await persistRunTransition(this.registryStore, record, {
13595
13909
  ...record,
13596
13910
  updatedAt: this.now(),
13597
13911
  metadata: {
@@ -13679,7 +13993,7 @@ var DefaultRunSupervisor = class {
13679
13993
  }
13680
13994
  const awaitingUserWithoutClaim = { ...awaitingUser };
13681
13995
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13682
- await this.registryStore.save({
13996
+ await persistRunTransition(this.registryStore, record, {
13683
13997
  ...record,
13684
13998
  status: "running",
13685
13999
  updatedAt: this.now(),
@@ -13700,7 +14014,7 @@ var DefaultRunSupervisor = class {
13700
14014
  });
13701
14015
  const executionController = new AbortController();
13702
14016
  forwardParentAbortSignal(executionController, parentSignal);
13703
- handle.replaceExecutionAbortController(executionController);
14017
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13704
14018
  this.controllers.set(runId, executionController);
13705
14019
  return handle;
13706
14020
  });
@@ -13718,7 +14032,7 @@ var DefaultRunSupervisor = class {
13718
14032
  }
13719
14033
  const awaitingUserWithoutClaim = { ...awaitingUser };
13720
14034
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13721
- await this.registryStore.save({
14035
+ await persistRunTransition(this.registryStore, record, {
13722
14036
  ...record,
13723
14037
  updatedAt: this.now(),
13724
14038
  metadata: {
@@ -13944,6 +14258,6 @@ function createGraphLoopHarness(options) {
13944
14258
  };
13945
14259
  }
13946
14260
 
13947
- export { AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, ChildRunParentTraceProjection, CommonParameterTypes, CompositeAuditPort, DefaultTokenizerPort, EMPTY_MODEL_INPUT_REQUIREMENT, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, INITIAL_CANONICAL_INFERENCE_STREAM_STATE, LLMPolicyEngine, LLM_IMAGE_INPUT_ERROR_CODES, LLM_MODEL_ELIGIBILITY_ERROR_CODE, LlmCaller, LlmImageInputError, LlmModelEligibilityError, LlmNode, MODEL_INPUT_ERROR_CODES, MODEL_INPUT_PLACEMENTS, MemoryCheckpointer, MemoryEventStore, ModelInputCapabilityError, ModelResolver, PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, REASONING_EFFORTS, RuntimeEventSubRunTracePublisher, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolModelInputResolutionError, ToolNode, ToolParameterSchemaError, UserNode, WaitUserNode, addLedgerAggregate, addUsageTotals, advanceCanonicalInferenceStreamState, agentHasToolTrigger, aggregateCanonicalUsage, aggregateTokenLedgerEntries, applySystemReminders, assertModelInputCompatibility, assertToolParameterSchema, audit_exports as audit, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, computeCost, computeToolIdempotencyKey, consoleAudit, consumeCanonicalInferenceStream, copyToolContextRuntimeCapability, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextComponentLedgerEntry, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createFixedChatModelCatalog, createGraphLoopHarness, createHostToolCallBootstrap, createLlmUsageLedgerEntry, createModelInputCompatibilityError, createMonotonicEventStoreIdFactory, createRunTokenUsageAggregate, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, deriveModelInputRequirement, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, evaluateModelInputCompatibility, evaluatePrimaryPromptCapacity, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, hostReminderTextTemplate, isRuntimeFailureFact, isValidReasoningEffort, lastStepsHintTemplate, listCompatibleModelIds, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, parseToolModelInputDeclaration, periodicProgressReflectionTemplate, phaseEqualsTrigger, projectChildRuntimeEventToSubRunTrace, readCheckpointContextUsage, readNonEmptyStrings, readToolContextPersistedHistory, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, requireEventStoreId, resolveEffectiveEffort, resolveEffectivePromptBudget, resolveToolModelInput, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, token_accounting_exports as tokenAccounting, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
14261
+ export { AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, ChildRunParentTraceProjection, CommonParameterTypes, CompositeAuditPort, DefaultTokenizerPort, EMPTY_MODEL_INPUT_REQUIREMENT, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, INITIAL_CANONICAL_INFERENCE_STREAM_STATE, LLMPolicyEngine, LLM_IMAGE_INPUT_ERROR_CODES, LLM_MODEL_ELIGIBILITY_ERROR_CODE, LlmCaller, LlmImageInputError, LlmModelEligibilityError, LlmNode, MODEL_INPUT_ERROR_CODES, MODEL_INPUT_PLACEMENTS, MemoryCheckpointer, MemoryEventStore, ModelInputCapabilityError, ModelResolver, PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, REASONING_EFFORTS, RunPauseRequested, RunRecoveryBlockedError, RuntimeEventSubRunTracePublisher, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolModelInputResolutionError, ToolNode, ToolParameterSchemaError, UserNode, WaitUserNode, addLedgerAggregate, addUsageTotals, advanceCanonicalInferenceStreamState, agentHasToolTrigger, aggregateCanonicalUsage, aggregateTokenLedgerEntries, applySystemReminders, assertModelInputCompatibility, assertToolParameterSchema, audit_exports as audit, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, computeCost, computeToolIdempotencyKey, consoleAudit, consumeCanonicalInferenceStream, copyToolContextRuntimeCapability, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextComponentLedgerEntry, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createFixedChatModelCatalog, createGraphLoopHarness, createHostToolCallBootstrap, createLlmUsageLedgerEntry, createModelInputCompatibilityError, createMonotonicEventStoreIdFactory, createRunTokenUsageAggregate, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, deriveModelInputRequirement, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, evaluateModelInputCompatibility, evaluatePrimaryPromptCapacity, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, hostReminderTextTemplate, isRunPauseSignal, isRuntimeFailureFact, isValidReasoningEffort, lastStepsHintTemplate, listCompatibleModelIds, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, parseToolModelInputDeclaration, periodicProgressReflectionTemplate, phaseEqualsTrigger, projectChildRuntimeEventToSubRunTrace, readCheckpointContextUsage, readNonEmptyStrings, readToolContextPersistedHistory, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, requireEventStoreId, resolveEffectiveEffort, resolveEffectivePromptBudget, resolveToolModelInput, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, token_accounting_exports as tokenAccounting, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
13948
14262
  //# sourceMappingURL=runtime-kernel.js.map
13949
14263
  //# sourceMappingURL=runtime-kernel.js.map