@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
@@ -5,6 +5,7 @@ require('eventsource-parser');
5
5
  var tiktoken = require('tiktoken');
6
6
  var async_hooks = require('async_hooks');
7
7
  var crypto = require('crypto');
8
+ var util = require('util');
8
9
  require('fs/promises');
9
10
  require('path');
10
11
 
@@ -2007,12 +2008,15 @@ __export(graph_engine_exports, {
2007
2008
  MemoryEventStore: () => MemoryEventStore,
2008
2009
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
2009
2010
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
2011
+ RunPauseRequested: () => RunPauseRequested,
2012
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
2010
2013
  ToolNode: () => ToolNode,
2011
2014
  UserNode: () => UserNode,
2012
2015
  WaitUserNode: () => WaitUserNode,
2013
2016
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
2014
2017
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
2015
2018
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
2019
+ isRunPauseSignal: () => isRunPauseSignal,
2016
2020
  isRuntimeFailureFact: () => isRuntimeFailureFact,
2017
2021
  readCheckpointContextUsage: () => readCheckpointContextUsage,
2018
2022
  requireEventStoreId: () => requireEventStoreId,
@@ -2608,6 +2612,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2608
2612
  "memory",
2609
2613
  "runtimeEventSink",
2610
2614
  "runtimeEventCommitPort",
2615
+ "commitExecutionBoundary",
2616
+ "toolRecoveryPort",
2611
2617
  "runtimeFailureFactSink",
2612
2618
  "signal",
2613
2619
  "summarizationCallbacks",
@@ -3158,6 +3164,7 @@ var GraphExecutor = class {
3158
3164
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3159
3165
  };
3160
3166
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3167
+ this.executionCheckpointPort = config.executionCheckpointPort;
3161
3168
  }
3162
3169
  checkpointer;
3163
3170
  nodes = /* @__PURE__ */ new Map();
@@ -3165,6 +3172,7 @@ var GraphExecutor = class {
3165
3172
  checkpointQueues = /* @__PURE__ */ new Map();
3166
3173
  config;
3167
3174
  telemetryPort;
3175
+ executionCheckpointPort;
3168
3176
  registerNode(node) {
3169
3177
  this.nodes.set(node.id, node);
3170
3178
  }
@@ -3173,6 +3181,7 @@ var GraphExecutor = class {
3173
3181
  }
3174
3182
  sanitize(state) {
3175
3183
  return {
3184
+ ...state,
3176
3185
  nodeId: state.nodeId,
3177
3186
  revision: state.revision ?? 0,
3178
3187
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3192,8 +3201,9 @@ var GraphExecutor = class {
3192
3201
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3193
3202
  }
3194
3203
  this.ephemeralLocals.set(checkpointKey, { ...local });
3195
- await this.checkpointer.save(checkpointKey, {
3204
+ await this.commitCheckpoint(checkpointKey, {
3196
3205
  nodeId,
3206
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3197
3207
  revision: 1,
3198
3208
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3199
3209
  local: sanitizeCheckpointLocal(local)
@@ -3204,6 +3214,33 @@ var GraphExecutor = class {
3204
3214
  );
3205
3215
  });
3206
3216
  }
3217
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3218
+ async continueSession(checkpointKey, input) {
3219
+ if (!this.executionCheckpointPort) {
3220
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3221
+ }
3222
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3223
+ const current = await this.checkpointer.load(checkpointKey);
3224
+ if (!current || current.revision !== input.expectedRevision) {
3225
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3226
+ }
3227
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3228
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3229
+ }
3230
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3231
+ return { checkpoint: current, events: [], stepCount: 0 };
3232
+ }
3233
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3234
+ try {
3235
+ return await this.runUntilYieldQueued(
3236
+ checkpointKey,
3237
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3238
+ );
3239
+ } finally {
3240
+ this.ephemeralLocals.delete(checkpointKey);
3241
+ }
3242
+ });
3243
+ }
3207
3244
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3208
3245
  async resumeSession(checkpointKey, input) {
3209
3246
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3224,17 +3261,21 @@ var GraphExecutor = class {
3224
3261
  );
3225
3262
  }
3226
3263
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3264
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3265
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3266
+ }
3227
3267
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3228
- await this.checkpointer.save(checkpointKey, {
3268
+ await this.commitCheckpoint(checkpointKey, {
3229
3269
  ...current,
3230
3270
  nodeId: input.nodeId ?? "llm",
3271
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3231
3272
  revision: currentRevision + 1,
3232
3273
  local: sanitizeCheckpointLocal(resumedLocal)
3233
3274
  });
3234
3275
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3235
3276
  return this.runUntilYieldQueued(
3236
3277
  checkpointKey,
3237
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3278
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3238
3279
  );
3239
3280
  });
