@linnlabs/linnkit 0.32.2 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/cli.cjs +312 -50
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +312 -50
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +1 -0
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +1 -0
  9. package/dist/context-manager.js.map +1 -1
  10. package/dist/contracts/agentSpec.d.cts +30 -30
  11. package/dist/contracts/agentSpec.d.ts +30 -30
  12. package/dist/contracts/audit.d.cts +32 -32
  13. package/dist/contracts/audit.d.ts +32 -32
  14. package/dist/contracts/contextPolicy.d.cts +36 -36
  15. package/dist/contracts/contextPolicy.d.ts +36 -36
  16. package/dist/contracts/events.d.cts +968 -968
  17. package/dist/contracts/events.d.ts +968 -968
  18. package/dist/contracts/execution.d.cts +8 -8
  19. package/dist/contracts/execution.d.ts +8 -8
  20. package/dist/contracts/messages.d.cts +204 -204
  21. package/dist/contracts/messages.d.ts +204 -204
  22. package/dist/contracts/sse.d.cts +891 -891
  23. package/dist/contracts/sse.d.ts +891 -891
  24. package/dist/contracts/sub-run-trace-payload.d.cts +26 -26
  25. package/dist/contracts/sub-run-trace-payload.d.ts +26 -26
  26. package/dist/contracts/token-accounting.d.cts +28 -28
  27. package/dist/contracts/token-accounting.d.ts +28 -28
  28. package/dist/index.cjs +383 -66
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.js +383 -66
  31. package/dist/index.js.map +1 -1
  32. package/dist/quickstart/toolRuntime.d.cts +1 -1
  33. package/dist/quickstart/toolRuntime.d.ts +1 -1
  34. package/dist/quickstart/types.d.cts +1 -1
  35. package/dist/quickstart/types.d.ts +1 -1
  36. package/dist/quickstart.cjs +312 -50
  37. package/dist/quickstart.cjs.map +1 -1
  38. package/dist/quickstart.js +312 -50
  39. package/dist/quickstart.js.map +1 -1
  40. package/dist/runtime-kernel/child-runs/childRunInvoker.d.cts +11 -0
  41. package/dist/runtime-kernel/child-runs/childRunInvoker.d.ts +11 -0
  42. package/dist/runtime-kernel/events/agentEvents.d.cts +98 -98
  43. package/dist/runtime-kernel/events/agentEvents.d.ts +98 -98
  44. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.cts +15 -1
  45. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.ts +15 -1
  46. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.cts +34 -0
  47. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.ts +34 -0
  48. package/dist/runtime-kernel/graph-engine/engine.d.cts +13 -2
  49. package/dist/runtime-kernel/graph-engine/engine.d.ts +13 -2
  50. package/dist/runtime-kernel/graph-engine/index.d.cts +2 -1
  51. package/dist/runtime-kernel/graph-engine/index.d.ts +2 -1
  52. package/dist/runtime-kernel/graph-engine/types.d.cts +8 -0
  53. package/dist/runtime-kernel/graph-engine/types.d.ts +8 -0
  54. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +14 -2
  55. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +14 -2
  56. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.cts +1 -0
  57. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.ts +1 -0
  58. package/dist/runtime-kernel/run-supervisor/runHandle.d.cts +9 -5
  59. package/dist/runtime-kernel/run-supervisor/runHandle.d.ts +9 -5
  60. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.cts +2 -0
  61. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.ts +2 -0
  62. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +7 -1
  63. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +7 -1
  64. package/dist/runtime-kernel.cjs +383 -66
  65. package/dist/runtime-kernel.cjs.map +1 -1
  66. package/dist/runtime-kernel.d.cts +2 -1
  67. package/dist/runtime-kernel.d.ts +2 -1
  68. package/dist/runtime-kernel.js +381 -67
  69. package/dist/runtime-kernel.js.map +1 -1
  70. package/dist/testkit.cjs +383 -66
  71. package/dist/testkit.cjs.map +1 -1
  72. package/dist/testkit.js +383 -66
  73. package/dist/testkit.js.map +1 -1
  74. package/docs/integration/01-installation.md +1 -1
  75. package/docs/integration/child-runs.md +12 -0
  76. package/docs/integration/persistence.md +23 -0
  77. package/docs/integration/run-supervisor.md +12 -2
  78. package/package.json +4 -4
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import 'eventsource-parser';
7
7
  import { get_encoding } from 'tiktoken';
