@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
  var promises = require('fs/promises');
9
10
  var path = require('path');
10
11
 
@@ -25,13 +26,17 @@ __export(graph_engine_exports, {
25
26
  MemoryEventStore: () => MemoryEventStore,
26
27
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
27
28
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
29
+ RunPauseRequested: () => RunPauseRequested,
30
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
28
31
  ToolNode: () => ToolNode,
29
32
  UserNode: () => UserNode,
30
33
  WaitUserNode: () => WaitUserNode,
31
34
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
32
35
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
33
36
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
37
+ isRunPauseSignal: () => isRunPauseSignal,
34
38
  isRuntimeFailureFact: () => isRuntimeFailureFact,
39
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
35
40
  readCheckpointContextUsage: () => readCheckpointContextUsage,
36
41
  requireEventStoreId: () => requireEventStoreId,
37
42
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -2399,6 +2404,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2399
2404
  "memory",
2400
2405
  "runtimeEventSink",
2401
2406
  "runtimeEventCommitPort",
2407
+ "commitExecutionBoundary",
2408
+ "toolRecoveryPort",
2402
2409
  "runtimeFailureFactSink",
2403
2410
  "signal",
2404
2411
  "summarizationCallbacks",
@@ -2949,6 +2956,7 @@ var GraphExecutor = class {
2949
2956
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
2950
2957
  };
2951
2958
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
2959
+ this.executionCheckpointPort = config.executionCheckpointPort;
2952
2960
  }
2953
2961
  checkpointer;
2954
2962
  nodes = /* @__PURE__ */ new Map();
@@ -2956,6 +2964,7 @@ var GraphExecutor = class {
2956
2964
  checkpointQueues = /* @__PURE__ */ new Map();
2957
2965
  config;
2958
2966
  telemetryPort;
2967
+ executionCheckpointPort;
2959
2968
  registerNode(node) {
2960
2969
  this.nodes.set(node.id, node);
2961
2970
  }
@@ -2964,6 +2973,7 @@ var GraphExecutor = class {
2964
2973
  }
2965
2974
  sanitize(state) {
2966
2975
  return {
2976
+ ...state,
2967
2977
  nodeId: state.nodeId,
2968
2978
  revision: state.revision ?? 0,
2969
2979
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -2983,8 +2993,9 @@ var GraphExecutor = class {
2983
2993
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
2984
2994
  }
2985
2995
  this.ephemeralLocals.set(checkpointKey, { ...local });
2986
- await this.checkpointer.save(checkpointKey, {
2996
+ await this.commitCheckpoint(checkpointKey, {
2987
2997
  nodeId,
2998
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
2988
2999
  revision: 1,
2989
3000
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
2990
3001
  local: sanitizeCheckpointLocal(local)
@@ -2995,6 +3006,33 @@ var GraphExecutor = class {
2995
3006
  );
2996
3007
  });
2997
3008
  }
3009
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3010
+ async continueSession(checkpointKey, input) {
3011
+ if (!this.executionCheckpointPort) {
3012
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3013
+ }
3014
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3015
+ const current = await this.checkpointer.load(checkpointKey);
3016
+ if (!current || current.revision !== input.expectedRevision) {
3017
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3018
+ }
3019
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3020
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3021
+ }
3022
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3023
+ return { checkpoint: current, events: [], stepCount: 0 };
3024
+ }
3025
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3026
+ try {
3027
+ return await this.runUntilYieldQueued(
3028
+ checkpointKey,
3029
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3030
+ );
3031
+ } finally {
3032
+ this.ephemeralLocals.delete(checkpointKey);
3033
+ }
3034
+ });
3035
+ }
2998
3036
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
2999
3037
  async resumeSession(checkpointKey, input) {
3000
3038
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3015,17 +3053,21 @@ var GraphExecutor = class {
3015
3053
  );
3016
3054
  }
3017
3055
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3056
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3057
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3058
+ }
3018
3059
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3019
- await this.checkpointer.save(checkpointKey, {
3060
+ await this.commitCheckpoint(checkpointKey, {
3020
3061
  ...current,
3021
3062
  nodeId: input.nodeId ?? "llm",
3063
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3022
3064
  revision: currentRevision + 1,
3023
3065
  local: sanitizeCheckpointLocal(resumedLocal)
3024
3066
  });
3025
3067
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3026
3068
  return this.runUntilYieldQueued(
3027
3069
  checkpointKey,
3028
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3070
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3029
3071
  );
3030
3072
  });
3031
3073
  }
@@ -3116,16 +3158,23 @@ var GraphExecutor = class {
3116
3158
  };
3117
3159
  }
3118
3160
  async saveCheckpoint(checkpointKey, state) {
3119
- const checkpoint = this.sanitize({
3161
+ const checkpoint2 = this.sanitize({
3120
3162
  ...state,
3121
3163
  revision: (state.revision ?? 0) + 1
3122
3164
  });
3123
- await this.checkpointer.save(checkpointKey, checkpoint);
3124
- return checkpoint;
3165
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3166
+ return checkpoint2;
3167
+ }
3168
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3169
+ if (this.executionCheckpointPort) {
3170
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3171
+ } else {
3172
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3173
+ }
3125
3174
  }
3126
3175
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3127
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3128
- return { events, checkpoint, stepCount };
3176
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3177
+ return { events, checkpoint: checkpoint2, stepCount };
3129
3178
  }
3130
3179
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3131
3180
  let state = initialState;
@@ -3135,6 +3184,15 @@ var GraphExecutor = class {
3135
3184
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3136
3185
  local: { ...state.local || {}, ...ephemeral }
3137
3186
  };
3187
+ if (this.executionCheckpointPort) {
3188
+ state.local = {
3189
+ ...state.local,
3190
+ commitExecutionBoundary: async (boundary) => {
3191
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3192
+ boundary.revision = saved.revision;
3193
+ }
3194
+ };
3195
+ }
3138
3196
  const isAbortSignal2 = (v) => {
3139
3197
  return v !== null && typeof v === "object" && "aborted" in v;
3140
3198
  };
