@linnlabs/linnkit 0.32.3 → 0.34.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 (83) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/cli.cjs +458 -70
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +458 -70
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +55 -0
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +55 -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 +24 -24
  13. package/dist/contracts/audit.d.ts +24 -24
  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 +1083 -1083
  17. package/dist/contracts/events.d.ts +1083 -1083
  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 +1178 -1178
  21. package/dist/contracts/messages.d.ts +1178 -1178
  22. package/dist/contracts/provider-continuation.d.cts +28 -28
  23. package/dist/contracts/provider-continuation.d.ts +28 -28
  24. package/dist/contracts/sse.d.cts +899 -899
  25. package/dist/contracts/sse.d.ts +899 -899
  26. package/dist/contracts/sub-run-trace-payload.d.cts +26 -26
  27. package/dist/contracts/sub-run-trace-payload.d.ts +26 -26
  28. package/dist/contracts/token-accounting.d.cts +30 -30
  29. package/dist/contracts/token-accounting.d.ts +30 -30
  30. package/dist/index.cjs +538 -94
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.js +538 -94
  33. package/dist/index.js.map +1 -1
  34. package/dist/quickstart/toolRuntime.d.cts +1 -1
  35. package/dist/quickstart/toolRuntime.d.ts +1 -1
  36. package/dist/quickstart/types.d.cts +1 -1
  37. package/dist/quickstart/types.d.ts +1 -1
  38. package/dist/quickstart.cjs +458 -70
  39. package/dist/quickstart.cjs.map +1 -1
  40. package/dist/quickstart.js +458 -70
  41. package/dist/quickstart.js.map +1 -1
  42. package/dist/runtime-kernel/child-runs/childRunInvoker.d.cts +11 -0
  43. package/dist/runtime-kernel/child-runs/childRunInvoker.d.ts +11 -0
  44. package/dist/runtime-kernel/events/agentEvents.d.cts +172 -172
  45. package/dist/runtime-kernel/events/agentEvents.d.ts +172 -172
  46. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.cts +15 -1
  47. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.ts +15 -1
  48. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.cts +34 -0
  49. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.ts +34 -0
  50. package/dist/runtime-kernel/graph-engine/engine.d.cts +13 -2
  51. package/dist/runtime-kernel/graph-engine/engine.d.ts +13 -2
  52. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.cts +6 -0
  53. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.ts +6 -0
  54. package/dist/runtime-kernel/graph-engine/index.d.cts +3 -1
  55. package/dist/runtime-kernel/graph-engine/index.d.ts +3 -1
  56. package/dist/runtime-kernel/graph-engine/types.d.cts +8 -0
  57. package/dist/runtime-kernel/graph-engine/types.d.ts +8 -0
  58. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +35 -6
  59. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +35 -6
  60. package/dist/runtime-kernel/run-supervisor/index.d.cts +1 -1
  61. package/dist/runtime-kernel/run-supervisor/index.d.ts +1 -1
  62. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.cts +1 -0
  63. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.ts +1 -0
  64. package/dist/runtime-kernel/run-supervisor/runHandle.d.cts +9 -5
  65. package/dist/runtime-kernel/run-supervisor/runHandle.d.ts +9 -5
  66. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.cts +2 -0
  67. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.ts +2 -0
  68. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +9 -2
  69. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +9 -2
  70. package/dist/runtime-kernel.cjs +535 -91
  71. package/dist/runtime-kernel.cjs.map +1 -1
  72. package/dist/runtime-kernel.d.cts +3 -1
  73. package/dist/runtime-kernel.d.ts +3 -1
  74. package/dist/runtime-kernel.js +532 -92
  75. package/dist/runtime-kernel.js.map +1 -1
  76. package/dist/testkit.cjs +535 -91
  77. package/dist/testkit.cjs.map +1 -1
  78. package/dist/testkit.js +535 -91
  79. package/dist/testkit.js.map +1 -1
  80. package/docs/integration/child-runs.md +12 -0
  81. package/docs/integration/persistence.md +24 -0
  82. package/docs/integration/run-supervisor.md +15 -2
  83. package/package.json +2 -2
@@ -5,6 +5,7 @@ require('eventsource-parser');
5
5
  var tiktoken = require('tiktoken');
6
6
  var async_hooks = require('async_hooks');
7
7
  var crypto = require('crypto');
8
+ var util = require('util');
8
9
  require('fs/promises');
9
10
  require('path');
10
11
 
