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