@@ -3144,11 +3202,12 @@ var GraphExecutor = class {
3144
3202
  throw err;
3145
3203
  };
3146
3204
  let stepCount = 0;
3205
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3147
3206
  let allEvents = [];
3148
3207
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3149
3208
  maxSteps
3150
3209
  });
3151
- while (stepCount < maxSteps) {
3210
+ while (previousSteps + stepCount < maxSteps) {
3152
3211
  stepCount += 1;
3153
3212
  reportStepsUsed(stepCount);
3154
3213
  const signalRaw = state.local?.signal;
@@ -3160,7 +3219,7 @@ var GraphExecutor = class {
3160
3219
  const stepPreparation = prepareGraphStep({
3161
3220
  state,
3162
3221
  maxSteps,
3163
- stepCount
3222
+ stepCount: previousSteps + stepCount
3164
3223
  });
3165
3224
  state = stepPreparation.state;
3166
3225
  const node = this.nodes.get(state.nodeId);
@@ -3169,6 +3228,7 @@ var GraphExecutor = class {
3169
3228
  maxSteps,
3170
3229
  stepCount
3171
3230
  });
3231
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3172
3232
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3173
3233
  this.ephemeralLocals.delete(checkpointKey);
3174
3234
  return result3;
@@ -3178,6 +3238,11 @@ var GraphExecutor = class {
3178
3238
  stepCount,
3179
3239
  nodeId: state.nodeId
3180
3240
  });
3241
+ if (this.executionCheckpointPort) {
3242
+ state.executionStatus = "executing";
3243
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3244
+ state.revision = saved.revision;
3245
+ }
3181
3246
  const result2 = await runGraphNodeWithTelemetry({
3182
3247
  node,
3183
3248
  state,
@@ -3202,10 +3267,13 @@ var GraphExecutor = class {
3202
3267
  fromNodeId: stepResolution.action.fromNodeId,
3203
3268
  nextNodeId: stepResolution.action.nextNodeId
3204
3269
  });
3205
- await this.saveCheckpoint(checkpointKey, state);
3270
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3271
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3272
+ state.revision = saved.revision;
3206
3273
  continue;
3207
3274
  }
3208
3275
  if (stepResolution.action.kind === "yield") {
3276
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3209
3277
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3210
3278
  maxSteps,
3211
3279
  stepCount
@@ -3216,6 +3284,7 @@ var GraphExecutor = class {
3216
3284
  maxSteps,
3217
3285
  stepCount
3218
3286
  });
3287
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3219
3288
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3220
3289
  }
3221
3290
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3236,6 +3305,7 @@ var GraphExecutor = class {
3236
3305
  },
3237
3306
  retryable: false
3238
3307
  }), "GraphExecutor.engine_budget_exhausted"));
3308
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3239
3309
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3240
3310
  this.ephemeralLocals.delete(checkpointKey);
3241
3311
  return result;
@@ -7129,10 +7199,11 @@ var LlmNode = class {
7129
7199
  bridge.handle
7130
7200
  );
7131
7201
  } catch (error) {
7132
- bridge.finalizePartialAnswer();
7202
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7133
7203
  throw error;
7134
7204
  }
