@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
@@ -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 { mkdir, appendFile } from 'fs/promises';
7
8
  import { dirname } from 'path';
8
9
 
@@ -23,13 +24,17 @@ __export(graph_engine_exports, {
23
24
  MemoryEventStore: () => MemoryEventStore,
24
25
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
25
26
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
27
+ RunPauseRequested: () => RunPauseRequested,
28
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
26
29
  ToolNode: () => ToolNode,
27
30
  UserNode: () => UserNode,
28
31
  WaitUserNode: () => WaitUserNode,
29
32
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
30
33
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
31
34
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
35
+ isRunPauseSignal: () => isRunPauseSignal,
32
36
  isRuntimeFailureFact: () => isRuntimeFailureFact,
37
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
33
38
  readCheckpointContextUsage: () => readCheckpointContextUsage,
34
39
  requireEventStoreId: () => requireEventStoreId,
35
40
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -2397,6 +2402,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2397
2402
  "memory",
2398
2403
  "runtimeEventSink",
2399
2404
  "runtimeEventCommitPort",
2405
+ "commitExecutionBoundary",
2406
+ "toolRecoveryPort",
2400
2407
  "runtimeFailureFactSink",
2401
2408
  "signal",
2402
2409
  "summarizationCallbacks",
@@ -2947,6 +2954,7 @@ var GraphExecutor = class {
2947
2954
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
2948
2955
  };
2949
2956
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
2957
+ this.executionCheckpointPort = config.executionCheckpointPort;
2950
2958
  }
2951
2959
  checkpointer;
2952
2960
  nodes = /* @__PURE__ */ new Map();
@@ -2954,6 +2962,7 @@ var GraphExecutor = class {
2954
2962
  checkpointQueues = /* @__PURE__ */ new Map();
2955
2963
  config;
2956
2964
  telemetryPort;
2965
+ executionCheckpointPort;
2957
2966
  registerNode(node) {
2958
2967
  this.nodes.set(node.id, node);
2959
2968
  }
@@ -2962,6 +2971,7 @@ var GraphExecutor = class {
2962
2971
  }
2963
2972
  sanitize(state) {
2964
2973
  return {
2974
+ ...state,
2965
2975
  nodeId: state.nodeId,
2966
2976
  revision: state.revision ?? 0,
2967
2977
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -2981,8 +2991,9 @@ var GraphExecutor = class {
2981
2991
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
2982
2992
  }
2983
2993
  this.ephemeralLocals.set(checkpointKey, { ...local });
2984
- await this.checkpointer.save(checkpointKey, {
2994
+ await this.commitCheckpoint(checkpointKey, {
2985
2995
  nodeId,
2996
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
2986
2997
  revision: 1,
2987
2998
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
2988
2999
  local: sanitizeCheckpointLocal(local)
@@ -2993,6 +3004,33 @@ var GraphExecutor = class {
2993
3004
  );
2994
3005
  });
2995
3006
  }
3007
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
3008
+ async continueSession(checkpointKey, input) {
3009
+ if (!this.executionCheckpointPort) {
3010
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
3011
+ }
3012
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
3013
+ const current = await this.checkpointer.load(checkpointKey);
3014
+ if (!current || current.revision !== input.expectedRevision) {
3015
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
3016
+ }
3017
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
3018
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
3019
+ }
3020
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
3021
+ return { checkpoint: current, events: [], stepCount: 0 };
3022
+ }
3023
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
3024
+ try {
3025
+ return await this.runUntilYieldQueued(
3026
+ checkpointKey,
3027
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
3028
+ );
3029
+ } finally {
3030
+ this.ephemeralLocals.delete(checkpointKey);
3031
+ }
3032
+ });
3033
+ }
2996
3034
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
2997
3035
  async resumeSession(checkpointKey, input) {
2998
3036
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -3013,17 +3051,21 @@ var GraphExecutor = class {
3013
3051
  );
3014
3052
  }
3015
3053
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
3054
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
3055
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
3056
+ }
3016
3057
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
3017
- await this.checkpointer.save(checkpointKey, {
3058
+ await this.commitCheckpoint(checkpointKey, {
3018
3059
  ...current,
3019
3060
  nodeId: input.nodeId ?? "llm",
3061
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3020
3062
  revision: currentRevision + 1,
3021
3063
  local: sanitizeCheckpointLocal(resumedLocal)
3022
3064
  });
3023
3065
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
3024
3066
  return this.runUntilYieldQueued(
3025
3067
  checkpointKey,
3026
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3068
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
3027
3069
  );
3028
3070
  });
3029
3071
  }
@@ -3114,16 +3156,23 @@ var GraphExecutor = class {
3114
3156
  };
3115
3157
  }
3116
3158
  async saveCheckpoint(checkpointKey, state) {
3117
- const checkpoint = this.sanitize({
3159
+ const checkpoint2 = this.sanitize({
3118
3160
  ...state,
3119
3161
  revision: (state.revision ?? 0) + 1
3120
3162
  });
3121
- await this.checkpointer.save(checkpointKey, checkpoint);
3122
- return checkpoint;
3163
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3164
+ return checkpoint2;
3165
+ }
3166
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3167
+ if (this.executionCheckpointPort) {
3168
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3169
+ } else {
3170
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3171
+ }
3123
3172
  }
3124
3173
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3125
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3126
- return { events, checkpoint, stepCount };
3174
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3175
+ return { events, checkpoint: checkpoint2, stepCount };
3127
3176
  }
3128
3177
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3129
3178
  let state = initialState;
@@ -3133,6 +3182,15 @@ var GraphExecutor = class {
3133
3182
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
3134
3183
  local: { ...state.local || {}, ...ephemeral }
3135
3184
  };
3185
+ if (this.executionCheckpointPort) {
3186
+ state.local = {
3187
+ ...state.local,
3188
+ commitExecutionBoundary: async (boundary) => {
3189
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
3190
+ boundary.revision = saved.revision;
3191
+ }
3192
+ };
3193
+ }
3136
3194
  const isAbortSignal2 = (v) => {
3137
3195
  return v !== null && typeof v === "object" && "aborted" in v;
3138
3196
  };
@@ -3142,11 +3200,12 @@ var GraphExecutor = class {
3142
3200
  throw err;
3143
3201
  };
3144
3202
  let stepCount = 0;
3203
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
3145
3204
  let allEvents = [];
3146
3205
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
3147
3206
  maxSteps
3148
3207
  });
