@linnlabs/linnkit 0.32.3 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/cli.cjs +458 -70
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +458 -70
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +55 -0
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +55 -0
  9. package/dist/context-manager.js.map +1 -1
  10. package/dist/contracts/agentSpec.d.cts +30 -30
  11. package/dist/contracts/agentSpec.d.ts +30 -30
  12. package/dist/contracts/audit.d.cts +24 -24
  13. package/dist/contracts/audit.d.ts +24 -24
  14. package/dist/contracts/contextPolicy.d.cts +36 -36
  15. package/dist/contracts/contextPolicy.d.ts +36 -36
  16. package/dist/contracts/events.d.cts +1083 -1083
  17. package/dist/contracts/events.d.ts +1083 -1083
  18. package/dist/contracts/execution.d.cts +8 -8
  19. package/dist/contracts/execution.d.ts +8 -8
  20. package/dist/contracts/messages.d.cts +1178 -1178
  21. package/dist/contracts/messages.d.ts +1178 -1178
  22. package/dist/contracts/provider-continuation.d.cts +28 -28
  23. package/dist/contracts/provider-continuation.d.ts +28 -28
  24. package/dist/contracts/sse.d.cts +899 -899
  25. package/dist/contracts/sse.d.ts +899 -899
  26. package/dist/contracts/sub-run-trace-payload.d.cts +26 -26
  27. package/dist/contracts/sub-run-trace-payload.d.ts +26 -26
  28. package/dist/contracts/token-accounting.d.cts +30 -30
  29. package/dist/contracts/token-accounting.d.ts +30 -30
  30. package/dist/index.cjs +538 -94
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.js +538 -94
  33. package/dist/index.js.map +1 -1
  34. package/dist/quickstart/toolRuntime.d.cts +1 -1
  35. package/dist/quickstart/toolRuntime.d.ts +1 -1
  36. package/dist/quickstart/types.d.cts +1 -1
  37. package/dist/quickstart/types.d.ts +1 -1
  38. package/dist/quickstart.cjs +458 -70
  39. package/dist/quickstart.cjs.map +1 -1
  40. package/dist/quickstart.js +458 -70
  41. package/dist/quickstart.js.map +1 -1
  42. package/dist/runtime-kernel/child-runs/childRunInvoker.d.cts +11 -0
  43. package/dist/runtime-kernel/child-runs/childRunInvoker.d.ts +11 -0
  44. package/dist/runtime-kernel/events/agentEvents.d.cts +172 -172
  45. package/dist/runtime-kernel/events/agentEvents.d.ts +172 -172
  46. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.cts +15 -1
  47. package/dist/runtime-kernel/execution/eventBusEventPersistence.d.ts +15 -1
  48. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.cts +34 -0
  49. package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.ts +34 -0
  50. package/dist/runtime-kernel/graph-engine/engine.d.cts +13 -2
  51. package/dist/runtime-kernel/graph-engine/engine.d.ts +13 -2
  52. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.cts +6 -0
  53. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.ts +6 -0
  54. package/dist/runtime-kernel/graph-engine/index.d.cts +3 -1
  55. package/dist/runtime-kernel/graph-engine/index.d.ts +3 -1
  56. package/dist/runtime-kernel/graph-engine/types.d.cts +8 -0
  57. package/dist/runtime-kernel/graph-engine/types.d.ts +8 -0
  58. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +35 -6
  59. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +35 -6
  60. package/dist/runtime-kernel/run-supervisor/index.d.cts +1 -1
  61. package/dist/runtime-kernel/run-supervisor/index.d.ts +1 -1
  62. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.cts +1 -0
  63. package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.ts +1 -0
  64. package/dist/runtime-kernel/run-supervisor/runHandle.d.cts +9 -5
  65. package/dist/runtime-kernel/run-supervisor/runHandle.d.ts +9 -5
  66. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.cts +2 -0
  67. package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.ts +2 -0
  68. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +9 -2
  69. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +9 -2
  70. package/dist/runtime-kernel.cjs +535 -91
  71. package/dist/runtime-kernel.cjs.map +1 -1
  72. package/dist/runtime-kernel.d.cts +3 -1
  73. package/dist/runtime-kernel.d.ts +3 -1
  74. package/dist/runtime-kernel.js +532 -92
  75. package/dist/runtime-kernel.js.map +1 -1
  76. package/dist/testkit.cjs +535 -91
  77. package/dist/testkit.cjs.map +1 -1
  78. package/dist/testkit.js +535 -91
  79. package/dist/testkit.js.map +1 -1
  80. package/docs/integration/child-runs.md +12 -0
  81. package/docs/integration/persistence.md +24 -0
  82. package/docs/integration/run-supervisor.md +15 -2
  83. package/package.json +2 -2
package/dist/testkit.js CHANGED
@@ -4,6 +4,7 @@ import 'eventsource-parser';
4
4
  import { get_encoding } from 'tiktoken';
5
5
  import { AsyncLocalStorage } from 'async_hooks';
6
6
  import { createHash } from 'crypto';
7
+ import { isDeepStrictEqual } from 'util';
7
8
  import { mkdir, appendFile } from 'fs/promises';
8
9
  import { dirname } from 'path';
9
10
 
