@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.cjs CHANGED
@@ -9,6 +9,7 @@ require('eventsource-parser');
9
9
  var tiktoken = require('tiktoken');
10
10
  var async_hooks = require('async_hooks');
11
11
  var crypto = require('crypto');
12
+ var util = require('util');
12
13
 
13
14
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
14
15
  var __defProp = Object.defineProperty;
@@ -1894,12 +1895,15 @@ __export(graph_engine_exports, {
1894
1895
  MemoryEventStore: () => MemoryEventStore,
1895
1896
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
1896
1897
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
1898
+ RunPauseRequested: () => RunPauseRequested,
1899
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
1897
1900
  ToolNode: () => ToolNode,
1898
1901
  UserNode: () => UserNode,
1899
1902
  WaitUserNode: () => WaitUserNode,
1900
1903
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
1901
1904
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
1902
1905
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
1906
+ isRunPauseSignal: () => isRunPauseSignal,
1903
1907
  isRuntimeFailureFact: () => isRuntimeFailureFact,
1904
1908
  readCheckpointContextUsage: () => readCheckpointContextUsage,
1905
1909
  requireEventStoreId: () => requireEventStoreId,
@@ -2495,6 +2499,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2495
2499
  "memory",
2496
2500
  "runtimeEventSink",
2497
2501
  "runtimeEventCommitPort",
2502
+ "commitExecutionBoundary",
2503
+ "toolRecoveryPort",
2498
2504
  "runtimeFailureFactSink",
2499
2505
  "signal",
2500
2506
  "summarizationCallbacks",
@@ -3045,6 +3051,7 @@ var GraphExecutor = class {
3045
3051
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3046
3052
  };
3047
3053
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3054
+ this.executionCheckpointPort = config.executionCheckpointPort;
3048
3055
  }
3049
3056
  checkpointer;
3050
3057
  nodes = /* @__PURE__ */ new Map();
@@ -3052,6 +3059,7 @@ var GraphExecutor = class {
3052
3059
  checkpointQueues = /* @__PURE__ */ new Map();
3053
3060
  config;
3054
3061
  telemetryPort;
3062
+ executionCheckpointPort;
3055
3063
  registerNode(node) {
3056
3064
  this.nodes.set(node.id, node);
3057
3065
  }
@@ -3060,6 +3068,7 @@ var GraphExecutor = class {
3060
3068
  }
3061
3069
  sanitize(state) {
3062
3070
  return {
3071
+ ...state,
3063
3072
  nodeId: state.nodeId,
3064
3073
  revision: state.revision ?? 0,
3065
3074
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3079,8 +3088,9 @@ var GraphExecutor = class {
3079
3088
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3080
3089
  }
3081
3090
  this.ephemeralLocals.set(checkpointKey, { ...local });
3082
- await this.checkpointer.save(checkpointKey, {
3091
+ await this.commitCheckpoint(checkpointKey, {
3083
3092
  nodeId,
3093
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3084
3094
  revision: 1,
3085
3095
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3086
3096
  local: sanitizeCheckpointLocal(local)
@@ -3091,6 +3101,33 @@ var GraphExecutor = class {
3091
3101
  );
3092
3102
  });
3093
3103
  }
3104
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3105
+ async continueSession(checkpointKey, input) {
3106
+ if (!this.executionCheckpointPort) {
3107
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3108
+ }
3109
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3110
+ const current = await this.checkpointer.load(checkpointKey);
3111
+ if (!current || current.revision !== input.expectedRevision) {
3112
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3113
+ }
3114
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3115
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3116
+ }
3117
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3118
+ return { checkpoint: current, events: [], stepCount: 0 };
3119
+ }
3120
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3121
+ try {
3122
+ return await this.runUntilYieldQueued(
3123
+ checkpointKey,
3124
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3125
+ );
3126
+ } finally {
3127
+ this.ephemeralLocals.delete(checkpointKey);
3128
+ }
3129
+ });
3130
+ }
3094
3131
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3095
3132
  async resumeSession(checkpointKey, input) {
3096
3133
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3111,17 +3148,21 @@ var GraphExecutor = class {
3111
3148
  );
3112
3149
  }
3113
3150
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3151
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3152
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3153
+ }
3114
3154
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3115
- await this.checkpointer.save(checkpointKey, {
3155
+ await this.commitCheckpoint(checkpointKey, {
3116
3156
  ...current,
3117
3157
  nodeId: input.nodeId ?? "llm",
3158
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3118
3159
  revision: currentRevision + 1,
3119
3160
  local: sanitizeCheckpointLocal(resumedLocal)
3120
3161
  });
3121
3162
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3122
3163
  return this.runUntilYieldQueued(
3123
3164
  checkpointKey,
3124
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3165
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3125
3166
  );
3126
3167
  });