3149
- while (stepCount < maxSteps) {
3208
+ while (previousSteps + stepCount < maxSteps) {
3150
3209
  stepCount += 1;
3151
3210
  reportStepsUsed(stepCount);
3152
3211
  const signalRaw = state.local?.signal;
@@ -3158,7 +3217,7 @@ var GraphExecutor = class {
3158
3217
  const stepPreparation = prepareGraphStep({
3159
3218
  state,
3160
3219
  maxSteps,
3161
- stepCount
3220
+ stepCount: previousSteps + stepCount
3162
3221
  });
3163
3222
  state = stepPreparation.state;
3164
3223
  const node = this.nodes.get(state.nodeId);
@@ -3167,6 +3226,7 @@ var GraphExecutor = class {
3167
3226
  maxSteps,
3168
3227
  stepCount
3169
3228
  });
3229
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3170
3230
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3171
3231
  this.ephemeralLocals.delete(checkpointKey);
3172
3232
  return result3;
@@ -3176,6 +3236,11 @@ var GraphExecutor = class {
3176
3236
  stepCount,
3177
3237
  nodeId: state.nodeId
3178
3238
  });
3239
+ if (this.executionCheckpointPort) {
3240
+ state.executionStatus = "executing";
3241
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3242
+ state.revision = saved.revision;
3243
+ }
3179
3244
  const result2 = await runGraphNodeWithTelemetry({
3180
3245
  node,
3181
3246
  state,
@@ -3200,10 +3265,13 @@ var GraphExecutor = class {
3200
3265
  fromNodeId: stepResolution.action.fromNodeId,
3201
3266
  nextNodeId: stepResolution.action.nextNodeId
3202
3267
  });
3203
- await this.saveCheckpoint(checkpointKey, state);
3268
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
3269
+ const saved = await this.saveCheckpoint(checkpointKey, state);
3270
+ state.revision = saved.revision;
3204
3271
  continue;
3205
3272
  }
3206
3273
  if (stepResolution.action.kind === "yield") {
3274
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3207
3275
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
3208
3276
  maxSteps,
3209
3277
  stepCount
@@ -3214,6 +3282,7 @@ var GraphExecutor = class {
3214
3282
  maxSteps,
3215
3283
  stepCount
3216
3284
  });
3285
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
3217
3286
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3218
3287
  }
3219
3288
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -3234,6 +3303,7 @@ var GraphExecutor = class {
3234
3303
  },
3235
3304
  retryable: false
3236
3305
  }), "GraphExecutor.engine_budget_exhausted"));
3306
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
3237
3307
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
3238
3308
  this.ephemeralLocals.delete(checkpointKey);
3239
3309
  return result;
@@ -7127,10 +7197,11 @@ var LlmNode = class {
7127
7197
  bridge.handle
7128
7198
  );
7129
7199
  } catch (error) {
7130
- bridge.finalizePartialAnswer();
7200
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
7131
7201
  throw error;
7132
7202
  }