@@ -103,6 +104,8 @@ __export(runtime_kernel_exports, {
103
104
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
104
105
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
105
106
  REASONING_EFFORTS: () => REASONING_EFFORTS,
107
+ RunPauseRequested: () => RunPauseRequested,
108
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
106
109
  RuntimeEventSubRunTracePublisher: () => RuntimeEventSubRunTracePublisher,
107
110
  SYSTEM_REMINDER_RULES: () => SYSTEM_REMINDER_RULES,
108
111
  SystemReminderRegistry: () => SystemReminderRegistry,
@@ -160,6 +163,7 @@ __export(runtime_kernel_exports, {
160
163
  getToolContextRuntimeBinding: () => getToolContextRuntimeBinding,
161
164
  graph: () => graph_engine_exports,
162
165
  hostReminderTextTemplate: () => hostReminderTextTemplate,
166
+ isRunPauseSignal: () => isRunPauseSignal,
163
167
  isRuntimeFailureFact: () => isRuntimeFailureFact,
164
168
  isValidReasoningEffort: () => isValidReasoningEffort,
165
169
  lastStepsHintTemplate: () => lastStepsHintTemplate,
@@ -168,6 +172,7 @@ __export(runtime_kernel_exports, {
168
172
  maxStepsForceFinalAnswerTemplate: () => maxStepsForceFinalAnswerTemplate,
169
173
  noopAudit: () => noopAudit,
170
174
  normalizeToolArgs: () => normalizeToolArgs,
175
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
171
176
  parseToolModelInputDeclaration: () => parseToolModelInputDeclaration,
172
177
  periodicProgressReflectionTemplate: () => periodicProgressReflectionTemplate,
173
178
  phaseEqualsTrigger: () => phaseEqualsTrigger,
@@ -207,13 +212,17 @@ __export(graph_engine_exports, {
207
212
  MemoryEventStore: () => MemoryEventStore,
208
213
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
209
214
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
215
+ RunPauseRequested: () => RunPauseRequested,
216
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
210
217
  ToolNode: () => ToolNode,
211
218
  UserNode: () => UserNode,
212
219
  WaitUserNode: () => WaitUserNode,
213
220
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
214
221
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
215
222
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
223
+ isRunPauseSignal: () => isRunPauseSignal,
216
224
  isRuntimeFailureFact: () => isRuntimeFailureFact,
225
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
217
226
  readCheckpointContextUsage: () => readCheckpointContextUsage,
218
227
  requireEventStoreId: () => requireEventStoreId,
219
228
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -2581,6 +2590,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2581
2590
  "memory",
2582
2591
  "runtimeEventSink",
2583
2592
  "runtimeEventCommitPort",
2593
+ "commitExecutionBoundary",
2594
+ "toolRecoveryPort",
2584
2595
  "runtimeFailureFactSink",
2585
2596
  "signal",
2586
2597
  "summarizationCallbacks",
@@ -3131,6 +3142,7 @@ var GraphExecutor = class {
3131
3142
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3132
3143
  };
3133
3144
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3145
+ this.executionCheckpointPort = config.executionCheckpointPort;
3134
3146
  }
3135
3147
  checkpointer;
3136
3148
  nodes = /* @__PURE__ */ new Map();
@@ -3138,6 +3150,7 @@ var GraphExecutor = class {
3138
3150
  checkpointQueues = /* @__PURE__ */ new Map();
3139
3151
  config;
3140
3152
  telemetryPort;
3153
+ executionCheckpointPort;
3141
3154
  registerNode(node) {
3142
3155
  this.nodes.set(node.id, node);
3143
3156
  }
@@ -3146,6 +3159,7 @@ var GraphExecutor = class {
3146
3159
  }
3147
3160
  sanitize(state) {
3148
3161
  return {
3162
+ ...state,
3149
3163
  nodeId: state.nodeId,
3150
3164
  revision: state.revision ?? 0,
3151
3165
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3165,8 +3179,9 @@ var GraphExecutor = class {
3165
3179
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3166
3180
  }
3167
3181
  this.ephemeralLocals.set(checkpointKey, { ...local });
3168
- await this.checkpointer.save(checkpointKey, {
3182
+ await this.commitCheckpoint(checkpointKey, {
3169
3183
  nodeId,
3184
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3170
3185
  revision: 1,
3171
3186
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3172
3187
  local: sanitizeCheckpointLocal(local)
@@ -3177,6 +3192,33 @@ var GraphExecutor = class {
3177
3192
  );
3178
3193
  });
3179
3194
  }
3195
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3196
+ async continueSession(checkpointKey, input) {
3197
+ if (!this.executionCheckpointPort) {
3198
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3199
+ }
3200
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3201
+ const current = await this.checkpointer.load(checkpointKey);
3202
+ if (!current || current.revision !== input.expectedRevision) {
3203
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3204
+ }
3205
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3206
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3207
+ }
3208
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3209
+ return { checkpoint: current, events: [], stepCount: 0 };
3210
+ }
3211
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3212
+ try {
3213
+ return await this.runUntilYieldQueued(
3214
+ checkpointKey,
3215
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3216
+ );
3217
+ } finally {
3218
+ this.ephemeralLocals.delete(checkpointKey);
3219
+ }
3220
+ });
3221
+ }
3180
3222
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3181
3223
  async resumeSession(checkpointKey, input) {
3182
3224
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3197,17 +3239,21 @@ var GraphExecutor = class {
3197
3239
  );
3198
3240
  }
3199
3241
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3242
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3243
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3244
+ }
3200
3245
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3201
- await this.checkpointer.save(checkpointKey, {
3246
+ await this.commitCheckpoint(checkpointKey, {
3202
3247
  ...current,
3203
3248
  nodeId: input.nodeId ?? "llm",
3249
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3204
3250
  revision: currentRevision + 1,
3205
3251
  local: sanitizeCheckpointLocal(resumedLocal)
3206
3252
  });
3207
3253
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3208
3254
  return this.runUntilYieldQueued(
3209
3255
  checkpointKey,
3210
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3256
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3211
3257
  );
3212
3258
  });
3213
3259
  }
@@ -3298,16 +3344,23 @@ var GraphExecutor = class {
3298
3344
  };
3299
3345
  }
3300
3346
  async saveCheckpoint(checkpointKey, state) {
3301
- const checkpoint = this.sanitize({
3347
+ const checkpoint2 = this.sanitize({
3302
3348
  ...state,
3303
3349
  revision: (state.revision ?? 0) + 1
3304
3350
  });
3305
- await this.checkpointer.save(checkpointKey, checkpoint);
3306
- return checkpoint;
3351
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3352
+ return checkpoint2;
3353
+ }
3354
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3355
+ if (this.executionCheckpointPort) {
3356
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3357
+ } else {
3358
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3359
+ }
3307
3360
  }
3308
3361
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3309
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3310
- return { events, checkpoint, stepCount };
3362
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3363
+ return { events, checkpoint: checkpoint2, stepCount };
3311
3364
  }
3312
3365
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3313
3366
  let state = initialState;
@@ -3317,6 +3370,15 @@ var GraphExecutor = class {
3317
3370
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3318
3371
  local: { ...state.local || {}, ...ephemeral }
3319
3372
  };
3373
+ if (this.executionCheckpointPort) {
3374
+ state.local = {
3375
+ ...state.local,
3376
+ commitExecutionBoundary: async (boundary) => {
3377
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3378
+ boundary.revision = saved.revision;
3379
+ }
3380
+ };
3381
+ }
3320
3382
  const isAbortSignal2 = (v) => {
3321
3383
  return v !== null && typeof v === "object" && "aborted" in v;
3322
3384
  };
@@ -3326,11 +3388,12 @@ var GraphExecutor = class {
3326
3388
  throw err;
3327
3389
  };
3328
3390
  let stepCount = 0;
3391
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3329
3392
  let allEvents = [];
3330
3393
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3331
3394
  maxSteps
3332
3395
  });
3333
- while (stepCount < maxSteps) {
3396
+ while (previousSteps + stepCount < maxSteps) {
3334
3397
  stepCount += 1;
3335
3398
  reportStepsUsed(stepCount);
3336
3399
  const signalRaw = state.local?.signal;
@@ -3342,7 +3405,7 @@ var GraphExecutor = class {
3342
3405
  const stepPreparation = prepareGraphStep({
3343
3406
  state,
3344
3407
  maxSteps,
3345
- stepCount
3408
+ stepCount: previousSteps + stepCount
3346
3409
  });
3347
3410
  state = stepPreparation.state;
3348
3411
  const node = this.nodes.get(state.nodeId);
@@ -3351,6 +3414,7 @@ var GraphExecutor = class {
3351
3414
  maxSteps,
3352
3415
  stepCount
3353
3416
  });
3417
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3354
3418
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3355
3419
  this.ephemeralLocals.delete(checkpointKey);
3356
3420
  return result3;
@@ -3360,6 +3424,11 @@ var GraphExecutor = class {
3360
3424
  stepCount,
3361
3425
  nodeId: state.nodeId
3362
3426
  });
3427
+ if (this.executionCheckpointPort) {
3428
+ state.executionStatus = "executing";
3429
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3430
+ state.revision = saved.revision;
3431
+ }
3363
3432
  const result2 = await runGraphNodeWithTelemetry({
3364
3433
  node,
3365
3434
  state,
@@ -3384,10 +3453,13 @@ var GraphExecutor = class {
3384
3453
  fromNodeId: stepResolution.action.fromNodeId,
3385
3454
  nextNodeId: stepResolution.action.nextNodeId
3386
3455
  });
3387
- await this.saveCheckpoint(checkpointKey, state);
3456
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3457
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3458
+ state.revision = saved.revision;
3388
3459
  continue;
3389
3460
  }
3390
3461
  if (stepResolution.action.kind === "yield") {
3462
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3391
3463
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3392
3464
  maxSteps,
3393
3465
  stepCount
@@ -3398,6 +3470,7 @@ var GraphExecutor = class {
3398
3470
  maxSteps,
3399
3471
  stepCount
3400
3472
  });
3473
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3401
3474
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3402
3475
  }
3403
3476
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3418,6 +3491,7 @@ var GraphExecutor = class {
3418
3491
  },
3419
3492
  retryable: false
3420
3493
  }), "GraphExecutor.engine_budget_exhausted"));
