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