@@ -2007,13 +2008,17 @@ __export(graph_engine_exports, {
2007
2008
  MemoryEventStore: () => MemoryEventStore,
2008
2009
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
2009
2010
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
2011
+ RunPauseRequested: () => RunPauseRequested,
2012
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
2010
2013
  ToolNode: () => ToolNode,
2011
2014
  UserNode: () => UserNode,
2012
2015
  WaitUserNode: () => WaitUserNode,
2013
2016
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
2014
2017
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
2015
2018
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
2019
+ isRunPauseSignal: () => isRunPauseSignal,
2016
2020
  isRuntimeFailureFact: () => isRuntimeFailureFact,
2021
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
2017
2022
  readCheckpointContextUsage: () => readCheckpointContextUsage,
2018
2023
  requireEventStoreId: () => requireEventStoreId,
2019
2024
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -2608,6 +2613,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2608
2613
  "memory",
2609
2614
  "runtimeEventSink",
2610
2615
  "runtimeEventCommitPort",
2616
+ "commitExecutionBoundary",
2617
+ "toolRecoveryPort",
2611
2618
  "runtimeFailureFactSink",
2612
2619
  "signal",
2613
2620
  "summarizationCallbacks",
@@ -3158,6 +3165,7 @@ var GraphExecutor = class {
3158
3165
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3159
3166
  };
3160
3167
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3168
+ this.executionCheckpointPort = config.executionCheckpointPort;
3161
3169
  }
3162
3170
  checkpointer;
3163
3171
  nodes = /* @__PURE__ */ new Map();
@@ -3165,6 +3173,7 @@ var GraphExecutor = class {
3165
3173
  checkpointQueues = /* @__PURE__ */ new Map();
3166
3174
  config;
3167
3175
  telemetryPort;
3176
+ executionCheckpointPort;
3168
3177
  registerNode(node) {
3169
3178
  this.nodes.set(node.id, node);
3170
3179
  }
@@ -3173,6 +3182,7 @@ var GraphExecutor = class {
3173
3182
  }
3174
3183
  sanitize(state) {
3175
3184
  return {
3185
+ ...state,
3176
3186
  nodeId: state.nodeId,
3177
3187
  revision: state.revision ?? 0,
3178
3188
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3192,8 +3202,9 @@ var GraphExecutor = class {
3192
3202
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3193
3203
  }
3194
3204
  this.ephemeralLocals.set(checkpointKey, { ...local });
3195
- await this.checkpointer.save(checkpointKey, {
3205
+ await this.commitCheckpoint(checkpointKey, {
3196
3206
  nodeId,
3207
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3197
3208
  revision: 1,
3198
3209
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3199
3210
  local: sanitizeCheckpointLocal(local)
@@ -3204,6 +3215,33 @@ var GraphExecutor = class {
3204
3215
  );
3205
3216
  });
3206
3217
  }
3218
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3219
+ async continueSession(checkpointKey, input) {
3220
+ if (!this.executionCheckpointPort) {
3221
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3222
+ }
3223
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3224
+ const current = await this.checkpointer.load(checkpointKey);
3225
+ if (!current || current.revision !== input.expectedRevision) {
3226
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3227
+ }
3228
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3229
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3230
+ }
3231
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3232
+ return { checkpoint: current, events: [], stepCount: 0 };
3233
+ }
3234
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3235
+ try {
3236
+ return await this.runUntilYieldQueued(
3237
+ checkpointKey,
3238
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3239
+ );
3240
+ } finally {
3241
+ this.ephemeralLocals.delete(checkpointKey);
3242
+ }
3243
+ });
3244
+ }
3207
3245
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3208
3246
  async resumeSession(checkpointKey, input) {
3209
3247
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3224,17 +3262,21 @@ var GraphExecutor = class {
3224
3262
  );
3225
3263
  }
3226
3264
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3265
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3266
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3267
+ }
3227
3268
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3228
- await this.checkpointer.save(checkpointKey, {
3269
+ await this.commitCheckpoint(checkpointKey, {
3229
3270
  ...current,
3230
3271
  nodeId: input.nodeId ?? "llm",
3272
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3231
3273
  revision: currentRevision + 1,
3232
3274
  local: sanitizeCheckpointLocal(resumedLocal)
3233
3275
  });
3234
3276
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3235
3277
  return this.runUntilYieldQueued(
3236
3278
  checkpointKey,
3237
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3279
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3238
3280
  );
3239
3281
  });
3240
3282
  }
@@ -3325,16 +3367,23 @@ var GraphExecutor = class {
3325
3367
  };
3326
3368
  }
3327
3369
  async saveCheckpoint(checkpointKey, state) {
3328
- const checkpoint = this.sanitize({
3370
+ const checkpoint2 = this.sanitize({
3329
3371
  ...state,
3330
3372
  revision: (state.revision ?? 0) + 1
3331
3373
  });
3332
- await this.checkpointer.save(checkpointKey, checkpoint);
3333
- return checkpoint;
3374
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3375
+ return checkpoint2;
3376
+ }
3377
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3378
+ if (this.executionCheckpointPort) {
3379
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3380
+ } else {
3381
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3382
+ }
3334
3383
  }
3335
3384
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3336
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3337
- return { events, checkpoint, stepCount };
3385
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3386
+ return { events, checkpoint: checkpoint2, stepCount };
3338
3387
  }
3339
3388
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3340
3389
  let state = initialState;
@@ -3344,6 +3393,15 @@ var GraphExecutor = class {
3344
3393
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3345
3394
  local: { ...state.local || {}, ...ephemeral }
3346
3395
  };
3396
+ if (this.executionCheckpointPort) {
3397
+ state.local = {
3398
+ ...state.local,
3399
+ commitExecutionBoundary: async (boundary) => {
3400
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3401
+ boundary.revision = saved.revision;
3402
+ }
3403
+ };
3404
+ }
3347
3405
  const isAbortSignal2 = (v) => {
3348
3406
  return v !== null && typeof v === "object" && "aborted" in v;
3349
3407
  };
@@ -3353,11 +3411,12 @@ var GraphExecutor = class {
3353
3411
  throw err;
3354
3412
  };
3355
3413
  let stepCount = 0;
3414
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3356
3415
  let allEvents = [];
3357
3416
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3358
3417
  maxSteps
3359
3418
  });