8
8
  import { AsyncLocalStorage } from 'async_hooks';
9
9
  import { createHash } from 'crypto';
10
+ import { isDeepStrictEqual } from 'util';
10
11
 
11
12
  var __defProp = Object.defineProperty;
12
13
  var __export = (target, all) => {
@@ -1891,12 +1892,15 @@ __export(graph_engine_exports, {
1891
1892
  MemoryEventStore: () => MemoryEventStore,
1892
1893
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
1893
1894
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
1895
+ RunPauseRequested: () => RunPauseRequested,
1896
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
1894
1897
  ToolNode: () => ToolNode,
1895
1898
  UserNode: () => UserNode,
1896
1899
  WaitUserNode: () => WaitUserNode,
1897
1900
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
1898
1901
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
1899
1902
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
1903
+ isRunPauseSignal: () => isRunPauseSignal,
1900
1904
  isRuntimeFailureFact: () => isRuntimeFailureFact,
1901
1905
  readCheckpointContextUsage: () => readCheckpointContextUsage,
1902
1906
  requireEventStoreId: () => requireEventStoreId,
@@ -2492,6 +2496,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2492
2496
  "memory",
2493
2497
  "runtimeEventSink",
2494
2498
  "runtimeEventCommitPort",
2499
+ "commitExecutionBoundary",
2500
+ "toolRecoveryPort",
2495
2501
  "runtimeFailureFactSink",
2496
2502
  "signal",
2497
2503
  "summarizationCallbacks",
@@ -3042,6 +3048,7 @@ var GraphExecutor = class {
3042
3048
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3043
3049
  };
3044
3050
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3051
+ this.executionCheckpointPort = config.executionCheckpointPort;
3045
3052
  }
3046
3053
  checkpointer;
3047
3054
  nodes = /* @__PURE__ */ new Map();
@@ -3049,6 +3056,7 @@ var GraphExecutor = class {
3049
3056
  checkpointQueues = /* @__PURE__ */ new Map();
3050
3057
  config;
3051
3058
  telemetryPort;
3059
+ executionCheckpointPort;
3052
3060
  registerNode(node) {
3053
3061
  this.nodes.set(node.id, node);
3054
3062
  }
@@ -3057,6 +3065,7 @@ var GraphExecutor = class {
3057
3065
  }
3058
3066
  sanitize(state) {
3059
3067
  return {
3068
+ ...state,
3060
3069
  nodeId: state.nodeId,
3061
3070
  revision: state.revision ?? 0,
3062
3071
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3076,8 +3085,9 @@ var GraphExecutor = class {
3076
3085
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3077
3086
  }
3078
3087
  this.ephemeralLocals.set(checkpointKey, { ...local });
3079
- await this.checkpointer.save(checkpointKey, {
3088
+ await this.commitCheckpoint(checkpointKey, {
3080
3089
  nodeId,
3090
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3081
3091
  revision: 1,
3082
3092
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3083
3093
  local: sanitizeCheckpointLocal(local)
@@ -3088,6 +3098,33 @@ var GraphExecutor = class {
3088
3098
  );
3089
3099
  });
3090
3100
  }
3101
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3102
+ async continueSession(checkpointKey, input) {
3103
+ if (!this.executionCheckpointPort) {
3104
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3105
+ }
3106
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3107
+ const current = await this.checkpointer.load(checkpointKey);
3108
+ if (!current || current.revision !== input.expectedRevision) {
3109
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3110
+ }
3111
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3112
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3113
+ }
3114
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3115
+ return { checkpoint: current, events: [], stepCount: 0 };
3116
+ }
3117
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3118
+ try {
3119
+ return await this.runUntilYieldQueued(
3120
+ checkpointKey,
3121
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3122
+ );
3123
+ } finally {
3124
+ this.ephemeralLocals.delete(checkpointKey);
3125
+ }
3126
+ });
3127
+ }
3091
3128
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3092
3129
  async resumeSession(checkpointKey, input) {
3093
3130
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3108,17 +3145,21 @@ var GraphExecutor = class {
3108
3145
  );
3109
3146
  }
3110
3147
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3148
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3149
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3150
+ }
3111
3151
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3112
- await this.checkpointer.save(checkpointKey, {
3152
+ await this.commitCheckpoint(checkpointKey, {
3113
3153
  ...current,
3114
3154
  nodeId: input.nodeId ?? "llm",
3155
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3115
3156
  revision: currentRevision + 1,
3116
3157
  local: sanitizeCheckpointLocal(resumedLocal)
3117
3158
  });
3118
3159
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3119
3160
  return this.runUntilYieldQueued(
3120
3161
  checkpointKey,
3121
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3162
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3122
3163
  );
3123
3164
  });
3124
3165
  }