3127
3168
  }
@@ -3216,9 +3257,16 @@ var GraphExecutor = class {
3216
3257
  ...state,
3217
3258
  revision: (state.revision ?? 0) + 1
3218
3259
  });
3219
- await this.checkpointer.save(checkpointKey, checkpoint);
3260
+ await this.commitCheckpoint(checkpointKey, checkpoint);
3220
3261
  return checkpoint;
3221
3262
  }
3263
+ async commitCheckpoint(checkpointKey, checkpoint) {
3264
+ if (this.executionCheckpointPort) {
3265
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3266
+ } else {
3267
+ await this.checkpointer.save(checkpointKey, checkpoint);
3268
+ }
3269
+ }
3222
3270
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3223
3271
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3224
3272
  return { events, checkpoint, stepCount };
@@ -3231,6 +3279,15 @@ var GraphExecutor = class {
3231
3279
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3232
3280
  local: { ...state.local || {}, ...ephemeral }
3233
3281
  };
3282
+ if (this.executionCheckpointPort) {
3283
+ state.local = {
3284
+ ...state.local,
3285
+ commitExecutionBoundary: async (boundary) => {
3286
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3287
+ boundary.revision = saved.revision;
3288
+ }
3289
+ };
3290
+ }
3234
3291
  const isAbortSignal2 = (v) => {
3235
3292
  return v !== null && typeof v === "object" && "aborted" in v;
3236
3293
  };
@@ -3240,11 +3297,12 @@ var GraphExecutor = class {
3240
3297
  throw err;
3241
3298
  };
3242
3299
  let stepCount = 0;
3300
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3243
3301
  let allEvents = [];
3244
3302
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3245
3303
  maxSteps
3246
3304
  });
3247
- while (stepCount < maxSteps) {
3305
+ while (previousSteps + stepCount < maxSteps) {
3248
3306
  stepCount += 1;
3249
3307
  reportStepsUsed(stepCount);
3250
3308
  const signalRaw = state.local?.signal;
@@ -3256,7 +3314,7 @@ var GraphExecutor = class {
3256
3314
  const stepPreparation = prepareGraphStep({
3257
3315
  state,
3258
3316
  maxSteps,
3259
- stepCount
3317
+ stepCount: previousSteps + stepCount
3260
3318
  });
3261
3319
  state = stepPreparation.state;
3262
3320
  const node = this.nodes.get(state.nodeId);
@@ -3265,6 +3323,7 @@ var GraphExecutor = class {
3265
3323
  maxSteps,
3266
3324
  stepCount
3267
3325
  });
3326
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3268
3327
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3269
3328
  this.ephemeralLocals.delete(checkpointKey);
3270
3329
  return result3;
@@ -3274,6 +3333,11 @@ var GraphExecutor = class {
3274
3333
  stepCount,
3275
3334
  nodeId: state.nodeId
3276
3335
  });
3336
+ if (this.executionCheckpointPort) {
3337
+ state.executionStatus = "executing";
3338
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3339
+ state.revision = saved.revision;
3340
+ }
3277
3341
  const result2 = await runGraphNodeWithTelemetry({
3278
3342
  node,
3279
3343
  state,
@@ -3298,10 +3362,13 @@ var GraphExecutor = class {
3298
3362
  fromNodeId: stepResolution.action.fromNodeId,
3299
3363
  nextNodeId: stepResolution.action.nextNodeId
3300
3364
  });
3301
- await this.saveCheckpoint(checkpointKey, state);
3365
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3366
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3367
+ state.revision = saved.revision;
3302
3368
  continue;
3303
3369
  }
3304
3370
  if (stepResolution.action.kind === "yield") {
3371
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3305
3372
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3306
3373
  maxSteps,
3307
3374
  stepCount
@@ -3312,6 +3379,7 @@ var GraphExecutor = class {
3312
3379
  maxSteps,
3313
3380
  stepCount
3314
3381
  });
3382
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3315
3383
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3316
3384
  }