3240
3281
  }
@@ -3329,9 +3370,16 @@ var GraphExecutor = class {
3329
3370
  ...state,
3330
3371
  revision: (state.revision ?? 0) + 1
3331
3372
  });
3332
- await this.checkpointer.save(checkpointKey, checkpoint);
3373
+ await this.commitCheckpoint(checkpointKey, checkpoint);
3333
3374
  return checkpoint;
3334
3375
  }
3376
+ async commitCheckpoint(checkpointKey, checkpoint) {
3377
+ if (this.executionCheckpointPort) {
3378
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3379
+ } else {
3380
+ await this.checkpointer.save(checkpointKey, checkpoint);
3381
+ }
3382
+ }
3335
3383
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3336
3384
  const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3337
3385
  return { events, checkpoint, stepCount };
@@ -3344,6 +3392,15 @@ var GraphExecutor = class {
3344
3392
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3345
3393
  local: { ...state.local || {}, ...ephemeral }
3346
3394
  };
3395
+ if (this.executionCheckpointPort) {
3396
+ state.local = {
3397
+ ...state.local,
3398
+ commitExecutionBoundary: async (boundary) => {
3399
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3400
+ boundary.revision = saved.revision;
3401
+ }
3402
+ };
3403
+ }
3347
3404
  const isAbortSignal2 = (v) => {
3348
3405
  return v !== null && typeof v === "object" && "aborted" in v;
3349
3406
  };
@@ -3353,11 +3410,12 @@ var GraphExecutor = class {
3353
3410
  throw err;
3354
3411
  };
3355
3412
  let stepCount = 0;
3413
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3356
3414
  let allEvents = [];
3357
3415
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3358
3416
  maxSteps
3359
3417
  });
3360
- while (stepCount < maxSteps) {
3418
+ while (previousSteps + stepCount < maxSteps) {
3361
3419
  stepCount += 1;
3362
3420
  reportStepsUsed(stepCount);
3363
3421
  const signalRaw = state.local?.signal;
@@ -3369,7 +3427,7 @@ var GraphExecutor = class {
3369
3427
  const stepPreparation = prepareGraphStep({
3370
3428
  state,
3371
3429
  maxSteps,
3372
- stepCount
3430
+ stepCount: previousSteps + stepCount
3373
3431
  });
3374
3432
  state = stepPreparation.state;
3375
3433
  const node = this.nodes.get(state.nodeId);
@@ -3378,6 +3436,7 @@ var GraphExecutor = class {
3378
3436
  maxSteps,
3379
3437
  stepCount
3380
3438
  });
3439
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3381
3440
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3382
3441
  this.ephemeralLocals.delete(checkpointKey);
3383
3442
  return result3;
@@ -3387,6 +3446,11 @@ var GraphExecutor = class {
3387
3446
  stepCount,
3388
3447
  nodeId: state.nodeId
3389
3448
  });
3449
+ if (this.executionCheckpointPort) {
3450
+ state.executionStatus = "executing";
3451
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3452
+ state.revision = saved.revision;
3453
+ }
3390
3454
  const result2 = await runGraphNodeWithTelemetry({
3391
3455
  node,
3392
3456
  state,
@@ -3411,10 +3475,13 @@ var GraphExecutor = class {
3411
3475
  fromNodeId: stepResolution.action.fromNodeId,
3412
3476
  nextNodeId: stepResolution.action.nextNodeId
3413
3477
  });
3414
- await this.saveCheckpoint(checkpointKey, state);
3478
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3479
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3480
+ state.revision = saved.revision;
3415
3481
  continue;
3416
3482
  }
3417
3483
  if (stepResolution.action.kind === "yield") {
3484
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3418
3485
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3419
3486
  maxSteps,
3420
3487
  stepCount
@@ -3425,6 +3492,7 @@ var GraphExecutor = class {
3425
3492
  maxSteps,
3426
3493
  stepCount
3427
3494
  });
3495
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3428
3496
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3429
3497
  }
3430
3498
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3445,6 +3513,7 @@ var GraphExecutor = class {
3445
3513
  },