@@ -3213,9 +3254,16 @@ var GraphExecutor = class {
3213
3254
  ...state,
3214
3255
  revision: (state.revision ?? 0) + 1
3215
3256
  });
3216
- await this.checkpointer.save(checkpointKey, checkpoint);
3257
+ await this.commitCheckpoint(checkpointKey, checkpoint);
3217
3258
  return checkpoint;
3218
3259
  }
3260
+ async commitCheckpoint(checkpointKey, checkpoint) {
3261
+ if (this.executionCheckpointPort) {
3262
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3263
+ } else {
3264
+ await this.checkpointer.save(checkpointKey, checkpoint);
3265
+ }
3266
+ }
3219
3267
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3220
3268
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3221
3269
  return { events, checkpoint, stepCount };
@@ -3228,6 +3276,15 @@ var GraphExecutor = class {
3228
3276
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3229
3277
  local: { ...state.local || {}, ...ephemeral }
3230
3278
  };
3279
+ if (this.executionCheckpointPort) {
3280
+ state.local = {
3281
+ ...state.local,
3282
+ commitExecutionBoundary: async (boundary) => {
3283
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3284
+ boundary.revision = saved.revision;
3285
+ }
3286
+ };
3287
+ }
3231
3288
  const isAbortSignal2 = (v) => {
3232
3289
  return v !== null && typeof v === "object" && "aborted" in v;
3233
3290
  };
@@ -3237,11 +3294,12 @@ var GraphExecutor = class {
3237
3294
  throw err;
3238
3295
  };
3239
3296
  let stepCount = 0;
3297
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3240
3298
  let allEvents = [];
3241
3299
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3242
3300
  maxSteps
3243
3301
  });
3244
- while (stepCount < maxSteps) {
3302
+ while (previousSteps + stepCount < maxSteps) {
3245
3303
  stepCount += 1;
3246
3304
  reportStepsUsed(stepCount);
3247
3305
  const signalRaw = state.local?.signal;
@@ -3253,7 +3311,7 @@ var GraphExecutor = class {
3253
3311
  const stepPreparation = prepareGraphStep({
3254
3312
  state,
3255
3313
  maxSteps,
3256
- stepCount
3314
+ stepCount: previousSteps + stepCount
3257
3315
  });
3258
3316
  state = stepPreparation.state;
3259
3317
  const node = this.nodes.get(state.nodeId);
@@ -3262,6 +3320,7 @@ var GraphExecutor = class {
3262
3320
  maxSteps,
3263
3321
  stepCount
3264
3322
  });
3323
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3265
3324
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3266
3325
  this.ephemeralLocals.delete(checkpointKey);
3267
3326
  return result3;
@@ -3271,6 +3330,11 @@ var GraphExecutor = class {
3271
3330
  stepCount,
3272
3331
  nodeId: state.nodeId
3273
3332
  });
3333
+ if (this.executionCheckpointPort) {
3334
+ state.executionStatus = "executing";
3335
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3336
+ state.revision = saved.revision;
3337
+ }
3274
3338
  const result2 = await runGraphNodeWithTelemetry({
3275
3339
  node,
3276
3340
  state,
@@ -3295,10 +3359,13 @@ var GraphExecutor = class {
3295
3359
  fromNodeId: stepResolution.action.fromNodeId,
3296
3360
  nextNodeId: stepResolution.action.nextNodeId
3297
3361
  });
3298
- await this.saveCheckpoint(checkpointKey, state);
3362
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3363
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3364
+ state.revision = saved.revision;
3299
3365
  continue;
3300
3366
  }
3301
3367
  if (stepResolution.action.kind === "yield") {
3368
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3302
3369
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3303
3370
  maxSteps,
3304
3371
  stepCount
@@ -3309,6 +3376,7 @@ var GraphExecutor = class {
3309
3376
  maxSteps,
3310
3377
  stepCount
3311
3378
  });
3379
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3312
3380
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3313
3381
  }
3314
3382
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3329,6 +3397,7 @@ var GraphExecutor = class {
3329
3397
  },
