@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/index.cjs CHANGED
@@ -5,6 +5,7 @@ var eventsourceParser = require('eventsource-parser');
5
5
  var tiktoken = require('tiktoken');
6
6
  var async_hooks = require('async_hooks');
7
7
  var crypto = require('crypto');
8
+ var util = require('util');
8
9
  var promises = require('fs/promises');
9
10
  var path = require('path');
10
11
 
@@ -52,6 +53,8 @@ __export(runtime_kernel_exports, {
52
53
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
53
54
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
54
55
  REASONING_EFFORTS: () => REASONING_EFFORTS,
56
+ RunPauseRequested: () => RunPauseRequested,
57
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
55
58
  RuntimeEventSubRunTracePublisher: () => RuntimeEventSubRunTracePublisher,
56
59
  SYSTEM_REMINDER_RULES: () => SYSTEM_REMINDER_RULES,
57
60
  SystemReminderRegistry: () => SystemReminderRegistry,
@@ -109,6 +112,7 @@ __export(runtime_kernel_exports, {
109
112
  getToolContextRuntimeBinding: () => getToolContextRuntimeBinding,
110
113
  graph: () => graph_engine_exports,
111
114
  hostReminderTextTemplate: () => hostReminderTextTemplate,
115
+ isRunPauseSignal: () => isRunPauseSignal,
112
116
  isRuntimeFailureFact: () => isRuntimeFailureFact,
113
117
  isValidReasoningEffort: () => isValidReasoningEffort,
114
118
  lastStepsHintTemplate: () => lastStepsHintTemplate,
@@ -117,6 +121,7 @@ __export(runtime_kernel_exports, {
117
121
  maxStepsForceFinalAnswerTemplate: () => maxStepsForceFinalAnswerTemplate,
118
122
  noopAudit: () => noopAudit,
119
123
  normalizeToolArgs: () => normalizeToolArgs,
124
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
120
125
  parseToolModelInputDeclaration: () => parseToolModelInputDeclaration,
121
126
  periodicProgressReflectionTemplate: () => periodicProgressReflectionTemplate,
122
127
  phaseEqualsTrigger: () => phaseEqualsTrigger,
@@ -156,13 +161,17 @@ __export(graph_engine_exports, {
156
161
  MemoryEventStore: () => MemoryEventStore,
157
162
  PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
158
163
  PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
164
+ RunPauseRequested: () => RunPauseRequested,
165
+ RunRecoveryBlockedError: () => RunRecoveryBlockedError,
159
166
  ToolNode: () => ToolNode,
160
167
  UserNode: () => UserNode,
161
168
  WaitUserNode: () => WaitUserNode,
162
169
  createHostToolCallBootstrap: () => createHostToolCallBootstrap,
163
170
  createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
164
171
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
172
+ isRunPauseSignal: () => isRunPauseSignal,
165
173
  isRuntimeFailureFact: () => isRuntimeFailureFact,
174
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
166
175
  readCheckpointContextUsage: () => readCheckpointContextUsage,
167
176
  requireEventStoreId: () => requireEventStoreId,
168
177
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -3385,6 +3394,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
3385
3394
  "memory",
3386
3395
  "runtimeEventSink",
3387
3396
  "runtimeEventCommitPort",
3397
+ "commitExecutionBoundary",
3398
+ "toolRecoveryPort",
3388
3399
  "runtimeFailureFactSink",
3389
3400
  "signal",
3390
3401
  "summarizationCallbacks",
@@ -3935,6 +3946,7 @@ var GraphExecutor = class {
3935
3946
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
3936
3947
  };
3937
3948
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
3949
+ this.executionCheckpointPort = config.executionCheckpointPort;
3938
3950
  }
3939
3951
  checkpointer;
3940
3952
  nodes = /* @__PURE__ */ new Map();
@@ -3942,6 +3954,7 @@ var GraphExecutor = class {
3942
3954
  checkpointQueues = /* @__PURE__ */ new Map();
3943
3955
  config;
3944
3956
  telemetryPort;
3957
+ executionCheckpointPort;
3945
3958
  registerNode(node) {
3946
3959
  this.nodes.set(node.id, node);
3947
3960
  }
@@ -3950,6 +3963,7 @@ var GraphExecutor = class {
3950
3963
  }
3951
3964
  sanitize(state) {
3952
3965
  return {
3966
+ ...state,
3953
3967
  nodeId: state.nodeId,
3954
3968
  revision: state.revision ?? 0,
3955
3969
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -3969,8 +3983,9 @@ var GraphExecutor = class {
3969
3983
  throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
3970
3984
  }
3971
3985
  this.ephemeralLocals.set(checkpointKey, { ...local });
3972
- await this.checkpointer.save(checkpointKey, {
3986
+ await this.commitCheckpoint(checkpointKey, {
3973
3987
  nodeId,
3988
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
3974
3989
  revision: 1,
3975
3990
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
3976
3991
  local: sanitizeCheckpointLocal(local)
@@ -3981,6 +3996,33 @@ var GraphExecutor = class {
3981
3996
  );
3982
3997
  });
3983
3998
  }
3999
+ /** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
4000
+ async continueSession(checkpointKey, input) {
4001
+ if (!this.executionCheckpointPort) {
4002
+ throw new Error("continueSession requires an ExecutionCheckpointPort");
4003
+ }
4004
+ return this.runWithCheckpointQueue(checkpointKey, async () => {
4005
+ const current = await this.checkpointer.load(checkpointKey);
4006
+ if (!current || current.revision !== input.expectedRevision) {
4007
+ throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
4008
+ }
4009
+ if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
4010
+ throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
4011
+ }
4012
+ if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
4013
+ return { checkpoint: current, events: [], stepCount: 0 };
4014
+ }
4015
+ this.ephemeralLocals.set(checkpointKey, input.capabilities);
4016
+ try {
4017
+ return await this.runUntilYieldQueued(
4018
+ checkpointKey,
4019
+ current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
4020
+ );
4021
+ } finally {
4022
+ this.ephemeralLocals.delete(checkpointKey);
4023
+ }
4024
+ });
4025
+ }
3984
4026
  /** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
3985
4027
  async resumeSession(checkpointKey, input) {
3986
4028
  return this.runWithCheckpointQueue(checkpointKey, async () => {
@@ -4001,17 +4043,21 @@ var GraphExecutor = class {
4001
4043
  );
4002
4044
  }
4003
4045
  const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
4046
+ if (this.executionCheckpointPort && current.local?.executorLocal) {
4047
+ resumedLocal.executorLocal = { ...current.local.executorLocal };
4048
+ }
4004
4049
  this.ephemeralLocals.set(checkpointKey, resumedLocal);
4005
- await this.checkpointer.save(checkpointKey, {
4050
+ await this.commitCheckpoint(checkpointKey, {
4006
4051
  ...current,
4007
4052
  nodeId: input.nodeId ?? "llm",
4053
+ ...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
4008
4054
  revision: currentRevision + 1,
4009
4055
  local: sanitizeCheckpointLocal(resumedLocal)
4010
4056
  });
4011
4057
  const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
4012
4058
  return this.runUntilYieldQueued(
4013
4059
  checkpointKey,
4014
- input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
4060
+ this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
4015
4061
  );
4016
4062
  });
4017
4063
  }
@@ -4102,16 +4148,23 @@ var GraphExecutor = class {
4102
4148
  };
4103
4149
  }
4104
4150
  async saveCheckpoint(checkpointKey, state) {
4105
- const checkpoint = this.sanitize({
4151
+ const checkpoint2 = this.sanitize({
4106
4152
  ...state,
4107
4153
  revision: (state.revision ?? 0) + 1
4108
4154
  });
4109
- await this.checkpointer.save(checkpointKey, checkpoint);
4110
- return checkpoint;
4155
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
4156
+ return checkpoint2;
4157
+ }
4158
+ async commitCheckpoint(checkpointKey, checkpoint2) {
4159
+ if (this.executionCheckpointPort) {
4160
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
4161
+ } else {
4162
+ await this.checkpointer.save(checkpointKey, checkpoint2);
4163
+ }
4111
4164
  }
4112
4165
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
4113
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
4114
- return { events, checkpoint, stepCount };
4166
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
4167
+ return { events, checkpoint: checkpoint2, stepCount };
4115
4168
  }
4116
4169
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
4117
4170
  let state = initialState;
@@ -4121,6 +4174,15 @@ var GraphExecutor = class {
4121
4174
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
4122
4175
  local: { ...state.local || {}, ...ephemeral }
4123
4176
  };
4177
+ if (this.executionCheckpointPort) {
4178
+ state.local = {
4179
+ ...state.local,
4180
+ commitExecutionBoundary: async (boundary) => {
4181
+ const saved = await this.saveCheckpoint(checkpointKey, boundary);
4182
+ boundary.revision = saved.revision;
4183
+ }
4184
+ };
4185
+ }
4124
4186
  const isAbortSignal2 = (v) => {
4125
4187
  return v !== null && typeof v === "object" && "aborted" in v;
4126
4188
  };
@@ -4130,11 +4192,12 @@ var GraphExecutor = class {
4130
4192
  throw err;
4131
4193
  };
4132
4194
  let stepCount = 0;
4195
+ const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
4133
4196
  let allEvents = [];
4134
4197
  logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
4135
4198
  maxSteps
4136
4199
  });
4137
- while (stepCount < maxSteps) {
4200
+ while (previousSteps + stepCount < maxSteps) {
4138
4201
  stepCount += 1;
4139
4202
  reportStepsUsed(stepCount);
4140
4203
  const signalRaw = state.local?.signal;
@@ -4146,7 +4209,7 @@ var GraphExecutor = class {
4146
4209
  const stepPreparation = prepareGraphStep({
4147
4210
  state,
4148
4211
  maxSteps,
4149
- stepCount
4212
+ stepCount: previousSteps + stepCount
4150
4213
  });
4151
4214
  state = stepPreparation.state;
4152
4215
  const node = this.nodes.get(state.nodeId);
@@ -4155,6 +4218,7 @@ var GraphExecutor = class {
4155
4218
  maxSteps,
4156
4219
  stepCount
4157
4220
  });
4221
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
4158
4222
  const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
4159
4223
  this.ephemeralLocals.delete(checkpointKey);
4160
4224
  return result3;
@@ -4164,6 +4228,11 @@ var GraphExecutor = class {
4164
4228
  stepCount,
4165
4229
  nodeId: state.nodeId
4166
4230
  });
4231
+ if (this.executionCheckpointPort) {
4232
+ state.executionStatus = "executing";
4233
+ const saved = await this.saveCheckpoint(checkpointKey, state);
4234
+ state.revision = saved.revision;
4235
+ }
4167
4236
  const result2 = await runGraphNodeWithTelemetry({
4168
4237
  node,
4169
4238
  state,
@@ -4188,10 +4257,13 @@ var GraphExecutor = class {
4188
4257
  fromNodeId: stepResolution.action.fromNodeId,
4189
4258
  nextNodeId: stepResolution.action.nextNodeId
4190
4259
  });
4191
- await this.saveCheckpoint(checkpointKey, state);
4260
+ if (this.executionCheckpointPort) state.executionStatus = "ready";
4261
+ const saved = await this.saveCheckpoint(checkpointKey, state);
4262
+ state.revision = saved.revision;
4192
4263
  continue;
4193
4264
  }
4194
4265
  if (stepResolution.action.kind === "yield") {
4266
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
4195
4267
  logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
4196
4268
  maxSteps,
4197
4269
  stepCount
@@ -4202,6 +4274,7 @@ var GraphExecutor = class {
4202
4274
  maxSteps,
4203
4275
  stepCount
4204
4276
  });
4277
+ if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
4205
4278
  return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
4206
4279
  }
4207
4280
  logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
@@ -4222,6 +4295,7 @@ var GraphExecutor = class {
4222
4295
  },
4223
4296
  retryable: false
4224
4297
  }), "GraphExecutor.engine_budget_exhausted"));
4298
+ if (this.executionCheckpointPort) state.executionStatus = "yielded";
4225
4299
  const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
4226
4300
  this.ephemeralLocals.delete(checkpointKey);
4227
4301
  return result;
@@ -8125,10 +8199,11 @@ var LlmNode = class {
8125
8199
  bridge.handle
8126
8200
  );
8127
8201
  } catch (error) {
8128
- bridge.finalizePartialAnswer();
8202
+ if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
8129
8203
  throw error;
8130
8204
  }
8131
8205
  const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
8206
+ if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
8132
8207
  switch (decision.kind) {
8133
8208
  case "tool_calls": {
8134
8209
  if (forceFinalAnswer) {
@@ -9403,6 +9478,58 @@ function recordToolProtocolError(params) {
9403
9478
  recorder?.recordToolProtocolError?.(params);
9404
9479
  }
9405
9480
 
9481
+ // src/runtime-kernel/graph-engine/definitions/runContinuation.ts
9482
+ var RunRecoveryBlockedError = class extends Error {
9483
+ code = "RUN_RECOVERY_BLOCKED";
9484
+ constructor(message) {
9485
+ super(message);
9486
+ this.name = "RunRecoveryBlockedError";
9487
+ }
9488
+ };
9489
+ var RunPauseRequested = class extends Error {
9490
+ code = "RUN_PAUSE_REQUESTED";
9491
+ constructor(message = "Run paused by user") {
9492
+ super(message);
9493
+ this.name = "RunPauseRequested";
9494
+ }
9495
+ };
9496
+ function isRunPauseSignal(signal) {
9497
+ const reason = signal?.reason;
9498
+ return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
9499
+ }
9500
+
9501
+ // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
9502
+ async function executeRecoverableTool(input) {
9503
+ const local = input.state.local;
9504
+ if (!local?.commitExecutionBoundary) return input.execute();
9505
+ if (local.executingToolCallId) {
9506
+ if (local.executingToolCallId !== input.call.id) {
9507
+ throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
9508
+ }
9509
+ const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
9510
+ if (!decision || decision.kind === "blocked") {
9511
+ throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
9512
+ }
9513
+ if (decision.kind === "settled") return decision.result;
9514
+ }
9515
+ local.executingToolCallId = input.call.id;
9516
+ await local.commitExecutionBoundary(input.state);
9517
+ const result = await input.execute();
9518
+ if (!result.success && isRunPauseSignal(local.signal)) {
9519
+ const error = new Error("Tool execution paused before its outcome was confirmed");
9520
+ error.name = "AbortError";
9521
+ throw error;
9522
+ }
9523
+ return result;
9524
+ }
9525
+ async function commitToolBoundary(state, result) {
9526
+ if (!state.local?.commitExecutionBoundary) return;
9527
+ delete state.local.executingToolCallId;
9528
+ state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
9529
+ state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
9530
+ await state.local.commitExecutionBoundary(state);
9531
+ }
9532
+
9406
9533
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
9407
9534
  var logger11 = new Logger("ToolNode");
9408
9535
  function isAbortSignal(value) {
@@ -9573,6 +9700,7 @@ var ToolNode = class {
9573
9700
  const events = [];
9574
9701
  while (true) {
9575
9702
  const result = await this.runNextPendingToolCall(state);
9703
+ await commitToolBoundary(state, result);
9576
9704
  if (Array.isArray(result.events) && result.events.length > 0) {
9577
9705
  events.push(...result.events);
9578
9706
  }
@@ -9589,11 +9717,9 @@ var ToolNode = class {
9589
9717
  const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
9590
9718
  const signalRaw = state.local?.signal;
9591
9719
  if (isAbortSignal(signalRaw) && signalRaw.aborted) {
9592
- settlePendingToolCallsAfterAbort({
9593
- state,
9594
- calls,
9595
- toolCatalog: this.toolRuntime
9596
- });
9720
+ if (!isRunPauseSignal(signalRaw)) {
9721
+ settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
9722
+ }
9597
9723
  const abortError = new Error("The user aborted a request.");
9598
9724
  abortError.name = "AbortError";
9599
9725
  throw abortError;
@@ -9732,16 +9858,21 @@ var ToolNode = class {
9732
9858
  tool_calls: [call]
9733
9859
  });
9734
9860
  try {
9735
- const exec = await executeToolWithIdempotency({
9736
- idempotencyKey: execution.idempotencyKey,
9737
- inFlight: this.idempotencyInFlight,
9738
- history: readHistoryEvents(prepared.local),
9739
- toolName: execution.toolName,
9740
- execute: () => this.toolRuntime.executeTool(
9741
- execution.toolName,
9742
- execution.toolArgs,
9743
- prepared.toolContext
9744
- )
9861
+ const exec = await executeRecoverableTool({
9862
+ state,
9863
+ call,
9864
+ context: prepared.toolContext,
9865
+ execute: () => executeToolWithIdempotency({
9866
+ idempotencyKey: execution.idempotencyKey,
9867
+ inFlight: this.idempotencyInFlight,
9868
+ history: readHistoryEvents(prepared.local),
9869
+ toolName: execution.toolName,
9870
+ execute: () => this.toolRuntime.executeTool(
9871
+ execution.toolName,
9872
+ execution.toolArgs,
9873
+ prepared.toolContext
9874
+ )
9875
+ })
9745
9876
  });
9746
9877
  if (exec.success) {
9747
9878
  const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
@@ -9821,7 +9952,7 @@ var ToolNode = class {
9821
9952
  bridge: execution.bridge
9822
9953
  });
9823
9954
  } catch (error) {
9824
- if (isToolExecutionAbort(error)) {
9955
+ if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
9825
9956
  settleToolCallsAfterExecutionAbort({
9826
9957
  state,
9827
9958
  remainingCalls: calls.slice(1),
@@ -9881,7 +10012,7 @@ var ToolNode = class {
9881
10012
  {
9882
10013
  attachments: context.attachments,
9883
10014
  metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
9884
- ephemeral: context.exec.idempotency?.cacheHit === true,
10015
+ // 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
9885
10016
  durationMs: context.exec.durationMs
9886
10017
  }
9887
10018
  );
@@ -9938,6 +10069,9 @@ var ToolNode = class {
9938
10069
  return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
9939
10070
  }
9940
10071
  async handleError(context) {
10072
+ if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
10073
+ throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
10074
+ }
9941
10075
  if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
9942
10076
  await this.emitToolDecisionAudit({
9943
10077
  action: "tool.deny",
@@ -10174,16 +10308,16 @@ function requireEventStoreId(eventStoreId) {
10174
10308
  }
10175
10309
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
10176
10310
  let lastTimestamp = 0;
10177
- let counter = 0;
10311
+ let counter2 = 0;
10178
10312
  return () => {
10179
10313
  const timestamp = Math.max(nowProvider(), lastTimestamp);
10180
10314
  if (timestamp === lastTimestamp) {
10181
- counter += 1;
10315
+ counter2 += 1;
10182
10316
  } else {
10183
10317
  lastTimestamp = timestamp;
10184
- counter = 0;
10318
+ counter2 = 0;
10185
10319
  }
10186
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
10320
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
10187
10321
  };
10188
10322
  }
10189
10323
 
@@ -10595,6 +10729,76 @@ function assertNonNegativeSafeInteger(value, field) {
10595
10729
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
10596
10730
  }
10597
10731
  }
10732
+ var counter = zod.z.number().int().nonnegative();
10733
+ var executor = zod.z.object({
10734
+ stepCount: counter,
10735
+ phase: zod.z.string().optional(),
10736
+ maxSteps: counter.optional(),
10737
+ remainingSteps: zod.z.number().int().optional(),
10738
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
10739
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
10740
+ lastStepsHintThreshold: counter.optional(),
10741
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
10742
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
10743
+ runLockedModelId: zod.z.string().optional(),
10744
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
10745
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
10746
+ llmInvocationCount: counter.optional(),
10747
+ lockRequestedModelId: zod.z.boolean().optional(),
10748
+ contextCompaction: zod.z.object({
10749
+ attemptCount: counter,
10750
+ committedCount: counter,
10751
+ lastCommittedFingerprint: zod.z.string().optional()
10752
+ }).strict().optional()
10753
+ }).strict();
10754
+ var checkpoint = zod.z.object({
10755
+ nodeId: zod.z.string().min(1),
10756
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
10757
+ revision: counter.optional(),
10758
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
10759
+ local: zod.z.object({
10760
+ runId: RunIdSchema.optional(),
10761
+ parentRunId: RunIdSchema.optional(),
10762
+ conversationId: zod.z.string().optional(),
10763
+ turnId: zod.z.string().optional(),
10764
+ request: SerializableJsonRecord.optional(),
10765
+ history: zod.z.array(RuntimeEvent).optional(),
10766
+ newEvents: zod.z.array(RuntimeEvent).optional(),
10767
+ executorLocal: executor.optional(),
10768
+ pendingToolCalls: zod.z.array(zod.z.object({
10769
+ id: ToolCallIdSchema,
10770
+ type: zod.z.literal("function"),
10771
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
10772
+ }).strict()).optional(),
10773
+ executingToolCallId: ToolCallIdSchema.optional(),
10774
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
10775
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
10776
+ lastToolResult: SerializableJsonRecord.optional(),
10777
+ finalAnswer: zod.z.string().optional(),
10778
+ answerId: zod.z.string().optional(),
10779
+ chunkSeq: counter.optional(),
10780
+ contextUsage: ContextUsageSnapshot.optional()
10781
+ }).passthrough().optional()
10782
+ }).strict();
10783
+ function parseEngineCheckpoint(value) {
10784
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
10785
+ for (const key of [
10786
+ "memory",
10787
+ "signal",
10788
+ "toolContext",
10789
+ "runtimeEventSink",
10790
+ "runtimeEventCommitPort",
10791
+ "runtimeFailureFactSink",
10792
+ "summarizationCallbacks",
10793
+ "commitExecutionBoundary",
10794
+ "toolRecoveryPort"
10795
+ ]) {
10796
+ if (result.local && Object.hasOwn(result.local, key)) {
10797
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
10798
+ }
10799
+ }
10800
+ return result;
10801
+ }
10598
10802
 
10599
10803
  // src/runtime-kernel/tools/index.ts
10600
10804
  var tools_exports = {};
@@ -11046,12 +11250,33 @@ var RuntimeEventPublisher = class {
11046
11250
  var EventBusEventPersistence = class {
11047
11251
  constructor(options) {
11048
11252
  this.options = options;
11253
+ this.checkpointWritesActive = options.checkpointWriter !== void 0;
11049
11254
  }
11050
11255
  options;
11051
11256
  scheduledEventIds = /* @__PURE__ */ new Set();
11052
11257
  writeTail = Promise.resolve();
11053
11258
  firstWriteError;
11054
11259
  connected = false;
11260
+ checkpointWritesActive;
11261
+ checkpointEvents = [];
11262
+ /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
11263
+ async commitCheckpoint(checkpointKey, checkpoint2) {
11264
+ const writer = this.options.checkpointWriter;
11265
+ if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
11266
+ const events = this.checkpointEvents;
11267
+ this.checkpointEvents = [];
11268
+ await this.enqueueWrite(() => writer({
11269
+ checkpointKey,
11270
+ checkpoint: checkpoint2,
11271
+ events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
11272
+ }));
11273
+ }
11274
+ /** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
11275
+ finishCheckpointWrites() {
11276
+ for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
11277
+ this.checkpointEvents = [];
11278
+ this.checkpointWritesActive = false;
11279
+ }
11055
11280
  connect() {
11056
11281
  if (this.connected) {
11057
11282
  throw new Error("[EventBusEventPersistence] consumer is already connected");
@@ -11098,14 +11323,22 @@ var EventBusEventPersistence = class {
11098
11323
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
11099
11324
  return;
11100
11325
  }
11326
+ if (this.checkpointWritesActive) {
11327
+ this.scheduledEventIds.add(event.id);
11328
+ this.checkpointEvents.push(event);
11329
+ return;
11330
+ }
11101
11331
  void this.scheduleWrite(event).catch(() => void 0);
11102
11332
  };
11103
11333
  scheduleWrite(event) {
11104
11334
  this.scheduledEventIds.add(event.id);
11105
- const eventStoreId = this.options.nextEventStoreId();
11106
- const write = this.writeTail.then(async () => {
11107
- await this.options.eventStore.append({ eventStoreId, event });
11108
- });
11335
+ return this.enqueueWrite(() => this.options.eventStore.append({
11336
+ eventStoreId: this.options.nextEventStoreId(),
11337
+ event
11338
+ }));
11339
+ }
11340
+ enqueueWrite(operation) {
11341
+ const write = this.writeTail.then(operation);
11109
11342
  this.writeTail = write;
11110
11343
  void write.catch((error) => {
11111
11344
  this.firstWriteError ??= error;
@@ -12727,15 +12960,15 @@ function hasSeedHistoryPrefix(history, seedHistory) {
12727
12960
  }
12728
12961
  return true;
12729
12962
  }
12730
- function readCheckpointHistory(checkpoint) {
12731
- if (!checkpoint?.local) return [];
12732
- const history = checkpoint.local.history;
12963
+ function readCheckpointHistory(checkpoint2) {
12964
+ if (!checkpoint2?.local) return [];
12965
+ const history = checkpoint2.local.history;
12733
12966
  if (!Array.isArray(history)) return [];
12734
12967
  return parseRuntimeEvents(history);
12735
12968
  }
12736
12969
  async function recoverChildRunEventsFromCheckpoint(params) {
12737
- const checkpoint = await params.checkpointer.load(params.checkpointKey);
12738
- const history = readCheckpointHistory(checkpoint);
12970
+ const checkpoint2 = await params.checkpointer.load(params.checkpointKey);
12971
+ const history = readCheckpointHistory(checkpoint2);
12739
12972
  if (history.length === 0) {
12740
12973
  return [];
12741
12974
  }
@@ -12826,6 +13059,9 @@ var ChildRunInvoker = class {
12826
13059
  explicitConversationId: conversationId,
12827
13060
  parentToolContext
12828
13061
  });
13062
+ if (config.persistence?.expectedRevision !== void 0) {
13063
+ return this.continueChild(config, childRunId, runtimeConversationId);
13064
+ }
12829
13065
  const turnId = generateTurnId();
12830
13066
  logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
12831
13067
  conversationId: runtimeConversationId,
@@ -12833,21 +13069,8 @@ var ChildRunInvoker = class {
12833
13069
  maxSteps,
12834
13070
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
12835
13071
  });
12836
- const checkpointer = new MemoryCheckpointer();
12837
- const graphExecutor = new GraphExecutor(checkpointer, { maxSteps });
12838
- const llmNode = this.createLlmNode();
12839
- const toolNode = new ToolNode({
12840
- toolRuntime: this.toolRuntime,
12841
- observationPreview: this.observationPreview,
12842
- telemetryPort: this.telemetryPort,
12843
- auditPort: this.auditPort,
12844
- modelInputCapabilityValidator: this.modelInputCapabilityValidator,
12845
- modelInputResolver: this.modelInputResolver
12846
- });
12847
- const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
12848
- graphExecutor.registerNode(llmNode);
12849
- graphExecutor.registerNode(toolNode);
12850
- graphExecutor.registerNode(waitUserNode);
13072
+ const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
13073
+ const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
12851
13074
  const childUserInput = createChildRunUserInput({
12852
13075
  id: generateRuntimeEventId(),
12853
13076
  conversationId: runtimeConversationId,
@@ -12927,6 +13150,7 @@ var ChildRunInvoker = class {
12927
13150
  ...abortSignal ? { signal: abortSignal } : {},
12928
13151
  ...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
12929
13152
  runtimeEventSink,
13153
+ toolRecoveryPort: config.persistence?.toolRecoveryPort,
12930
13154
  ...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
12931
13155
  systemPrompt
12932
13156
  };
@@ -12967,6 +13191,7 @@ var ChildRunInvoker = class {
12967
13191
  eventToMessageConverter: this.eventToMessageConverter
12968
13192
  });
12969
13193
  } catch (err) {
13194
+ if (config.persistence) throw err;
12970
13195
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
12971
13196
  checkpointer,
12972
13197
  checkpointKey: internalCheckpointKey,
@@ -13005,7 +13230,7 @@ var ChildRunInvoker = class {
13005
13230
  events: allEvents,
13006
13231
  eventToMessageConverter: this.eventToMessageConverter
13007
13232
  });
13008
- await checkpointer.clear(internalCheckpointKey);
13233
+ if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
13009
13234
  return {
13010
13235
  success: !error && !cancelled,
13011
13236
  runId: childRunId,
@@ -13022,6 +13247,66 @@ var ChildRunInvoker = class {
13022
13247
  error
13023
13248
  };
13024
13249
  }
13250
+ createGraph(checkpointer, maxSteps, executionCheckpointPort) {
13251
+ const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
13252
+ graph.registerNode(this.createLlmNode());
13253
+ graph.registerNode(new ToolNode({
13254
+ toolRuntime: this.toolRuntime,
13255
+ observationPreview: this.observationPreview,
13256
+ telemetryPort: this.telemetryPort,
13257
+ auditPort: this.auditPort,
13258
+ modelInputCapabilityValidator: this.modelInputCapabilityValidator,
13259
+ modelInputResolver: this.modelInputResolver
13260
+ }));
13261
+ graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
13262
+ return graph;
13263
+ }
13264
+ async continueChild(config, runId, conversationId) {
13265
+ const persistence = config.persistence;
13266
+ if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
13267
+ const checkpoint2 = await persistence.checkpointer.load(runId);
13268
+ if (!checkpoint2 || checkpoint2.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
13269
+ const local = readGraphAgentLocal({ ...checkpoint2.local, runtimeEventSink: config.runtimeEventSink });
13270
+ const request = local.request;
13271
+ if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
13272
+ const context = createChildRunToolContext({
13273
+ parentToolContext: config.parentToolContext,
13274
+ conversationId,
13275
+ turnId: local.turnId,
13276
+ runId,
13277
+ parentRunId: config.parentRunId,
13278
+ userQuery: request.query,
13279
+ modelId: request.model_id,
13280
+ seedHistory: local.history,
13281
+ abortSignal: config.abortSignal
13282
+ });
13283
+ const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
13284
+ const result = await graph.continueSession(runId, {
13285
+ expectedRevision: persistence.expectedRevision,
13286
+ capabilities: {
13287
+ toolContext: context,
13288
+ signal: config.abortSignal,
13289
+ runtimeEventSink: config.runtimeEventSink,
13290
+ runtimeEventCommitPort: config.runtimeEventCommitPort,
13291
+ toolRecoveryPort: persistence.toolRecoveryPort
13292
+ }
13293
+ });
13294
+ if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
13295
+ const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
13296
+ const finalAnswer = extractFinalAnswer(events);
13297
+ return {
13298
+ runId,
13299
+ parentRunId: config.parentRunId,
13300
+ subrunId: runId,
13301
+ success: true,
13302
+ events,
13303
+ finalAnswer,
13304
+ lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
13305
+ judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
13306
+ stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
13307
+ toolset: { availableTools: request.availableTools }
13308
+ };
13309
+ }
13025
13310
  };
13026
13311
  function isAbortError2(error) {
13027
13312
  return error instanceof Error && error.name === "AbortError";
@@ -13423,8 +13708,6 @@ __export(run_supervisor_exports, {
13423
13708
  RunNotFoundError: () => RunNotFoundError,
13424
13709
  runMetaFromRecord: () => runMetaFromRecord
13425
13710
  });
13426
-
13427
- // src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
13428
13711
  function cloneRunRecord(record) {
13429
13712
  return {
13430
13713
  ...record,
@@ -13444,6 +13727,11 @@ function matchesStatus(candidate, filter) {
13444
13727
  }
13445
13728
  var MemoryRunRegistryStore = class {
13446
13729
  store = /* @__PURE__ */ new Map();
13730
+ async compareAndSwap(previous, next) {
13731
+ if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
13732
+ this.store.set(next.runId, cloneRunRecord(next));
13733
+ return true;
13734
+ }
13447
13735
  async save(record) {
13448
13736
  this.store.set(record.runId, cloneRunRecord(record));
13449
13737
  }
@@ -13591,6 +13879,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
13591
13879
  }
13592
13880
  };
13593
13881
 
13882
+ // src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
13883
+ async function persistRunTransition(store, previous, next) {
13884
+ if (store.compareAndSwap) {
13885
+ if (!await store.compareAndSwap(previous, next)) {
13886
+ throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
13887
+ }
13888
+ } else {
13889
+ await store.save(next);
13890
+ }
13891
+ }
13892
+
13594
13893
  // src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
13595
13894
  function isRunTerminalStatus(status) {
13596
13895
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -13646,6 +13945,7 @@ var DefaultRunHandle = class {
13646
13945
  parentRunId;
13647
13946
  runRecord;
13648
13947
  abortController;
13948
+ executionId;
13649
13949
  agentSpecSnapshot;
13650
13950
  requestSnapshot;
13651
13951
  transportEventBus;
@@ -13661,6 +13961,9 @@ var DefaultRunHandle = class {
13661
13961
  this.runId = options.runRecord.runId;
13662
13962
  this.parentRunId = options.runRecord.parentRunId;
13663
13963
  this.abortController = options.abortController;
13964
+ const executionId = options.runRecord.metadata?.executionId;
13965
+ if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
13966
+ this.executionId = executionId;
13664
13967
  this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
13665
13968
  this.requestSnapshot = cloneRequest(options.request);
13666
13969
  this.transportEventBus = options.eventBus;
@@ -13680,8 +13983,9 @@ var DefaultRunHandle = class {
13680
13983
  * awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
13681
13984
  * 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
13682
13985
  */
13683
- replaceExecutionAbortController(controller) {
13986
+ replaceExecutionAbortController(controller, executionId) {
13684
13987
  this.abortController = controller;
13988
+ this.executionId = executionId;
13685
13989
  }
13686
13990
  async spec() {
13687
13991
  return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
@@ -13701,6 +14005,7 @@ var DefaultRunHandle = class {
13701
14005
  this.abortController.abort(opts.reason);
13702
14006
  const latestRecord = await this.registryStore.load(this.runId);
13703
14007
  const baseRecord = latestRecord ?? this.runRecord;
14008
+ this.assertExecutionOwner(baseRecord);
13704
14009
  const transition = decideRunLifecycleTransition(baseRecord.status);
13705
14010
  if (transition.kind === "skip_terminal") {
13706
14011
  if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
@@ -13710,7 +14015,7 @@ var DefaultRunHandle = class {
13710
14015
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13711
14016
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
13712
14017
  };
13713
- await this.registryStore.save(settledRecord);
14018
+ await persistRunTransition(this.registryStore, baseRecord, settledRecord);
13714
14019
  this.runRecord = { ...settledRecord };
13715
14020
  return;
13716
14021
  }
@@ -13737,7 +14042,7 @@ var DefaultRunHandle = class {
13737
14042
  }
13738
14043
  }
13739
14044
  };
13740
- await this.registryStore.save(nextRecord);
14045
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13741
14046
  this.runRecord = { ...nextRecord };
13742
14047
  await this.auditPort.emit({
13743
14048
  envelopeId: generateAuditEnvelopeId(),
@@ -13845,21 +14150,35 @@ var DefaultRunHandle = class {
13845
14150
  async markFailed(error, patch = {}) {
13846
14151
  await this.saveLifecycleStatus("failed", patch, error);
13847
14152
  }
13848
- async pause(_reason) {
13849
- throw new NotImplementedError("RunHandle.pause is N-3.B; not implemented in N-3.A");
14153
+ async pause(reason = "Run paused by user") {
14154
+ const latest = await this.registryStore.load(this.runId);
14155
+ if (latest) this.assertExecutionOwner(latest);
14156
+ if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
14157
+ const next = {
14158
+ ...latest,
14159
+ status: "paused",
14160
+ updatedAt: Date.now(),
14161
+ pauseReason: reason,
14162
+ pausedAt: void 0
14163
+ };
14164
+ await persistRunTransition(this.registryStore, latest, next);
14165
+ this.runRecord = next;
14166
+ this.abortController.abort(new RunPauseRequested(reason));
13850
14167
  }
13851
- async resume() {
13852
- throw new NotImplementedError("RunHandle.resume is N-3.B; not implemented in N-3.A");
14168
+ async markPaused(patch = {}) {
14169
+ await this.saveLifecycleStatus("paused", patch);
13853
14170
  }
13854
14171
  async saveLifecycleStatus(status, patch, errorIfAny) {
13855
14172
  const latestRecord = await this.registryStore.load(this.runId);
13856
14173
  const baseRecord = latestRecord ?? this.runRecord;
13857
14174
  const transition = decideRunLifecycleTransition(baseRecord.status);
14175
+ this.assertExecutionOwner(baseRecord);
14176
+ if (status === "running" && baseRecord.status === "paused") return;
13858
14177
  if (transition.kind === "skip_terminal") {
13859
14178
  this.runRecord = { ...baseRecord };
13860
14179
  return;
13861
14180
  }
13862
- const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
14181
+ const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
13863
14182
  const updatedAt = Date.now();
13864
14183
  const nextRecord = {
13865
14184
  ...baseRecord,
@@ -13867,8 +14186,8 @@ var DefaultRunHandle = class {
13867
14186
  updatedAt,
13868
14187
  currentNode: patch.currentNode ?? baseRecord.currentNode,
13869
14188
  iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
13870
- pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
13871
- pausedAt: status === "awaiting_user" ? updatedAt : void 0,
14189
+ pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
14190
+ pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
13872
14191
  errorIfAny,
13873
14192
  metadata: awaitingUserPatch?.eventId ? {
13874
14193
  ...baseRecord.metadata ?? {},
@@ -13879,7 +14198,7 @@ var DefaultRunHandle = class {
13879
14198
  }
13880
14199
  } : baseRecord.metadata
13881
14200
  };
13882
- await this.registryStore.save(nextRecord);
14201
+ await persistRunTransition(this.registryStore, baseRecord, nextRecord);
13883
14202
  this.runRecord = { ...nextRecord };
13884
14203
  if (status === "completed" || status === "failed") {
13885
14204
  this.closeObservationChannel();
@@ -13889,6 +14208,11 @@ var DefaultRunHandle = class {
13889
14208
  forwardTransportEvent = (envelope) => {
13890
14209
  this.observationEventBus.emit("event", envelope);
13891
14210
  };
14211
+ assertExecutionOwner(record) {
14212
+ if (record.metadata?.executionId !== this.executionId) {
14213
+ throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
14214
+ }
14215
+ }
13892
14216
  forwardTransportError = (error) => {
13893
14217
  this.observationEventBus.emit("error", error);
13894
14218
  };
@@ -14219,7 +14543,15 @@ function createRunConcurrencyKeyRegistry() {
14219
14543
  runIdByKey.delete(concurrencyKey);
14220
14544
  }
14221
14545
  }
14222
- return { acquire, release };
14546
+ function transfer(previous, next, concurrencyKey) {
14547
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
14548
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
14549
+ }
14550
+ keyByRunId.delete(previous);
14551
+ keyByRunId.set(next, concurrencyKey);
14552
+ runIdByKey.set(concurrencyKey, next);
14553
+ }
14554
+ return { acquire, release, transfer };
14223
14555
  }
14224
14556
 
14225
14557
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -14270,6 +14602,24 @@ async function recoverRunsOnBoot(options) {
14270
14602
  const outcomes = [];
14271
14603
  for (const record of activeRecords) {
14272
14604
  const updatedAt = options.now();
14605
+ if (await options.canRestoreRun?.(record)) {
14606
+ const metadata = { ...record.metadata };
14607
+ const awaitingUser = metadata.awaitingUser;
14608
+ if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
14609
+ const restored = { ...awaitingUser };
14610
+ Reflect.deleteProperty(restored, "resumeClaim");
14611
+ metadata.awaitingUser = restored;
14612
+ }
14613
+ await persistRunTransition(options.registryStore, record, {
14614
+ ...record,
14615
+ status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
14616
+ pausedAt: record.pausedAt ?? updatedAt,
14617
+ pauseReason: record.pauseReason ?? options.reason,
14618
+ updatedAt,
14619
+ metadata
14620
+ });
14621
+ continue;
14622
+ }
14273
14623
  const nextRecord = {
14274
14624
  ...record,
14275
14625
  status: "failed",
@@ -14287,7 +14637,7 @@ async function recoverRunsOnBoot(options) {
14287
14637
  }
14288
14638
  }
14289
14639
  };
14290
- await options.registryStore.save(nextRecord);
14640
+ await persistRunTransition(options.registryStore, record, nextRecord);
14291
14641
  const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
14292
14642
  options.notifyTerminal(outcome);
14293
14643
  outcomes.push(outcome);
@@ -14411,8 +14761,13 @@ var DefaultRunSupervisor = class {
14411
14761
  inFlight = /* @__PURE__ */ new Map();
14412
14762
  eventWatchDisposers = /* @__PURE__ */ new Map();
14413
14763
  controlOperations = /* @__PURE__ */ new Map();
14764
+ canRestoreRun;
14414
14765
  constructor(options) {
14766
+ if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
14767
+ throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
14768
+ }
14415
14769
  this.registryStore = options.registryStore;
14770
+ this.canRestoreRun = options.canRestoreRun;
14416
14771
  this.auditPort = options.auditPort;
14417
14772
  this.executor = options.executor;
14418
14773
  this.runIdFactory = options.runIdFactory ?? generateRunId;
@@ -14445,6 +14800,9 @@ var DefaultRunSupervisor = class {
14445
14800
  });
14446
14801
  }
14447
14802
  async registerRun(spec) {
14803
+ if (spec.replacesPausedRun) {
14804
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
14805
+ }
14448
14806
  const runId = spec.runId ?? this.runIdFactory();
14449
14807
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
14450
14808
  throw new RunAlreadyRegisteredError(runId);
@@ -14455,11 +14813,66 @@ var DefaultRunSupervisor = class {
14455
14813
  forwardParentAbortSignal(controller, spec.parentSignal);
14456
14814
  const record = createInitialRunRecord({ runId, spec, startedAt });
14457
14815
  try {
14458
- await this.registryStore.save(record);
14816
+ if (spec.admissionCommit) await spec.admissionCommit(record);
14817
+ else await this.registryStore.save(record);
14459
14818
  } catch (error) {
14460
14819
  this.releaseRunAdmission(runId);
14461
14820
  throw error;
14462
14821
  }
14822
+ return this.attachRun(record, spec, controller);
14823
+ }
14824
+ async registerPausedReplacement(spec) {
14825
+ const target = spec.replacesPausedRun;
14826
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
14827
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
14828
+ }
14829
+ this.getHandle(target.runId);
14830
+ const previous = await this.registryStore.load(target.runId);
14831
+ 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) {
14832
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
14833
+ }
14834
+ const runId = spec.runId ?? this.runIdFactory();
14835
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
14836
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
14837
+ this.runSlotLimiter.release(previous.runId);
14838
+ this.runSlotLimiter.acquire(runId);
14839
+ const now = this.now();
14840
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
14841
+ const next = {
14842
+ ...previous,
14843
+ status: "cancelled",
14844
+ updatedAt: now,
14845
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
14846
+ };
14847
+ try {
14848
+ await spec.admissionCommit(record, { previous, next });
14849
+ } catch (error) {
14850
+ this.runSlotLimiter.release(runId);
14851
+ this.runSlotLimiter.acquire(previous.runId);
14852
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
14853
+ throw error;
14854
+ }
14855
+ this.cleanupRunResources(previous.runId);
14856
+ this.notifyTerminalWaiters(previous.runId);
14857
+ const controller = new AbortController();
14858
+ forwardParentAbortSignal(controller, spec.parentSignal);
14859
+ return this.attachRun(record, spec, controller);
14860
+ }
14861
+ async restoreRun(spec) {
14862
+ if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
14863
+ return this.withRunControlLock(spec.runId, async () => {
14864
+ if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
14865
+ const record = await this.registryStore.load(spec.runId);
14866
+ if (!record) throw new RunNotFoundError(spec.runId);
14867
+ if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
14868
+ throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
14869
+ }
14870
+ this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
14871
+ return this.attachRun(record, spec, new AbortController());
14872
+ });
14873
+ }
14874
+ attachRun(record, spec, controller) {
14875
+ const runId = record.runId;
14463
14876
  try {
14464
14877
  const handle = new DefaultRunHandle({
14465
14878
  runRecord: record,
@@ -14557,11 +14970,36 @@ var DefaultRunSupervisor = class {
14557
14970
  registryStore: this.registryStore,
14558
14971
  reason,
14559
14972
  now: this.now,
14560
- notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
14973
+ notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
14974
+ canRestoreRun: this.canRestoreRun
14561
14975
  });
14562
14976
  }
14563
- async pause(_runId, _reason) {
14564
- throw new NotImplementedError("RunSupervisor.pause is N-3.B; not implemented in N-3.A");
14977
+ async pause(runId, reason) {
14978
+ await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
14979
+ }
14980
+ async resumePausedRun(input) {
14981
+ return this.withRunControlLock(input.runId, async () => {
14982
+ const handle = this.getHandle(input.runId);
14983
+ const record = await this.registryStore.load(input.runId);
14984
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
14985
+ throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
14986
+ }
14987
+ await persistRunTransition(this.registryStore, record, {
14988
+ ...record,
14989
+ status: "running",
14990
+ updatedAt: this.now(),
14991
+ pausedAt: void 0,
14992
+ pauseReason: void 0,
14993
+ errorIfAny: void 0,
14994
+ metadata: { ...record.metadata, executionId: input.executionId }
14995
+ });
14996
+ const controller = new AbortController();
14997
+ handle.replaceExecutionAbortController(controller, input.executionId);
14998
+ handle.attachTransportEventBus(input.eventBus);
14999
+ this.controllers.set(input.runId, controller);
15000
+ this.attachAwaitingUserWatcher(input.runId, input.eventBus);
15001
+ return handle;
15002
+ });
14565
15003
  }
14566
15004
  async claimResume(runId, interaction, eventBus, parentSignal) {
14567
15005
  return this.withRunControlLock(runId, async () => {
@@ -14596,7 +15034,7 @@ var DefaultRunSupervisor = class {
14596
15034
  throw new RunNotFoundError(runId);
14597
15035
  }
14598
15036
  const claimId = generateRunResumeClaimId();
14599
- await this.registryStore.save({
15037
+ await persistRunTransition(this.registryStore, record, {
14600
15038
  ...record,
14601
15039
  updatedAt: this.now(),
14602
15040
  metadata: {
@@ -14684,7 +15122,7 @@ var DefaultRunSupervisor = class {
14684
15122
  }
14685
15123
  const awaitingUserWithoutClaim = { ...awaitingUser };
14686
15124
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
14687
- await this.registryStore.save({
15125
+ const nextRecord = {
14688
15126
  ...record,
14689
15127
  status: "running",
14690
15128
  updatedAt: this.now(),
@@ -14694,6 +15132,10 @@ var DefaultRunSupervisor = class {
14694
15132
  metadata: {
14695
15133
  ...record.metadata ?? {},
14696
15134
  ...execution ? { executionId: execution.executionId } : {},
15135
+ ...execution?.inputEventIds ? { resumeInputs: {
15136
+ eventIds: [...execution.inputEventIds],
15137
+ checkpointRevision: pendingInteraction.checkpointRevision
15138
+ } } : {},
14697
15139
  awaitingUser: {
14698
15140
  ...awaitingUserWithoutClaim,
14699
15141
  interaction: {
@@ -14702,10 +15144,12 @@ var DefaultRunSupervisor = class {
14702
15144
  }
14703
15145
  }
14704
15146
  }
14705
- });
15147
+ };
15148
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
15149
+ else await persistRunTransition(this.registryStore, record, nextRecord);
14706
15150
  const executionController = new AbortController();
14707
15151
  forwardParentAbortSignal(executionController, parentSignal);
14708
- handle.replaceExecutionAbortController(executionController);
15152
+ handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
14709
15153
  this.controllers.set(runId, executionController);
14710
15154
  return handle;
14711
15155
  });
@@ -14723,7 +15167,7 @@ var DefaultRunSupervisor = class {
14723
15167
  }
14724
15168
  const awaitingUserWithoutClaim = { ...awaitingUser };
14725
15169
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
14726
- await this.registryStore.save({
15170
+ await persistRunTransition(this.registryStore, record, {
14727
15171
  ...record,
14728
15172
  updatedAt: this.now(),
14729
15173
  metadata: {
@@ -14868,13 +15312,13 @@ __export(system_reminder_exports, {
14868
15312
 
14869
15313
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
14870
15314
  function createDefaultGraphExecutor(options) {
14871
- const executor = new GraphExecutor(
15315
+ const executor2 = new GraphExecutor(
14872
15316
  options.checkpointer ?? new MemoryCheckpointer(),
14873
15317
  { maxSteps: options.maxSteps ?? 8 }
14874
15318
  );
14875
- executor.registerNode(new UserNode());
14876
- executor.registerNode(options.llmNode);
14877
- executor.registerNode(new ToolNode({
15319
+ executor2.registerNode(new UserNode());
15320
+ executor2.registerNode(options.llmNode);
15321
+ executor2.registerNode(new ToolNode({
14878
15322
  toolRuntime: options.toolRuntime,
14879
15323
  observationPreview: options.observationPreview,
14880
15324
  auditPort: options.auditPort,
@@ -14882,8 +15326,8 @@ function createDefaultGraphExecutor(options) {
14882
15326
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
14883
15327
  modelInputResolver: options.modelInputResolver
14884
15328
  }));
14885
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14886
- return executor;
15329
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
15330
+ return executor2;
14887
15331
  }
14888
15332
 
14889
15333
  // src/runtime-kernel/testkit/graphLoopHarness.ts
@@ -14908,7 +15352,7 @@ function createGraphLoopHarness(options) {
14908
15352
  return {
14909
15353
  async run() {
14910
15354
  const checkpointKey = options.runId ?? options.turnId;
14911
- const executor = createDefaultGraphExecutor({
15355
+ const executor2 = createDefaultGraphExecutor({
14912
15356
  llmNode: options.createLlmNode({
14913
15357
  llmCaller: options.llmCaller,
14914
15358
  toolRuntime: options.toolRuntime
@@ -14938,8 +15382,8 @@ function createGraphLoopHarness(options) {
14938
15382
  signal: options.signal ?? options.toolContext.abortSignal,
14939
15383
  executorLocal
14940
15384
  };
14941
- await executor.prime(checkpointKey, local, "user");
14942
- const result = await executor.runUntilYield(checkpointKey);
15385
+ await executor2.prime(checkpointKey, local, "user");
15386
+ const result = await executor2.runUntilYield(checkpointKey);
14943
15387
  return {
14944
15388
  checkpointNodeId: result.checkpoint.nodeId,
14945
15389
  stepCount: result.stepCount,
@@ -15351,7 +15795,7 @@ async function runAgent(agent, options) {
15351
15795
  contextBuilder: new QuickstartContextBuilder(agent),
15352
15796
  telemetryPort
15353
15797
  });
15354
- const executor = createDefaultGraphExecutor({
15798
+ const executor2 = createDefaultGraphExecutor({
15355
15799
  llmNode: new LlmNode({ reasoner }),
15356
15800
  toolRuntime,
15357
15801
  observationPreview: createNoopObservationPreview(),
@@ -15387,7 +15831,7 @@ async function runAgent(agent, options) {
15387
15831
  };
15388
15832
  await handle.markRunning({ currentNode: "user" });
15389
15833
  try {
15390
- await executor.prime(checkpointKey, {
15834
+ await executor2.prime(checkpointKey, {
15391
15835
  conversationId,
15392
15836
  turnId,
15393
15837
  request: {
@@ -15404,7 +15848,7 @@ async function runAgent(agent, options) {
15404
15848
  signal: handle.signal,
15405
15849
  runtimeEventSink: (event, source) => publisher.publish(event, source)
15406
15850
  });
15407
- const result = await executor.runUntilYield(checkpointKey);
15851
+ const result = await executor2.runUntilYield(checkpointKey);
15408
15852
  await Promise.all([callbackTail, persistenceTail]);
15409
15853
  await handle.markCompleted({
15410
15854
  currentNode: result.checkpoint.nodeId,