3360
- while (stepCount < maxSteps) {
3419
+ while (previousSteps + stepCount < maxSteps) {
3361
3420
  stepCount += 1;
3362
3421
  reportStepsUsed(stepCount);
3363
3422
  const signalRaw = state.local?.signal;
@@ -3369,7 +3428,7 @@ var GraphExecutor = class {
3369
3428
  const stepPreparation = prepareGraphStep({
3370
3429
  state,
3371
3430
  maxSteps,
3372
- stepCount
3431
+ stepCount: previousSteps + stepCount
3373
3432
  });
3374
3433
  state = stepPreparation.state;
3375
3434
  const node = this.nodes.get(state.nodeId);
@@ -3378,6 +3437,7 @@ var GraphExecutor = class {
3378
3437
  maxSteps,
3379
3438
  stepCount
3380
3439
  });
3440
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3381
3441
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3382
3442
  this.ephemeralLocals.delete(checkpointKey);
3383
3443
  return result3;
@@ -3387,6 +3447,11 @@ var GraphExecutor = class {
3387
3447
  stepCount,
3388
3448
  nodeId: state.nodeId
3389
3449
  });
3450
+ if (this.executionCheckpointPort) {
3451
+ state.executionStatus = "executing";
3452
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3453
+ state.revision = saved.revision;
3454
+ }
3390
3455
  const result2 = await runGraphNodeWithTelemetry({
3391
3456
  node,
3392
3457
  state,
@@ -3411,10 +3476,13 @@ var GraphExecutor = class {
3411
3476
  fromNodeId: stepResolution.action.fromNodeId,
3412
3477
  nextNodeId: stepResolution.action.nextNodeId
3413
3478
  });
3414
- await this.saveCheckpoint(checkpointKey, state);
3479
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3480
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3481
+ state.revision = saved.revision;
3415
3482
  continue;
3416
3483
  }
3417
3484
  if (stepResolution.action.kind === "yield") {
3485
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3418
3486
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3419
3487
  maxSteps,
3420
3488
  stepCount
@@ -3425,6 +3493,7 @@ var GraphExecutor = class {
3425
3493
  maxSteps,
3426
3494
  stepCount
3427
3495
  });
3496
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3428
3497
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3429
3498
  }
3430
3499
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3445,6 +3514,7 @@ var GraphExecutor = class {
3445
3514
  },
3446
3515
  retryable: false
3447
3516
  }), "GraphExecutor.engine_budget_exhausted"));
3517
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3448
3518
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3449
3519
  this.ephemeralLocals.delete(checkpointKey);
3450
3520
  return result;
@@ -7120,10 +7190,11 @@ var LlmNode = class {
7120
7190
  bridge.handle
7121
7191
  );
7122
7192
  } catch (error) {
7123
- bridge.finalizePartialAnswer();
7193
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7124
7194
  throw error;
7125
7195
  }