3330
3398
  retryable: false
3331
3399
  }), "GraphExecutor.engine_budget_exhausted"));
3400
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3332
3401
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3333
3402
  this.ephemeralLocals.delete(checkpointKey);
3334
3403
  return result;
@@ -7004,10 +7073,11 @@ var LlmNode = class {
7004
7073
  bridge.handle
7005
7074
  );
7006
7075
  } catch (error) {
7007
- bridge.finalizePartialAnswer();
7076
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7008
7077
  throw error;
7009
7078
  }
7010
7079
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7080
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7011
7081
  switch (decision.kind) {
7012
7082
  case "tool_calls": {
7013
7083
  if (forceFinalAnswer) {
@@ -8214,6 +8284,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8214
8284
  function recordToolProtocolError(params) {
8215
8285
  }
8216
8286
 
8287
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8288
+ var RunRecoveryBlockedError = class extends Error {
8289
+ code = "RUN_RECOVERY_BLOCKED";
8290
+ constructor(message) {
8291
+ super(message);
8292
+ this.name = "RunRecoveryBlockedError";
8293
+ }
8294
+ };
8295
+ var RunPauseRequested = class extends Error {
8296
+ code = "RUN_PAUSE_REQUESTED";
8297
+ constructor(message = "Run paused by user") {
8298
+ super(message);
8299
+ this.name = "RunPauseRequested";
8300
+ }
8301
+ };
8302
+ function isRunPauseSignal(signal) {
8303
+ const reason = signal?.reason;
8304
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8305
+ }
8306
+
8307
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8308
+ async function executeRecoverableTool(input) {
8309
+ const local = input.state.local;
8310
+ if (!local?.commitExecutionBoundary) return input.execute();
8311
+ if (local.executingToolCallId) {
8312
+ if (local.executingToolCallId !== input.call.id) {
8313
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8314
+ }
8315
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8316
+ if (!decision || decision.kind === "blocked") {
8317
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8318
+ }
8319
+ if (decision.kind === "settled") return decision.result;
8320
+ }
8321
+ local.executingToolCallId = input.call.id;
8322
+ await local.commitExecutionBoundary(input.state);
8323
+ const result = await input.execute();
8324
+ if (!result.success && isRunPauseSignal(local.signal)) {
8325
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8326
+ error.name = "AbortError";
8327
+ throw error;
8328
+ }
8329
+ return result;
8330
+ }
8331
+ async function commitToolBoundary(state, result) {
8332
+ if (!state.local?.commitExecutionBoundary) return;
8333
+ delete state.local.executingToolCallId;
8334
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8335
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8336
+ await state.local.commitExecutionBoundary(state);
8337
+ }
8338
+
8217
8339
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8218
8340
  var logger11 = new Logger("ToolNode");
8219
8341
  function isAbortSignal(value) {
@@ -8384,6 +8506,7 @@ var ToolNode = class {
8384
8506
  const events = [];
8385
8507
  while (true) {
8386
8508
  const result = await this.runNextPendingToolCall(state);
8509
+ await commitToolBoundary(state, result);
8387
8510
  if (Array.isArray(result.events) && result.events.length > 0) {
8388
8511
  events.push(...result.events);
8389
8512
  }
@@ -8400,11 +8523,9 @@ var ToolNode = class {
8400
8523
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8401
8524
  const signalRaw = state.local?.signal;
8402
8525
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8403
- settlePendingToolCallsAfterAbort({
8404
- state,
8405
- calls,
8406
- toolCatalog: this.toolRuntime
8407
- });
8526
+ if (!isRunPauseSignal(signalRaw)) {
8527
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8528
+ }
8408
8529
  const abortError = new Error("The user aborted a request.");
8409
8530
  abortError.name = "AbortError";
8410
8531
  throw abortError;
@@ -8543,16 +8664,21 @@ var ToolNode = class {
8543
8664
  tool_calls: [call]
8544
8665
  });
8545
8666
  try {
8546
- const exec = await executeToolWithIdempotency({
8547
- idempotencyKey: execution.idempotencyKey,
8548
- inFlight: this.idempotencyInFlight,
8549
- history: readHistoryEvents(prepared.local),
8550
- toolName: execution.toolName,
8551
- execute: () => this.toolRuntime.executeTool(
8552
- execution.toolName,
8553
- execution.toolArgs,
8554
- prepared.toolContext
8555
- )
8667
+ const exec = await executeRecoverableTool({
8668
+ state,
8669
+ call,
8670
+ context: prepared.toolContext,
8671
+ execute: () => executeToolWithIdempotency({
8672
+ idempotencyKey: execution.idempotencyKey,
8673
+ inFlight: this.idempotencyInFlight,
8674
+ history: readHistoryEvents(prepared.local),
8675
+ toolName: execution.toolName,
8676
+ execute: () => this.toolRuntime.executeTool(
8677
+ execution.toolName,
8678
+ execution.toolArgs,
8679
+ prepared.toolContext
8680
+ )
8681
+ })
8556
8682
  });
8557
8683
  if (exec.success) {
8558
8684
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8632,7 +8758,7 @@ var ToolNode = class {
8632
8758
  bridge: execution.bridge
8633
8759
  });
8634
8760
  } catch (error) {
8635
- if (isToolExecutionAbort(error)) {
8761
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8636
8762
  settleToolCallsAfterExecutionAbort({
8637
8763
  state,
8638
8764
  remainingCalls: calls.slice(1),
@@ -8692,7 +8818,7 @@ var ToolNode = class {
8692
8818
  {
8693
8819
  attachments: context.attachments,
8694
8820
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8695
- ephemeral: context.exec.idempotency?.cacheHit === true,
8821
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8696
8822
  durationMs: context.exec.durationMs
8697
8823
  }
8698
8824
  );
@@ -8749,6 +8875,9 @@ var ToolNode = class {
8749
8875
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8750
8876
  }
8751
8877
  async handleError(context) {
8878
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
8879
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
8880
+ }
8752
8881
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8753
8882
  await this.emitToolDecisionAudit({
8754
8883
  action: "tool.deny",
@@ -9646,12 +9775,33 @@ var RuntimeEventPublisher = class {
9646
9775
  var EventBusEventPersistence = class {
9647
9776
  constructor(options) {
9648
9777
  this.options = options;
9778
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
9649
9779
  }
9650
9780
  options;
9651
9781
  scheduledEventIds = /* @__PURE__ */ new Set();
9652
9782
  writeTail = Promise.resolve();
9653
9783
  firstWriteError;
9654
9784
  connected = false;
9785
+ checkpointWritesActive;
9786
+ checkpointEvents = [];
9787
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9788
+ async commitCheckpoint(checkpointKey, checkpoint) {
9789
+ const writer = this.options.checkpointWriter;
9790
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9791
+ const events = this.checkpointEvents;
9792
+ this.checkpointEvents = [];
9793
+ await this.enqueueWrite(() => writer({
9794
+ checkpointKey,
9795
+ checkpoint,
9796
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9797
+ }));
9798
+ }
9799
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
9800
+ finishCheckpointWrites() {
9801
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
9802
+ this.checkpointEvents = [];
9803
+ this.checkpointWritesActive = false;
9804
+ }
9655
9805
  connect() {
9656
9806
  if (this.connected) {
9657
9807
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -9698,14 +9848,22 @@ var EventBusEventPersistence = class {
9698
9848
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
9699
9849
  return;
9700
9850
  }
9851
+ if (this.checkpointWritesActive) {
9852
+ this.scheduledEventIds.add(event.id);
9853
+ this.checkpointEvents.push(event);
9854
+ return;
9855
+ }
9701
9856
  void this.scheduleWrite(event).catch(() => void 0);
9702
9857
  };
9703
9858
  scheduleWrite(event) {
9704
9859
  this.scheduledEventIds.add(event.id);
9705
- const eventStoreId = this.options.nextEventStoreId();
9706
- const write = this.writeTail.then(async () => {
9707
- await this.options.eventStore.append({ eventStoreId, event });
9708
- });
9860
+ return this.enqueueWrite(() => this.options.eventStore.append({
9861
+ eventStoreId: this.options.nextEventStoreId(),
9862
+ event
9863
+ }));
9864
+ }
9865
+ enqueueWrite(operation) {
9866
+ const write = this.writeTail.then(operation);
9709
9867
  this.writeTail = write;
9710
9868
  void write.catch((error) => {
9711
9869
  this.firstWriteError ??= error;
@@ -11112,8 +11270,6 @@ __export(run_supervisor_exports, {
11112
11270
  RunNotFoundError: () => RunNotFoundError,
11113
11271
  runMetaFromRecord: () => runMetaFromRecord
11114
11272
  });
11115
-
11116
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
11117
11273
  function cloneRunRecord(record) {
11118
11274
  return {
11119
11275
  ...record,
@@ -11133,6 +11289,11 @@ function matchesStatus(candidate, filter) {
11133
11289
  }
11134
11290
  var MemoryRunRegistryStore = class {
11135
11291
  store = /* @__PURE__ */ new Map();
11292
+ async compareAndSwap(previous, next) {
11293
+ if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
11294
+ this.store.set(next.runId, cloneRunRecord(next));
11295
+ return true;
11296
+ }
11136
11297
  async save(record) {
11137
11298
  this.store.set(record.runId, cloneRunRecord(record));
11138
11299
  }
@@ -11280,6 +11441,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
11280
11441
  }
11281
11442
  };
11282
11443
 
11444
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
11445
+ async function persistRunTransition(store, previous, next) {
11446
+ if (store.compareAndSwap) {
11447
+ if (!await store.compareAndSwap(previous, next)) {
11448
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
11449
+ }
11450
+ } else {
11451
+ await store.save(next);
11452
+ }
11453
+ }
11454
+
11283
11455
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
11284
11456
  function isRunTerminalStatus(status) {
11285
11457
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -11335,6 +11507,7 @@ var DefaultRunHandle = class {
11335
11507
  parentRunId;
11336
11508
  runRecord;
11337
11509
  abortController;
11510
+ executionId;
11338
11511
  agentSpecSnapshot;
11339
11512
  requestSnapshot;
11340
11513
  transportEventBus;
@@ -11350,6 +11523,9 @@ var DefaultRunHandle = class {
11350
11523
  this.runId = options.runRecord.runId;
11351
11524
  this.parentRunId = options.runRecord.parentRunId;
11352
11525
  this.abortController = options.abortController;
11526
+ const executionId = options.runRecord.metadata?.executionId;
11527
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
11528
+ this.executionId = executionId;
11353
11529
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
11354
11530
  this.requestSnapshot = cloneRequest(options.request);
11355
11531
  this.transportEventBus = options.eventBus;
@@ -11369,8 +11545,9 @@ var DefaultRunHandle = class {
11369
11545
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
11370
11546
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
11371
11547
  */
11372
- replaceExecutionAbortController(controller) {
11548
+ replaceExecutionAbortController(controller, executionId) {
11373
11549
  this.abortController = controller;
11550
+ this.executionId = executionId;
11374
11551
  }
11375
11552
  async spec() {
11376
11553
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -11390,6 +11567,7 @@ var DefaultRunHandle = class {
11390
11567
  this.abortController.abort(opts.reason);
11391
11568
  const latestRecord = await this.registryStore.load(this.runId);
11392
11569
  const baseRecord = latestRecord ?? this.runRecord;
11570
+ this.assertExecutionOwner(baseRecord);
11393
11571
  const transition = decideRunLifecycleTransition(baseRecord.status);
11394
11572
  if (transition.kind === "skip_terminal") {
11395
11573
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -11399,7 +11577,7 @@ var DefaultRunHandle = class {
11399
11577
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11400
11578
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
11401
11579
  };
11402
- await this.registryStore.save(settledRecord);
11580
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
11403
11581
  this.runRecord = { ...settledRecord };
11404
11582
  return;
11405
11583
  }
@@ -11426,7 +11604,7 @@ var DefaultRunHandle = class {
11426
11604
  }
11427
11605
  }
11428
11606
  };
11429
- await this.registryStore.save(nextRecord);
11607
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11430
11608
  this.runRecord = { ...nextRecord };
11431
11609
  await this.auditPort.emit({
11432
11610
  envelopeId: generateAuditEnvelopeId(),
@@ -11534,21 +11712,35 @@ var DefaultRunHandle = class {
11534
11712
  async markFailed(error, patch = {}) {
11535
11713
  await this.saveLifecycleStatus("failed", patch, error);
11536
11714
  }
11537
- async pause(_reason) {
11538
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
11715
+ async pause(reason = "Run paused by user") {
11716
+ const latest = await this.registryStore.load(this.runId);
11717
+ if (latest) this.assertExecutionOwner(latest);
11718
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
11719
+ const next = {
11720
+ ...latest,
11721
+ status: "paused",
11722
+ updatedAt: Date.now(),
11723
+ pauseReason: reason,
11724
+ pausedAt: void 0
11725
+ };
11726
+ await persistRunTransition(this.registryStore, latest, next);
11727
+ this.runRecord = next;
11728
+ this.abortController.abort(new RunPauseRequested(reason));
11539
11729
  }
11540
- async resume() {
11541
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
11730
+ async markPaused(patch = {}) {
11731
+ await this.saveLifecycleStatus("paused", patch);
11542
11732
  }
11543
11733
  async saveLifecycleStatus(status, patch, errorIfAny) {
11544
11734
  const latestRecord = await this.registryStore.load(this.runId);
11545
11735
  const baseRecord = latestRecord ?? this.runRecord;
11546
11736
  const transition = decideRunLifecycleTransition(baseRecord.status);
11737
+ this.assertExecutionOwner(baseRecord);
11738
+ if (status === "running" && baseRecord.status === "paused") return;
11547
11739
  if (transition.kind === "skip_terminal") {
11548
11740
  this.runRecord = { ...baseRecord };
11549
11741
  return;
11550
11742
  }
11551
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
11743
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
11552
11744
  const updatedAt = Date.now();
11553
11745
  const nextRecord = {
11554
11746
  ...baseRecord,
@@ -11556,8 +11748,8 @@ var DefaultRunHandle = class {
11556
11748
  updatedAt,
11557
11749
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11558
11750
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
11559
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11560
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
11751
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11752
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
11561
11753
  errorIfAny,
11562
11754
  metadata: awaitingUserPatch?.eventId ? {
11563
11755
  ...baseRecord.metadata ?? {},
@@ -11568,7 +11760,7 @@ var DefaultRunHandle = class {
11568
11760
  }
11569
11761
  } : baseRecord.metadata
11570
11762
  };
11571
- await this.registryStore.save(nextRecord);
11763
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11572
11764
  this.runRecord = { ...nextRecord };
11573
11765
  if (status === "completed" || status === "failed") {
11574
11766
  this.closeObservationChannel();
@@ -11578,6 +11770,11 @@ var DefaultRunHandle = class {
11578
11770
  forwardTransportEvent = (envelope) => {
11579
11771
  this.observationEventBus.emit("event", envelope);
11580
11772
  };
11773
+ assertExecutionOwner(record) {
11774
+ if (record.metadata?.executionId !== this.executionId) {
11775
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
11776
+ }
11777
+ }
11581
11778
  forwardTransportError = (error) => {
11582
11779
  this.observationEventBus.emit("error", error);
11583
11780
  };
@@ -11959,6 +12156,24 @@ async function recoverRunsOnBoot(options) {
11959
12156
  const outcomes = [];
11960
12157
  for (const record of activeRecords) {
11961
12158
  const updatedAt = options.now();
12159
+ if (await options.canRestoreRun?.(record)) {
12160
+ const metadata = { ...record.metadata };
12161
+ const awaitingUser = metadata.awaitingUser;
12162
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
12163
+ const restored = { ...awaitingUser };
12164
+ Reflect.deleteProperty(restored, "resumeClaim");
12165
+ metadata.awaitingUser = restored;
12166
+ }
12167
+ await persistRunTransition(options.registryStore, record, {
12168
+ ...record,
12169
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
12170
+ pausedAt: record.pausedAt ?? updatedAt,
12171
+ pauseReason: record.pauseReason ?? options.reason,
12172
+ updatedAt,
12173
+ metadata
12174
+ });
12175
+ continue;
12176
+ }
11962
12177
  const nextRecord = {
11963
12178
  ...record,
11964
12179
  status: "failed",
@@ -11976,7 +12191,7 @@ async function recoverRunsOnBoot(options) {
11976
12191
  }
11977
12192
  }
11978
12193
  };
11979
- await options.registryStore.save(nextRecord);
12194
+ await persistRunTransition(options.registryStore, record, nextRecord);
11980
12195
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
11981
12196
  options.notifyTerminal(outcome);
11982
12197
  outcomes.push(outcome);
@@ -12100,8 +12315,13 @@ var DefaultRunSupervisor = class {
12100
12315
  inFlight = /* @__PURE__ */ new Map();
12101
12316
  eventWatchDisposers = /* @__PURE__ */ new Map();
12102
12317
  controlOperations = /* @__PURE__ */ new Map();
12318
+ canRestoreRun;
12103
12319
  constructor(options) {
12320
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
12321
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
12322
+ }
12104
12323
  this.registryStore = options.registryStore;
12324
+ this.canRestoreRun = options.canRestoreRun;
12105
12325
  this.auditPort = options.auditPort;
12106
12326
  this.executor = options.executor;
12107
12327
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -12149,6 +12369,23 @@ var DefaultRunSupervisor = class {
12149
12369
  this.releaseRunAdmission(runId);
12150
12370
  throw error;
12151
12371
  }
12372
+ return this.attachRun(record, spec, controller);
12373
+ }
12374
+ async restoreRun(spec) {
12375
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12376
+ return this.withRunControlLock(spec.runId, async () => {
12377
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
12378
+ const record = await this.registryStore.load(spec.runId);
12379
+ if (!record) throw new RunNotFoundError(spec.runId);
12380
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
12381
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
12382
+ }
12383
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
12384
+ return this.attachRun(record, spec, new AbortController());
12385
+ });
12386
+ }
12387
+ attachRun(record, spec, controller) {
12388
+ const runId = record.runId;
12152
12389
  try {
12153
12390
  const handle = new DefaultRunHandle({
12154
12391
  runRecord: record,
@@ -12246,11 +12483,36 @@ var DefaultRunSupervisor = class {
12246
12483
  registryStore: this.registryStore,
12247
12484
  reason,
12248
12485
  now: this.now,
12249
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
12486
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
12487
+ canRestoreRun: this.canRestoreRun
12250
12488
  });
12251
12489
  }
12252
- async pause(_runId, _reason) {
12253
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
12490
+ async pause(runId, reason) {
12491
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
12492
+ }
12493
+ async resumePausedRun(input) {
12494
+ return this.withRunControlLock(input.runId, async () => {
12495
+ const handle = this.getHandle(input.runId);
12496
+ const record = await this.registryStore.load(input.runId);
12497
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
12498
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12499
+ }
12500
+ await persistRunTransition(this.registryStore, record, {
12501
+ ...record,
12502
+ status: "running",
12503
+ updatedAt: this.now(),
12504
+ pausedAt: void 0,
12505
+ pauseReason: void 0,
12506
+ errorIfAny: void 0,
12507
+ metadata: { ...record.metadata, executionId: input.executionId }
12508
+ });
12509
+ const controller = new AbortController();
12510
+ handle.replaceExecutionAbortController(controller, input.executionId);
12511
+ handle.attachTransportEventBus(input.eventBus);
12512
+ this.controllers.set(input.runId, controller);
12513
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
12514
+ return handle;
12515
+ });
12254
12516
  }
12255
12517
  async claimResume(runId, interaction, eventBus, parentSignal) {
12256
12518
  return this.withRunControlLock(runId, async () => {
@@ -12285,7 +12547,7 @@ var DefaultRunSupervisor = class {
12285
12547
  throw new RunNotFoundError(runId);
12286
12548
  }
12287
12549
  const claimId = generateRunResumeClaimId();
12288
- await this.registryStore.save({
12550
+ await persistRunTransition(this.registryStore, record, {
12289
12551
  ...record,
12290
12552
  updatedAt: this.now(),
12291
12553
  metadata: {
@@ -12373,7 +12635,7 @@ var DefaultRunSupervisor = class {
12373
12635
  }
12374
12636
  const awaitingUserWithoutClaim = { ...awaitingUser };
12375
12637
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12376
- await this.registryStore.save({
12638
+ await persistRunTransition(this.registryStore, record, {
12377
12639
  ...record,
12378
12640
  status: "running",
12379
12641
  updatedAt: this.now(),
@@ -12394,7 +12656,7 @@ var DefaultRunSupervisor = class {
12394
12656
  });
12395
12657
  const executionController = new AbortController();
12396
12658
  forwardParentAbortSignal(executionController, parentSignal);
12397
- handle.replaceExecutionAbortController(executionController);
12659
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
12398
12660
  this.controllers.set(runId, executionController);
12399
12661
  return handle;
12400
12662
  });
@@ -12412,7 +12674,7 @@ var DefaultRunSupervisor = class {
12412
12674
  }
12413
12675
  const awaitingUserWithoutClaim = { ...awaitingUser };
12414
12676
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12415
- await this.registryStore.save({
12677
+ await persistRunTransition(this.registryStore, record, {
12416
12678
  ...record,
12417
12679
  updatedAt: this.now(),
12418
12680
  metadata: {