3494
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3421
3495
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3422
3496
  this.ephemeralLocals.delete(checkpointKey);
3423
3497
  return result;
@@ -7311,10 +7385,11 @@ var LlmNode = class {
7311
7385
  bridge.handle
7312
7386
  );
7313
7387
  } catch (error) {
7314
- bridge.finalizePartialAnswer();
7388
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7315
7389
  throw error;
7316
7390
  }
7317
7391
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7392
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7318
7393
  switch (decision.kind) {
7319
7394
  case "tool_calls": {
7320
7395
  if (forceFinalAnswer) {
@@ -8582,6 +8657,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8582
8657
  function recordToolProtocolError(params) {
8583
8658
  }
8584
8659
 
8660
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8661
+ var RunRecoveryBlockedError = class extends Error {
8662
+ code = "RUN_RECOVERY_BLOCKED";
8663
+ constructor(message) {
8664
+ super(message);
8665
+ this.name = "RunRecoveryBlockedError";
8666
+ }
8667
+ };
8668
+ var RunPauseRequested = class extends Error {
8669
+ code = "RUN_PAUSE_REQUESTED";
8670
+ constructor(message = "Run paused by user") {
8671
+ super(message);
8672
+ this.name = "RunPauseRequested";
8673
+ }
8674
+ };
8675
+ function isRunPauseSignal(signal) {
8676
+ const reason = signal?.reason;
8677
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8678
+ }
8679
+
8680
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8681
+ async function executeRecoverableTool(input) {
8682
+ const local = input.state.local;
8683
+ if (!local?.commitExecutionBoundary) return input.execute();
8684
+ if (local.executingToolCallId) {
8685
+ if (local.executingToolCallId !== input.call.id) {
8686
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8687
+ }
8688
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8689
+ if (!decision || decision.kind === "blocked") {
8690
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8691
+ }
8692
+ if (decision.kind === "settled") return decision.result;
8693
+ }
8694
+ local.executingToolCallId = input.call.id;
8695
+ await local.commitExecutionBoundary(input.state);
8696
+ const result = await input.execute();
8697
+ if (!result.success && isRunPauseSignal(local.signal)) {
8698
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8699
+ error.name = "AbortError";
8700
+ throw error;
8701
+ }
8702
+ return result;
8703
+ }
8704
+ async function commitToolBoundary(state, result) {
8705
+ if (!state.local?.commitExecutionBoundary) return;
8706
+ delete state.local.executingToolCallId;
8707
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8708
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8709
+ await state.local.commitExecutionBoundary(state);
8710
+ }
8711
+
8585
8712
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8586
8713
  var logger11 = new Logger("ToolNode");
8587
8714
  function isAbortSignal(value) {
@@ -8752,6 +8879,7 @@ var ToolNode = class {
8752
8879
  const events = [];
8753
8880
  while (true) {
8754
8881
  const result = await this.runNextPendingToolCall(state);
8882
+ await commitToolBoundary(state, result);
8755
8883
  if (Array.isArray(result.events) && result.events.length > 0) {
8756
8884
  events.push(...result.events);
8757
8885
  }
@@ -8768,11 +8896,9 @@ var ToolNode = class {
8768
8896
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8769
8897
  const signalRaw = state.local?.signal;
8770
8898
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8771
- settlePendingToolCallsAfterAbort({
8772
- state,
8773
- calls,
8774
- toolCatalog: this.toolRuntime
8775
- });
8899
+ if (!isRunPauseSignal(signalRaw)) {
8900
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8901
+ }
8776
8902
  const abortError = new Error("The user aborted a request.");
8777
8903
  abortError.name = "AbortError";
8778
8904
  throw abortError;
@@ -8911,16 +9037,21 @@ var ToolNode = class {
8911
9037
  tool_calls: [call]
8912
9038
  });
8913
9039
  try {
8914
- const exec = await executeToolWithIdempotency({
8915
- idempotencyKey: execution.idempotencyKey,
8916
- inFlight: this.idempotencyInFlight,
8917
- history: readHistoryEvents(prepared.local),
8918
- toolName: execution.toolName,
8919
- execute: () => this.toolRuntime.executeTool(
8920
- execution.toolName,
8921
- execution.toolArgs,
8922
- prepared.toolContext
8923
- )
9040
+ const exec = await executeRecoverableTool({
9041
+ state,
9042
+ call,
9043
+ context: prepared.toolContext,
9044
+ execute: () => executeToolWithIdempotency({
9045
+ idempotencyKey: execution.idempotencyKey,
9046
+ inFlight: this.idempotencyInFlight,
9047
+ history: readHistoryEvents(prepared.local),
9048
+ toolName: execution.toolName,
9049
+ execute: () => this.toolRuntime.executeTool(
9050
+ execution.toolName,
9051
+ execution.toolArgs,
9052
+ prepared.toolContext
9053
+ )
9054
+ })
8924
9055
  });
8925
9056
  if (exec.success) {
8926
9057
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -9000,7 +9131,7 @@ var ToolNode = class {
9000
9131
  bridge: execution.bridge
9001
9132
  });
9002
9133
  } catch (error) {
9003
- if (isToolExecutionAbort(error)) {
9134
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
9004
9135
  settleToolCallsAfterExecutionAbort({
9005
9136
  state,
9006
9137
  remainingCalls: calls.slice(1),
@@ -9060,7 +9191,7 @@ var ToolNode = class {
9060
9191
  {
9061
9192
  attachments: context.attachments,
9062
9193
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
9063
- ephemeral: context.exec.idempotency?.cacheHit === true,
9194
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
9064
9195
  durationMs: context.exec.durationMs
9065
9196
  }
9066
9197
  );
@@ -9117,6 +9248,9 @@ var ToolNode = class {
9117
9248
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
9118
9249
  }
9119
9250
  async handleError(context) {
9251
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9252
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9253
+ }
9120
9254
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
9121
9255
  await this.emitToolDecisionAudit({
9122
9256
  action: "tool.deny",
@@ -9353,16 +9487,16 @@ function requireEventStoreId(eventStoreId) {
9353
9487
  }
9354
9488
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9355
9489
  let lastTimestamp = 0;
9356
- let counter = 0;
9490
+ let counter2 = 0;
9357
9491
  return () => {
9358
9492
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9359
9493
  if (timestamp === lastTimestamp) {
9360
- counter += 1;
9494
+ counter2 += 1;
9361
9495
  } else {
9362
9496
  lastTimestamp = timestamp;
9363
- counter = 0;
9497
+ counter2 = 0;
9364
9498
  }
9365
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9499
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9366
9500
  };
9367
9501
  }
9368
9502
 
@@ -9774,6 +9908,76 @@ function assertNonNegativeSafeInteger(value, field) {
9774
9908
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9775
9909
  }
9776
9910
  }
9911
+ var counter = z.number().int().nonnegative();
9912
+ var executor = z.object({
9913
+ stepCount: counter,
9914
+ phase: z.string().optional(),
9915
+ maxSteps: counter.optional(),
9916
+ remainingSteps: z.number().int().optional(),
9917
+ finalStepPolicy: z.enum(["final_answer", "force_tools"]).optional(),
9918
+ finalStepForcedTools: z.array(z.string()).optional(),
9919
+ lastStepsHintThreshold: counter.optional(),
9920
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9921
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9922
+ runLockedModelId: z.string().optional(),
9923
+ lastSuccessfulLlmModelId: z.string().optional(),
9924
+ llmInvocationKind: z.enum(["user_initiated", "continuation"]).optional(),
9925
+ llmInvocationCount: counter.optional(),
9926
+ lockRequestedModelId: z.boolean().optional(),
9927
+ contextCompaction: z.object({
9928
+ attemptCount: counter,
9929
+ committedCount: counter,
9930
+ lastCommittedFingerprint: z.string().optional()
9931
+ }).strict().optional()
9932
+ }).strict();
9933
+ var checkpoint = z.object({
9934
+ nodeId: z.string().min(1),
9935
+ schemaVersion: z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9936
+ revision: counter.optional(),
9937
+ executionStatus: z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9938
+ local: z.object({
9939
+ runId: RunIdSchema.optional(),
9940
+ parentRunId: RunIdSchema.optional(),
9941
+ conversationId: z.string().optional(),
9942
+ turnId: z.string().optional(),
9943
+ request: SerializableJsonRecord.optional(),
9944
+ history: z.array(RuntimeEvent).optional(),
9945
+ newEvents: z.array(RuntimeEvent).optional(),
9946
+ executorLocal: executor.optional(),
9947
+ pendingToolCalls: z.array(z.object({
9948
+ id: ToolCallIdSchema,
9949
+ type: z.literal("function"),
9950
+ function: z.object({ name: z.string().min(1), arguments: z.string() }).strict()
9951
+ }).strict()).optional(),
9952
+ executingToolCallId: ToolCallIdSchema.optional(),
9953
+ toolBatchCompletionMode: z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9954
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9955
+ lastToolResult: SerializableJsonRecord.optional(),
9956
+ finalAnswer: z.string().optional(),
9957
+ answerId: z.string().optional(),
9958
+ chunkSeq: counter.optional(),
9959
+ contextUsage: ContextUsageSnapshot.optional()
9960
+ }).passthrough().optional()
9961
+ }).strict();
9962
+ function parseEngineCheckpoint(value) {
9963
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9964
+ for (const key of [
9965
+ "memory",
9966
+ "signal",
9967
+ "toolContext",
9968
+ "runtimeEventSink",
9969
+ "runtimeEventCommitPort",
9970
+ "runtimeFailureFactSink",
9971
+ "summarizationCallbacks",
9972
+ "commitExecutionBoundary",
9973
+ "toolRecoveryPort"
9974
+ ]) {
9975
+ if (result.local && Object.hasOwn(result.local, key)) {
9976
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9977
+ }
9978
+ }
9979
+ return result;
9980
+ }
9777
9981
 
9778
9982
  // src/runtime-kernel/tools/index.ts
9779
9983
  var tools_exports = {};
@@ -10225,12 +10429,33 @@ var RuntimeEventPublisher = class {
10225
10429
  var EventBusEventPersistence = class {
10226
10430
  constructor(options) {
10227
10431
  this.options = options;
10432
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10228
10433
  }
10229
10434
  options;
10230
10435
  scheduledEventIds = /* @__PURE__ */ new Set();
10231
10436
  writeTail = Promise.resolve();
10232
10437
  firstWriteError;
10233
10438
  connected = false;
10439
+ checkpointWritesActive;
10440
+ checkpointEvents = [];
10441
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10442
+ async commitCheckpoint(checkpointKey, checkpoint2) {
10443
+ const writer = this.options.checkpointWriter;
10444
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10445
+ const events = this.checkpointEvents;
10446
+ this.checkpointEvents = [];
10447
+ await this.enqueueWrite(() => writer({
10448
+ checkpointKey,
10449
+ checkpoint: checkpoint2,
10450
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10451
+ }));
10452
+ }
10453
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10454
+ finishCheckpointWrites() {
10455
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10456
+ this.checkpointEvents = [];
10457
+ this.checkpointWritesActive = false;
10458
+ }
10234
10459
  connect() {
10235
10460
  if (this.connected) {
10236
10461
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10277,14 +10502,22 @@ var EventBusEventPersistence = class {
10277
10502
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10278
10503
  return;
10279
10504
  }
10505
+ if (this.checkpointWritesActive) {
10506
+ this.scheduledEventIds.add(event.id);
10507
+ this.checkpointEvents.push(event);
10508
+ return;
10509
+ }
10280
10510
  void this.scheduleWrite(event).catch(() => void 0);
10281
10511
  };
10282
10512
  scheduleWrite(event) {
10283
10513
  this.scheduledEventIds.add(event.id);
10284
- const eventStoreId = this.options.nextEventStoreId();
10285
- const write = this.writeTail.then(async () => {
10286
- await this.options.eventStore.append({ eventStoreId, event });
10287
- });
10514
+ return this.enqueueWrite(() => this.options.eventStore.append({
10515
+ eventStoreId: this.options.nextEventStoreId(),
10516
+ event
10517
+ }));
10518
+ }
10519
+ enqueueWrite(operation) {
10520
+ const write = this.writeTail.then(operation);
10288
10521
  this.writeTail = write;
10289
10522
  void write.catch((error) => {
10290
10523
  this.firstWriteError ??= error;
@@ -11906,15 +12139,15 @@ function hasSeedHistoryPrefix(history, seedHistory) {
11906
12139
  }
11907
12140
  return true;
11908
12141
  }
11909
- function readCheckpointHistory(checkpoint) {
11910
- if (!checkpoint?.local) return [];
11911
- const history = checkpoint.local.history;
12142
+ function readCheckpointHistory(checkpoint2) {
12143
+ if (!checkpoint2?.local) return [];
12144
+ const history = checkpoint2.local.history;
11912
12145
  if (!Array.isArray(history)) return [];
11913
12146
  return parseRuntimeEvents(history);
11914
12147
  }
11915
12148
  async function recoverChildRunEventsFromCheckpoint(params) {
11916
- const checkpoint = await params.checkpointer.load(params.checkpointKey);
11917
- const history = readCheckpointHistory(checkpoint);
12149
+ const checkpoint2 = await params.checkpointer.load(params.checkpointKey);
12150
+ const history = readCheckpointHistory(checkpoint2);
11918
12151
  if (history.length === 0) {
11919
12152
  return [];
11920
12153
  }
@@ -12005,6 +12238,9 @@ var ChildRunInvoker = class {
12005
12238
  explicitConversationId: conversationId,
12006
12239
  parentToolContext
12007
12240
  });
12241
+ if (config.persistence?.expectedRevision !== void 0) {
12242
+ return this.continueChild(config, childRunId, runtimeConversationId);
12243
+ }
12008
12244
  const turnId = generateTurnId();
12009
12245
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
12010
12246
  conversationId: runtimeConversationId,
@@ -12012,21 +12248,8 @@ var ChildRunInvoker = class {
12012
12248
  maxSteps,
12013
12249
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
12014
12250
  });
12015
- const checkpointer = new MemoryCheckpointer();
12016
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
12017
- const llmNode = this.createLlmNode();
12018
- const toolNode = new ToolNode({
12019
- toolRuntime: this.toolRuntime,
12020
- observationPreview: this.observationPreview,
12021
- telemetryPort: this.telemetryPort,
12022
- auditPort: this.auditPort,
12023
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12024
- modelInputResolver: this.modelInputResolver
12025
- });
12026
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
12027
- graphExecutor.registerNode(llmNode);
12028
- graphExecutor.registerNode(toolNode);
12029
- graphExecutor.registerNode(waitUserNode);
12251
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
12252
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
12030
12253
  const childUserInput = createChildRunUserInput({
12031
12254
  id: generateRuntimeEventId(),
12032
12255
  conversationId: runtimeConversationId,
@@ -12106,6 +12329,7 @@ var ChildRunInvoker = class {
12106
12329
  ...abortSignal ? { signal: abortSignal } : {},
12107
12330
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
12108
12331
  runtimeEventSink,
12332
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
12109
12333
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
12110
12334
  systemPrompt
12111
12335
  };
@@ -12146,6 +12370,7 @@ var ChildRunInvoker = class {
12146
12370
  eventToMessageConverter: this.eventToMessageConverter
12147
12371
  });
12148
12372
  } catch (err) {
12373
+ if (config.persistence) throw err;
12149
12374
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
12150
12375
  checkpointer,
12151
12376
  checkpointKey: internalCheckpointKey,
@@ -12184,7 +12409,7 @@ var ChildRunInvoker = class {
12184
12409
  events: allEvents,
12185
12410
  eventToMessageConverter: this.eventToMessageConverter
12186
12411
  });
12187
- await checkpointer.clear(internalCheckpointKey);
12412
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12188
12413
  return {
12189
12414
  success: !error && !cancelled,
12190
12415
  runId: childRunId,
@@ -12201,6 +12426,66 @@ var ChildRunInvoker = class {
12201
12426
  error
12202
12427
  };
12203
12428
  }
12429
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12430
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12431
+ graph.registerNode(this.createLlmNode());
12432
+ graph.registerNode(new ToolNode({
12433
+ toolRuntime: this.toolRuntime,
12434
+ observationPreview: this.observationPreview,
12435
+ telemetryPort: this.telemetryPort,
12436
+ auditPort: this.auditPort,
12437
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12438
+ modelInputResolver: this.modelInputResolver
12439
+ }));
12440
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12441
+ return graph;
12442
+ }
12443
+ async continueChild(config, runId, conversationId) {
12444
+ const persistence = config.persistence;
12445
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12446
+ const checkpoint2 = await persistence.checkpointer.load(runId);
12447
+ if (!checkpoint2 || checkpoint2.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12448
+ const local = readGraphAgentLocal({ ...checkpoint2.local, runtimeEventSink: config.runtimeEventSink });
12449
+ const request = local.request;
12450
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12451
+ const context = createChildRunToolContext({
12452
+ parentToolContext: config.parentToolContext,
12453
+ conversationId,
12454
+ turnId: local.turnId,
12455
+ runId,
12456
+ parentRunId: config.parentRunId,
12457
+ userQuery: request.query,
12458
+ modelId: request.model_id,
12459
+ seedHistory: local.history,
12460
+ abortSignal: config.abortSignal
12461
+ });
12462
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12463
+ const result = await graph.continueSession(runId, {
12464
+ expectedRevision: persistence.expectedRevision,
12465
+ capabilities: {
12466
+ toolContext: context,
12467
+ signal: config.abortSignal,
12468
+ runtimeEventSink: config.runtimeEventSink,
12469
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12470
+ toolRecoveryPort: persistence.toolRecoveryPort
12471
+ }
12472
+ });
12473
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12474
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12475
+ const finalAnswer = extractFinalAnswer(events);
12476
+ return {
12477
+ runId,
12478
+ parentRunId: config.parentRunId,
12479
+ subrunId: runId,
12480
+ success: true,
12481
+ events,
12482
+ finalAnswer,
12483
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12484
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12485
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12486
+ toolset: { availableTools: request.availableTools }
12487
+ };
12488
+ }
12204
12489
  };
12205
12490
  function isAbortError2(error) {
12206
12491
  return error instanceof Error && error.name === "AbortError";
@@ -12602,8 +12887,6 @@ __export(run_supervisor_exports, {
12602
12887
  RunNotFoundError: () => RunNotFoundError,
12603
12888
  runMetaFromRecord: () => runMetaFromRecord
12604
12889
  });
12605
-
12606
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12607
12890
  function cloneRunRecord(record) {
12608
12891
  return {
12609
12892
  ...record,
@@ -12623,6 +12906,11 @@ function matchesStatus(candidate, filter) {
12623
12906
  }
12624
12907
  var MemoryRunRegistryStore = class {
12625
12908
  store = /* @__PURE__ */ new Map();
12909
+ async compareAndSwap(previous, next) {
12910
+ if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12911
+ this.store.set(next.runId, cloneRunRecord(next));
12912
+ return true;
12913
+ }
12626
12914
  async save(record) {
12627
12915
  this.store.set(record.runId, cloneRunRecord(record));
12628
12916
  }
@@ -12770,6 +13058,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12770
13058
  }
12771
13059
  };
12772
13060
 
13061
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
13062
+ async function persistRunTransition(store, previous, next) {
13063
+ if (store.compareAndSwap) {
13064
+ if (!await store.compareAndSwap(previous, next)) {
13065
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
13066
+ }
13067
+ } else {
13068
+ await store.save(next);
13069
+ }
13070
+ }
13071
+
12773
13072
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12774
13073
  function isRunTerminalStatus(status) {
12775
13074
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12825,6 +13124,7 @@ var DefaultRunHandle = class {
12825
13124
  parentRunId;
12826
13125
  runRecord;
12827
13126
  abortController;
13127
+ executionId;
12828
13128
  agentSpecSnapshot;
12829
13129
  requestSnapshot;
12830
13130
  transportEventBus;
@@ -12840,6 +13140,9 @@ var DefaultRunHandle = class {
12840
13140
  this.runId = options.runRecord.runId;
12841
13141
  this.parentRunId = options.runRecord.parentRunId;
12842
13142
  this.abortController = options.abortController;
13143
+ const executionId = options.runRecord.metadata?.executionId;
13144
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
13145
+ this.executionId = executionId;
12843
13146
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12844
13147
  this.requestSnapshot = cloneRequest(options.request);
12845
13148
  this.transportEventBus = options.eventBus;
@@ -12859,8 +13162,9 @@ var DefaultRunHandle = class {
12859
13162
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12860
13163
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12861
13164
  */
12862
- replaceExecutionAbortController(controller) {
13165
+ replaceExecutionAbortController(controller, executionId) {
12863
13166
  this.abortController = controller;
13167
+ this.executionId = executionId;
12864
13168
  }
12865
13169
  async spec() {
12866
13170
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12880,6 +13184,7 @@ var DefaultRunHandle = class {
12880
13184
  this.abortController.abort(opts.reason);
12881
13185
  const latestRecord = await this.registryStore.load(this.runId);
12882
13186
  const baseRecord = latestRecord ?? this.runRecord;
13187
+ this.assertExecutionOwner(baseRecord);
12883
13188
  const transition = decideRunLifecycleTransition(baseRecord.status);
12884
13189
  if (transition.kind === "skip_terminal") {
12885
13190
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12889,7 +13194,7 @@ var DefaultRunHandle = class {
12889
13194
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12890
13195
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12891
13196
  };
12892
- await this.registryStore.save(settledRecord);
13197
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12893
13198
  this.runRecord = { ...settledRecord };
12894
13199
  return;
12895
13200
  }
@@ -12916,7 +13221,7 @@ var DefaultRunHandle = class {
12916
13221
  }
12917
13222
  }
12918
13223
  };
12919
- await this.registryStore.save(nextRecord);
13224
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12920
13225
  this.runRecord = { ...nextRecord };
12921
13226
  await this.auditPort.emit({
12922
13227
  envelopeId: generateAuditEnvelopeId(),
@@ -13024,21 +13329,35 @@ var DefaultRunHandle = class {
13024
13329
  async markFailed(error, patch = {}) {
13025
13330
  await this.saveLifecycleStatus("failed", patch, error);
13026
13331
  }
13027
- async pause(_reason) {
13028
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13332
+ async pause(reason = "Run paused by user") {
13333
+ const latest = await this.registryStore.load(this.runId);
13334
+ if (latest) this.assertExecutionOwner(latest);
13335
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13336
+ const next = {
13337
+ ...latest,
13338
+ status: "paused",
13339
+ updatedAt: Date.now(),
13340
+ pauseReason: reason,
13341
+ pausedAt: void 0
13342
+ };
13343
+ await persistRunTransition(this.registryStore, latest, next);
13344
+ this.runRecord = next;
13345
+ this.abortController.abort(new RunPauseRequested(reason));
13029
13346
  }
13030
- async resume() {
13031
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13347
+ async markPaused(patch = {}) {
13348
+ await this.saveLifecycleStatus("paused", patch);
13032
13349
  }
13033
13350
  async saveLifecycleStatus(status, patch, errorIfAny) {
13034
13351
  const latestRecord = await this.registryStore.load(this.runId);
13035
13352
  const baseRecord = latestRecord ?? this.runRecord;
13036
13353
  const transition = decideRunLifecycleTransition(baseRecord.status);
13354
+ this.assertExecutionOwner(baseRecord);
13355
+ if (status === "running" && baseRecord.status === "paused") return;
13037
13356
  if (transition.kind === "skip_terminal") {
13038
13357
  this.runRecord = { ...baseRecord };
13039
13358
  return;
13040
13359
  }
13041
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13360
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
13042
13361
  const updatedAt = Date.now();
13043
13362
  const nextRecord = {
13044
13363
  ...baseRecord,
@@ -13046,8 +13365,8 @@ var DefaultRunHandle = class {
13046
13365
  updatedAt,
13047
13366
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13048
13367
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
13049
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13050
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13368
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13369
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
13051
13370
  errorIfAny,
13052
13371
  metadata: awaitingUserPatch?.eventId ? {
13053
13372
  ...baseRecord.metadata ?? {},
@@ -13058,7 +13377,7 @@ var DefaultRunHandle = class {
13058
13377
  }
13059
13378
  } : baseRecord.metadata
13060
13379
  };
13061
- await this.registryStore.save(nextRecord);
13380
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13062
13381
  this.runRecord = { ...nextRecord };
13063
13382
  if (status === "completed" || status === "failed") {
13064
13383
  this.closeObservationChannel();
@@ -13068,6 +13387,11 @@ var DefaultRunHandle = class {
13068
13387
  forwardTransportEvent = (envelope) => {
13069
13388
  this.observationEventBus.emit("event", envelope);
13070
13389
  };
13390
+ assertExecutionOwner(record) {
13391
+ if (record.metadata?.executionId !== this.executionId) {
13392
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13393
+ }
13394
+ }
13071
13395
  forwardTransportError = (error) => {
13072
13396
  this.observationEventBus.emit("error", error);
13073
13397
  };
@@ -13398,7 +13722,15 @@ function createRunConcurrencyKeyRegistry() {
13398
13722
  runIdByKey.delete(concurrencyKey);
13399
13723
  }
13400
13724
  }
13401
- return { acquire, release };
13725
+ function transfer(previous, next, concurrencyKey) {
13726
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
13727
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
13728
+ }
13729
+ keyByRunId.delete(previous);
13730
+ keyByRunId.set(next, concurrencyKey);
13731
+ runIdByKey.set(concurrencyKey, next);
13732
+ }
13733
+ return { acquire, release, transfer };
13402
13734
  }
13403
13735
 
13404
13736
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -13449,6 +13781,24 @@ async function recoverRunsOnBoot(options) {
13449
13781
  const outcomes = [];
13450
13782
  for (const record of activeRecords) {
13451
13783
  const updatedAt = options.now();
13784
+ if (await options.canRestoreRun?.(record)) {
13785
+ const metadata = { ...record.metadata };
13786
+ const awaitingUser = metadata.awaitingUser;
13787
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13788
+ const restored = { ...awaitingUser };
13789
+ Reflect.deleteProperty(restored, "resumeClaim");
13790
+ metadata.awaitingUser = restored;
13791
+ }
13792
+ await persistRunTransition(options.registryStore, record, {
13793
+ ...record,
13794
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13795
+ pausedAt: record.pausedAt ?? updatedAt,
13796
+ pauseReason: record.pauseReason ?? options.reason,
13797
+ updatedAt,
13798
+ metadata
13799
+ });
13800
+ continue;
13801
+ }
13452
13802
  const nextRecord = {
13453
13803
  ...record,
13454
13804
  status: "failed",
@@ -13466,7 +13816,7 @@ async function recoverRunsOnBoot(options) {
13466
13816
  }
13467
13817
  }
13468
13818
  };
13469
- await options.registryStore.save(nextRecord);
13819
+ await persistRunTransition(options.registryStore, record, nextRecord);
13470
13820
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13471
13821
  options.notifyTerminal(outcome);
13472
13822
  outcomes.push(outcome);
@@ -13590,8 +13940,13 @@ var DefaultRunSupervisor = class {
13590
13940
  inFlight = /* @__PURE__ */ new Map();
13591
13941
  eventWatchDisposers = /* @__PURE__ */ new Map();
13592
13942
  controlOperations = /* @__PURE__ */ new Map();
13943
+ canRestoreRun;
13593
13944
  constructor(options) {
13945
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13946
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13947
+ }
13594
13948
  this.registryStore = options.registryStore;
13949
+ this.canRestoreRun = options.canRestoreRun;
13595
13950
  this.auditPort = options.auditPort;
13596
13951
  this.executor = options.executor;
13597
13952
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13624,6 +13979,9 @@ var DefaultRunSupervisor = class {
13624
13979
  });
13625
13980
  }
13626
13981
  async registerRun(spec) {
13982
+ if (spec.replacesPausedRun) {
13983
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
13984
+ }
13627
13985
  const runId = spec.runId ?? this.runIdFactory();
13628
13986
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
13629
13987
  throw new RunAlreadyRegisteredError(runId);
@@ -13634,11 +13992,66 @@ var DefaultRunSupervisor = class {
13634
13992
  forwardParentAbortSignal(controller, spec.parentSignal);
13635
13993
  const record = createInitialRunRecord({ runId, spec, startedAt });
13636
13994
  try {
13637
- await this.registryStore.save(record);
13995
+ if (spec.admissionCommit) await spec.admissionCommit(record);
13996
+ else await this.registryStore.save(record);
13638
13997
  } catch (error) {
13639
13998
  this.releaseRunAdmission(runId);
13640
13999
  throw error;
13641
14000
  }
14001
+ return this.attachRun(record, spec, controller);
14002
+ }
14003
+ async registerPausedReplacement(spec) {
14004
+ const target = spec.replacesPausedRun;
14005
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
14006
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
14007
+ }
14008
+ this.getHandle(target.runId);
14009
+ const previous = await this.registryStore.load(target.runId);
14010
+ if (!previous || previous.status !== "paused" || previous.pausedAt === void 0 || previous.updatedAt !== target.expectedUpdatedAt || previous.metadata?.executionId !== target.expectedExecutionId || previous.conversationId !== spec.conversationId || previous.parentRunId !== spec.parentRunId) {
14011
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
14012
+ }
14013
+ const runId = spec.runId ?? this.runIdFactory();
14014
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
14015
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
14016
+ this.runSlotLimiter.release(previous.runId);
14017
+ this.runSlotLimiter.acquire(runId);
14018
+ const now = this.now();
14019
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
14020
+ const next = {
14021
+ ...previous,
14022
+ status: "cancelled",
14023
+ updatedAt: now,
14024
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
14025
+ };
14026
+ try {
14027
+ await spec.admissionCommit(record, { previous, next });
14028
+ } catch (error) {
14029
+ this.runSlotLimiter.release(runId);
14030
+ this.runSlotLimiter.acquire(previous.runId);
14031
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
14032
+ throw error;
14033
+ }
14034
+ this.cleanupRunResources(previous.runId);
14035
+ this.notifyTerminalWaiters(previous.runId);
14036
+ const controller = new AbortController();
14037
+ forwardParentAbortSignal(controller, spec.parentSignal);
14038
+ return this.attachRun(record, spec, controller);
14039
+ }
14040
+ async restoreRun(spec) {
14041
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
14042
+ return this.withRunControlLock(spec.runId, async () => {
14043
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
14044
+ const record = await this.registryStore.load(spec.runId);
14045
+ if (!record) throw new RunNotFoundError(spec.runId);
14046
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
14047
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
14048
+ }
14049
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
14050
+ return this.attachRun(record, spec, new AbortController());
14051
+ });
14052
+ }
14053
+ attachRun(record, spec, controller) {
14054
+ const runId = record.runId;
13642
14055
  try {
13643
14056
  const handle = new DefaultRunHandle({
13644
14057
  runRecord: record,
@@ -13736,11 +14149,36 @@ var DefaultRunSupervisor = class {
13736
14149
  registryStore: this.registryStore,
13737
14150
  reason,
13738
14151
  now: this.now,
13739
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
14152
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
14153
+ canRestoreRun: this.canRestoreRun
13740
14154
  });
13741
14155
  }
13742
- async pause(_runId, _reason) {
13743
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
14156
+ async pause(runId, reason) {
14157
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
14158
+ }
14159
+ async resumePausedRun(input) {
14160
+ return this.withRunControlLock(input.runId, async () => {
14161
+ const handle = this.getHandle(input.runId);
14162
+ const record = await this.registryStore.load(input.runId);
14163
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
14164
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
14165
+ }
14166
+ await persistRunTransition(this.registryStore, record, {
14167
+ ...record,
14168
+ status: "running",
14169
+ updatedAt: this.now(),
14170
+ pausedAt: void 0,
14171
+ pauseReason: void 0,
14172
+ errorIfAny: void 0,
14173
+ metadata: { ...record.metadata, executionId: input.executionId }
14174
+ });
14175
+ const controller = new AbortController();
14176
+ handle.replaceExecutionAbortController(controller, input.executionId);
14177
+ handle.attachTransportEventBus(input.eventBus);
14178
+ this.controllers.set(input.runId, controller);
14179
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
14180
+ return handle;
14181
+ });
13744
14182
  }
13745
14183
  async claimResume(runId, interaction, eventBus, parentSignal) {
13746
14184
  return this.withRunControlLock(runId, async () => {
@@ -13775,7 +14213,7 @@ var DefaultRunSupervisor = class {
13775
14213
  throw new RunNotFoundError(runId);
13776
14214
  }
13777
14215
  const claimId = generateRunResumeClaimId();
13778
- await this.registryStore.save({
14216
+ await persistRunTransition(this.registryStore, record, {
13779
14217
  ...record,
13780
14218
  updatedAt: this.now(),
13781
14219
  metadata: {
@@ -13863,7 +14301,7 @@ var DefaultRunSupervisor = class {
13863
14301
  }
13864
14302
  const awaitingUserWithoutClaim = { ...awaitingUser };
13865
14303
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13866
- await this.registryStore.save({
14304
+ const nextRecord = {
13867
14305
  ...record,
13868
14306
  status: "running",
13869
14307
  updatedAt: this.now(),
@@ -13873,6 +14311,10 @@ var DefaultRunSupervisor = class {
13873
14311
  metadata: {
13874
14312
  ...record.metadata ?? {},
13875
14313
  ...execution ? { executionId: execution.executionId } : {},
14314
+ ...execution?.inputEventIds ? { resumeInputs: {
14315
+ eventIds: [...execution.inputEventIds],
14316
+ checkpointRevision: pendingInteraction.checkpointRevision
14317
+ } } : {},
13876
14318
  awaitingUser: {
13877
14319
  ...awaitingUserWithoutClaim,
13878
14320
  interaction: {
@@ -13881,10 +14323,12 @@ var DefaultRunSupervisor = class {
13881
14323
  }
13882
14324
  }
13883
14325
  }
13884
- });
14326
+ };
14327
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
14328
+ else await persistRunTransition(this.registryStore, record, nextRecord);
13885
14329
  const executionController = new AbortController();
13886
14330
  forwardParentAbortSignal(executionController, parentSignal);
13887
- handle.replaceExecutionAbortController(executionController);
14331
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13888
14332
  this.controllers.set(runId, executionController);
13889
14333
  return handle;
13890
14334
  });
@@ -13902,7 +14346,7 @@ var DefaultRunSupervisor = class {
13902
14346
  }
13903
14347
  const awaitingUserWithoutClaim = { ...awaitingUser };
13904
14348
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13905
- await this.registryStore.save({
14349
+ await persistRunTransition(this.registryStore, record, {
13906
14350
  ...record,
13907
14351
  updatedAt: this.now(),
13908
14352
  metadata: {
@@ -14047,13 +14491,13 @@ __export(system_reminder_exports, {
14047
14491
 
14048
14492
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
14049
14493
  function createDefaultGraphExecutor(options) {
14050
- const executor = new GraphExecutor(
14494
+ const executor2 = new GraphExecutor(
14051
14495
  options.checkpointer ?? new MemoryCheckpointer(),
14052
14496
  { maxSteps: options.maxSteps ?? 8 }
14053
14497
  );
14054
- executor.registerNode(new UserNode());
14055
- executor.registerNode(options.llmNode);
14056
- executor.registerNode(new ToolNode({
14498
+ executor2.registerNode(new UserNode());
14499
+ executor2.registerNode(options.llmNode);
14500
+ executor2.registerNode(new ToolNode({
14057
14501
  toolRuntime: options.toolRuntime,
14058
14502
  observationPreview: options.observationPreview,
14059
14503
  auditPort: options.auditPort,
@@ -14061,8 +14505,8 @@ function createDefaultGraphExecutor(options) {
14061
14505
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
14062
14506
  modelInputResolver: options.modelInputResolver
14063
14507
  }));
14064
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14065
- return executor;
14508
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14509
+ return executor2;
14066
14510
  }
14067
14511
 
14068
14512
  // src/runtime-kernel/testkit/graphLoopHarness.ts
@@ -14087,7 +14531,7 @@ function createGraphLoopHarness(options) {
14087
14531
  return {
14088
14532
  async run() {
14089
14533
  const checkpointKey = options.runId ?? options.turnId;
14090
- const executor = createDefaultGraphExecutor({
14534
+ const executor2 = createDefaultGraphExecutor({
14091
14535
  llmNode: options.createLlmNode({
14092
14536
  llmCaller: options.llmCaller,
14093
14537
  toolRuntime: options.toolRuntime
@@ -14117,8 +14561,8 @@ function createGraphLoopHarness(options) {
14117
14561
  signal: options.signal ?? options.toolContext.abortSignal,
14118
14562
  executorLocal
14119
14563
  };
14120
- await executor.prime(checkpointKey, local, "user");
14121
- const result = await executor.runUntilYield(checkpointKey);
14564
+ await executor2.prime(checkpointKey, local, "user");
14565
+ const result = await executor2.runUntilYield(checkpointKey);
14122
14566
  return {
14123
14567
  checkpointNodeId: result.checkpoint.nodeId,
14124
14568
  stepCount: result.stepCount,