7135
7205
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7206
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7136
7207
  switch (decision.kind) {
7137
7208
  case "tool_calls": {
7138
7209
  if (forceFinalAnswer) {
@@ -8400,6 +8471,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8400
8471
  function recordToolProtocolError(params) {
8401
8472
  }
8402
8473
 
8474
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8475
+ var RunRecoveryBlockedError = class extends Error {
8476
+ code = "RUN_RECOVERY_BLOCKED";
8477
+ constructor(message) {
8478
+ super(message);
8479
+ this.name = "RunRecoveryBlockedError";
8480
+ }
8481
+ };
8482
+ var RunPauseRequested = class extends Error {
8483
+ code = "RUN_PAUSE_REQUESTED";
8484
+ constructor(message = "Run paused by user") {
8485
+ super(message);
8486
+ this.name = "RunPauseRequested";
8487
+ }
8488
+ };
8489
+ function isRunPauseSignal(signal) {
8490
+ const reason = signal?.reason;
8491
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8492
+ }
8493
+
8494
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8495
+ async function executeRecoverableTool(input) {
8496
+ const local = input.state.local;
8497
+ if (!local?.commitExecutionBoundary) return input.execute();
8498
+ if (local.executingToolCallId) {
8499
+ if (local.executingToolCallId !== input.call.id) {
8500
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8501
+ }
8502
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8503
+ if (!decision || decision.kind === "blocked") {
8504
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8505
+ }
8506
+ if (decision.kind === "settled") return decision.result;
8507
+ }
8508
+ local.executingToolCallId = input.call.id;
8509
+ await local.commitExecutionBoundary(input.state);
8510
+ const result = await input.execute();
8511
+ if (!result.success && isRunPauseSignal(local.signal)) {
8512
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8513
+ error.name = "AbortError";
8514
+ throw error;
8515
+ }
8516
+ return result;
8517
+ }
8518
+ async function commitToolBoundary(state, result) {
8519
+ if (!state.local?.commitExecutionBoundary) return;
8520
+ delete state.local.executingToolCallId;
8521
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8522
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8523
+ await state.local.commitExecutionBoundary(state);
8524
+ }
8525
+
8403
8526
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8404
8527
  var logger11 = new Logger("ToolNode");
8405
8528
  function isAbortSignal(value) {
@@ -8570,6 +8693,7 @@ var ToolNode = class {
8570
8693
  const events = [];
8571
8694
  while (true) {
8572
8695
  const result = await this.runNextPendingToolCall(state);
8696
+ await commitToolBoundary(state, result);
8573
8697
  if (Array.isArray(result.events) && result.events.length > 0) {
8574
8698
  events.push(...result.events);
8575
8699
  }
@@ -8586,11 +8710,9 @@ var ToolNode = class {
8586
8710
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8587
8711
  const signalRaw = state.local?.signal;
8588
8712
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8589
- settlePendingToolCallsAfterAbort({
8590
- state,
8591
- calls,
8592
- toolCatalog: this.toolRuntime
8593
- });
8713
+ if (!isRunPauseSignal(signalRaw)) {
8714
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8715
+ }
8594
8716
  const abortError = new Error("The user aborted a request.");
8595
8717
  abortError.name = "AbortError";
8596
8718
  throw abortError;
@@ -8729,16 +8851,21 @@ var ToolNode = class {
8729
8851
  tool_calls: [call]
8730
8852
  });
8731
8853
  try {
8732
- const exec = await executeToolWithIdempotency({
8733
- idempotencyKey: execution.idempotencyKey,
8734
- inFlight: this.idempotencyInFlight,
8735
- history: readHistoryEvents(prepared.local),
8736
- toolName: execution.toolName,
8737
- execute: () => this.toolRuntime.executeTool(
8738
- execution.toolName,
8739
- execution.toolArgs,
8740
- prepared.toolContext
8741
- )
8854
+ const exec = await executeRecoverableTool({
8855
+ state,
8856
+ call,
8857
+ context: prepared.toolContext,
8858
+ execute: () => executeToolWithIdempotency({
8859
+ idempotencyKey: execution.idempotencyKey,
8860
+ inFlight: this.idempotencyInFlight,
8861
+ history: readHistoryEvents(prepared.local),
8862
+ toolName: execution.toolName,
8863
+ execute: () => this.toolRuntime.executeTool(
8864
+ execution.toolName,
8865
+ execution.toolArgs,
8866
+ prepared.toolContext
8867
+ )
8868
+ })
8742
8869
  });
8743
8870
  if (exec.success) {
8744
8871
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8818,7 +8945,7 @@ var ToolNode = class {
8818
8945
  bridge: execution.bridge
8819
8946
  });
8820
8947
  } catch (error) {
8821
- if (isToolExecutionAbort(error)) {
8948
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8822
8949
  settleToolCallsAfterExecutionAbort({
8823
8950
  state,
8824
8951
  remainingCalls: calls.slice(1),
@@ -8878,7 +9005,7 @@ var ToolNode = class {
8878
9005
  {
8879
9006
  attachments: context.attachments,
8880
9007
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8881
- ephemeral: context.exec.idempotency?.cacheHit === true,
9008
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8882
9009
  durationMs: context.exec.durationMs
8883
9010
  }
8884
9011
  );
@@ -8935,6 +9062,9 @@ var ToolNode = class {
8935
9062
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8936
9063
  }
8937
9064
  async handleError(context) {
9065
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9066
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9067
+ }
8938
9068
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8939
9069
  await this.emitToolDecisionAudit({
8940
9070
  action: "tool.deny",
@@ -9171,16 +9301,16 @@ function requireEventStoreId(eventStoreId) {
9171
9301
  }
9172
9302
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9173
9303
  let lastTimestamp = 0;
9174
- let counter = 0;
9304
+ let counter2 = 0;
9175
9305
  return () => {
9176
9306
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9177
9307
  if (timestamp === lastTimestamp) {
9178
- counter += 1;
9308
+ counter2 += 1;
9179
9309
  } else {
9180
9310
  lastTimestamp = timestamp;
9181
- counter = 0;
9311
+ counter2 = 0;
9182
9312
  }
9183
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9313
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9184
9314
  };
9185
9315
  }
9186
9316
 
@@ -9592,6 +9722,76 @@ function assertNonNegativeSafeInteger(value, field) {
9592
9722
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9593
9723
  }
9594
9724
  }
9725
+ var counter = zod.z.number().int().nonnegative();
9726
+ var executor = zod.z.object({
9727
+ stepCount: counter,
9728
+ phase: zod.z.string().optional(),
9729
+ maxSteps: counter.optional(),
9730
+ remainingSteps: zod.z.number().int().optional(),
9731
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
9732
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
9733
+ lastStepsHintThreshold: counter.optional(),
9734
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9735
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9736
+ runLockedModelId: zod.z.string().optional(),
9737
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
9738
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
9739
+ llmInvocationCount: counter.optional(),
9740
+ lockRequestedModelId: zod.z.boolean().optional(),
9741
+ contextCompaction: zod.z.object({
9742
+ attemptCount: counter,
9743
+ committedCount: counter,
9744
+ lastCommittedFingerprint: zod.z.string().optional()
9745
+ }).strict().optional()
9746
+ }).strict();
9747
+ var checkpoint = zod.z.object({
9748
+ nodeId: zod.z.string().min(1),
9749
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9750
+ revision: counter.optional(),
9751
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9752
+ local: zod.z.object({
9753
+ runId: RunIdSchema.optional(),
9754
+ parentRunId: RunIdSchema.optional(),
9755
+ conversationId: zod.z.string().optional(),
9756
+ turnId: zod.z.string().optional(),
9757
+ request: SerializableJsonRecord.optional(),
9758
+ history: zod.z.array(RuntimeEvent).optional(),
9759
+ newEvents: zod.z.array(RuntimeEvent).optional(),
9760
+ executorLocal: executor.optional(),
9761
+ pendingToolCalls: zod.z.array(zod.z.object({
9762
+ id: ToolCallIdSchema,
9763
+ type: zod.z.literal("function"),
9764
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
9765
+ }).strict()).optional(),
9766
+ executingToolCallId: ToolCallIdSchema.optional(),
9767
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9768
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9769
+ lastToolResult: SerializableJsonRecord.optional(),
9770
+ finalAnswer: zod.z.string().optional(),
9771
+ answerId: zod.z.string().optional(),
9772
+ chunkSeq: counter.optional(),
9773
+ contextUsage: ContextUsageSnapshot.optional()
9774
+ }).passthrough().optional()
9775
+ }).strict();
9776
+ function parseEngineCheckpoint(value) {
9777
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9778
+ for (const key of [
9779
+ "memory",
9780
+ "signal",
9781
+ "toolContext",
9782
+ "runtimeEventSink",
9783
+ "runtimeEventCommitPort",
9784
+ "runtimeFailureFactSink",
9785
+ "summarizationCallbacks",
9786
+ "commitExecutionBoundary",
9787
+ "toolRecoveryPort"
9788
+ ]) {
9789
+ if (result.local && Object.hasOwn(result.local, key)) {
9790
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9791
+ }
9792
+ }
9793
+ return result;
9794
+ }
9595
9795
 
9596
9796
  // src/runtime-kernel/tools/index.ts
9597
9797
  var tools_exports = {};
@@ -10043,12 +10243,33 @@ var RuntimeEventPublisher = class {
10043
10243
  var EventBusEventPersistence = class {
10044
10244
  constructor(options) {
10045
10245
  this.options = options;
10246
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10046
10247
  }
10047
10248
  options;
10048
10249
  scheduledEventIds = /* @__PURE__ */ new Set();
10049
10250
  writeTail = Promise.resolve();
10050
10251
  firstWriteError;
10051
10252
  connected = false;
10253
+ checkpointWritesActive;
10254
+ checkpointEvents = [];
10255
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10256
+ async commitCheckpoint(checkpointKey, checkpoint2) {
10257
+ const writer = this.options.checkpointWriter;
10258
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10259
+ const events = this.checkpointEvents;
10260
+ this.checkpointEvents = [];
10261
+ await this.enqueueWrite(() => writer({
10262
+ checkpointKey,
10263
+ checkpoint: checkpoint2,
10264
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10265
+ }));
10266
+ }
10267
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10268
+ finishCheckpointWrites() {
10269
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10270
+ this.checkpointEvents = [];
10271
+ this.checkpointWritesActive = false;
10272
+ }
10052
10273
  connect() {
10053
10274
  if (this.connected) {
10054
10275
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10095,14 +10316,22 @@ var EventBusEventPersistence = class {
10095
10316
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10096
10317
  return;
10097
10318
  }
10319
+ if (this.checkpointWritesActive) {
10320
+ this.scheduledEventIds.add(event.id);
10321
+ this.checkpointEvents.push(event);
10322
+ return;
10323
+ }
10098
10324
  void this.scheduleWrite(event).catch(() => void 0);
10099
10325
  };
10100
10326
  scheduleWrite(event) {
10101
10327
  this.scheduledEventIds.add(event.id);
10102
- const eventStoreId = this.options.nextEventStoreId();
10103
- const write = this.writeTail.then(async () => {
10104
- await this.options.eventStore.append({ eventStoreId, event });
10105
- });
10328
+ return this.enqueueWrite(() => this.options.eventStore.append({
10329
+ eventStoreId: this.options.nextEventStoreId(),
10330
+ event
10331
+ }));
10332
+ }
10333
+ enqueueWrite(operation) {
10334
+ const write = this.writeTail.then(operation);
10106
10335
  this.writeTail = write;
10107
10336
  void write.catch((error) => {
10108
10337
  this.firstWriteError ??= error;
@@ -11724,15 +11953,15 @@ function hasSeedHistoryPrefix(history, seedHistory) {
11724
11953
  }
11725
11954
  return true;
11726
11955
  }
11727
- function readCheckpointHistory(checkpoint) {
11728
- if (!checkpoint?.local) return [];
11729
- const history = checkpoint.local.history;
11956
+ function readCheckpointHistory(checkpoint2) {
11957
+ if (!checkpoint2?.local) return [];
11958
+ const history = checkpoint2.local.history;
11730
11959
  if (!Array.isArray(history)) return [];
11731
11960
  return parseRuntimeEvents(history);
11732
11961
  }
11733
11962
  async function recoverChildRunEventsFromCheckpoint(params) {
11734
- const checkpoint = await params.checkpointer.load(params.checkpointKey);
11735
- const history = readCheckpointHistory(checkpoint);
11963
+ const checkpoint2 = await params.checkpointer.load(params.checkpointKey);
11964
+ const history = readCheckpointHistory(checkpoint2);
11736
11965
  if (history.length === 0) {
11737
11966
  return [];
11738
11967
  }
@@ -11823,6 +12052,9 @@ var ChildRunInvoker = class {
11823
12052
  explicitConversationId: conversationId,
11824
12053
  parentToolContext
11825
12054
  });
12055
+ if (config.persistence?.expectedRevision !== void 0) {
12056
+ return this.continueChild(config, childRunId, runtimeConversationId);
12057
+ }
11826
12058
  const turnId = generateTurnId();
11827
12059
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
11828
12060
  conversationId: runtimeConversationId,
@@ -11830,21 +12062,8 @@ var ChildRunInvoker = class {
11830
12062
  maxSteps,
11831
12063
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
11832
12064
  });
11833
- const checkpointer = new MemoryCheckpointer();
11834
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
11835
- const llmNode = this.createLlmNode();
11836
- const toolNode = new ToolNode({
11837
- toolRuntime: this.toolRuntime,
11838
- observationPreview: this.observationPreview,
11839
- telemetryPort: this.telemetryPort,
11840
- auditPort: this.auditPort,
11841
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
11842
- modelInputResolver: this.modelInputResolver
11843
- });
11844
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
11845
- graphExecutor.registerNode(llmNode);
11846
- graphExecutor.registerNode(toolNode);
11847
- graphExecutor.registerNode(waitUserNode);
12065
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
12066
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
11848
12067
  const childUserInput = createChildRunUserInput({
11849
12068
  id: generateRuntimeEventId(),
11850
12069
  conversationId: runtimeConversationId,
@@ -11924,6 +12143,7 @@ var ChildRunInvoker = class {
11924
12143
  ...abortSignal ? { signal: abortSignal } : {},
11925
12144
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
11926
12145
  runtimeEventSink,
12146
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
11927
12147
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
11928
12148
  systemPrompt
11929
12149
  };
@@ -11964,6 +12184,7 @@ var ChildRunInvoker = class {
11964
12184
  eventToMessageConverter: this.eventToMessageConverter
11965
12185
  });
11966
12186
  } catch (err) {
12187
+ if (config.persistence) throw err;
11967
12188
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
11968
12189
  checkpointer,
11969
12190
  checkpointKey: internalCheckpointKey,
@@ -12002,7 +12223,7 @@ var ChildRunInvoker = class {
12002
12223
  events: allEvents,
12003
12224
  eventToMessageConverter: this.eventToMessageConverter
12004
12225
  });
12005
- await checkpointer.clear(internalCheckpointKey);
12226
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12006
12227
  return {
12007
12228
  success: !error && !cancelled,
12008
12229
  runId: childRunId,
@@ -12019,6 +12240,66 @@ var ChildRunInvoker = class {
12019
12240
  error
12020
12241
  };
12021
12242
  }
12243
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12244
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12245
+ graph.registerNode(this.createLlmNode());
12246
+ graph.registerNode(new ToolNode({
12247
+ toolRuntime: this.toolRuntime,
12248
+ observationPreview: this.observationPreview,
12249
+ telemetryPort: this.telemetryPort,
12250
+ auditPort: this.auditPort,
12251
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12252
+ modelInputResolver: this.modelInputResolver
12253
+ }));
12254
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12255
+ return graph;
12256
+ }
12257
+ async continueChild(config, runId, conversationId) {
12258
+ const persistence = config.persistence;
12259
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12260
+ const checkpoint2 = await persistence.checkpointer.load(runId);
12261
+ if (!checkpoint2 || checkpoint2.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12262
+ const local = readGraphAgentLocal({ ...checkpoint2.local, runtimeEventSink: config.runtimeEventSink });
12263
+ const request = local.request;
12264
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12265
+ const context = createChildRunToolContext({
12266
+ parentToolContext: config.parentToolContext,
12267
+ conversationId,
12268
+ turnId: local.turnId,
12269
+ runId,
12270
+ parentRunId: config.parentRunId,
12271
+ userQuery: request.query,
12272
+ modelId: request.model_id,
12273
+ seedHistory: local.history,
12274
+ abortSignal: config.abortSignal
12275
+ });
12276
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12277
+ const result = await graph.continueSession(runId, {
12278
+ expectedRevision: persistence.expectedRevision,
12279
+ capabilities: {
12280
+ toolContext: context,
12281
+ signal: config.abortSignal,
12282
+ runtimeEventSink: config.runtimeEventSink,
12283
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12284
+ toolRecoveryPort: persistence.toolRecoveryPort
12285
+ }
12286
+ });
12287
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12288
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12289
+ const finalAnswer = extractFinalAnswer(events);
12290
+ return {
12291
+ runId,
12292
+ parentRunId: config.parentRunId,
12293
+ subrunId: runId,
12294
+ success: true,
12295
+ events,
12296
+ finalAnswer,
12297
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12298
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12299
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12300
+ toolset: { availableTools: request.availableTools }
12301
+ };
12302
+ }
12022
12303
  };
12023
12304
  function isAbortError2(error) {
12024
12305
  return error instanceof Error && error.name === "AbortError";
@@ -12420,8 +12701,6 @@ __export(run_supervisor_exports, {
12420
12701
  RunNotFoundError: () => RunNotFoundError,
12421
12702
  runMetaFromRecord: () => runMetaFromRecord
12422
12703
  });
12423
-
12424
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12425
12704
  function cloneRunRecord(record) {
12426
12705
  return {
12427
12706
  ...record,
@@ -12441,6 +12720,11 @@ function matchesStatus(candidate, filter) {
12441
12720
  }
12442
12721
  var MemoryRunRegistryStore = class {
12443
12722
  store = /* @__PURE__ */ new Map();
12723
+ async compareAndSwap(previous, next) {
12724
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12725
+ this.store.set(next.runId, cloneRunRecord(next));
12726
+ return true;
12727
+ }
12444
12728
  async save(record) {
12445
12729
  this.store.set(record.runId, cloneRunRecord(record));
12446
12730
  }
@@ -12588,6 +12872,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12588
12872
  }
12589
12873
  };
12590
12874
 
12875
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
12876
+ async function persistRunTransition(store, previous, next) {
12877
+ if (store.compareAndSwap) {
12878
+ if (!await store.compareAndSwap(previous, next)) {
12879
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
12880
+ }
12881
+ } else {
12882
+ await store.save(next);
12883
+ }
12884
+ }
12885
+
12591
12886
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12592
12887
  function isRunTerminalStatus(status) {
12593
12888
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12643,6 +12938,7 @@ var DefaultRunHandle = class {
12643
12938
  parentRunId;
12644
12939
  runRecord;
12645
12940
  abortController;
12941
+ executionId;
12646
12942
  agentSpecSnapshot;
12647
12943
  requestSnapshot;
12648
12944
  transportEventBus;
@@ -12658,6 +12954,9 @@ var DefaultRunHandle = class {
12658
12954
  this.runId = options.runRecord.runId;
12659
12955
  this.parentRunId = options.runRecord.parentRunId;
12660
12956
  this.abortController = options.abortController;
12957
+ const executionId = options.runRecord.metadata?.executionId;
12958
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
12959
+ this.executionId = executionId;
12661
12960
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12662
12961
  this.requestSnapshot = cloneRequest(options.request);
12663
12962
  this.transportEventBus = options.eventBus;
@@ -12677,8 +12976,9 @@ var DefaultRunHandle = class {
12677
12976
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12678
12977
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12679
12978
  */
12680
- replaceExecutionAbortController(controller) {
12979
+ replaceExecutionAbortController(controller, executionId) {
12681
12980
  this.abortController = controller;
12981
+ this.executionId = executionId;
12682
12982
  }
12683
12983
  async spec() {
12684
12984
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12698,6 +12998,7 @@ var DefaultRunHandle = class {
12698
12998
  this.abortController.abort(opts.reason);
12699
12999
  const latestRecord = await this.registryStore.load(this.runId);
12700
13000
  const baseRecord = latestRecord ?? this.runRecord;
13001
+ this.assertExecutionOwner(baseRecord);
12701
13002
  const transition = decideRunLifecycleTransition(baseRecord.status);
12702
13003
  if (transition.kind === "skip_terminal") {
12703
13004
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12707,7 +13008,7 @@ var DefaultRunHandle = class {
12707
13008
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12708
13009
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12709
13010
  };
12710
- await this.registryStore.save(settledRecord);
13011
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12711
13012
  this.runRecord = { ...settledRecord };
12712
13013
  return;
12713
13014
  }
@@ -12734,7 +13035,7 @@ var DefaultRunHandle = class {
12734
13035
  }
12735
13036
  }
12736
13037
  };
12737
- await this.registryStore.save(nextRecord);
13038
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12738
13039
  this.runRecord = { ...nextRecord };
12739
13040
  await this.auditPort.emit({
12740
13041
  envelopeId: generateAuditEnvelopeId(),
@@ -12842,21 +13143,35 @@ var DefaultRunHandle = class {
12842
13143
  async markFailed(error, patch = {}) {
12843
13144
  await this.saveLifecycleStatus("failed", patch, error);
12844
13145
  }
12845
- async pause(_reason) {
12846
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13146
+ async pause(reason = "Run paused by user") {
13147
+ const latest = await this.registryStore.load(this.runId);
13148
+ if (latest) this.assertExecutionOwner(latest);
13149
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13150
+ const next = {
13151
+ ...latest,
13152
+ status: "paused",
13153
+ updatedAt: Date.now(),
13154
+ pauseReason: reason,
13155
+ pausedAt: void 0
13156
+ };
13157
+ await persistRunTransition(this.registryStore, latest, next);
13158
+ this.runRecord = next;
13159
+ this.abortController.abort(new RunPauseRequested(reason));
12847
13160
  }
12848
- async resume() {
12849
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13161
+ async markPaused(patch = {}) {
13162
+ await this.saveLifecycleStatus("paused", patch);
12850
13163
  }
12851
13164
  async saveLifecycleStatus(status, patch, errorIfAny) {
12852
13165
  const latestRecord = await this.registryStore.load(this.runId);
12853
13166
  const baseRecord = latestRecord ?? this.runRecord;
12854
13167
  const transition = decideRunLifecycleTransition(baseRecord.status);
13168
+ this.assertExecutionOwner(baseRecord);
13169
+ if (status === "running" && baseRecord.status === "paused") return;
12855
13170
  if (transition.kind === "skip_terminal") {
12856
13171
  this.runRecord = { ...baseRecord };
12857
13172
  return;
12858
13173
  }
12859
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13174
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
12860
13175
  const updatedAt = Date.now();
12861
13176
  const nextRecord = {
12862
13177
  ...baseRecord,
@@ -12864,8 +13179,8 @@ var DefaultRunHandle = class {
12864
13179
  updatedAt,
12865
13180
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12866
13181
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
12867
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
12868
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13182
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13183
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
12869
13184
  errorIfAny,
12870
13185
  metadata: awaitingUserPatch?.eventId ? {
12871
13186
  ...baseRecord.metadata ?? {},
@@ -12876,7 +13191,7 @@ var DefaultRunHandle = class {
12876
13191
  }
12877
13192
  } : baseRecord.metadata
12878
13193
  };
12879
- await this.registryStore.save(nextRecord);
13194
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12880
13195
  this.runRecord = { ...nextRecord };
12881
13196
  if (status === "completed" || status === "failed") {
12882
13197
  this.closeObservationChannel();
@@ -12886,6 +13201,11 @@ var DefaultRunHandle = class {
12886
13201
  forwardTransportEvent = (envelope) => {
12887
13202
  this.observationEventBus.emit("event", envelope);
12888
13203
  };
13204
+ assertExecutionOwner(record) {
13205
+ if (record.metadata?.executionId !== this.executionId) {
13206
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13207
+ }
13208
+ }
12889
13209
  forwardTransportError = (error) => {
12890
13210
  this.observationEventBus.emit("error", error);
12891
13211
  };
@@ -13216,7 +13536,15 @@ function createRunConcurrencyKeyRegistry() {
13216
13536
  runIdByKey.delete(concurrencyKey);
13217
13537
  }
13218
13538
  }
13219
- return { acquire, release };
13539
+ function transfer(previous, next, concurrencyKey) {
13540
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
13541
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
13542
+ }
13543
+ keyByRunId.delete(previous);
13544
+ keyByRunId.set(next, concurrencyKey);
13545
+ runIdByKey.set(concurrencyKey, next);
13546
+ }
13547
+ return { acquire, release, transfer };
13220
13548
  }
13221
13549
 
13222
13550
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -13267,6 +13595,24 @@ async function recoverRunsOnBoot(options) {
13267
13595
  const outcomes = [];
13268
13596
  for (const record of activeRecords) {
13269
13597
  const updatedAt = options.now();
13598
+ if (await options.canRestoreRun?.(record)) {
13599
+ const metadata = { ...record.metadata };
13600
+ const awaitingUser = metadata.awaitingUser;
13601
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13602
+ const restored = { ...awaitingUser };
13603
+ Reflect.deleteProperty(restored, "resumeClaim");
13604
+ metadata.awaitingUser = restored;
13605
+ }
13606
+ await persistRunTransition(options.registryStore, record, {
13607
+ ...record,
13608
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13609
+ pausedAt: record.pausedAt ?? updatedAt,
13610
+ pauseReason: record.pauseReason ?? options.reason,
13611
+ updatedAt,
13612
+ metadata
13613
+ });
13614
+ continue;
13615
+ }
13270
13616
  const nextRecord = {
13271
13617
  ...record,
13272
13618
  status: "failed",
@@ -13284,7 +13630,7 @@ async function recoverRunsOnBoot(options) {
13284
13630
  }
13285
13631
  }
13286
13632
  };
13287
- await options.registryStore.save(nextRecord);
13633
+ await persistRunTransition(options.registryStore, record, nextRecord);
13288
13634
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13289
13635
  options.notifyTerminal(outcome);
13290
13636
  outcomes.push(outcome);
@@ -13408,8 +13754,13 @@ var DefaultRunSupervisor = class {
13408
13754
  inFlight = /* @__PURE__ */ new Map();
13409
13755
  eventWatchDisposers = /* @__PURE__ */ new Map();
13410
13756
  controlOperations = /* @__PURE__ */ new Map();
13757
+ canRestoreRun;
13411
13758
  constructor(options) {
13759
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13760
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13761
+ }
13412
13762
  this.registryStore = options.registryStore;
13763
+ this.canRestoreRun = options.canRestoreRun;
13413
13764
  this.auditPort = options.auditPort;
13414
13765
  this.executor = options.executor;
13415
13766
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13442,6 +13793,9 @@ var DefaultRunSupervisor = class {
13442
13793
  });
13443
13794
  }
13444
13795
  async registerRun(spec) {
13796
+ if (spec.replacesPausedRun) {
13797
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
13798
+ }
13445
13799
  const runId = spec.runId ?? this.runIdFactory();
13446
13800
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
13447
13801
  throw new RunAlreadyRegisteredError(runId);
@@ -13452,11 +13806,66 @@ var DefaultRunSupervisor = class {
13452
13806
  forwardParentAbortSignal(controller, spec.parentSignal);
13453
13807
  const record = createInitialRunRecord({ runId, spec, startedAt });
13454
13808
  try {
13455
- await this.registryStore.save(record);
13809
+ if (spec.admissionCommit) await spec.admissionCommit(record);
13810
+ else await this.registryStore.save(record);
13456
13811
  } catch (error) {
13457
13812
  this.releaseRunAdmission(runId);
13458
13813
  throw error;
13459
13814
  }
13815
+ return this.attachRun(record, spec, controller);
13816
+ }
13817
+ async registerPausedReplacement(spec) {
13818
+ const target = spec.replacesPausedRun;
13819
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
13820
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
13821
+ }
13822
+ this.getHandle(target.runId);
13823
+ const previous = await this.registryStore.load(target.runId);
13824
+ 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) {
13825
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
13826
+ }
13827
+ const runId = spec.runId ?? this.runIdFactory();
13828
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
13829
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
13830
+ this.runSlotLimiter.release(previous.runId);
13831
+ this.runSlotLimiter.acquire(runId);
13832
+ const now = this.now();
13833
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
13834
+ const next = {
13835
+ ...previous,
13836
+ status: "cancelled",
13837
+ updatedAt: now,
13838
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
13839
+ };
13840
+ try {
13841
+ await spec.admissionCommit(record, { previous, next });
13842
+ } catch (error) {
13843
+ this.runSlotLimiter.release(runId);
13844
+ this.runSlotLimiter.acquire(previous.runId);
13845
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
13846
+ throw error;
13847
+ }
13848
+ this.cleanupRunResources(previous.runId);
13849
+ this.notifyTerminalWaiters(previous.runId);
13850
+ const controller = new AbortController();
13851
+ forwardParentAbortSignal(controller, spec.parentSignal);
13852
+ return this.attachRun(record, spec, controller);
13853
+ }
13854
+ async restoreRun(spec) {
13855
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13856
+ return this.withRunControlLock(spec.runId, async () => {
13857
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
13858
+ const record = await this.registryStore.load(spec.runId);
13859
+ if (!record) throw new RunNotFoundError(spec.runId);
13860
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
13861
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
13862
+ }
13863
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
13864
+ return this.attachRun(record, spec, new AbortController());
13865
+ });
13866
+ }
13867
+ attachRun(record, spec, controller) {
13868
+ const runId = record.runId;
13460
13869
  try {
13461
13870
  const handle = new DefaultRunHandle({
13462
13871
  runRecord: record,
@@ -13554,11 +13963,36 @@ var DefaultRunSupervisor = class {
13554
13963
  registryStore: this.registryStore,
13555
13964
  reason,
13556
13965
  now: this.now,
13557
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
13966
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
13967
+ canRestoreRun: this.canRestoreRun
13558
13968
  });
13559
13969
  }
13560
- async pause(_runId, _reason) {
13561
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
13970
+ async pause(runId, reason) {
13971
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
13972
+ }
13973
+ async resumePausedRun(input) {
13974
+ return this.withRunControlLock(input.runId, async () => {
13975
+ const handle = this.getHandle(input.runId);
13976
+ const record = await this.registryStore.load(input.runId);
13977
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
13978
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
13979
+ }
13980
+ await persistRunTransition(this.registryStore, record, {
13981
+ ...record,
13982
+ status: "running",
13983
+ updatedAt: this.now(),
13984
+ pausedAt: void 0,
13985
+ pauseReason: void 0,
13986
+ errorIfAny: void 0,
13987
+ metadata: { ...record.metadata, executionId: input.executionId }
13988
+ });
13989
+ const controller = new AbortController();
13990
+ handle.replaceExecutionAbortController(controller, input.executionId);
13991
+ handle.attachTransportEventBus(input.eventBus);
13992
+ this.controllers.set(input.runId, controller);
13993
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
13994
+ return handle;
13995
+ });
13562
13996
  }
13563
13997
  async claimResume(runId, interaction, eventBus, parentSignal) {
13564
13998
  return this.withRunControlLock(runId, async () => {
@@ -13593,7 +14027,7 @@ var DefaultRunSupervisor = class {
13593
14027
  throw new RunNotFoundError(runId);
13594
14028
  }
13595
14029
  const claimId = generateRunResumeClaimId();
13596
- await this.registryStore.save({
14030
+ await persistRunTransition(this.registryStore, record, {
13597
14031
  ...record,
13598
14032
  updatedAt: this.now(),
13599
14033
  metadata: {
@@ -13681,7 +14115,7 @@ var DefaultRunSupervisor = class {
13681
14115
  }
13682
14116
  const awaitingUserWithoutClaim = { ...awaitingUser };
13683
14117
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13684
- await this.registryStore.save({
14118
+ const nextRecord = {
13685
14119
  ...record,
13686
14120
  status: "running",
13687
14121
  updatedAt: this.now(),
@@ -13691,6 +14125,10 @@ var DefaultRunSupervisor = class {
13691
14125
  metadata: {
13692
14126
  ...record.metadata ?? {},
13693
14127
  ...execution ? { executionId: execution.executionId } : {},
14128
+ ...execution?.inputEventIds ? { resumeInputs: {
14129
+ eventIds: [...execution.inputEventIds],
14130
+ checkpointRevision: pendingInteraction.checkpointRevision
14131
+ } } : {},
13694
14132
  awaitingUser: {
13695
14133
  ...awaitingUserWithoutClaim,
13696
14134
  interaction: {
@@ -13699,10 +14137,12 @@ var DefaultRunSupervisor = class {
13699
14137
  }
13700
14138
  }
13701
14139
  }
13702
- });
14140
+ };
14141
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
14142
+ else await persistRunTransition(this.registryStore, record, nextRecord);
13703
14143
  const executionController = new AbortController();
13704
14144
  forwardParentAbortSignal(executionController, parentSignal);
13705
- handle.replaceExecutionAbortController(executionController);
14145
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13706
14146
  this.controllers.set(runId, executionController);
13707
14147
  return handle;
13708
14148
  });
@@ -13720,7 +14160,7 @@ var DefaultRunSupervisor = class {
13720
14160
  }
13721
14161
  const awaitingUserWithoutClaim = { ...awaitingUser };
13722
14162
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13723
- await this.registryStore.save({
14163
+ await persistRunTransition(this.registryStore, record, {
13724
14164
  ...record,
13725
14165
  updatedAt: this.now(),
13726
14166
  metadata: {
@@ -13865,13 +14305,13 @@ __export(system_reminder_exports, {
13865
14305
 
13866
14306
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
13867
14307
  function createDefaultGraphExecutor(options) {
13868
- const executor = new GraphExecutor(
14308
+ const executor2 = new GraphExecutor(
13869
14309
  options.checkpointer ?? new MemoryCheckpointer(),
13870
14310
  { maxSteps: options.maxSteps ?? 8 }
13871
14311
  );
13872
- executor.registerNode(new UserNode());
13873
- executor.registerNode(options.llmNode);
13874
- executor.registerNode(new ToolNode({
14312
+ executor2.registerNode(new UserNode());
14313
+ executor2.registerNode(options.llmNode);
14314
+ executor2.registerNode(new ToolNode({
13875
14315
  toolRuntime: options.toolRuntime,
13876
14316
  observationPreview: options.observationPreview,
13877
14317
  auditPort: options.auditPort,
@@ -13879,8 +14319,8 @@ function createDefaultGraphExecutor(options) {
13879
14319
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
13880
14320
  modelInputResolver: options.modelInputResolver
13881
14321
  }));
13882
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
13883
- return executor;
14322
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14323
+ return executor2;
13884
14324
  }
13885
14325
 
13886
14326
  // src/runtime-kernel/testkit/graphLoopHarness.ts
@@ -13905,7 +14345,7 @@ function createGraphLoopHarness(options) {
13905
14345
  return {
13906
14346
  async run() {
13907
14347
  const checkpointKey = options.runId ?? options.turnId;
13908
- const executor = createDefaultGraphExecutor({
14348
+ const executor2 = createDefaultGraphExecutor({
13909
14349
  llmNode: options.createLlmNode({
13910
14350
  llmCaller: options.llmCaller,
13911
14351
  toolRuntime: options.toolRuntime
@@ -13935,8 +14375,8 @@ function createGraphLoopHarness(options) {
13935
14375
  signal: options.signal ?? options.toolContext.abortSignal,
13936
14376
  executorLocal
13937
14377
  };
13938
- await executor.prime(checkpointKey, local, "user");
13939
- const result = await executor.runUntilYield(checkpointKey);
14378
+ await executor2.prime(checkpointKey, local, "user");
14379
+ const result = await executor2.runUntilYield(checkpointKey);
13940
14380
  return {
13941
14381
  checkpointNodeId: result.checkpoint.nodeId,
13942
14382
  stepCount: result.stepCount,
@@ -13978,6 +14418,8 @@ exports.ModelResolver = ModelResolver;
13978
14418
  exports.PRIMARY_PROMPT_CAPACITY_ERROR_CODE = PRIMARY_PROMPT_CAPACITY_ERROR_CODE;
13979
14419
  exports.PrimaryPromptCapacityError = PrimaryPromptCapacityError;
13980
14420
  exports.REASONING_EFFORTS = REASONING_EFFORTS;
14421
+ exports.RunPauseRequested = RunPauseRequested;
14422
+ exports.RunRecoveryBlockedError = RunRecoveryBlockedError;
13981
14423
  exports.RuntimeEventSubRunTracePublisher = RuntimeEventSubRunTracePublisher;
13982
14424
  exports.SYSTEM_REMINDER_RULES = SYSTEM_REMINDER_RULES;
13983
14425
  exports.SystemReminderRegistry = SystemReminderRegistry;
@@ -14035,6 +14477,7 @@ exports.findCachedToolOutputByIdempotencyKey = findCachedToolOutputByIdempotency
14035
14477
  exports.getToolContextRuntimeBinding = getToolContextRuntimeBinding;
14036
14478
  exports.graph = graph_engine_exports;
14037
14479
  exports.hostReminderTextTemplate = hostReminderTextTemplate;
14480
+ exports.isRunPauseSignal = isRunPauseSignal;
14038
14481
  exports.isRuntimeFailureFact = isRuntimeFailureFact;
14039
14482
  exports.isValidReasoningEffort = isValidReasoningEffort;
14040
14483
  exports.lastStepsHintTemplate = lastStepsHintTemplate;
@@ -14043,6 +14486,7 @@ exports.llm = llm_exports;
14043
14486
  exports.maxStepsForceFinalAnswerTemplate = maxStepsForceFinalAnswerTemplate;
14044
14487
  exports.noopAudit = noopAudit;
14045
14488
  exports.normalizeToolArgs = normalizeToolArgs;
14489
+ exports.parseEngineCheckpoint = parseEngineCheckpoint;
14046
14490
  exports.parseToolModelInputDeclaration = parseToolModelInputDeclaration;
14047
14491
  exports.periodicProgressReflectionTemplate = periodicProgressReflectionTemplate;
14048
14492
  exports.phaseEqualsTrigger = phaseEqualsTrigger;