3446
3514
  retryable: false
3447
3515
  }), "GraphExecutor.engine_budget_exhausted"));
3516
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3448
3517
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3449
3518
  this.ephemeralLocals.delete(checkpointKey);
3450
3519
  return result;
@@ -7120,10 +7189,11 @@ var LlmNode = class {
7120
7189
  bridge.handle
7121
7190
  );
7122
7191
  } catch (error) {
7123
- bridge.finalizePartialAnswer();
7192
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7124
7193
  throw error;
7125
7194
  }
7126
7195
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7196
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7127
7197
  switch (decision.kind) {
7128
7198
  case "tool_calls": {
7129
7199
  if (forceFinalAnswer) {
@@ -8330,6 +8400,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8330
8400
  function recordToolProtocolError(params) {
8331
8401
  }
8332
8402
 
8403
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8404
+ var RunRecoveryBlockedError = class extends Error {
8405
+ code = "RUN_RECOVERY_BLOCKED";
8406
+ constructor(message) {
8407
+ super(message);
8408
+ this.name = "RunRecoveryBlockedError";
8409
+ }
8410
+ };
8411
+ var RunPauseRequested = class extends Error {
8412
+ code = "RUN_PAUSE_REQUESTED";
8413
+ constructor(message = "Run paused by user") {
8414
+ super(message);
8415
+ this.name = "RunPauseRequested";
8416
+ }
8417
+ };
8418
+ function isRunPauseSignal(signal) {
8419
+ const reason = signal?.reason;
8420
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8421
+ }
8422
+
8423
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8424
+ async function executeRecoverableTool(input) {
8425
+ const local = input.state.local;
8426
+ if (!local?.commitExecutionBoundary) return input.execute();
8427
+ if (local.executingToolCallId) {
8428
+ if (local.executingToolCallId !== input.call.id) {
8429
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8430
+ }
8431
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8432
+ if (!decision || decision.kind === "blocked") {
8433
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8434
+ }
8435
+ if (decision.kind === "settled") return decision.result;
8436
+ }
8437
+ local.executingToolCallId = input.call.id;
8438
+ await local.commitExecutionBoundary(input.state);
8439
+ const result = await input.execute();
8440
+ if (!result.success && isRunPauseSignal(local.signal)) {
8441
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8442
+ error.name = "AbortError";
8443
+ throw error;
8444
+ }
8445
+ return result;
8446
+ }
8447
+ async function commitToolBoundary(state, result) {
8448
+ if (!state.local?.commitExecutionBoundary) return;
8449
+ delete state.local.executingToolCallId;
8450
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8451
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8452
+ await state.local.commitExecutionBoundary(state);
8453
+ }
8454
+
8333
8455
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8334
8456
  var logger11 = new Logger("ToolNode");
8335
8457
  function isAbortSignal(value) {
@@ -8500,6 +8622,7 @@ var ToolNode = class {
8500
8622
  const events = [];
8501
8623
  while (true) {
8502
8624
  const result = await this.runNextPendingToolCall(state);
8625
+ await commitToolBoundary(state, result);
8503
8626
  if (Array.isArray(result.events) && result.events.length > 0) {
8504
8627
  events.push(...result.events);
8505
8628
  }
@@ -8516,11 +8639,9 @@ var ToolNode = class {
8516
8639
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8517
8640
  const signalRaw = state.local?.signal;
8518
8641
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8519
- settlePendingToolCallsAfterAbort({
8520
- state,
8521
- calls,
8522
- toolCatalog: this.toolRuntime
8523
- });
8642
+ if (!isRunPauseSignal(signalRaw)) {
8643
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8644
+ }
8524
8645
  const abortError = new Error("The user aborted a request.");
8525
8646
  abortError.name = "AbortError";
8526
8647
  throw abortError;
@@ -8659,16 +8780,21 @@ var ToolNode = class {
8659
8780
  tool_calls: [call]
8660
8781
  });
8661
8782
  try {
8662
- const exec = await executeToolWithIdempotency({
8663
- idempotencyKey: execution.idempotencyKey,
8664
- inFlight: this.idempotencyInFlight,
8665
- history: readHistoryEvents(prepared.local),
8666
- toolName: execution.toolName,
8667
- execute: () => this.toolRuntime.executeTool(
8668
- execution.toolName,
8669
- execution.toolArgs,
8670
- prepared.toolContext
8671
- )
8783
+ const exec = await executeRecoverableTool({
8784
+ state,
8785
+ call,
8786
+ context: prepared.toolContext,
8787
+ execute: () => executeToolWithIdempotency({
8788
+ idempotencyKey: execution.idempotencyKey,
8789
+ inFlight: this.idempotencyInFlight,
8790
+ history: readHistoryEvents(prepared.local),
8791
+ toolName: execution.toolName,
8792
+ execute: () => this.toolRuntime.executeTool(
8793
+ execution.toolName,
8794
+ execution.toolArgs,
8795
+ prepared.toolContext
8796
+ )
8797
+ })
8672
8798
  });
8673
8799
  if (exec.success) {
8674
8800
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8748,7 +8874,7 @@ var ToolNode = class {
8748
8874
  bridge: execution.bridge
8749
8875
  });
8750
8876
  } catch (error) {
8751
- if (isToolExecutionAbort(error)) {
8877
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8752
8878
  settleToolCallsAfterExecutionAbort({
8753
8879
  state,
8754
8880
  remainingCalls: calls.slice(1),
@@ -8808,7 +8934,7 @@ var ToolNode = class {
8808
8934
  {
8809
8935
  attachments: context.attachments,
8810
8936
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8811
- ephemeral: context.exec.idempotency?.cacheHit === true,
8937
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8812
8938
  durationMs: context.exec.durationMs
8813
8939
  }
8814
8940
  );
@@ -8865,6 +8991,9 @@ var ToolNode = class {
8865
8991
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8866
8992
  }
8867
8993
  async handleError(context) {
8994
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
8995
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
8996
+ }
8868
8997
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8869
8998
  await this.emitToolDecisionAudit({
8870
8999
  action: "tool.deny",
@@ -9762,12 +9891,33 @@ var RuntimeEventPublisher = class {
9762
9891
  var EventBusEventPersistence = class {
9763
9892
  constructor(options) {
9764
9893
  this.options = options;
9894
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
9765
9895
  }
9766
9896
  options;
9767
9897
  scheduledEventIds = /* @__PURE__ */ new Set();
9768
9898
  writeTail = Promise.resolve();
9769
9899
  firstWriteError;
9770
9900
  connected = false;
9901
+ checkpointWritesActive;
9902
+ checkpointEvents = [];
9903
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9904
+ async commitCheckpoint(checkpointKey, checkpoint) {
9905
+ const writer = this.options.checkpointWriter;
9906
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9907
+ const events = this.checkpointEvents;
9908
+ this.checkpointEvents = [];
9909
+ await this.enqueueWrite(() => writer({
9910
+ checkpointKey,
9911
+ checkpoint,
9912
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9913
+ }));
9914
+ }
9915
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
9916
+ finishCheckpointWrites() {
9917
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
9918
+ this.checkpointEvents = [];
9919
+ this.checkpointWritesActive = false;
9920
+ }
9771
9921
  connect() {
9772
9922
  if (this.connected) {
9773
9923
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -9814,14 +9964,22 @@ var EventBusEventPersistence = class {
9814
9964
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
9815
9965
  return;
9816
9966
  }
9967
+ if (this.checkpointWritesActive) {
9968
+ this.scheduledEventIds.add(event.id);
9969
+ this.checkpointEvents.push(event);
9970
+ return;
9971
+ }
9817
9972
  void this.scheduleWrite(event).catch(() => void 0);
9818
9973
  };
9819
9974
  scheduleWrite(event) {
9820
9975
  this.scheduledEventIds.add(event.id);
9821
- const eventStoreId = this.options.nextEventStoreId();
9822
- const write = this.writeTail.then(async () => {
9823
- await this.options.eventStore.append({ eventStoreId, event });
9824
- });
9976
+ return this.enqueueWrite(() => this.options.eventStore.append({
9977
+ eventStoreId: this.options.nextEventStoreId(),
9978
+ event
9979
+ }));
9980
+ }
9981
+ enqueueWrite(operation) {
9982
+ const write = this.writeTail.then(operation);
9825
9983
  this.writeTail = write;
9826
9984
  void write.catch((error) => {
9827
9985
  this.firstWriteError ??= error;
@@ -11228,8 +11386,6 @@ __export(run_supervisor_exports, {
11228
11386
  RunNotFoundError: () => RunNotFoundError,
11229
11387
  runMetaFromRecord: () => runMetaFromRecord
11230
11388
  });
11231
-
11232
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
11233
11389
  function cloneRunRecord(record) {
11234
11390
  return {
11235
11391
  ...record,
@@ -11249,6 +11405,11 @@ function matchesStatus(candidate, filter) {
11249
11405
  }
11250
11406
  var MemoryRunRegistryStore = class {
11251
11407
  store = /* @__PURE__ */ new Map();
11408
+ async compareAndSwap(previous, next) {
11409
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
11410
+ this.store.set(next.runId, cloneRunRecord(next));
11411
+ return true;
11412
+ }
11252
11413
  async save(record) {
11253
11414
  this.store.set(record.runId, cloneRunRecord(record));
11254
11415
  }
@@ -11396,6 +11557,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
11396
11557
  }
11397
11558
  };
11398
11559
 
11560
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
11561
+ async function persistRunTransition(store, previous, next) {
11562
+ if (store.compareAndSwap) {
11563
+ if (!await store.compareAndSwap(previous, next)) {
11564
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
11565
+ }
11566
+ } else {
11567
+ await store.save(next);
11568
+ }
11569
+ }
11570
+
11399
11571
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
11400
11572
  function isRunTerminalStatus(status) {
11401
11573
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -11451,6 +11623,7 @@ var DefaultRunHandle = class {
11451
11623
  parentRunId;
11452
11624
  runRecord;
11453
11625
  abortController;
11626
+ executionId;
11454
11627
  agentSpecSnapshot;
11455
11628
  requestSnapshot;
11456
11629
  transportEventBus;
@@ -11466,6 +11639,9 @@ var DefaultRunHandle = class {
11466
11639
  this.runId = options.runRecord.runId;
11467
11640
  this.parentRunId = options.runRecord.parentRunId;
11468
11641
  this.abortController = options.abortController;
11642
+ const executionId = options.runRecord.metadata?.executionId;
11643
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
11644
+ this.executionId = executionId;
11469
11645
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
11470
11646
  this.requestSnapshot = cloneRequest(options.request);
11471
11647
  this.transportEventBus = options.eventBus;
@@ -11485,8 +11661,9 @@ var DefaultRunHandle = class {
11485
11661
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
11486
11662
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
11487
11663
  */
11488
- replaceExecutionAbortController(controller) {
11664
+ replaceExecutionAbortController(controller, executionId) {
11489
11665
  this.abortController = controller;
11666
+ this.executionId = executionId;
11490
11667
  }
11491
11668
  async spec() {
11492
11669
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -11506,6 +11683,7 @@ var DefaultRunHandle = class {
11506
11683
  this.abortController.abort(opts.reason);
11507
11684
  const latestRecord = await this.registryStore.load(this.runId);
11508
11685
  const baseRecord = latestRecord ?? this.runRecord;
11686
+ this.assertExecutionOwner(baseRecord);
11509
11687
  const transition = decideRunLifecycleTransition(baseRecord.status);
11510
11688
  if (transition.kind === "skip_terminal") {
11511
11689
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -11515,7 +11693,7 @@ var DefaultRunHandle = class {
11515
11693
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11516
11694
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
11517
11695
  };
11518
- await this.registryStore.save(settledRecord);
11696
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
11519
11697
  this.runRecord = { ...settledRecord };
11520
11698
  return;
11521
11699
  }
@@ -11542,7 +11720,7 @@ var DefaultRunHandle = class {
11542
11720
  }
11543
11721
  }
11544
11722
  };
11545
- await this.registryStore.save(nextRecord);
11723
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11546
11724
  this.runRecord = { ...nextRecord };
11547
11725
  await this.auditPort.emit({
11548
11726
  envelopeId: generateAuditEnvelopeId(),
@@ -11650,21 +11828,35 @@ var DefaultRunHandle = class {
11650
11828
  async markFailed(error, patch = {}) {
11651
11829
  await this.saveLifecycleStatus("failed", patch, error);
11652
11830
  }
11653
- async pause(_reason) {
11654
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
11831
+ async pause(reason = "Run paused by user") {
11832
+ const latest = await this.registryStore.load(this.runId);
11833
+ if (latest) this.assertExecutionOwner(latest);
11834
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
11835
+ const next = {
11836
+ ...latest,
11837
+ status: "paused",
11838
+ updatedAt: Date.now(),
11839
+ pauseReason: reason,
11840
+ pausedAt: void 0
11841
+ };
11842
+ await persistRunTransition(this.registryStore, latest, next);
11843
+ this.runRecord = next;
11844
+ this.abortController.abort(new RunPauseRequested(reason));
11655
11845
  }
11656
- async resume() {
11657
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
11846
+ async markPaused(patch = {}) {
11847
+ await this.saveLifecycleStatus("paused", patch);
11658
11848
  }
11659
11849
  async saveLifecycleStatus(status, patch, errorIfAny) {
11660
11850
  const latestRecord = await this.registryStore.load(this.runId);
11661
11851
  const baseRecord = latestRecord ?? this.runRecord;
11662
11852
  const transition = decideRunLifecycleTransition(baseRecord.status);
11853
+ this.assertExecutionOwner(baseRecord);
11854
+ if (status === "running" && baseRecord.status === "paused") return;
11663
11855
  if (transition.kind === "skip_terminal") {
11664
11856
  this.runRecord = { ...baseRecord };
11665
11857
  return;
11666
11858
  }
11667
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
11859
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
11668
11860
  const updatedAt = Date.now();
11669
11861
  const nextRecord = {
11670
11862
  ...baseRecord,
@@ -11672,8 +11864,8 @@ var DefaultRunHandle = class {
11672
11864
  updatedAt,
11673
11865
  currentNode: patch.currentNode ?? baseRecord.currentNode,
11674
11866
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
11675
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11676
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
11867
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
11868
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
11677
11869
  errorIfAny,
11678
11870
  metadata: awaitingUserPatch?.eventId ? {
11679
11871
  ...baseRecord.metadata ?? {},
@@ -11684,7 +11876,7 @@ var DefaultRunHandle = class {
11684
11876
  }
11685
11877
  } : baseRecord.metadata
11686
11878
  };
11687
- await this.registryStore.save(nextRecord);
11879
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
11688
11880
  this.runRecord = { ...nextRecord };
11689
11881
  if (status === "completed" || status === "failed") {
11690
11882
  this.closeObservationChannel();
@@ -11694,6 +11886,11 @@ var DefaultRunHandle = class {
11694
11886
  forwardTransportEvent = (envelope) => {
11695
11887
  this.observationEventBus.emit("event", envelope);
11696
11888
  };
11889
+ assertExecutionOwner(record) {
11890
+ if (record.metadata?.executionId !== this.executionId) {
11891
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
11892
+ }
11893
+ }
11697
11894
  forwardTransportError = (error) => {
11698
11895
  this.observationEventBus.emit("error", error);
11699
11896
  };
@@ -12075,6 +12272,24 @@ async function recoverRunsOnBoot(options) {
12075
12272
  const outcomes = [];
12076
12273
  for (const record of activeRecords) {
12077
12274
  const updatedAt = options.now();
12275
+ if (await options.canRestoreRun?.(record)) {
12276
+ const metadata = { ...record.metadata };
12277
+ const awaitingUser = metadata.awaitingUser;
12278
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
12279
+ const restored = { ...awaitingUser };
12280
+ Reflect.deleteProperty(restored, "resumeClaim");
12281
+ metadata.awaitingUser = restored;
12282
+ }
12283
+ await persistRunTransition(options.registryStore, record, {
12284
+ ...record,
12285
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
12286
+ pausedAt: record.pausedAt ?? updatedAt,
12287
+ pauseReason: record.pauseReason ?? options.reason,
12288
+ updatedAt,
12289
+ metadata
12290
+ });
12291
+ continue;
12292
+ }
12078
12293
  const nextRecord = {
12079
12294
  ...record,
12080
12295
  status: "failed",
@@ -12092,7 +12307,7 @@ async function recoverRunsOnBoot(options) {
12092
12307
  }
12093
12308
  }
12094
12309
  };
12095
- await options.registryStore.save(nextRecord);
12310
+ await persistRunTransition(options.registryStore, record, nextRecord);
12096
12311
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
12097
12312
  options.notifyTerminal(outcome);
12098
12313
  outcomes.push(outcome);
@@ -12216,8 +12431,13 @@ var DefaultRunSupervisor = class {
12216
12431
  inFlight = /* @__PURE__ */ new Map();
12217
12432
  eventWatchDisposers = /* @__PURE__ */ new Map();
12218
12433
  controlOperations = /* @__PURE__ */ new Map();
12434
+ canRestoreRun;
12219
12435
  constructor(options) {
12436
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
12437
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
12438
+ }
12220
12439
  this.registryStore = options.registryStore;
12440
+ this.canRestoreRun = options.canRestoreRun;
12221
12441
  this.auditPort = options.auditPort;
12222
12442
  this.executor = options.executor;
12223
12443
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -12265,6 +12485,23 @@ var DefaultRunSupervisor = class {
12265
12485
  this.releaseRunAdmission(runId);
12266
12486
  throw error;
12267
12487
  }
12488
+ return this.attachRun(record, spec, controller);
12489
+ }
12490
+ async restoreRun(spec) {
12491
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12492
+ return this.withRunControlLock(spec.runId, async () => {
12493
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
12494
+ const record = await this.registryStore.load(spec.runId);
12495
+ if (!record) throw new RunNotFoundError(spec.runId);
12496
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
12497
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
12498
+ }
12499
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
12500
+ return this.attachRun(record, spec, new AbortController());
12501
+ });
12502
+ }
12503
+ attachRun(record, spec, controller) {
12504
+ const runId = record.runId;
12268
12505
  try {
12269
12506
  const handle = new DefaultRunHandle({
12270
12507
  runRecord: record,
@@ -12362,11 +12599,36 @@ var DefaultRunSupervisor = class {
12362
12599
  registryStore: this.registryStore,
12363
12600
  reason,
12364
12601
  now: this.now,
12365
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
12602
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
12603
+ canRestoreRun: this.canRestoreRun
12366
12604
  });
12367
12605
  }
12368
- async pause(_runId, _reason) {
12369
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
12606
+ async pause(runId, reason) {
12607
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
12608
+ }
12609
+ async resumePausedRun(input) {
12610
+ return this.withRunControlLock(input.runId, async () => {
12611
+ const handle = this.getHandle(input.runId);
12612
+ const record = await this.registryStore.load(input.runId);
12613
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
12614
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12615
+ }
12616
+ await persistRunTransition(this.registryStore, record, {
12617
+ ...record,
12618
+ status: "running",
12619
+ updatedAt: this.now(),
12620
+ pausedAt: void 0,
12621
+ pauseReason: void 0,
12622
+ errorIfAny: void 0,
12623
+ metadata: { ...record.metadata, executionId: input.executionId }
12624
+ });
12625
+ const controller = new AbortController();
12626
+ handle.replaceExecutionAbortController(controller, input.executionId);
12627
+ handle.attachTransportEventBus(input.eventBus);
12628
+ this.controllers.set(input.runId, controller);
12629
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
12630
+ return handle;
12631
+ });
12370
12632
  }
12371
12633
  async claimResume(runId, interaction, eventBus, parentSignal) {
12372
12634
  return this.withRunControlLock(runId, async () => {
@@ -12401,7 +12663,7 @@ var DefaultRunSupervisor = class {
12401
12663
  throw new RunNotFoundError(runId);
12402
12664
  }
12403
12665
  const claimId = generateRunResumeClaimId();
12404
- await this.registryStore.save({
12666
+ await persistRunTransition(this.registryStore, record, {
12405
12667
  ...record,
12406
12668
  updatedAt: this.now(),
12407
12669
  metadata: {
@@ -12489,7 +12751,7 @@ var DefaultRunSupervisor = class {
12489
12751
  }
12490
12752
  const awaitingUserWithoutClaim = { ...awaitingUser };
12491
12753
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12492
- await this.registryStore.save({
12754
+ await persistRunTransition(this.registryStore, record, {
12493
12755
  ...record,
12494
12756
  status: "running",
12495
12757
  updatedAt: this.now(),
@@ -12510,7 +12772,7 @@ var DefaultRunSupervisor = class {
12510
12772
  });
12511
12773
  const executionController = new AbortController();
12512
12774
  forwardParentAbortSignal(executionController, parentSignal);
12513
- handle.replaceExecutionAbortController(executionController);
12775
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
12514
12776
  this.controllers.set(runId, executionController);
12515
12777
  return handle;
12516
12778
  });
@@ -12528,7 +12790,7 @@ var DefaultRunSupervisor = class {
12528
12790
  }
12529
12791
  const awaitingUserWithoutClaim = { ...awaitingUser };
12530
12792
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12531
- await this.registryStore.save({
12793
+ await persistRunTransition(this.registryStore, record, {
12532
12794
  ...record,
12533
12795
  updatedAt: this.now(),
12534
12796
  metadata: {