7126
7196
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7197
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7127
7198
  switch (decision.kind) {
7128
7199
  case "tool_calls": {
7129
7200
  if (forceFinalAnswer) {
@@ -8330,6 +8401,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8330
8401
  function recordToolProtocolError(params) {
8331
8402
  }
8332
8403
 
8404
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8405
+ var RunRecoveryBlockedError = class extends Error {
8406
+ code = "RUN_RECOVERY_BLOCKED";
8407
+ constructor(message) {
8408
+ super(message);
8409
+ this.name = "RunRecoveryBlockedError";
8410
+ }
8411
+ };
8412
+ var RunPauseRequested = class extends Error {
8413
+ code = "RUN_PAUSE_REQUESTED";
8414
+ constructor(message = "Run paused by user") {
8415
+ super(message);
8416
+ this.name = "RunPauseRequested";
8417
+ }
8418
+ };
8419
+ function isRunPauseSignal(signal) {
8420
+ const reason = signal?.reason;
8421
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8422
+ }
8423
+
8424
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8425
+ async function executeRecoverableTool(input) {
8426
+ const local = input.state.local;
8427
+ if (!local?.commitExecutionBoundary) return input.execute();
8428
+ if (local.executingToolCallId) {
8429
+ if (local.executingToolCallId !== input.call.id) {
8430
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8431
+ }
8432
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8433
+ if (!decision || decision.kind === "blocked") {
8434
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8435
+ }
8436
+ if (decision.kind === "settled") return decision.result;
8437
+ }
8438
+ local.executingToolCallId = input.call.id;
8439
+ await local.commitExecutionBoundary(input.state);
8440
+ const result = await input.execute();
8441
+ if (!result.success && isRunPauseSignal(local.signal)) {
8442
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8443
+ error.name = "AbortError";
8444
+ throw error;
8445
+ }
8446
+ return result;
8447
+ }
8448
+ async function commitToolBoundary(state, result) {
8449
+ if (!state.local?.commitExecutionBoundary) return;
8450
+ delete state.local.executingToolCallId;
8451
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8452
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8453
+ await state.local.commitExecutionBoundary(state);
8454
+ }
8455
+
8333
8456
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8334
8457
  var logger11 = new Logger("ToolNode");
8335
8458
  function isAbortSignal(value) {
@@ -8500,6 +8623,7 @@ var ToolNode = class {
8500
8623
  const events = [];
8501
8624
  while (true) {
8502
8625
  const result = await this.runNextPendingToolCall(state);
8626
+ await commitToolBoundary(state, result);
8503
8627
  if (Array.isArray(result.events) && result.events.length > 0) {
8504
8628
  events.push(...result.events);
8505
8629
  }
@@ -8516,11 +8640,9 @@ var ToolNode = class {
8516
8640
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8517
8641
  const signalRaw = state.local?.signal;
8518
8642
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8519
- settlePendingToolCallsAfterAbort({
8520
- state,
8521
- calls,
8522
- toolCatalog: this.toolRuntime
8523
- });
8643
+ if (!isRunPauseSignal(signalRaw)) {
8644
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8645
+ }
8524
8646
  const abortError = new Error("The user aborted a request.");
8525
8647
  abortError.name = "AbortError";
8526
8648
  throw abortError;
@@ -8659,16 +8781,21 @@ var ToolNode = class {
8659
8781
  tool_calls: [call]
8660
8782
  });
8661
8783
  try {
8662
- const exec = await executeToolWithIdempotency({
8663
- idempotencyKey: execution.idempotencyKey,
8664
- inFlight: this.idempotencyInFlight,
8665
- history: readHistoryEvents(prepared.local),
8666
- toolName: execution.toolName,
8667
- execute: () => this.toolRuntime.executeTool(
8668
- execution.toolName,
8669
- execution.toolArgs,
8670
- prepared.toolContext
8671
- )
8784
+ const exec = await executeRecoverableTool({
8785
+ state,
8786
+ call,
8787
+ context: prepared.toolContext,
8788
+ execute: () => executeToolWithIdempotency({
8789
+ idempotencyKey: execution.idempotencyKey,
8790
+ inFlight: this.idempotencyInFlight,
8791
+ history: readHistoryEvents(prepared.local),
8792
+ toolName: execution.toolName,
8793
+ execute: () => this.toolRuntime.executeTool(
8794
+ execution.toolName,
8795
+ execution.toolArgs,
8796
+ prepared.toolContext
8797
+ )
8798
+ })
8672
8799
  });
8673
8800
  if (exec.success) {
8674
8801
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8748,7 +8875,7 @@ var ToolNode = class {
8748
8875
  bridge: execution.bridge
8749
8876
  });
8750
8877
  } catch (error) {
8751
- if (isToolExecutionAbort(error)) {
8878
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8752
8879
  settleToolCallsAfterExecutionAbort({
8753
8880
  state,
8754
8881
  remainingCalls: calls.slice(1),
@@ -8808,7 +8935,7 @@ var ToolNode = class {
8808
8935
  {
8809
8936
  attachments: context.attachments,
8810
8937
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8811
- ephemeral: context.exec.idempotency?.cacheHit === true,
8938
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8812
8939
  durationMs: context.exec.durationMs
8813
8940
  }
8814
8941
  );
@@ -8865,6 +8992,9 @@ var ToolNode = class {
8865
8992
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8866
8993
  }
8867
8994
  async handleError(context) {
8995
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
8996
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
8997
+ }
8868
8998
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8869
8999
  await this.emitToolDecisionAudit({
8870
9000
  action: "tool.deny",
@@ -9101,16 +9231,16 @@ function requireEventStoreId(eventStoreId) {
9101
9231
  }
9102
9232
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9103
9233
  let lastTimestamp = 0;
9104
- let counter = 0;
9234
+ let counter2 = 0;
9105
9235
  return () => {
9106
9236
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9107
9237
  if (timestamp === lastTimestamp) {
9108
- counter += 1;
9238
+ counter2 += 1;
9109
9239
  } else {
9110
9240
  lastTimestamp = timestamp;
9111
- counter = 0;
9241
+ counter2 = 0;
9112
9242
  }
9113
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9243
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9114
9244
  };
9115
9245
  }
9116
9246
 
@@ -9522,6 +9652,76 @@ function assertNonNegativeSafeInteger(value, field) {
9522
9652
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9523
9653
  }
9524
9654
  }
9655
+ var counter = zod.z.number().int().nonnegative();
9656
+ var executor = zod.z.object({
9657
+ stepCount: counter,
9658
+ phase: zod.z.string().optional(),
9659
+ maxSteps: counter.optional(),
9660
+ remainingSteps: zod.z.number().int().optional(),
9661
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
9662
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
9663
+ lastStepsHintThreshold: counter.optional(),
9664
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9665
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9666
+ runLockedModelId: zod.z.string().optional(),
9667
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
9668
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
9669
+ llmInvocationCount: counter.optional(),
9670
+ lockRequestedModelId: zod.z.boolean().optional(),
9671
+ contextCompaction: zod.z.object({
9672
+ attemptCount: counter,
9673
+ committedCount: counter,
9674
+ lastCommittedFingerprint: zod.z.string().optional()
9675
+ }).strict().optional()
9676
+ }).strict();
9677
+ var checkpoint = zod.z.object({
9678
+ nodeId: zod.z.string().min(1),
9679
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9680
+ revision: counter.optional(),
9681
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9682
+ local: zod.z.object({
9683
+ runId: RunIdSchema.optional(),
9684
+ parentRunId: RunIdSchema.optional(),
9685
+ conversationId: zod.z.string().optional(),
9686
+ turnId: zod.z.string().optional(),
9687
+ request: SerializableJsonRecord.optional(),
9688
+ history: zod.z.array(RuntimeEvent).optional(),
9689
+ newEvents: zod.z.array(RuntimeEvent).optional(),
9690
+ executorLocal: executor.optional(),
9691
+ pendingToolCalls: zod.z.array(zod.z.object({
9692
+ id: ToolCallIdSchema,
9693
+ type: zod.z.literal("function"),
9694
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
9695
+ }).strict()).optional(),
9696
+ executingToolCallId: ToolCallIdSchema.optional(),
9697
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9698
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9699
+ lastToolResult: SerializableJsonRecord.optional(),
9700
+ finalAnswer: zod.z.string().optional(),
9701
+ answerId: zod.z.string().optional(),
9702
+ chunkSeq: counter.optional(),
9703
+ contextUsage: ContextUsageSnapshot.optional()
9704
+ }).passthrough().optional()
9705
+ }).strict();
9706
+ function parseEngineCheckpoint(value) {
9707
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9708
+ for (const key of [
9709
+ "memory",
9710
+ "signal",
9711
+ "toolContext",
9712
+ "runtimeEventSink",
9713
+ "runtimeEventCommitPort",
9714
+ "runtimeFailureFactSink",
9715
+ "summarizationCallbacks",
9716
+ "commitExecutionBoundary",
9717
+ "toolRecoveryPort"
9718
+ ]) {
9719
+ if (result.local && Object.hasOwn(result.local, key)) {
9720
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9721
+ }
9722
+ }
9723
+ return result;
9724
+ }
9525
9725
 
9526
9726
  // src/runtime-kernel/execution/index.ts
9527
9727
  var execution_exports = {};
@@ -9762,12 +9962,33 @@ var RuntimeEventPublisher = class {
9762
9962
  var EventBusEventPersistence = class {
9763
9963
  constructor(options) {
9764
9964
  this.options = options;
9965
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
9765
9966
  }
9766
9967
  options;
9767
9968
  scheduledEventIds = /* @__PURE__ */ new Set();
9768
9969
  writeTail = Promise.resolve();
9769
9970
  firstWriteError;
9770
9971
  connected = false;
9972
+ checkpointWritesActive;
9973
+ checkpointEvents = [];
9974
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9975
+ async commitCheckpoint(checkpointKey, checkpoint2) {
9976
+ const writer = this.options.checkpointWriter;
9977
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9978
+ const events = this.checkpointEvents;
9979
+ this.checkpointEvents = [];
9980
+ await this.enqueueWrite(() => writer({
9981
+ checkpointKey,
9982
+ checkpoint: checkpoint2,
9983
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9984
+ }));
9985
+ }
9986
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
9987
+ finishCheckpointWrites() {
9988
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
9989
+ this.checkpointEvents = [];
9990
+ this.checkpointWritesActive = false;
9991
+ }
9771
9992
  connect() {
9772
9993
  if (this.connected) {
9773
9994
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -9814,14 +10035,22 @@ var EventBusEventPersistence = class {
9814
10035
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
9815
10036
  return;
9816
10037
  }
10038
+ if (this.checkpointWritesActive) {
10039
+ this.scheduledEventIds.add(event.id);
10040
+ this.checkpointEvents.push(event);
10041
+ return;
10042
+ }
9817
10043
  void this.scheduleWrite(event).catch(() => void 0);
9818
10044
  };
9819
10045
  scheduleWrite(event) {
9820
10046
  this.scheduledEventIds.add(event.id);
9821
- const eventStoreId = this.options.nextEventStoreId();
9822
- const write = this.writeTail.then(async () => {
9823
- await this.options.eventStore.append({ eventStoreId, event });
9824
- });
10047
+ return this.enqueueWrite(() => this.options.eventStore.append({
10048
+ eventStoreId: this.options.nextEventStoreId(),
10049
+ event
10050
+ }));
10051
+ }
10052
+ enqueueWrite(operation) {
10053
+ const write = this.writeTail.then(operation);
9825
10054
  this.writeTail = write;
9826
10055
  void write.catch((error) => {
9827
10056
  this.firstWriteError ??= error;
@@ -11228,8 +11457,6 @@ __export(run_supervisor_exports, {
11228
11457
  RunNotFoundError: () => RunNotFoundError,
11229
11458
  runMetaFromRecord: () => runMetaFromRecord
11230
11459
  });
11231
-
11232
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
11233
11460
  function cloneRunRecord(record) {
11234
11461
  return {
11235
11462
  ...record,
@@ -11249,6 +11476,11 @@ function matchesStatus(candidate, filter) {
11249
11476
  }
11250
11477
  var MemoryRunRegistryStore = class {
11251
11478
  store = /* @__PURE__ */ new Map();
11479
+ async compareAndSwap(previous, next) {
11480
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
11481
+ this.store.set(next.runId, cloneRunRecord(next));
11482
+ return true;
11483
+ }
11252
11484
  async save(record) {
11253
11485
  this.store.set(record.runId, cloneRunRecord(record));
11254
11486
  }
@@ -11396,6 +11628,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
11396
11628
  }
11397
11629
  };
11398
11630
 
11631
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
11632
+ async function persistRunTransition(store, previous, next) {
11633
+ if (store.compareAndSwap) {
11634
+ if (!await store.compareAndSwap(previous, next)) {
11635
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
11636
+ }
11637
+ } else {
11638
+ await store.save(next);
11639
+ }
11640
+ }
11641
+
11399
11642
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
11400
11643
  function isRunTerminalStatus(status) {
11401
11644
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -11451,6 +11694,7 @@ var DefaultRunHandle = class {
11451
11694
  parentRunId;
11452
11695
  runRecord;
11453
11696
  abortController;
11697
+ executionId;
11454
11698
  agentSpecSnapshot;
11455
11699
  requestSnapshot;
11456
11700
  transportEventBus;
@@ -11466,6 +11710,9 @@ var DefaultRunHandle = class {
11466
11710
  this.runId = options.runRecord.runId;
11467
11711
  this.parentRunId = options.runRecord.parentRunId;
11468
11712
  this.abortController = options.abortController;
11713
+ const executionId = options.runRecord.metadata?.executionId;
11714
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
11715
+ this.executionId = executionId;
11469
11716
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
11470
11717
  this.requestSnapshot = cloneRequest(options.request);
11471
11718
  this.transportEventBus = options.eventBus;
@@ -11485,8 +11732,9 @@ var DefaultRunHandle = class {
11485
11732
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
11486
11733
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
11487
11734
  */
11488
- replaceExecutionAbortController(controller) {
11735
+ replaceExecutionAbortController(controller, executionId) {
11489
11736
  this.abortController = controller;
11737
+ this.executionId = executionId;
11490
11738
  }
11491
11739
  async spec() {
11492
11740
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -11506,6 +11754,7 @@ var DefaultRunHandle = class {
11506
11754
  this.abortController.abort(opts.reason);
11507
11755
  const latestRecord = await this.registryStore.load(this.runId);
11508
11756
  const baseRecord = latestRecord ?? this.runRecord;
11757
+ this.assertExecutionOwner(baseRecord);
11509
11758
  const transition = decideRunLifecycleTransition(baseRecord.status);
11510
11759
  if (transition.kind === "skip_terminal") {
11511
11760
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -11515,7 +11764,7 @@ var DefaultRunHandle = class {
11515
11764
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11516
11765
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
11517
11766
  };
11518
- await this.registryStore.save(settledRecord);
11767
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
11519
11768
  this.runRecord = { ...settledRecord };
11520
11769
  return;
11521
11770
  }
@@ -11542,7 +11791,7 @@ var DefaultRunHandle = class {
11542
11791
  }
11543
11792
  }
11544
11793
  };
11545
- await this.registryStore.save(nextRecord);
11794
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11546
11795
  this.runRecord = { ...nextRecord };
11547
11796
  await this.auditPort.emit({
11548
11797
  envelopeId: generateAuditEnvelopeId(),
@@ -11650,21 +11899,35 @@ var DefaultRunHandle = class {
11650
11899
  async markFailed(error, patch = {}) {
11651
11900
  await this.saveLifecycleStatus("failed", patch, error);
11652
11901
  }
11653
- async pause(_reason) {
11654
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
11902
+ async pause(reason = "Run paused by user") {
11903
+ const latest = await this.registryStore.load(this.runId);
11904
+ if (latest) this.assertExecutionOwner(latest);
11905
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
11906
+ const next = {
11907
+ ...latest,
11908
+ status: "paused",
11909
+ updatedAt: Date.now(),
11910
+ pauseReason: reason,
11911
+ pausedAt: void 0
11912
+ };
11913
+ await persistRunTransition(this.registryStore, latest, next);
11914
+ this.runRecord = next;
11915
+ this.abortController.abort(new RunPauseRequested(reason));
11655
11916
  }
11656
- async resume() {
11657
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
11917
+ async markPaused(patch = {}) {
11918
+ await this.saveLifecycleStatus("paused", patch);
11658
11919
  }
11659
11920
  async saveLifecycleStatus(status, patch, errorIfAny) {
11660
11921
  const latestRecord = await this.registryStore.load(this.runId);
11661
11922
  const baseRecord = latestRecord ?? this.runRecord;
11662
11923
  const transition = decideRunLifecycleTransition(baseRecord.status);
11924
+ this.assertExecutionOwner(baseRecord);
11925
+ if (status === "running" && baseRecord.status === "paused") return;
11663
11926
  if (transition.kind === "skip_terminal") {
11664
11927
  this.runRecord = { ...baseRecord };
11665
11928
  return;
11666
11929
  }
11667
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
11930
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
11668
11931
  const updatedAt = Date.now();
11669
11932
  const nextRecord = {
11670
11933
  ...baseRecord,
@@ -11672,8 +11935,8 @@ var DefaultRunHandle = class {
11672
11935
  updatedAt,
11673
11936
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11674
11937
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
11675
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11676
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
11938
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11939
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
11677
11940
  errorIfAny,
11678
11941
  metadata: awaitingUserPatch?.eventId ? {
11679
11942
  ...baseRecord.metadata ?? {},
@@ -11684,7 +11947,7 @@ var DefaultRunHandle = class {
11684
11947
  }
11685
11948
  } : baseRecord.metadata
11686
11949
  };
11687
- await this.registryStore.save(nextRecord);
11950
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11688
11951
  this.runRecord = { ...nextRecord };
11689
11952
  if (status === "completed" || status === "failed") {
11690
11953
  this.closeObservationChannel();
@@ -11694,6 +11957,11 @@ var DefaultRunHandle = class {
11694
11957
  forwardTransportEvent = (envelope) => {
11695
11958
  this.observationEventBus.emit("event", envelope);
11696
11959
  };
11960
+ assertExecutionOwner(record) {
11961
+ if (record.metadata?.executionId !== this.executionId) {
11962
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
11963
+ }
11964
+ }
11697
11965
  forwardTransportError = (error) => {
11698
11966
  this.observationEventBus.emit("error", error);
11699
11967
  };
@@ -12024,7 +12292,15 @@ function createRunConcurrencyKeyRegistry() {
12024
12292
  runIdByKey.delete(concurrencyKey);
12025
12293
  }
12026
12294
  }
12027
- return { acquire, release };
12295
+ function transfer(previous, next, concurrencyKey) {
12296
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
12297
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
12298
+ }
12299
+ keyByRunId.delete(previous);
12300
+ keyByRunId.set(next, concurrencyKey);
12301
+ runIdByKey.set(concurrencyKey, next);
12302
+ }
12303
+ return { acquire, release, transfer };
12028
12304
  }
12029
12305
 
12030
12306
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -12075,6 +12351,24 @@ async function recoverRunsOnBoot(options) {
12075
12351
  const outcomes = [];
12076
12352
  for (const record of activeRecords) {
12077
12353
  const updatedAt = options.now();
12354
+ if (await options.canRestoreRun?.(record)) {
12355
+ const metadata = { ...record.metadata };
12356
+ const awaitingUser = metadata.awaitingUser;
12357
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
12358
+ const restored = { ...awaitingUser };
12359
+ Reflect.deleteProperty(restored, "resumeClaim");
12360
+ metadata.awaitingUser = restored;
12361
+ }
12362
+ await persistRunTransition(options.registryStore, record, {
12363
+ ...record,
12364
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
12365
+ pausedAt: record.pausedAt ?? updatedAt,
12366
+ pauseReason: record.pauseReason ?? options.reason,
12367
+ updatedAt,
12368
+ metadata
12369
+ });
12370
+ continue;
12371
+ }
12078
12372
  const nextRecord = {
12079
12373
  ...record,
12080
12374
  status: "failed",
@@ -12092,7 +12386,7 @@ async function recoverRunsOnBoot(options) {
12092
12386
  }
12093
12387
  }
12094
12388
  };
12095
- await options.registryStore.save(nextRecord);
12389
+ await persistRunTransition(options.registryStore, record, nextRecord);
12096
12390
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
12097
12391
  options.notifyTerminal(outcome);
12098
12392
  outcomes.push(outcome);
@@ -12216,8 +12510,13 @@ var DefaultRunSupervisor = class {
12216
12510
  inFlight = /* @__PURE__ */ new Map();
12217
12511
  eventWatchDisposers = /* @__PURE__ */ new Map();
12218
12512
  controlOperations = /* @__PURE__ */ new Map();
12513
+ canRestoreRun;
12219
12514
  constructor(options) {
12515
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
12516
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
12517
+ }
12220
12518
  this.registryStore = options.registryStore;
12519
+ this.canRestoreRun = options.canRestoreRun;
12221
12520
  this.auditPort = options.auditPort;
12222
12521
  this.executor = options.executor;
12223
12522
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -12250,6 +12549,9 @@ var DefaultRunSupervisor = class {
12250
12549
  });
12251
12550
  }
12252
12551
  async registerRun(spec) {
12552
+ if (spec.replacesPausedRun) {
12553
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
12554
+ }
12253
12555
  const runId = spec.runId ?? this.runIdFactory();
12254
12556
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
12255
12557
  throw new RunAlreadyRegisteredError(runId);
@@ -12260,11 +12562,66 @@ var DefaultRunSupervisor = class {
12260
12562
  forwardParentAbortSignal(controller, spec.parentSignal);
12261
12563
  const record = createInitialRunRecord({ runId, spec, startedAt });
12262
12564
  try {
12263
- await this.registryStore.save(record);
12565
+ if (spec.admissionCommit) await spec.admissionCommit(record);
12566
+ else await this.registryStore.save(record);
12264
12567
  } catch (error) {
12265
12568
  this.releaseRunAdmission(runId);
12266
12569
  throw error;
12267
12570
  }
12571
+ return this.attachRun(record, spec, controller);
12572
+ }
12573
+ async registerPausedReplacement(spec) {
12574
+ const target = spec.replacesPausedRun;
12575
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
12576
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
12577
+ }
12578
+ this.getHandle(target.runId);
12579
+ const previous = await this.registryStore.load(target.runId);
12580
+ if (!previous || previous.status !== "paused" || previous.pausedAt === void 0 || previous.updatedAt !== target.expectedUpdatedAt || previous.metadata?.executionId !== target.expectedExecutionId || previous.conversationId !== spec.conversationId || previous.parentRunId !== spec.parentRunId) {
12581
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
12582
+ }
12583
+ const runId = spec.runId ?? this.runIdFactory();
12584
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
12585
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
12586
+ this.runSlotLimiter.release(previous.runId);
12587
+ this.runSlotLimiter.acquire(runId);
12588
+ const now = this.now();
12589
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
12590
+ const next = {
12591
+ ...previous,
12592
+ status: "cancelled",
12593
+ updatedAt: now,
12594
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
12595
+ };
12596
+ try {
12597
+ await spec.admissionCommit(record, { previous, next });
12598
+ } catch (error) {
12599
+ this.runSlotLimiter.release(runId);
12600
+ this.runSlotLimiter.acquire(previous.runId);
12601
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
12602
+ throw error;
12603
+ }
12604
+ this.cleanupRunResources(previous.runId);
12605
+ this.notifyTerminalWaiters(previous.runId);
12606
+ const controller = new AbortController();
12607
+ forwardParentAbortSignal(controller, spec.parentSignal);
12608
+ return this.attachRun(record, spec, controller);
12609
+ }
12610
+ async restoreRun(spec) {
12611
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12612
+ return this.withRunControlLock(spec.runId, async () => {
12613
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
12614
+ const record = await this.registryStore.load(spec.runId);
12615
+ if (!record) throw new RunNotFoundError(spec.runId);
12616
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
12617
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
12618
+ }
12619
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
12620
+ return this.attachRun(record, spec, new AbortController());
12621
+ });
12622
+ }
12623
+ attachRun(record, spec, controller) {
12624
+ const runId = record.runId;
12268
12625
  try {
12269
12626
  const handle = new DefaultRunHandle({
12270
12627
  runRecord: record,
@@ -12362,11 +12719,36 @@ var DefaultRunSupervisor = class {
12362
12719
  registryStore: this.registryStore,
12363
12720
  reason,
12364
12721
  now: this.now,
12365
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
12722
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
12723
+ canRestoreRun: this.canRestoreRun
12366
12724
  });
12367
12725
  }
12368
- async pause(_runId, _reason) {
12369
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
12726
+ async pause(runId, reason) {
12727
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
12728
+ }
12729
+ async resumePausedRun(input) {
12730
+ return this.withRunControlLock(input.runId, async () => {
12731
+ const handle = this.getHandle(input.runId);
12732
+ const record = await this.registryStore.load(input.runId);
12733
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
12734
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12735
+ }
12736
+ await persistRunTransition(this.registryStore, record, {
12737
+ ...record,
12738
+ status: "running",
12739
+ updatedAt: this.now(),
12740
+ pausedAt: void 0,
12741
+ pauseReason: void 0,
12742
+ errorIfAny: void 0,
12743
+ metadata: { ...record.metadata, executionId: input.executionId }
12744
+ });
12745
+ const controller = new AbortController();
12746
+ handle.replaceExecutionAbortController(controller, input.executionId);
12747
+ handle.attachTransportEventBus(input.eventBus);
12748
+ this.controllers.set(input.runId, controller);
12749
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
12750
+ return handle;
12751
+ });
12370
12752
  }
12371
12753
  async claimResume(runId, interaction, eventBus, parentSignal) {
12372
12754
  return this.withRunControlLock(runId, async () => {
@@ -12401,7 +12783,7 @@ var DefaultRunSupervisor = class {
12401
12783
  throw new RunNotFoundError(runId);
12402
12784
  }
12403
12785
  const claimId = generateRunResumeClaimId();
12404
- await this.registryStore.save({
12786
+ await persistRunTransition(this.registryStore, record, {
12405
12787
  ...record,
12406
12788
  updatedAt: this.now(),
12407
12789
  metadata: {
@@ -12489,7 +12871,7 @@ var DefaultRunSupervisor = class {
12489
12871
  }
12490
12872
  const awaitingUserWithoutClaim = { ...awaitingUser };
12491
12873
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12492
- await this.registryStore.save({
12874
+ const nextRecord = {
12493
12875
  ...record,
12494
12876
  status: "running",
12495
12877
  updatedAt: this.now(),
@@ -12499,6 +12881,10 @@ var DefaultRunSupervisor = class {
12499
12881
  metadata: {
12500
12882
  ...record.metadata ?? {},
12501
12883
  ...execution ? { executionId: execution.executionId } : {},
12884
+ ...execution?.inputEventIds ? { resumeInputs: {
12885
+ eventIds: [...execution.inputEventIds],
12886
+ checkpointRevision: pendingInteraction.checkpointRevision
12887
+ } } : {},
12502
12888
  awaitingUser: {
12503
12889
  ...awaitingUserWithoutClaim,
12504
12890
  interaction: {
@@ -12507,10 +12893,12 @@ var DefaultRunSupervisor = class {
12507
12893
  }
12508
12894
  }
12509
12895
  }
12510
- });
12896
+ };
12897
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
12898
+ else await persistRunTransition(this.registryStore, record, nextRecord);
12511
12899
  const executionController = new AbortController();
12512
12900
  forwardParentAbortSignal(executionController, parentSignal);
12513
- handle.replaceExecutionAbortController(executionController);
12901
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
12514
12902
  this.controllers.set(runId, executionController);
12515
12903
  return handle;
12516
12904
  });
@@ -12528,7 +12916,7 @@ var DefaultRunSupervisor = class {
12528
12916
  }
12529
12917
  const awaitingUserWithoutClaim = { ...awaitingUser };
12530
12918
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12531
- await this.registryStore.save({
12919
+ await persistRunTransition(this.registryStore, record, {
12532
12920
  ...record,
12533
12921
  updatedAt: this.now(),
12534
12922
  metadata: {
@@ -12578,13 +12966,13 @@ createConsoleAudit();
12578
12966
 
12579
12967
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
12580
12968
  function createDefaultGraphExecutor(options) {
12581
- const executor = new GraphExecutor(
12969
+ const executor2 = new GraphExecutor(
12582
12970
  options.checkpointer ?? new MemoryCheckpointer(),
12583
12971
  { maxSteps: options.maxSteps ?? 8 }
12584
12972
  );
12585
- executor.registerNode(new UserNode());
12586
- executor.registerNode(options.llmNode);
12587
- executor.registerNode(new ToolNode({
12973
+ executor2.registerNode(new UserNode());
12974
+ executor2.registerNode(options.llmNode);
12975
+ executor2.registerNode(new ToolNode({
12588
12976
  toolRuntime: options.toolRuntime,
12589
12977
  observationPreview: options.observationPreview,
12590
12978
  auditPort: options.auditPort,
@@ -12592,8 +12980,8 @@ function createDefaultGraphExecutor(options) {
12592
12980
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
12593
12981
  modelInputResolver: options.modelInputResolver
12594
12982
  }));
12595
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12596
- return executor;
12983
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12984
+ return executor2;
12597
12985
  }
12598
12986
 
12599
12987
  // src/quickstart/functions/contextTrace.ts
@@ -12872,7 +13260,7 @@ async function runAgent(agent, options) {
12872
13260
  contextBuilder: new QuickstartContextBuilder(agent),
12873
13261
  telemetryPort
12874
13262
  });
12875
- const executor = createDefaultGraphExecutor({
13263
+ const executor2 = createDefaultGraphExecutor({
12876
13264
  llmNode: new LlmNode({ reasoner }),
12877
13265
  toolRuntime,
12878
13266
  observationPreview: createNoopObservationPreview(),
@@ -12908,7 +13296,7 @@ async function runAgent(agent, options) {
12908
13296
  };
12909
13297
  await handle.markRunning({ currentNode: "user" });
12910
13298
  try {
12911
- await executor.prime(checkpointKey, {
13299
+ await executor2.prime(checkpointKey, {
12912
13300
  conversationId,
12913
13301
  turnId,
12914
13302
  request: {
@@ -12925,7 +13313,7 @@ async function runAgent(agent, options) {
12925
13313
  signal: handle.signal,
12926
13314
  runtimeEventSink: (event, source) => publisher.publish(event, source)
12927
13315
  });
12928
- const result = await executor.runUntilYield(checkpointKey);
13316
+ const result = await executor2.runUntilYield(checkpointKey);
12929
13317
  await Promise.all([callbackTail, persistenceTail]);
12930
13318
  await handle.markCompleted({
12931
13319
  currentNode: result.checkpoint.nodeId,