7133
7203
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
7204
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
7134
7205
  switch (decision.kind) {
7135
7206
  case "tool_calls": {
7136
7207
  if (forceFinalAnswer) {
@@ -8398,6 +8469,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
8398
8469
  function recordToolProtocolError(params) {
8399
8470
  }
8400
8471
 
8472
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
8473
+ var RunRecoveryBlockedError = class extends Error {
8474
+ code = "RUN_RECOVERY_BLOCKED";
8475
+ constructor(message) {
8476
+ super(message);
8477
+ this.name = "RunRecoveryBlockedError";
8478
+ }
8479
+ };
8480
+ var RunPauseRequested = class extends Error {
8481
+ code = "RUN_PAUSE_REQUESTED";
8482
+ constructor(message = "Run paused by user") {
8483
+ super(message);
8484
+ this.name = "RunPauseRequested";
8485
+ }
8486
+ };
8487
+ function isRunPauseSignal(signal) {
8488
+ const reason = signal?.reason;
8489
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
8490
+ }
8491
+
8492
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8493
+ async function executeRecoverableTool(input) {
8494
+ const local = input.state.local;
8495
+ if (!local?.commitExecutionBoundary) return input.execute();
8496
+ if (local.executingToolCallId) {
8497
+ if (local.executingToolCallId !== input.call.id) {
8498
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
8499
+ }
8500
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
8501
+ if (!decision || decision.kind === "blocked") {
8502
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
8503
+ }
8504
+ if (decision.kind === "settled") return decision.result;
8505
+ }
8506
+ local.executingToolCallId = input.call.id;
8507
+ await local.commitExecutionBoundary(input.state);
8508
+ const result = await input.execute();
8509
+ if (!result.success && isRunPauseSignal(local.signal)) {
8510
+ const error = new Error("Tool execution paused before its outcome was confirmed");
8511
+ error.name = "AbortError";
8512
+ throw error;
8513
+ }
8514
+ return result;
8515
+ }
8516
+ async function commitToolBoundary(state, result) {
8517
+ if (!state.local?.commitExecutionBoundary) return;
8518
+ delete state.local.executingToolCallId;
8519
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
8520
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
8521
+ await state.local.commitExecutionBoundary(state);
8522
+ }
8523
+
8401
8524
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8402
8525
  var logger11 = new Logger("ToolNode");
8403
8526
  function isAbortSignal(value) {
@@ -8568,6 +8691,7 @@ var ToolNode = class {
8568
8691
  const events = [];
8569
8692
  while (true) {
8570
8693
  const result = await this.runNextPendingToolCall(state);
8694
+ await commitToolBoundary(state, result);
8571
8695
  if (Array.isArray(result.events) && result.events.length > 0) {
8572
8696
  events.push(...result.events);
8573
8697
  }
@@ -8584,11 +8708,9 @@ var ToolNode = class {
8584
8708
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
8585
8709
  const signalRaw = state.local?.signal;
8586
8710
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
8587
- settlePendingToolCallsAfterAbort({
8588
- state,
8589
- calls,
8590
- toolCatalog: this.toolRuntime
8591
- });
8711
+ if (!isRunPauseSignal(signalRaw)) {
8712
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
8713
+ }
8592
8714
  const abortError = new Error("The user aborted a request.");
8593
8715
  abortError.name = "AbortError";
8594
8716
  throw abortError;
@@ -8727,16 +8849,21 @@ var ToolNode = class {
8727
8849
  tool_calls: [call]
8728
8850
  });
8729
8851
  try {
8730
- const exec = await executeToolWithIdempotency({
8731
- idempotencyKey: execution.idempotencyKey,
8732
- inFlight: this.idempotencyInFlight,
8733
- history: readHistoryEvents(prepared.local),
8734
- toolName: execution.toolName,
8735
- execute: () => this.toolRuntime.executeTool(
8736
- execution.toolName,
8737
- execution.toolArgs,
8738
- prepared.toolContext
8739
- )
8852
+ const exec = await executeRecoverableTool({
8853
+ state,
8854
+ call,
8855
+ context: prepared.toolContext,
8856
+ execute: () => executeToolWithIdempotency({
8857
+ idempotencyKey: execution.idempotencyKey,
8858
+ inFlight: this.idempotencyInFlight,
8859
+ history: readHistoryEvents(prepared.local),
8860
+ toolName: execution.toolName,
8861
+ execute: () => this.toolRuntime.executeTool(
8862
+ execution.toolName,
8863
+ execution.toolArgs,
8864
+ prepared.toolContext
8865
+ )
8866
+ })
8740
8867
  });
8741
8868
  if (exec.success) {
8742
8869
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -8816,7 +8943,7 @@ var ToolNode = class {
8816
8943
  bridge: execution.bridge
8817
8944
  });
8818
8945
  } catch (error) {
8819
- if (isToolExecutionAbort(error)) {
8946
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
8820
8947
  settleToolCallsAfterExecutionAbort({
8821
8948
  state,
8822
8949
  remainingCalls: calls.slice(1),
@@ -8876,7 +9003,7 @@ var ToolNode = class {
8876
9003
  {
8877
9004
  attachments: context.attachments,
8878
9005
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
8879
- ephemeral: context.exec.idempotency?.cacheHit === true,
9006
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
8880
9007
  durationMs: context.exec.durationMs
8881
9008
  }
8882
9009
  );
@@ -8933,6 +9060,9 @@ var ToolNode = class {
8933
9060
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
8934
9061
  }
8935
9062
  async handleError(context) {
9063
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
9064
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
9065
+ }
8936
9066
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
8937
9067
  await this.emitToolDecisionAudit({
8938
9068
  action: "tool.deny",
@@ -9169,16 +9299,16 @@ function requireEventStoreId(eventStoreId) {
9169
9299
  }
9170
9300
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9171
9301
  let lastTimestamp = 0;
9172
- let counter = 0;
9302
+ let counter2 = 0;
9173
9303
  return () => {
9174
9304
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9175
9305
  if (timestamp === lastTimestamp) {
9176
- counter += 1;
9306
+ counter2 += 1;
9177
9307
  } else {
9178
9308
  lastTimestamp = timestamp;
9179
- counter = 0;
9309
+ counter2 = 0;
9180
9310
  }
9181
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9311
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9182
9312
  };
9183
9313
  }
9184
9314
 
@@ -9590,6 +9720,76 @@ function assertNonNegativeSafeInteger(value, field) {
9590
9720
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9591
9721
  }
9592
9722
  }
9723
+ var counter = z.number().int().nonnegative();
9724
+ var executor = z.object({
9725
+ stepCount: counter,
9726
+ phase: z.string().optional(),
9727
+ maxSteps: counter.optional(),
9728
+ remainingSteps: z.number().int().optional(),
9729
+ finalStepPolicy: z.enum(["final_answer", "force_tools"]).optional(),
9730
+ finalStepForcedTools: z.array(z.string()).optional(),
9731
+ lastStepsHintThreshold: counter.optional(),
9732
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9733
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9734
+ runLockedModelId: z.string().optional(),
9735
+ lastSuccessfulLlmModelId: z.string().optional(),
9736
+ llmInvocationKind: z.enum(["user_initiated", "continuation"]).optional(),
9737
+ llmInvocationCount: counter.optional(),
9738
+ lockRequestedModelId: z.boolean().optional(),
9739
+ contextCompaction: z.object({
9740
+ attemptCount: counter,
9741
+ committedCount: counter,
9742
+ lastCommittedFingerprint: z.string().optional()
9743
+ }).strict().optional()
9744
+ }).strict();
9745
+ var checkpoint = z.object({
9746
+ nodeId: z.string().min(1),
9747
+ schemaVersion: z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9748
+ revision: counter.optional(),
9749
+ executionStatus: z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9750
+ local: z.object({
9751
+ runId: RunIdSchema.optional(),
9752
+ parentRunId: RunIdSchema.optional(),
9753
+ conversationId: z.string().optional(),
9754
+ turnId: z.string().optional(),
9755
+ request: SerializableJsonRecord.optional(),
9756
+ history: z.array(RuntimeEvent).optional(),
9757
+ newEvents: z.array(RuntimeEvent).optional(),
9758
+ executorLocal: executor.optional(),
9759
+ pendingToolCalls: z.array(z.object({
9760
+ id: ToolCallIdSchema,
9761
+ type: z.literal("function"),
9762
+ function: z.object({ name: z.string().min(1), arguments: z.string() }).strict()
9763
+ }).strict()).optional(),
9764
+ executingToolCallId: ToolCallIdSchema.optional(),
9765
+ toolBatchCompletionMode: z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9766
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9767
+ lastToolResult: SerializableJsonRecord.optional(),
9768
+ finalAnswer: z.string().optional(),
9769
+ answerId: z.string().optional(),
9770
+ chunkSeq: counter.optional(),
9771
+ contextUsage: ContextUsageSnapshot.optional()
9772
+ }).passthrough().optional()
9773
+ }).strict();
9774
+ function parseEngineCheckpoint(value) {
9775
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9776
+ for (const key of [
9777
+ "memory",
9778
+ "signal",
9779
+ "toolContext",
9780
+ "runtimeEventSink",
9781
+ "runtimeEventCommitPort",
9782
+ "runtimeFailureFactSink",
9783
+ "summarizationCallbacks",
9784
+ "commitExecutionBoundary",
9785
+ "toolRecoveryPort"
9786
+ ]) {
9787
+ if (result.local && Object.hasOwn(result.local, key)) {
9788
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9789
+ }
9790
+ }
9791
+ return result;
9792
+ }
9593
9793
 
9594
9794
  // src/runtime-kernel/tools/index.ts
9595
9795
  var tools_exports = {};
@@ -10041,12 +10241,33 @@ var RuntimeEventPublisher = class {
10041
10241
  var EventBusEventPersistence = class {
10042
10242
  constructor(options) {
10043
10243
  this.options = options;
10244
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
10044
10245
  }
10045
10246
  options;
10046
10247
  scheduledEventIds = /* @__PURE__ */ new Set();
10047
10248
  writeTail = Promise.resolve();
10048
10249
  firstWriteError;
10049
10250
  connected = false;
10251
+ checkpointWritesActive;
10252
+ checkpointEvents = [];
10253
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10254
+ async commitCheckpoint(checkpointKey, checkpoint2) {
10255
+ const writer = this.options.checkpointWriter;
10256
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10257
+ const events = this.checkpointEvents;
10258
+ this.checkpointEvents = [];
10259
+ await this.enqueueWrite(() => writer({
10260
+ checkpointKey,
10261
+ checkpoint: checkpoint2,
10262
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10263
+ }));
10264
+ }
10265
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
10266
+ finishCheckpointWrites() {
10267
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
10268
+ this.checkpointEvents = [];
10269
+ this.checkpointWritesActive = false;
10270
+ }
10050
10271
  connect() {
10051
10272
  if (this.connected) {
10052
10273
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -10093,14 +10314,22 @@ var EventBusEventPersistence = class {
10093
10314
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10094
10315
  return;
10095
10316
  }
10317
+ if (this.checkpointWritesActive) {
10318
+ this.scheduledEventIds.add(event.id);
10319
+ this.checkpointEvents.push(event);
10320
+ return;
10321
+ }
10096
10322
  void this.scheduleWrite(event).catch(() => void 0);
10097
10323
  };
10098
10324
  scheduleWrite(event) {
10099
10325
  this.scheduledEventIds.add(event.id);
10100
- const eventStoreId = this.options.nextEventStoreId();
10101
- const write = this.writeTail.then(async () => {
10102
- await this.options.eventStore.append({ eventStoreId, event });
10103
- });
10326
+ return this.enqueueWrite(() => this.options.eventStore.append({
10327
+ eventStoreId: this.options.nextEventStoreId(),
10328
+ event
10329
+ }));
10330
+ }
10331
+ enqueueWrite(operation) {
10332
+ const write = this.writeTail.then(operation);
10104
10333
  this.writeTail = write;
10105
10334
  void write.catch((error) => {
10106
10335
  this.firstWriteError ??= error;
@@ -11722,15 +11951,15 @@ function hasSeedHistoryPrefix(history, seedHistory) {
11722
11951
  }
11723
11952
  return true;
11724
11953
  }
11725
- function readCheckpointHistory(checkpoint) {
11726
- if (!checkpoint?.local) return [];
11727
- const history = checkpoint.local.history;
11954
+ function readCheckpointHistory(checkpoint2) {
11955
+ if (!checkpoint2?.local) return [];
11956
+ const history = checkpoint2.local.history;
11728
11957
  if (!Array.isArray(history)) return [];
11729
11958
  return parseRuntimeEvents(history);
11730
11959
  }
11731
11960
  async function recoverChildRunEventsFromCheckpoint(params) {
11732
- const checkpoint = await params.checkpointer.load(params.checkpointKey);
11733
- const history = readCheckpointHistory(checkpoint);
11961
+ const checkpoint2 = await params.checkpointer.load(params.checkpointKey);
11962
+ const history = readCheckpointHistory(checkpoint2);
11734
11963
  if (history.length === 0) {
11735
11964
  return [];
11736
11965
  }
@@ -11821,6 +12050,9 @@ var ChildRunInvoker = class {
11821
12050
  explicitConversationId: conversationId,
11822
12051
  parentToolContext
11823
12052
  });
12053
+ if (config.persistence?.expectedRevision !== void 0) {
12054
+ return this.continueChild(config, childRunId, runtimeConversationId);
12055
+ }
11824
12056
  const turnId = generateTurnId();
11825
12057
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
11826
12058
  conversationId: runtimeConversationId,
@@ -11828,21 +12060,8 @@ var ChildRunInvoker = class {
11828
12060
  maxSteps,
11829
12061
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
11830
12062
  });
11831
- const checkpointer = new MemoryCheckpointer();
11832
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
11833
- const llmNode = this.createLlmNode();
11834
- const toolNode = new ToolNode({
11835
- toolRuntime: this.toolRuntime,
11836
- observationPreview: this.observationPreview,
11837
- telemetryPort: this.telemetryPort,
11838
- auditPort: this.auditPort,
11839
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
11840
- modelInputResolver: this.modelInputResolver
11841
- });
11842
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
11843
- graphExecutor.registerNode(llmNode);
11844
- graphExecutor.registerNode(toolNode);
11845
- graphExecutor.registerNode(waitUserNode);
12063
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
12064
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
11846
12065
  const childUserInput = createChildRunUserInput({
11847
12066
  id: generateRuntimeEventId(),
11848
12067
  conversationId: runtimeConversationId,
@@ -11922,6 +12141,7 @@ var ChildRunInvoker = class {
11922
12141
  ...abortSignal ? { signal: abortSignal } : {},
11923
12142
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
11924
12143
  runtimeEventSink,
12144
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
11925
12145
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
11926
12146
  systemPrompt
11927
12147
  };
@@ -11962,6 +12182,7 @@ var ChildRunInvoker = class {
11962
12182
  eventToMessageConverter: this.eventToMessageConverter
11963
12183
  });
11964
12184
  } catch (err) {
12185
+ if (config.persistence) throw err;
11965
12186
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
11966
12187
  checkpointer,
11967
12188
  checkpointKey: internalCheckpointKey,
@@ -12000,7 +12221,7 @@ var ChildRunInvoker = class {
12000
12221
  events: allEvents,
12001
12222
  eventToMessageConverter: this.eventToMessageConverter
12002
12223
  });
12003
- await checkpointer.clear(internalCheckpointKey);
12224
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
12004
12225
  return {
12005
12226
  success: !error && !cancelled,
12006
12227
  runId: childRunId,
@@ -12017,6 +12238,66 @@ var ChildRunInvoker = class {
12017
12238
  error
12018
12239
  };
12019
12240
  }
12241
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
12242
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
12243
+ graph.registerNode(this.createLlmNode());
12244
+ graph.registerNode(new ToolNode({
12245
+ toolRuntime: this.toolRuntime,
12246
+ observationPreview: this.observationPreview,
12247
+ telemetryPort: this.telemetryPort,
12248
+ auditPort: this.auditPort,
12249
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12250
+ modelInputResolver: this.modelInputResolver
12251
+ }));
12252
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
12253
+ return graph;
12254
+ }
12255
+ async continueChild(config, runId, conversationId) {
12256
+ const persistence = config.persistence;
12257
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12258
+ const checkpoint2 = await persistence.checkpointer.load(runId);
12259
+ if (!checkpoint2 || checkpoint2.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12260
+ const local = readGraphAgentLocal({ ...checkpoint2.local, runtimeEventSink: config.runtimeEventSink });
12261
+ const request = local.request;
12262
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12263
+ const context = createChildRunToolContext({
12264
+ parentToolContext: config.parentToolContext,
12265
+ conversationId,
12266
+ turnId: local.turnId,
12267
+ runId,
12268
+ parentRunId: config.parentRunId,
12269
+ userQuery: request.query,
12270
+ modelId: request.model_id,
12271
+ seedHistory: local.history,
12272
+ abortSignal: config.abortSignal
12273
+ });
12274
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
12275
+ const result = await graph.continueSession(runId, {
12276
+ expectedRevision: persistence.expectedRevision,
12277
+ capabilities: {
12278
+ toolContext: context,
12279
+ signal: config.abortSignal,
12280
+ runtimeEventSink: config.runtimeEventSink,
12281
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
12282
+ toolRecoveryPort: persistence.toolRecoveryPort
12283
+ }
12284
+ });
12285
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
12286
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
12287
+ const finalAnswer = extractFinalAnswer(events);
12288
+ return {
12289
+ runId,
12290
+ parentRunId: config.parentRunId,
12291
+ subrunId: runId,
12292
+ success: true,
12293
+ events,
12294
+ finalAnswer,
12295
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
12296
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
12297
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
12298
+ toolset: { availableTools: request.availableTools }
12299
+ };
12300
+ }
12020
12301
  };
12021
12302
  function isAbortError2(error) {
12022
12303
  return error instanceof Error && error.name === "AbortError";
@@ -12418,8 +12699,6 @@ __export(run_supervisor_exports, {
12418
12699
  RunNotFoundError: () => RunNotFoundError,
12419
12700
  runMetaFromRecord: () => runMetaFromRecord
12420
12701
  });
12421
-
12422
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
12423
12702
  function cloneRunRecord(record) {
12424
12703
  return {
12425
12704
  ...record,
@@ -12439,6 +12718,11 @@ function matchesStatus(candidate, filter) {
12439
12718
  }
12440
12719
  var MemoryRunRegistryStore = class {
12441
12720
  store = /* @__PURE__ */ new Map();
12721
+ async compareAndSwap(previous, next) {
12722
+ if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
12723
+ this.store.set(next.runId, cloneRunRecord(next));
12724
+ return true;
12725
+ }
12442
12726
  async save(record) {
12443
12727
  this.store.set(record.runId, cloneRunRecord(record));
12444
12728
  }
@@ -12586,6 +12870,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
12586
12870
  }
12587
12871
  };
12588
12872
 
12873
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
12874
+ async function persistRunTransition(store, previous, next) {
12875
+ if (store.compareAndSwap) {
12876
+ if (!await store.compareAndSwap(previous, next)) {
12877
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
12878
+ }
12879
+ } else {
12880
+ await store.save(next);
12881
+ }
12882
+ }
12883
+
12589
12884
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
12590
12885
  function isRunTerminalStatus(status) {
12591
12886
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -12641,6 +12936,7 @@ var DefaultRunHandle = class {
12641
12936
  parentRunId;
12642
12937
  runRecord;
12643
12938
  abortController;
12939
+ executionId;
12644
12940
  agentSpecSnapshot;
12645
12941
  requestSnapshot;
12646
12942
  transportEventBus;
@@ -12656,6 +12952,9 @@ var DefaultRunHandle = class {
12656
12952
  this.runId = options.runRecord.runId;
12657
12953
  this.parentRunId = options.runRecord.parentRunId;
12658
12954
  this.abortController = options.abortController;
12955
+ const executionId = options.runRecord.metadata?.executionId;
12956
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
12957
+ this.executionId = executionId;
12659
12958
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
12660
12959
  this.requestSnapshot = cloneRequest(options.request);
12661
12960
  this.transportEventBus = options.eventBus;
@@ -12675,8 +12974,9 @@ var DefaultRunHandle = class {
12675
12974
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
12676
12975
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
12677
12976
  */
12678
- replaceExecutionAbortController(controller) {
12977
+ replaceExecutionAbortController(controller, executionId) {
12679
12978
  this.abortController = controller;
12979
+ this.executionId = executionId;
12680
12980
  }
12681
12981
  async spec() {
12682
12982
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -12696,6 +12996,7 @@ var DefaultRunHandle = class {
12696
12996
  this.abortController.abort(opts.reason);
12697
12997
  const latestRecord = await this.registryStore.load(this.runId);
12698
12998
  const baseRecord = latestRecord ?? this.runRecord;
12999
+ this.assertExecutionOwner(baseRecord);
12699
13000
  const transition = decideRunLifecycleTransition(baseRecord.status);
12700
13001
  if (transition.kind === "skip_terminal") {
12701
13002
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -12705,7 +13006,7 @@ var DefaultRunHandle = class {
12705
13006
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12706
13007
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
12707
13008
  };
12708
- await this.registryStore.save(settledRecord);
13009
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
12709
13010
  this.runRecord = { ...settledRecord };
12710
13011
  return;
12711
13012
  }
@@ -12732,7 +13033,7 @@ var DefaultRunHandle = class {
12732
13033
  }
12733
13034
  }
12734
13035
  };
12735
- await this.registryStore.save(nextRecord);
13036
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12736
13037
  this.runRecord = { ...nextRecord };
12737
13038
  await this.auditPort.emit({
12738
13039
  envelopeId: generateAuditEnvelopeId(),
@@ -12840,21 +13141,35 @@ var DefaultRunHandle = class {
12840
13141
  async markFailed(error, patch = {}) {
12841
13142
  await this.saveLifecycleStatus("failed", patch, error);
12842
13143
  }
12843
- async pause(_reason) {
12844
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
13144
+ async pause(reason = "Run paused by user") {
13145
+ const latest = await this.registryStore.load(this.runId);
13146
+ if (latest) this.assertExecutionOwner(latest);
13147
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
13148
+ const next = {
13149
+ ...latest,
13150
+ status: "paused",
13151
+ updatedAt: Date.now(),
13152
+ pauseReason: reason,
13153
+ pausedAt: void 0
13154
+ };
13155
+ await persistRunTransition(this.registryStore, latest, next);
13156
+ this.runRecord = next;
13157
+ this.abortController.abort(new RunPauseRequested(reason));
12845
13158
  }
12846
- async resume() {
12847
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
13159
+ async markPaused(patch = {}) {
13160
+ await this.saveLifecycleStatus("paused", patch);
12848
13161
  }
12849
13162
  async saveLifecycleStatus(status, patch, errorIfAny) {
12850
13163
  const latestRecord = await this.registryStore.load(this.runId);
12851
13164
  const baseRecord = latestRecord ?? this.runRecord;
12852
13165
  const transition = decideRunLifecycleTransition(baseRecord.status);
13166
+ this.assertExecutionOwner(baseRecord);
13167
+ if (status === "running" && baseRecord.status === "paused") return;
12853
13168
  if (transition.kind === "skip_terminal") {
12854
13169
  this.runRecord = { ...baseRecord };
12855
13170
  return;
12856
13171
  }
12857
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
13172
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
12858
13173
  const updatedAt = Date.now();
12859
13174
  const nextRecord = {
12860
13175
  ...baseRecord,
@@ -12862,8 +13177,8 @@ var DefaultRunHandle = class {
12862
13177
  updatedAt,
12863
13178
  currentNode: patch.currentNode ?? baseRecord.currentNode,
12864
13179
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
12865
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
12866
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
13180
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13181
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
12867
13182
  errorIfAny,
12868
13183
  metadata: awaitingUserPatch?.eventId ? {
12869
13184
  ...baseRecord.metadata ?? {},
@@ -12874,7 +13189,7 @@ var DefaultRunHandle = class {
12874
13189
  }
12875
13190
  } : baseRecord.metadata
12876
13191
  };
12877
- await this.registryStore.save(nextRecord);
13192
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
12878
13193
  this.runRecord = { ...nextRecord };
12879
13194
  if (status === "completed" || status === "failed") {
12880
13195
  this.closeObservationChannel();
@@ -12884,6 +13199,11 @@ var DefaultRunHandle = class {
12884
13199
  forwardTransportEvent = (envelope) => {
12885
13200
  this.observationEventBus.emit("event", envelope);
12886
13201
  };
13202
+ assertExecutionOwner(record) {
13203
+ if (record.metadata?.executionId !== this.executionId) {
13204
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
13205
+ }
13206
+ }
12887
13207
  forwardTransportError = (error) => {
12888
13208
  this.observationEventBus.emit("error", error);
12889
13209
  };
@@ -13214,7 +13534,15 @@ function createRunConcurrencyKeyRegistry() {
13214
13534
  runIdByKey.delete(concurrencyKey);
13215
13535
  }
13216
13536
  }
13217
- return { acquire, release };
13537
+ function transfer(previous, next, concurrencyKey) {
13538
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
13539
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
13540
+ }
13541
+ keyByRunId.delete(previous);
13542
+ keyByRunId.set(next, concurrencyKey);
13543
+ runIdByKey.set(concurrencyKey, next);
13544
+ }
13545
+ return { acquire, release, transfer };
13218
13546
  }
13219
13547
 
13220
13548
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -13265,6 +13593,24 @@ async function recoverRunsOnBoot(options) {
13265
13593
  const outcomes = [];
13266
13594
  for (const record of activeRecords) {
13267
13595
  const updatedAt = options.now();
13596
+ if (await options.canRestoreRun?.(record)) {
13597
+ const metadata = { ...record.metadata };
13598
+ const awaitingUser = metadata.awaitingUser;
13599
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
13600
+ const restored = { ...awaitingUser };
13601
+ Reflect.deleteProperty(restored, "resumeClaim");
13602
+ metadata.awaitingUser = restored;
13603
+ }
13604
+ await persistRunTransition(options.registryStore, record, {
13605
+ ...record,
13606
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
13607
+ pausedAt: record.pausedAt ?? updatedAt,
13608
+ pauseReason: record.pauseReason ?? options.reason,
13609
+ updatedAt,
13610
+ metadata
13611
+ });
13612
+ continue;
13613
+ }
13268
13614
  const nextRecord = {
13269
13615
  ...record,
13270
13616
  status: "failed",
@@ -13282,7 +13628,7 @@ async function recoverRunsOnBoot(options) {
13282
13628
  }
13283
13629
  }
13284
13630
  };
13285
- await options.registryStore.save(nextRecord);
13631
+ await persistRunTransition(options.registryStore, record, nextRecord);
13286
13632
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
13287
13633
  options.notifyTerminal(outcome);
13288
13634
  outcomes.push(outcome);
@@ -13406,8 +13752,13 @@ var DefaultRunSupervisor = class {
13406
13752
  inFlight = /* @__PURE__ */ new Map();
13407
13753
  eventWatchDisposers = /* @__PURE__ */ new Map();
13408
13754
  controlOperations = /* @__PURE__ */ new Map();
13755
+ canRestoreRun;
13409
13756
  constructor(options) {
13757
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
13758
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
13759
+ }
13410
13760
  this.registryStore = options.registryStore;
13761
+ this.canRestoreRun = options.canRestoreRun;
13411
13762
  this.auditPort = options.auditPort;
13412
13763
  this.executor = options.executor;
13413
13764
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -13440,6 +13791,9 @@ var DefaultRunSupervisor = class {
13440
13791
  });
13441
13792
  }
13442
13793
  async registerRun(spec) {
13794
+ if (spec.replacesPausedRun) {
13795
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
13796
+ }
13443
13797
  const runId = spec.runId ?? this.runIdFactory();
13444
13798
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
13445
13799
  throw new RunAlreadyRegisteredError(runId);
@@ -13450,11 +13804,66 @@ var DefaultRunSupervisor = class {
13450
13804
  forwardParentAbortSignal(controller, spec.parentSignal);
13451
13805
  const record = createInitialRunRecord({ runId, spec, startedAt });
13452
13806
  try {
13453
- await this.registryStore.save(record);
13807
+ if (spec.admissionCommit) await spec.admissionCommit(record);
13808
+ else await this.registryStore.save(record);
13454
13809
  } catch (error) {
13455
13810
  this.releaseRunAdmission(runId);
13456
13811
  throw error;
13457
13812
  }
13813
+ return this.attachRun(record, spec, controller);
13814
+ }
13815
+ async registerPausedReplacement(spec) {
13816
+ const target = spec.replacesPausedRun;
13817
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
13818
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
13819
+ }
13820
+ this.getHandle(target.runId);
13821
+ const previous = await this.registryStore.load(target.runId);
13822
+ 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) {
13823
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
13824
+ }
13825
+ const runId = spec.runId ?? this.runIdFactory();
13826
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
13827
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
13828
+ this.runSlotLimiter.release(previous.runId);
13829
+ this.runSlotLimiter.acquire(runId);
13830
+ const now = this.now();
13831
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
13832
+ const next = {
13833
+ ...previous,
13834
+ status: "cancelled",
13835
+ updatedAt: now,
13836
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
13837
+ };
13838
+ try {
13839
+ await spec.admissionCommit(record, { previous, next });
13840
+ } catch (error) {
13841
+ this.runSlotLimiter.release(runId);
13842
+ this.runSlotLimiter.acquire(previous.runId);
13843
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
13844
+ throw error;
13845
+ }
13846
+ this.cleanupRunResources(previous.runId);
13847
+ this.notifyTerminalWaiters(previous.runId);
13848
+ const controller = new AbortController();
13849
+ forwardParentAbortSignal(controller, spec.parentSignal);
13850
+ return this.attachRun(record, spec, controller);
13851
+ }
13852
+ async restoreRun(spec) {
13853
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13854
+ return this.withRunControlLock(spec.runId, async () => {
13855
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
13856
+ const record = await this.registryStore.load(spec.runId);
13857
+ if (!record) throw new RunNotFoundError(spec.runId);
13858
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
13859
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
13860
+ }
13861
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
13862
+ return this.attachRun(record, spec, new AbortController());
13863
+ });
13864
+ }
13865
+ attachRun(record, spec, controller) {
13866
+ const runId = record.runId;
13458
13867
  try {
13459
13868
  const handle = new DefaultRunHandle({
13460
13869
  runRecord: record,
@@ -13552,11 +13961,36 @@ var DefaultRunSupervisor = class {
13552
13961
  registryStore: this.registryStore,
13553
13962
  reason,
13554
13963
  now: this.now,
13555
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
13964
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
13965
+ canRestoreRun: this.canRestoreRun
13556
13966
  });
13557
13967
  }
13558
- async pause(_runId, _reason) {
13559
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
13968
+ async pause(runId, reason) {
13969
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
13970
+ }
13971
+ async resumePausedRun(input) {
13972
+ return this.withRunControlLock(input.runId, async () => {
13973
+ const handle = this.getHandle(input.runId);
13974
+ const record = await this.registryStore.load(input.runId);
13975
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
13976
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
13977
+ }
13978
+ await persistRunTransition(this.registryStore, record, {
13979
+ ...record,
13980
+ status: "running",
13981
+ updatedAt: this.now(),
13982
+ pausedAt: void 0,
13983
+ pauseReason: void 0,
13984
+ errorIfAny: void 0,
13985
+ metadata: { ...record.metadata, executionId: input.executionId }
13986
+ });
13987
+ const controller = new AbortController();
13988
+ handle.replaceExecutionAbortController(controller, input.executionId);
13989
+ handle.attachTransportEventBus(input.eventBus);
13990
+ this.controllers.set(input.runId, controller);
13991
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
13992
+ return handle;
13993
+ });
13560
13994
  }
13561
13995
  async claimResume(runId, interaction, eventBus, parentSignal) {
13562
13996
  return this.withRunControlLock(runId, async () => {
@@ -13591,7 +14025,7 @@ var DefaultRunSupervisor = class {
13591
14025
  throw new RunNotFoundError(runId);
13592
14026
  }
13593
14027
  const claimId = generateRunResumeClaimId();
13594
- await this.registryStore.save({
14028
+ await persistRunTransition(this.registryStore, record, {
13595
14029
  ...record,
13596
14030
  updatedAt: this.now(),
13597
14031
  metadata: {
@@ -13679,7 +14113,7 @@ var DefaultRunSupervisor = class {
13679
14113
  }
13680
14114
  const awaitingUserWithoutClaim = { ...awaitingUser };
13681
14115
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13682
- await this.registryStore.save({
14116
+ const nextRecord = {
13683
14117
  ...record,
13684
14118
  status: "running",
13685
14119
  updatedAt: this.now(),
@@ -13689,6 +14123,10 @@ var DefaultRunSupervisor = class {
13689
14123
  metadata: {
13690
14124
  ...record.metadata ?? {},
13691
14125
  ...execution ? { executionId: execution.executionId } : {},
14126
+ ...execution?.inputEventIds ? { resumeInputs: {
14127
+ eventIds: [...execution.inputEventIds],
14128
+ checkpointRevision: pendingInteraction.checkpointRevision
14129
+ } } : {},
13692
14130
  awaitingUser: {
13693
14131
  ...awaitingUserWithoutClaim,
13694
14132
  interaction: {
@@ -13697,10 +14135,12 @@ var DefaultRunSupervisor = class {
13697
14135
  }
13698
14136
  }
13699
14137
  }
13700
- });
14138
+ };
14139
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
14140
+ else await persistRunTransition(this.registryStore, record, nextRecord);
13701
14141
  const executionController = new AbortController();
13702
14142
  forwardParentAbortSignal(executionController, parentSignal);
13703
- handle.replaceExecutionAbortController(executionController);
14143
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
13704
14144
  this.controllers.set(runId, executionController);
13705
14145
  return handle;
13706
14146
  });
@@ -13718,7 +14158,7 @@ var DefaultRunSupervisor = class {
13718
14158
  }
13719
14159
  const awaitingUserWithoutClaim = { ...awaitingUser };
13720
14160
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13721
- await this.registryStore.save({
14161
+ await persistRunTransition(this.registryStore, record, {
13722
14162
  ...record,
13723
14163
  updatedAt: this.now(),
13724
14164
  metadata: {
@@ -13863,13 +14303,13 @@ __export(system_reminder_exports, {
13863
14303
 
13864
14304
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
13865
14305
  function createDefaultGraphExecutor(options) {
13866
- const executor = new GraphExecutor(
14306
+ const executor2 = new GraphExecutor(
13867
14307
  options.checkpointer ?? new MemoryCheckpointer(),
13868
14308
  { maxSteps: options.maxSteps ?? 8 }
13869
14309
  );
13870
- executor.registerNode(new UserNode());
13871
- executor.registerNode(options.llmNode);
13872
- executor.registerNode(new ToolNode({
14310
+ executor2.registerNode(new UserNode());
14311
+ executor2.registerNode(options.llmNode);
14312
+ executor2.registerNode(new ToolNode({
13873
14313
  toolRuntime: options.toolRuntime,
13874
14314
  observationPreview: options.observationPreview,
13875
14315
  auditPort: options.auditPort,
@@ -13877,8 +14317,8 @@ function createDefaultGraphExecutor(options) {
13877
14317
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
13878
14318
  modelInputResolver: options.modelInputResolver
13879
14319
  }));
13880
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
13881
- return executor;
14320
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14321
+ return executor2;
13882
14322
  }
13883
14323
 
13884
14324
  // src/runtime-kernel/testkit/graphLoopHarness.ts
@@ -13903,7 +14343,7 @@ function createGraphLoopHarness(options) {
13903
14343
  return {
13904
14344
  async run() {
13905
14345
  const checkpointKey = options.runId ?? options.turnId;
13906
- const executor = createDefaultGraphExecutor({
14346
+ const executor2 = createDefaultGraphExecutor({
13907
14347
  llmNode: options.createLlmNode({
13908
14348
  llmCaller: options.llmCaller,
13909
14349
  toolRuntime: options.toolRuntime
@@ -13933,8 +14373,8 @@ function createGraphLoopHarness(options) {
13933
14373
  signal: options.signal ?? options.toolContext.abortSignal,
13934
14374
  executorLocal
13935
14375
  };
13936
- await executor.prime(checkpointKey, local, "user");
13937
- const result = await executor.runUntilYield(checkpointKey);
14376
+ await executor2.prime(checkpointKey, local, "user");
14377
+ const result = await executor2.runUntilYield(checkpointKey);
13938
14378
  return {
13939
14379
  checkpointNodeId: result.checkpoint.nodeId,
13940
14380
  stepCount: result.stepCount,
@@ -13944,6 +14384,6 @@ function createGraphLoopHarness(options) {
13944
14384
  };
13945
14385
  }
13946
14386
 
13947
- export { AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, ChildRunParentTraceProjection, CommonParameterTypes, CompositeAuditPort, DefaultTokenizerPort, EMPTY_MODEL_INPUT_REQUIREMENT, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, INITIAL_CANONICAL_INFERENCE_STREAM_STATE, LLMPolicyEngine, LLM_IMAGE_INPUT_ERROR_CODES, LLM_MODEL_ELIGIBILITY_ERROR_CODE, LlmCaller, LlmImageInputError, LlmModelEligibilityError, LlmNode, MODEL_INPUT_ERROR_CODES, MODEL_INPUT_PLACEMENTS, MemoryCheckpointer, MemoryEventStore, ModelInputCapabilityError, ModelResolver, PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, REASONING_EFFORTS, RuntimeEventSubRunTracePublisher, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolModelInputResolutionError, ToolNode, ToolParameterSchemaError, UserNode, WaitUserNode, addLedgerAggregate, addUsageTotals, advanceCanonicalInferenceStreamState, agentHasToolTrigger, aggregateCanonicalUsage, aggregateTokenLedgerEntries, applySystemReminders, assertModelInputCompatibility, assertToolParameterSchema, audit_exports as audit, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, computeCost, computeToolIdempotencyKey, consoleAudit, consumeCanonicalInferenceStream, copyToolContextRuntimeCapability, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextComponentLedgerEntry, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createFixedChatModelCatalog, createGraphLoopHarness, createHostToolCallBootstrap, createLlmUsageLedgerEntry, createModelInputCompatibilityError, createMonotonicEventStoreIdFactory, createRunTokenUsageAggregate, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, deriveModelInputRequirement, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, evaluateModelInputCompatibility, evaluatePrimaryPromptCapacity, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, hostReminderTextTemplate, isRuntimeFailureFact, isValidReasoningEffort, lastStepsHintTemplate, listCompatibleModelIds, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, parseToolModelInputDeclaration, periodicProgressReflectionTemplate, phaseEqualsTrigger, projectChildRuntimeEventToSubRunTrace, readCheckpointContextUsage, readNonEmptyStrings, readToolContextPersistedHistory, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, requireEventStoreId, resolveEffectiveEffort, resolveEffectivePromptBudget, resolveToolModelInput, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, token_accounting_exports as tokenAccounting, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
14387
+ export { AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, ChildRunParentTraceProjection, CommonParameterTypes, CompositeAuditPort, DefaultTokenizerPort, EMPTY_MODEL_INPUT_REQUIREMENT, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, INITIAL_CANONICAL_INFERENCE_STREAM_STATE, LLMPolicyEngine, LLM_IMAGE_INPUT_ERROR_CODES, LLM_MODEL_ELIGIBILITY_ERROR_CODE, LlmCaller, LlmImageInputError, LlmModelEligibilityError, LlmNode, MODEL_INPUT_ERROR_CODES, MODEL_INPUT_PLACEMENTS, MemoryCheckpointer, MemoryEventStore, ModelInputCapabilityError, ModelResolver, PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, REASONING_EFFORTS, RunPauseRequested, RunRecoveryBlockedError, RuntimeEventSubRunTracePublisher, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolModelInputResolutionError, ToolNode, ToolParameterSchemaError, UserNode, WaitUserNode, addLedgerAggregate, addUsageTotals, advanceCanonicalInferenceStreamState, agentHasToolTrigger, aggregateCanonicalUsage, aggregateTokenLedgerEntries, applySystemReminders, assertModelInputCompatibility, assertToolParameterSchema, audit_exports as audit, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, computeCost, computeToolIdempotencyKey, consoleAudit, consumeCanonicalInferenceStream, copyToolContextRuntimeCapability, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextComponentLedgerEntry, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createFixedChatModelCatalog, createGraphLoopHarness, createHostToolCallBootstrap, createLlmUsageLedgerEntry, createModelInputCompatibilityError, createMonotonicEventStoreIdFactory, createRunTokenUsageAggregate, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, deriveModelInputRequirement, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, evaluateModelInputCompatibility, evaluatePrimaryPromptCapacity, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, hostReminderTextTemplate, isRunPauseSignal, isRuntimeFailureFact, isValidReasoningEffort, lastStepsHintTemplate, listCompatibleModelIds, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, parseEngineCheckpoint, parseToolModelInputDeclaration, periodicProgressReflectionTemplate, phaseEqualsTrigger, projectChildRuntimeEventToSubRunTrace, readCheckpointContextUsage, readNonEmptyStrings, readToolContextPersistedHistory, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, requireEventStoreId, resolveEffectiveEffort, resolveEffectivePromptBudget, resolveToolModelInput, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, token_accounting_exports as tokenAccounting, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
13948
14388
  //# sourceMappingURL=runtime-kernel.js.map
13949
14389
  //# sourceMappingURL=runtime-kernel.js.map