3317
3385
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3332,6 +3400,7 @@ var GraphExecutor = class {
3332
3400
  },
3333
3401
  retryable: false
3334
3402
  }), "GraphExecutor.engine_budget_exhausted"));
3403
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3335
3404
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3336
3405
  this.ephemeralLocals.delete(checkpointKey);
3337
3406
  return result;
@@ -7007,10 +7076,11 @@ var LlmNode = class {
7007
7076
  bridge.handle
7008
7077
  );
7009
7078
  } catch (error) {
7010
- bridge.finalizePartialAnswer();
7079
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7011
7080
  throw error;
7012
7081
  }
7013
7082
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7083
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7014
7084
  switch (decision.kind) {
7015
7085
  case "tool_calls": {
7016
7086
  if (forceFinalAnswer) {
@@ -8217,6 +8287,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8217
8287
  function recordToolProtocolError(params) {
8218
8288
  }
8219
8289
 
8290
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8291
+ var RunRecoveryBlockedError = class extends Error {
8292
+ code = "RUN_RECOVERY_BLOCKED";
8293
+ constructor(message) {
8294
+ super(message);
8295
+ this.name = "RunRecoveryBlockedError";
8296
+ }
8297
+ };
8298
+ var RunPauseRequested = class extends Error {
8299
+ code = "RUN_PAUSE_REQUESTED";
8300
+ constructor(message = "Run paused by user") {
8301
+ super(message);
8302
+ this.name = "RunPauseRequested";
8303
+ }
8304
+ };
8305
+ function isRunPauseSignal(signal) {
8306
+ const reason = signal?.reason;
8307
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8308
+ }
8309
+
8310
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8311
+ async function executeRecoverableTool(input) {
8312
+ const local = input.state.local;
8313
+ if (!local?.commitExecutionBoundary) return input.execute();
8314
+ if (local.executingToolCallId) {
8315
+ if (local.executingToolCallId !== input.call.id) {
8316
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8317
+ }
8318
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8319
+ if (!decision || decision.kind === "blocked") {
8320
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8321
+ }
8322
+ if (decision.kind === "settled") return decision.result;
8323
+ }
8324
+ local.executingToolCallId = input.call.id;
8325
+ await local.commitExecutionBoundary(input.state);
8326
+ const result = await input.execute();
8327
+ if (!result.success && isRunPauseSignal(local.signal)) {
8328
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8329
+ error.name = "AbortError";
8330
+ throw error;
8331
+ }
8332
+ return result;
8333
+ }
8334
+ async function commitToolBoundary(state, result) {
8335
+ if (!state.local?.commitExecutionBoundary) return;
8336
+ delete state.local.executingToolCallId;
8337
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8338
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8339
+ await state.local.commitExecutionBoundary(state);
8340
+ }
8341
+
8220
8342
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8221
8343
  var logger11 = new Logger("ToolNode");
8222
8344
  function isAbortSignal(value) {
@@ -8387,6 +8509,7 @@ var ToolNode = class {
8387
8509
  const events = [];
8388
8510
  while (true) {
8389
8511
  const result = await this.runNextPendingToolCall(state);
8512
+ await commitToolBoundary(state, result);
8390
8513
  if (Array.isArray(result.events) && result.events.length > 0) {
8391
8514
  events.push(...result.events);
8392
8515
  }
@@ -8403,11 +8526,9 @@ var ToolNode = class {
8403
8526
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8404
8527
  const signalRaw = state.local?.signal;
8405
8528
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8406
- settlePendingToolCallsAfterAbort({
8407
- state,
8408
- calls,
8409
- toolCatalog: this.toolRuntime
8410
- });
8529
+ if (!isRunPauseSignal(signalRaw)) {
8530
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8531
+ }
8411
8532
  const abortError = new Error("The user aborted a request.");
8412
8533
  abortError.name = "AbortError";
8413
8534
  throw abortError;
@@ -8546,16 +8667,21 @@ var ToolNode = class {
8546
8667
  tool_calls: [call]
8547
8668
  });
8548
8669
  try {
8549
- const exec = await executeToolWithIdempotency({
8550
- idempotencyKey: execution.idempotencyKey,
8551
- inFlight: this.idempotencyInFlight,
8552
- history: readHistoryEvents(prepared.local),
8553
- toolName: execution.toolName,
8554
- execute: () => this.toolRuntime.executeTool(
8555
- execution.toolName,
8556
- execution.toolArgs,
8557
- prepared.toolContext
8558
- )
8670
+ const exec = await executeRecoverableTool({
8671
+ state,
8672
+ call,
8673
+ context: prepared.toolContext,
8674
+ execute: () => executeToolWithIdempotency({
8675
+ idempotencyKey: execution.idempotencyKey,
8676
+ inFlight: this.idempotencyInFlight,
8677
+ history: readHistoryEvents(prepared.local),
8678
+ toolName: execution.toolName,
8679
+ execute: () => this.toolRuntime.executeTool(
8680
+ execution.toolName,
8681
+ execution.toolArgs,
8682
+ prepared.toolContext
8683
+ )
8684
+ })
8559
8685
  });
8560
8686
  if (exec.success) {
8561
8687
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8635,7 +8761,7 @@ var ToolNode = class {
8635
8761
  bridge: execution.bridge
8636
8762
  });
8637
8763
  } catch (error) {
8638
- if (isToolExecutionAbort(error)) {
8764
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8639
8765
  settleToolCallsAfterExecutionAbort({
8640
8766
  state,
8641
8767
  remainingCalls: calls.slice(1),
@@ -8695,7 +8821,7 @@ var ToolNode = class {
8695
8821
  {
8696
8822
  attachments: context.attachments,
8697
8823
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8698
- ephemeral: context.exec.idempotency?.cacheHit === true,
8824
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8699
8825
  durationMs: context.exec.durationMs
8700
8826
  }
8701
8827
  );
@@ -8752,6 +8878,9 @@ var ToolNode = class {
8752
8878
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8753
8879
  }
8754
8880
  async handleError(context) {
8881
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
8882
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
8883
+ }
8755
8884
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8756
8885
  await this.emitToolDecisionAudit({
8757
8886
  action: "tool.deny",
@@ -9649,12 +9778,33 @@ var RuntimeEventPublisher = class {
9649
9778
  var EventBusEventPersistence = class {
9650
9779
  constructor(options) {
9651
9780
  this.options = options;
9781
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
9652
9782
  }
9653
9783
  options;
9654
9784
  scheduledEventIds = /* @__PURE__ */ new Set();
9655
9785
  writeTail = Promise.resolve();
9656
9786
  firstWriteError;
9657
9787
  connected = false;
9788
+ checkpointWritesActive;
9789
+ checkpointEvents = [];
9790
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9791
+ async commitCheckpoint(checkpointKey, checkpoint) {
9792
+ const writer = this.options.checkpointWriter;
9793
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9794
+ const events = this.checkpointEvents;
9795
+ this.checkpointEvents = [];
9796
+ await this.enqueueWrite(() => writer({
9797
+ checkpointKey,
9798
+ checkpoint,
9799
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9800
+ }));
9801
+ }
9802
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
9803
+ finishCheckpointWrites() {
9804
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
9805
+ this.checkpointEvents = [];
9806
+ this.checkpointWritesActive = false;
9807
+ }
9658
9808
  connect() {
9659
9809
  if (this.connected) {
9660
9810
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -9701,14 +9851,22 @@ var EventBusEventPersistence = class {
9701
9851
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
9702
9852
  return;
9703
9853
  }
9854
+ if (this.checkpointWritesActive) {
9855
+ this.scheduledEventIds.add(event.id);
9856
+ this.checkpointEvents.push(event);
9857
+ return;
9858
+ }
9704
9859
  void this.scheduleWrite(event).catch(() => void 0);
9705
9860
  };
9706
9861
  scheduleWrite(event) {
9707
9862
  this.scheduledEventIds.add(event.id);
9708
- const eventStoreId = this.options.nextEventStoreId();
9709
- const write = this.writeTail.then(async () => {
9710
- await this.options.eventStore.append({ eventStoreId, event });
9711
- });
9863
+ return this.enqueueWrite(() => this.options.eventStore.append({
9864
+ eventStoreId: this.options.nextEventStoreId(),
9865
+ event
9866
+ }));
9867
+ }
9868
+ enqueueWrite(operation) {
9869
+ const write = this.writeTail.then(operation);
9712
9870
  this.writeTail = write;
9713
9871
  void write.catch((error) => {
9714
9872
  this.firstWriteError ??= error;
@@ -11115,8 +11273,6 @@ __export(run_supervisor_exports, {
11115
11273
  RunNotFoundError: () => RunNotFoundError,
11116
11274
  runMetaFromRecord: () => runMetaFromRecord
11117
11275
  });
11118
-
11119
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
11120
11276
  function cloneRunRecord(record) {
11121
11277
  return {
11122
11278
  ...record,
@@ -11136,6 +11292,11 @@ function matchesStatus(candidate, filter) {
11136
11292
  }
11137
11293
  var MemoryRunRegistryStore = class {
11138
11294
  store = /* @__PURE__ */ new Map();
11295
+ async compareAndSwap(previous, next) {
11296
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
11297
+ this.store.set(next.runId, cloneRunRecord(next));
11298
+ return true;
11299
+ }
11139
11300
  async save(record) {
11140
11301
  this.store.set(record.runId, cloneRunRecord(record));
11141
11302
  }
@@ -11283,6 +11444,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
11283
11444
  }
11284
11445
  };
11285
11446
 
11447
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
11448
+ async function persistRunTransition(store, previous, next) {
11449
+ if (store.compareAndSwap) {
11450
+ if (!await store.compareAndSwap(previous, next)) {
11451
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
11452
+ }
11453
+ } else {
11454
+ await store.save(next);
11455
+ }
11456
+ }
11457
+
11286
11458
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
11287
11459
  function isRunTerminalStatus(status) {
11288
11460
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -11338,6 +11510,7 @@ var DefaultRunHandle = class {
11338
11510
  parentRunId;
11339
11511
  runRecord;
11340
11512
  abortController;
11513
+ executionId;
11341
11514
  agentSpecSnapshot;
11342
11515
  requestSnapshot;
11343
11516
  transportEventBus;
@@ -11353,6 +11526,9 @@ var DefaultRunHandle = class {
11353
11526
  this.runId = options.runRecord.runId;
11354
11527
  this.parentRunId = options.runRecord.parentRunId;
11355
11528
  this.abortController = options.abortController;
11529
+ const executionId = options.runRecord.metadata?.executionId;
11530
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
11531
+ this.executionId = executionId;
11356
11532
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
11357
11533
  this.requestSnapshot = cloneRequest(options.request);
11358
11534
  this.transportEventBus = options.eventBus;
@@ -11372,8 +11548,9 @@ var DefaultRunHandle = class {
11372
11548
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
11373
11549
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
11374
11550
  */
11375
- replaceExecutionAbortController(controller) {
11551
+ replaceExecutionAbortController(controller, executionId) {
11376
11552
  this.abortController = controller;
11553
+ this.executionId = executionId;
11377
11554
  }
11378
11555
  async spec() {
11379
11556
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -11393,6 +11570,7 @@ var DefaultRunHandle = class {
11393
11570
  this.abortController.abort(opts.reason);
11394
11571
  const latestRecord = await this.registryStore.load(this.runId);
11395
11572
  const baseRecord = latestRecord ?? this.runRecord;
11573
+ this.assertExecutionOwner(baseRecord);
11396
11574
  const transition = decideRunLifecycleTransition(baseRecord.status);
11397
11575
  if (transition.kind === "skip_terminal") {
11398
11576
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -11402,7 +11580,7 @@ var DefaultRunHandle = class {
11402
11580
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11403
11581
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
11404
11582
  };
11405
- await this.registryStore.save(settledRecord);
11583
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
11406
11584
  this.runRecord = { ...settledRecord };
11407
11585
  return;
11408
11586
  }
@@ -11429,7 +11607,7 @@ var DefaultRunHandle = class {
11429
11607
  }
11430
11608
  }
11431
11609
  };
11432
- await this.registryStore.save(nextRecord);
11610
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11433
11611
  this.runRecord = { ...nextRecord };
11434
11612
  await this.auditPort.emit({
11435
11613
  envelopeId: generateAuditEnvelopeId(),
@@ -11537,21 +11715,35 @@ var DefaultRunHandle = class {
11537
11715
  async markFailed(error, patch = {}) {
11538
11716
  await this.saveLifecycleStatus("failed", patch, error);
11539
11717
  }
11540
- async pause(_reason) {
11541
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
11718
+ async pause(reason = "Run paused by user") {
11719
+ const latest = await this.registryStore.load(this.runId);
11720
+ if (latest) this.assertExecutionOwner(latest);
11721
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
11722
+ const next = {
11723
+ ...latest,
11724
+ status: "paused",
11725
+ updatedAt: Date.now(),
11726
+ pauseReason: reason,
11727
+ pausedAt: void 0
11728
+ };
11729
+ await persistRunTransition(this.registryStore, latest, next);
11730
+ this.runRecord = next;
11731
+ this.abortController.abort(new RunPauseRequested(reason));
11542
11732
  }
11543
- async resume() {
11544
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
11733
+ async markPaused(patch = {}) {
11734
+ await this.saveLifecycleStatus("paused", patch);
11545
11735
  }
11546
11736
  async saveLifecycleStatus(status, patch, errorIfAny) {
11547
11737
  const latestRecord = await this.registryStore.load(this.runId);
11548
11738
  const baseRecord = latestRecord ?? this.runRecord;
11549
11739
  const transition = decideRunLifecycleTransition(baseRecord.status);
11740
+ this.assertExecutionOwner(baseRecord);
11741
+ if (status === "running" && baseRecord.status === "paused") return;
11550
11742
  if (transition.kind === "skip_terminal") {
11551
11743
  this.runRecord = { ...baseRecord };
11552
11744
  return;
11553
11745
  }
11554
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
11746
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
11555
11747
  const updatedAt = Date.now();
11556
11748
  const nextRecord = {
11557
11749
  ...baseRecord,
@@ -11559,8 +11751,8 @@ var DefaultRunHandle = class {
11559
11751
  updatedAt,
11560
11752
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11561
11753
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
11562
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11563
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
11754
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11755
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
11564
11756
  errorIfAny,
11565
11757
  metadata: awaitingUserPatch?.eventId ? {
11566
11758
  ...baseRecord.metadata ?? {},
@@ -11571,7 +11763,7 @@ var DefaultRunHandle = class {
11571
11763
  }
11572
11764
  } : baseRecord.metadata
11573
11765
  };
11574
- await this.registryStore.save(nextRecord);
11766
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11575
11767
  this.runRecord = { ...nextRecord };
11576
11768
  if (status === "completed" || status === "failed") {
11577
11769
  this.closeObservationChannel();
@@ -11581,6 +11773,11 @@ var DefaultRunHandle = class {
11581
11773
  forwardTransportEvent = (envelope) => {
11582
11774
  this.observationEventBus.emit("event", envelope);
11583
11775
  };
11776
+ assertExecutionOwner(record) {
11777
+ if (record.metadata?.executionId !== this.executionId) {
11778
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
11779
+ }
11780
+ }
11584
11781
  forwardTransportError = (error) => {
11585
11782
  this.observationEventBus.emit("error", error);
11586
11783
  };
@@ -11962,6 +12159,24 @@ async function recoverRunsOnBoot(options) {
11962
12159
  const outcomes = [];
11963
12160
  for (const record of activeRecords) {
11964
12161
  const updatedAt = options.now();
12162
+ if (await options.canRestoreRun?.(record)) {
12163
+ const metadata = { ...record.metadata };
12164
+ const awaitingUser = metadata.awaitingUser;
12165
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
12166
+ const restored = { ...awaitingUser };
12167
+ Reflect.deleteProperty(restored, "resumeClaim");
12168
+ metadata.awaitingUser = restored;
12169
+ }
12170
+ await persistRunTransition(options.registryStore, record, {
12171
+ ...record,
12172
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
12173
+ pausedAt: record.pausedAt ?? updatedAt,
12174
+ pauseReason: record.pauseReason ?? options.reason,
12175
+ updatedAt,
12176
+ metadata
12177
+ });
12178
+ continue;
12179
+ }
11965
12180
  const nextRecord = {
11966
12181
  ...record,
11967
12182
  status: "failed",
@@ -11979,7 +12194,7 @@ async function recoverRunsOnBoot(options) {
11979
12194
  }
11980
12195
  }
11981
12196
  };
11982
- await options.registryStore.save(nextRecord);
12197
+ await persistRunTransition(options.registryStore, record, nextRecord);
11983
12198
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
11984
12199
  options.notifyTerminal(outcome);
11985
12200
  outcomes.push(outcome);
@@ -12103,8 +12318,13 @@ var DefaultRunSupervisor = class {
12103
12318
  inFlight = /* @__PURE__ */ new Map();
12104
12319
  eventWatchDisposers = /* @__PURE__ */ new Map();
12105
12320
  controlOperations = /* @__PURE__ */ new Map();
12321
+ canRestoreRun;
12106
12322
  constructor(options) {
12323
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
12324
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
12325
+ }
12107
12326
  this.registryStore = options.registryStore;
12327
+ this.canRestoreRun = options.canRestoreRun;
12108
12328
  this.auditPort = options.auditPort;
12109
12329
  this.executor = options.executor;
12110
12330
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -12152,6 +12372,23 @@ var DefaultRunSupervisor = class {
12152
12372
  this.releaseRunAdmission(runId);
12153
12373
  throw error;
12154
12374
  }
12375
+ return this.attachRun(record, spec, controller);
12376
+ }
12377
+ async restoreRun(spec) {
12378
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12379
+ return this.withRunControlLock(spec.runId, async () => {
12380
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
12381
+ const record = await this.registryStore.load(spec.runId);
12382
+ if (!record) throw new RunNotFoundError(spec.runId);
12383
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
12384
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
12385
+ }
12386
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
12387
+ return this.attachRun(record, spec, new AbortController());
12388
+ });
12389
+ }
12390
+ attachRun(record, spec, controller) {
12391
+ const runId = record.runId;
12155
12392
  try {
12156
12393
  const handle = new DefaultRunHandle({
12157
12394
  runRecord: record,
@@ -12249,11 +12486,36 @@ var DefaultRunSupervisor = class {
12249
12486
  registryStore: this.registryStore,
12250
12487
  reason,
12251
12488
  now: this.now,
12252
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
12489
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
12490
+ canRestoreRun: this.canRestoreRun
12253
12491
  });
12254
12492
  }
12255
- async pause(_runId, _reason) {
12256
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
12493
+ async pause(runId, reason) {
12494
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
12495
+ }
12496
+ async resumePausedRun(input) {
12497
+ return this.withRunControlLock(input.runId, async () => {
12498
+ const handle = this.getHandle(input.runId);
12499
+ const record = await this.registryStore.load(input.runId);
12500
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
12501
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12502
+ }
12503
+ await persistRunTransition(this.registryStore, record, {
12504
+ ...record,
12505
+ status: "running",
12506
+ updatedAt: this.now(),
12507
+ pausedAt: void 0,
12508
+ pauseReason: void 0,
12509
+ errorIfAny: void 0,
12510
+ metadata: { ...record.metadata, executionId: input.executionId }
12511
+ });
12512
+ const controller = new AbortController();
12513
+ handle.replaceExecutionAbortController(controller, input.executionId);
12514
+ handle.attachTransportEventBus(input.eventBus);
12515
+ this.controllers.set(input.runId, controller);
12516
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
12517
+ return handle;
12518
+ });
12257
12519
  }
12258
12520
  async claimResume(runId, interaction, eventBus, parentSignal) {
12259
12521
  return this.withRunControlLock(runId, async () => {
@@ -12288,7 +12550,7 @@ var DefaultRunSupervisor = class {
12288
12550
  throw new RunNotFoundError(runId);
12289
12551
  }
12290
12552
  const claimId = generateRunResumeClaimId();
12291
- await this.registryStore.save({
12553
+ await persistRunTransition(this.registryStore, record, {
12292
12554
  ...record,
12293
12555
  updatedAt: this.now(),
12294
12556
  metadata: {
@@ -12376,7 +12638,7 @@ var DefaultRunSupervisor = class {
12376
12638
  }
12377
12639
  const awaitingUserWithoutClaim = { ...awaitingUser };
12378
12640
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12379
- await this.registryStore.save({
12641
+ await persistRunTransition(this.registryStore, record, {
12380
12642
  ...record,
12381
12643
  status: "running",
12382
12644
  updatedAt: this.now(),
@@ -12397,7 +12659,7 @@ var DefaultRunSupervisor = class {
12397
12659
  });
12398
12660
  const executionController = new AbortController();
12399
12661
  forwardParentAbortSignal(executionController, parentSignal);
12400
- handle.replaceExecutionAbortController(executionController);
12662
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
12401
12663
  this.controllers.set(runId, executionController);
12402
12664
  return handle;
12403
12665
  });
@@ -12415,7 +12677,7 @@ var DefaultRunSupervisor = class {
12415
12677
  }
12416
12678
  const awaitingUserWithoutClaim = { ...awaitingUser };
12417
12679
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12418
- await this.registryStore.save({
12680
+ await persistRunTransition(this.registryStore, record, {
12419
12681
  ...record,
12420
12682
  updatedAt: this.now(),
12421
12683
  metadata: {