@linnlabs/linnkit 0.33.0 → 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 (40) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/cli.cjs +154 -28
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +154 -28
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +54 -0
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +54 -0
  9. package/dist/context-manager.js.map +1 -1
  10. package/dist/index.cjs +166 -39
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.js +166 -39
  13. package/dist/index.js.map +1 -1
  14. package/dist/quickstart.cjs +154 -28
  15. package/dist/quickstart.cjs.map +1 -1
  16. package/dist/quickstart.js +154 -28
  17. package/dist/quickstart.js.map +1 -1
  18. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.cts +6 -0
  19. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.ts +6 -0
  20. package/dist/runtime-kernel/graph-engine/index.d.cts +1 -0
  21. package/dist/runtime-kernel/graph-engine/index.d.ts +1 -0
  22. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +21 -4
  23. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +21 -4
  24. package/dist/runtime-kernel/run-supervisor/index.d.cts +1 -1
  25. package/dist/runtime-kernel/run-supervisor/index.d.ts +1 -1
  26. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +2 -1
  27. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +2 -1
  28. package/dist/runtime-kernel.cjs +163 -36
  29. package/dist/runtime-kernel.cjs.map +1 -1
  30. package/dist/runtime-kernel.d.cts +1 -0
  31. package/dist/runtime-kernel.d.ts +1 -0
  32. package/dist/runtime-kernel.js +163 -37
  33. package/dist/runtime-kernel.js.map +1 -1
  34. package/dist/testkit.cjs +163 -36
  35. package/dist/testkit.cjs.map +1 -1
  36. package/dist/testkit.js +163 -36
  37. package/dist/testkit.js.map +1 -1
  38. package/docs/integration/persistence.md +1 -0
  39. package/docs/integration/run-supervisor.md +3 -0
  40. package/package.json +2 -2
@@ -0,0 +1,6 @@
1
+ import { EngineState } from '../types.cjs';
2
+
3
+ /** 存储边界先验证数据形态,再验证 framework 字段;Host 不复制或断言 Graph 内部协议。 */
4
+ declare function parseEngineCheckpoint(value: unknown): EngineState;
5
+
6
+ export { parseEngineCheckpoint };
@@ -0,0 +1,6 @@
1
+ import { EngineState } from '../types.js';
2
+
3
+ /** 存储边界先验证数据形态,再验证 framework 字段;Host 不复制或断言 Graph 内部协议。 */
4
+ declare function parseEngineCheckpoint(value: unknown): EngineState;
5
+
6
+ export { parseEngineCheckpoint };
@@ -13,6 +13,7 @@ export { EffectivePromptBudget, ResolveEffectivePromptBudgetInput, resolveEffect
13
13
  export { PrimaryPromptCapacityAdmission, evaluatePrimaryPromptCapacity } from './functions/evaluatePrimaryPromptCapacity.cjs';
14
14
  export { PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, PrimaryPromptCapacityErrorMetadata } from './definitions/primaryPromptCapacityError.cjs';
15
15
  export { readCheckpointContextUsage } from './functions/engineStateSnapshot.cjs';
16
+ export { parseEngineCheckpoint } from './functions/parseEngineCheckpoint.cjs';
16
17
  export { isRuntimeFailureFact } from './functions/runtimeFailureFact.cjs';
17
18
  export { ENGINE_STATE_SCHEMA_VERSION, EngineState, ExecutorLlmInvocationKind, ExecutorLocalPatch, ExecutorLocalState, GraphNode, RuntimeEventCommitPort, RuntimeEventSink, RuntimeFailureFact, RuntimeFailureFactSink, ToolBatchCompletionMode } from './types.cjs';
18
19
  export { ExecutionCheckpointPort, RunPauseRequested, RunRecoveryBlockedError, ToolRecoveryDecision, ToolRecoveryPort, isRunPauseSignal } from './definitions/runContinuation.cjs';
@@ -13,6 +13,7 @@ export { EffectivePromptBudget, ResolveEffectivePromptBudgetInput, resolveEffect
13
13
  export { PrimaryPromptCapacityAdmission, evaluatePrimaryPromptCapacity } from './functions/evaluatePrimaryPromptCapacity.js';
14
14
  export { PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, PrimaryPromptCapacityErrorMetadata } from './definitions/primaryPromptCapacityError.js';
15
15
  export { readCheckpointContextUsage } from './functions/engineStateSnapshot.js';
16
+ export { parseEngineCheckpoint } from './functions/parseEngineCheckpoint.js';
16
17
  export { isRuntimeFailureFact } from './functions/runtimeFailureFact.js';
17
18
  export { ENGINE_STATE_SCHEMA_VERSION, EngineState, ExecutorLlmInvocationKind, ExecutorLocalPatch, ExecutorLocalState, GraphNode, RuntimeEventCommitPort, RuntimeEventSink, RuntimeFailureFact, RuntimeFailureFactSink, ToolBatchCompletionMode } from './types.js';
18
19
  export { ExecutionCheckpointPort, RunPauseRequested, RunRecoveryBlockedError, ToolRecoveryDecision, ToolRecoveryPort, isRunPauseSignal } from './definitions/runContinuation.js';
@@ -51,11 +51,16 @@ interface RunResumeClaim<TRequest extends RunRequestSnapshot = RunRequestSnapsho
51
51
  readonly runId: RunId;
52
52
  readonly handle: RunHandle<TRequest>;
53
53
  /** 同一逻辑 run 的新 execution 身份必须与 claim 激活原子写入。 */
54
- activate(execution?: {
55
- readonly executionId: ExecutionId;
56
- }): Promise<RunHandle<TRequest>>;
54
+ activate(execution?: RunResumeActivation): Promise<RunHandle<TRequest>>;
57
55
  release(): Promise<void>;
58
56
  }
57
+ interface RunResumeActivation {
58
+ readonly executionId: ExecutionId;
59
+ /** 持久响应引用仅供 Host 重启后接续已提交的原交互,不是新的用户输入。 */
60
+ readonly inputEventIds?: readonly string[];
61
+ /** 将 interaction 激活和响应事实放进同一事务;必须核对 previous。 */
62
+ readonly admissionCommit?: (previous: RunRecord, next: RunRecord) => Promise<void>;
63
+ }
59
64
  interface RunExecutionContext<TRequest extends RunRequestSnapshot = RunRequestSnapshot> {
60
65
  runId: RunId;
61
66
  parentRunId?: RunId;
@@ -79,6 +84,17 @@ interface RunRegistrationSpec<TRequest extends RunRequestSnapshot = RunRequestSn
79
84
  runId?: RunId;
80
85
  /** 同一 supervisor 内,活跃 run 不得共享同一个业务并发 key。 */
81
86
  concurrencyKey?: string;
87
+ /** 替代已收口的暂停运行;必须通过 admissionCommit 原子提交旧终态、新身份和 Host 输入。 */
88
+ replacesPausedRun?: {
89
+ runId: RunId;
90
+ expectedUpdatedAt: number;
91
+ expectedExecutionId: ExecutionId;
92
+ };
93
+ /** Host 必须在一个持久事务中写入 record 及其必要输入;不能在提交后再抛错误。 */
94
+ admissionCommit?: (record: RunRecord, replacement?: {
95
+ previous: RunRecord;
96
+ next: RunRecord;
97
+ }) => Promise<void>;
82
98
  parentRunId?: RunId;
83
99
  parentSignal?: AbortSignal;
84
100
  conversationId: string;
@@ -122,6 +138,7 @@ interface RunSupervisor<TRequest extends RunRequestSnapshot = RunRequestSnapshot
122
138
  resumePausedRun(input: {
123
139
  readonly runId: RunId;
124
140
  readonly expectedUpdatedAt: number;
141
+ readonly expectedExecutionId?: ExecutionId;
125
142
  readonly eventBus: EventBus;
126
143
  readonly executionId: ExecutionId;
127
144
  }): Promise<RunHandle<TRequest>>;
@@ -140,4 +157,4 @@ interface DefaultRunSupervisorOptions<TRequest extends RunRequestSnapshot = RunR
140
157
  canRestoreRun?: (record: RunRecord) => Promise<boolean>;
141
158
  }
142
159
 
143
- export type { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions };
160
+ export type { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeActivation, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions };
@@ -51,11 +51,16 @@ interface RunResumeClaim<TRequest extends RunRequestSnapshot = RunRequestSnapsho
51
51
  readonly runId: RunId;
52
52
  readonly handle: RunHandle<TRequest>;
53
53
  /** 同一逻辑 run 的新 execution 身份必须与 claim 激活原子写入。 */
54
- activate(execution?: {
55
- readonly executionId: ExecutionId;
56
- }): Promise<RunHandle<TRequest>>;
54
+ activate(execution?: RunResumeActivation): Promise<RunHandle<TRequest>>;
57
55
  release(): Promise<void>;
58
56
  }
57
+ interface RunResumeActivation {
58
+ readonly executionId: ExecutionId;
59
+ /** 持久响应引用仅供 Host 重启后接续已提交的原交互,不是新的用户输入。 */
60
+ readonly inputEventIds?: readonly string[];
61
+ /** 将 interaction 激活和响应事实放进同一事务;必须核对 previous。 */
62
+ readonly admissionCommit?: (previous: RunRecord, next: RunRecord) => Promise<void>;
63
+ }
59
64
  interface RunExecutionContext<TRequest extends RunRequestSnapshot = RunRequestSnapshot> {
60
65
  runId: RunId;
61
66
  parentRunId?: RunId;
@@ -79,6 +84,17 @@ interface RunRegistrationSpec<TRequest extends RunRequestSnapshot = RunRequestSn
79
84
  runId?: RunId;
80
85
  /** 同一 supervisor 内,活跃 run 不得共享同一个业务并发 key。 */
81
86
  concurrencyKey?: string;
87
+ /** 替代已收口的暂停运行;必须通过 admissionCommit 原子提交旧终态、新身份和 Host 输入。 */
88
+ replacesPausedRun?: {
89
+ runId: RunId;
90
+ expectedUpdatedAt: number;
91
+ expectedExecutionId: ExecutionId;
92
+ };
93
+ /** Host 必须在一个持久事务中写入 record 及其必要输入;不能在提交后再抛错误。 */
94
+ admissionCommit?: (record: RunRecord, replacement?: {
95
+ previous: RunRecord;
96
+ next: RunRecord;
97
+ }) => Promise<void>;
82
98
  parentRunId?: RunId;
83
99
  parentSignal?: AbortSignal;
84
100
  conversationId: string;
@@ -122,6 +138,7 @@ interface RunSupervisor<TRequest extends RunRequestSnapshot = RunRequestSnapshot
122
138
  resumePausedRun(input: {
123
139
  readonly runId: RunId;
124
140
  readonly expectedUpdatedAt: number;
141
+ readonly expectedExecutionId?: ExecutionId;
125
142
  readonly eventBus: EventBus;
126
143
  readonly executionId: ExecutionId;
127
144
  }): Promise<RunHandle<TRequest>>;
@@ -140,4 +157,4 @@ interface DefaultRunSupervisorOptions<TRequest extends RunRequestSnapshot = RunR
140
157
  canRestoreRun?: (record: RunRecord) => Promise<boolean>;
141
158
  }
142
159
 
143
- export type { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions };
160
+ export type { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeActivation, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions };
@@ -3,4 +3,4 @@ export { CancelOpts, DefaultRunHandle, DefaultRunHandleOptions, RunAwaitingUserP
3
3
  export { DefaultRunSupervisor } from './runSupervisor.cjs';
4
4
  export { NotImplementedError, RunAlreadyRegisteredError, RunConcurrencyKeyOccupiedError, RunConcurrencyLimitExceededError, RunNotFoundError } from './runErrors.cjs';
5
5
  export { ListRunsFilter, RunRecord, RunRegistryStore, RunStatus } from './runRegistryStorePort.cjs';
6
- export { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions } from './definitions/runSupervisorContracts.cjs';
6
+ export { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeActivation, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions } from './definitions/runSupervisorContracts.cjs';
@@ -3,4 +3,4 @@ export { CancelOpts, DefaultRunHandle, DefaultRunHandleOptions, RunAwaitingUserP
3
3
  export { DefaultRunSupervisor } from './runSupervisor.js';
4
4
  export { NotImplementedError, RunAlreadyRegisteredError, RunConcurrencyKeyOccupiedError, RunConcurrencyLimitExceededError, RunNotFoundError } from './runErrors.js';
5
5
  export { ListRunsFilter, RunRecord, RunRegistryStore, RunStatus } from './runRegistryStorePort.js';
6
- export { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions } from './definitions/runSupervisorContracts.js';
6
+ export { DefaultRunSupervisorOptions, FindActiveByConversationOptions, FindRunsByConversationOptions, RunExecutionContext, RunExecutorPort, RunOutcome, RunRegistrationSpec, RunResumeActivation, RunResumeClaim, RunResumeInteraction, RunSnapshot, RunSupervisor, RunTerminalError, RunTerminalEvent, RunTerminalStatus, RunWaitForTerminalOptions } from './definitions/runSupervisorContracts.js';
@@ -2,7 +2,7 @@ import { EventBus } from '../execution/event-bus.cjs';
2
2
  import { RunId } from '../../contracts/identity/definitions.cjs';
3
3
  import { RuntimeEvent } from '../../contracts/events.cjs';
4
4
  import { RunSupervisor, DefaultRunSupervisorOptions, RunRegistrationSpec, RunWaitForTerminalOptions, RunOutcome, FindActiveByConversationOptions, RunSnapshot, FindRunsByConversationOptions, RunResumeInteraction, RunResumeClaim } from './definitions/runSupervisorContracts.cjs';
5
- export { RunExecutionContext, RunExecutorPort, RunTerminalError, RunTerminalEvent, RunTerminalStatus } from './definitions/runSupervisorContracts.cjs';
5
+ export { RunExecutionContext, RunExecutorPort, RunResumeActivation, RunTerminalError, RunTerminalEvent, RunTerminalStatus } from './definitions/runSupervisorContracts.cjs';
6
6
  import { RunRequestSnapshot, RunHandle, RunObserveFilter, CancelOpts, RunAwaitingUserPatch, RunMeta } from './runHandle.cjs';
7
7
  import { ListRunsFilter } from './runRegistryStorePort.cjs';
8
8
 
@@ -25,6 +25,7 @@ declare class DefaultRunSupervisor<TRequest extends RunRequestSnapshot = RunRequ
25
25
  private readonly canRestoreRun?;
26
26
  constructor(options: DefaultRunSupervisorOptions<TRequest>);
27
27
  registerRun(spec: RunRegistrationSpec<TRequest>): Promise<RunHandle<TRequest>>;
28
+ private registerPausedReplacement;
28
29
  restoreRun(spec: RunRegistrationSpec<TRequest> & {
29
30
  runId: RunId;
30
31
  }): Promise<RunHandle<TRequest>>;
@@ -2,7 +2,7 @@ import { EventBus } from '../execution/event-bus.js';
2
2
  import { RunId } from '../../contracts/identity/definitions.js';
3
3
  import { RuntimeEvent } from '../../contracts/events.js';
4
4
  import { RunSupervisor, DefaultRunSupervisorOptions, RunRegistrationSpec, RunWaitForTerminalOptions, RunOutcome, FindActiveByConversationOptions, RunSnapshot, FindRunsByConversationOptions, RunResumeInteraction, RunResumeClaim } from './definitions/runSupervisorContracts.js';
5
- export { RunExecutionContext, RunExecutorPort, RunTerminalError, RunTerminalEvent, RunTerminalStatus } from './definitions/runSupervisorContracts.js';
5
+ export { RunExecutionContext, RunExecutorPort, RunResumeActivation, RunTerminalError, RunTerminalEvent, RunTerminalStatus } from './definitions/runSupervisorContracts.js';
6
6
  import { RunRequestSnapshot, RunHandle, RunObserveFilter, CancelOpts, RunAwaitingUserPatch, RunMeta } from './runHandle.js';
7
7
  import { ListRunsFilter } from './runRegistryStorePort.js';
8
8
 
@@ -25,6 +25,7 @@ declare class DefaultRunSupervisor<TRequest extends RunRequestSnapshot = RunRequ
25
25
  private readonly canRestoreRun?;
26
26
  constructor(options: DefaultRunSupervisorOptions<TRequest>);
27
27
  registerRun(spec: RunRegistrationSpec<TRequest>): Promise<RunHandle<TRequest>>;
28
+ private registerPausedReplacement;
28
29
  restoreRun(spec: RunRegistrationSpec<TRequest> & {
29
30
  runId: RunId;
30
31
  }): Promise<RunHandle<TRequest>>;
@@ -36,6 +36,7 @@ __export(graph_engine_exports, {
36
36
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
37
37
  isRunPauseSignal: () => isRunPauseSignal,
38
38
  isRuntimeFailureFact: () => isRuntimeFailureFact,
39
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
39
40
  readCheckpointContextUsage: () => readCheckpointContextUsage,
40
41
  requireEventStoreId: () => requireEventStoreId,
41
42
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -3157,23 +3158,23 @@ var GraphExecutor = class {
3157
3158
  };
3158
3159
  }
3159
3160
  async saveCheckpoint(checkpointKey, state) {
3160
- const checkpoint = this.sanitize({
3161
+ const checkpoint2 = this.sanitize({
3161
3162
  ...state,
3162
3163
  revision: (state.revision ?? 0) + 1
3163
3164
  });
3164
- await this.commitCheckpoint(checkpointKey, checkpoint);
3165
- return checkpoint;
3165
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3166
+ return checkpoint2;
3166
3167
  }
3167
- async commitCheckpoint(checkpointKey, checkpoint) {
3168
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3168
3169
  if (this.executionCheckpointPort) {
3169
- await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3170
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3170
3171
  } else {
3171
- await this.checkpointer.save(checkpointKey, checkpoint);
3172
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3172
3173
  }
3173
3174
  }
3174
3175
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3175
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3176
- return { events, checkpoint, stepCount };
3176
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3177
+ return { events, checkpoint: checkpoint2, stepCount };
3177
3178
  }
3178
3179
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3179
3180
  let state = initialState;
@@ -9300,16 +9301,16 @@ function requireEventStoreId(eventStoreId) {
9300
9301
  }
9301
9302
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9302
9303
  let lastTimestamp = 0;
9303
- let counter = 0;
9304
+ let counter2 = 0;
9304
9305
  return () => {
9305
9306
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9306
9307
  if (timestamp === lastTimestamp) {
9307
- counter += 1;
9308
+ counter2 += 1;
9308
9309
  } else {
9309
9310
  lastTimestamp = timestamp;
9310
- counter = 0;
9311
+ counter2 = 0;
9311
9312
  }
9312
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9313
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9313
9314
  };
9314
9315
  }
9315
9316
 
@@ -9721,6 +9722,76 @@ function assertNonNegativeSafeInteger(value, field) {
9721
9722
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9722
9723
  }
9723
9724
  }
9725
+ var counter = zod.z.number().int().nonnegative();
9726
+ var executor = zod.z.object({
9727
+ stepCount: counter,
9728
+ phase: zod.z.string().optional(),
9729
+ maxSteps: counter.optional(),
9730
+ remainingSteps: zod.z.number().int().optional(),
9731
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
9732
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
9733
+ lastStepsHintThreshold: counter.optional(),
9734
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9735
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9736
+ runLockedModelId: zod.z.string().optional(),
9737
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
9738
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
9739
+ llmInvocationCount: counter.optional(),
9740
+ lockRequestedModelId: zod.z.boolean().optional(),
9741
+ contextCompaction: zod.z.object({
9742
+ attemptCount: counter,
9743
+ committedCount: counter,
9744
+ lastCommittedFingerprint: zod.z.string().optional()
9745
+ }).strict().optional()
9746
+ }).strict();
9747
+ var checkpoint = zod.z.object({
9748
+ nodeId: zod.z.string().min(1),
9749
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9750
+ revision: counter.optional(),
9751
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9752
+ local: zod.z.object({
9753
+ runId: RunIdSchema.optional(),
9754
+ parentRunId: RunIdSchema.optional(),
9755
+ conversationId: zod.z.string().optional(),
9756
+ turnId: zod.z.string().optional(),
9757
+ request: SerializableJsonRecord.optional(),
9758
+ history: zod.z.array(RuntimeEvent).optional(),
9759
+ newEvents: zod.z.array(RuntimeEvent).optional(),
9760
+ executorLocal: executor.optional(),
9761
+ pendingToolCalls: zod.z.array(zod.z.object({
9762
+ id: ToolCallIdSchema,
9763
+ type: zod.z.literal("function"),
9764
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
9765
+ }).strict()).optional(),
9766
+ executingToolCallId: ToolCallIdSchema.optional(),
9767
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9768
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9769
+ lastToolResult: SerializableJsonRecord.optional(),
9770
+ finalAnswer: zod.z.string().optional(),
9771
+ answerId: zod.z.string().optional(),
9772
+ chunkSeq: counter.optional(),
9773
+ contextUsage: ContextUsageSnapshot.optional()
9774
+ }).passthrough().optional()
9775
+ }).strict();
9776
+ function parseEngineCheckpoint(value) {
9777
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9778
+ for (const key of [
9779
+ "memory",
9780
+ "signal",
9781
+ "toolContext",
9782
+ "runtimeEventSink",
9783
+ "runtimeEventCommitPort",
9784
+ "runtimeFailureFactSink",
9785
+ "summarizationCallbacks",
9786
+ "commitExecutionBoundary",
9787
+ "toolRecoveryPort"
9788
+ ]) {
9789
+ if (result.local && Object.hasOwn(result.local, key)) {
9790
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9791
+ }
9792
+ }
9793
+ return result;
9794
+ }
9724
9795
 
9725
9796
  // src/runtime-kernel/tools/index.ts
9726
9797
  var tools_exports = {};
@@ -10182,14 +10253,14 @@ var EventBusEventPersistence = class {
10182
10253
  checkpointWritesActive;
10183
10254
  checkpointEvents = [];
10184
10255
  /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10185
- async commitCheckpoint(checkpointKey, checkpoint) {
10256
+ async commitCheckpoint(checkpointKey, checkpoint2) {
10186
10257
  const writer = this.options.checkpointWriter;
10187
10258
  if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10188
10259
  const events = this.checkpointEvents;
10189
10260
  this.checkpointEvents = [];
10190
10261
  await this.enqueueWrite(() => writer({
10191
10262
  checkpointKey,
10192
- checkpoint,
10263
+ checkpoint: checkpoint2,
10193
10264
  events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10194
10265
  }));
10195
10266
  }
@@ -11882,15 +11953,15 @@ function hasSeedHistoryPrefix(history, seedHistory) {
11882
11953
  }
11883
11954
  return true;
11884
11955
  }
11885
- function readCheckpointHistory(checkpoint) {
11886
- if (!checkpoint?.local) return [];
11887
- const history = checkpoint.local.history;
11956
+ function readCheckpointHistory(checkpoint2) {
11957
+ if (!checkpoint2?.local) return [];
11958
+ const history = checkpoint2.local.history;
11888
11959
  if (!Array.isArray(history)) return [];
11889
11960
  return parseRuntimeEvents(history);
11890
11961
  }
11891
11962
  async function recoverChildRunEventsFromCheckpoint(params) {
11892
- const checkpoint = await params.checkpointer.load(params.checkpointKey);
11893
- const history = readCheckpointHistory(checkpoint);
11963
+ const checkpoint2 = await params.checkpointer.load(params.checkpointKey);
11964
+ const history = readCheckpointHistory(checkpoint2);
11894
11965
  if (history.length === 0) {
11895
11966
  return [];
11896
11967
  }
@@ -12186,9 +12257,9 @@ var ChildRunInvoker = class {
12186
12257
  async continueChild(config, runId, conversationId) {
12187
12258
  const persistence = config.persistence;
12188
12259
  if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12189
- const checkpoint = await persistence.checkpointer.load(runId);
12190
- if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12191
- const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
12260
+ const checkpoint2 = await persistence.checkpointer.load(runId);
12261
+ if (!checkpoint2 || checkpoint2.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12262
+ const local = readGraphAgentLocal({ ...checkpoint2.local, runtimeEventSink: config.runtimeEventSink });
12192
12263
  const request = local.request;
12193
12264
  if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12194
12265
  const context = createChildRunToolContext({
@@ -13465,7 +13536,15 @@ function createRunConcurrencyKeyRegistry() {
13465
13536
  runIdByKey.delete(concurrencyKey);
13466
13537
  }
13467
13538
  }
13468
- return { acquire, release };
13539
+ function transfer(previous, next, concurrencyKey) {
13540
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
13541
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
13542
+ }
13543
+ keyByRunId.delete(previous);
13544
+ keyByRunId.set(next, concurrencyKey);
13545
+ runIdByKey.set(concurrencyKey, next);
13546
+ }
13547
+ return { acquire, release, transfer };
13469
13548
  }
13470
13549
 
13471
13550
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -13714,6 +13793,9 @@ var DefaultRunSupervisor = class {
13714
13793
  });
13715
13794
  }
13716
13795
  async registerRun(spec) {
13796
+ if (spec.replacesPausedRun) {
13797
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
13798
+ }
13717
13799
  const runId = spec.runId ?? this.runIdFactory();
13718
13800
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
13719
13801
  throw new RunAlreadyRegisteredError(runId);
@@ -13724,13 +13806,51 @@ var DefaultRunSupervisor = class {
13724
13806
  forwardParentAbortSignal(controller, spec.parentSignal);
13725
13807
  const record = createInitialRunRecord({ runId, spec, startedAt });
13726
13808
  try {
13727
- await this.registryStore.save(record);
13809
+ if (spec.admissionCommit) await spec.admissionCommit(record);
13810
+ else await this.registryStore.save(record);
13728
13811
  } catch (error) {
13729
13812
  this.releaseRunAdmission(runId);
13730
13813
  throw error;
13731
13814
  }
13732
13815
  return this.attachRun(record, spec, controller);
13733
13816
  }
13817
+ async registerPausedReplacement(spec) {
13818
+ const target = spec.replacesPausedRun;
13819
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
13820
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
13821
+ }
13822
+ this.getHandle(target.runId);
13823
+ const previous = await this.registryStore.load(target.runId);
13824
+ 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) {
13825
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
13826
+ }
13827
+ const runId = spec.runId ?? this.runIdFactory();
13828
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
13829
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
13830
+ this.runSlotLimiter.release(previous.runId);
13831
+ this.runSlotLimiter.acquire(runId);
13832
+ const now = this.now();
13833
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
13834
+ const next = {
13835
+ ...previous,
13836
+ status: "cancelled",
13837
+ updatedAt: now,
13838
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
13839
+ };
13840
+ try {
13841
+ await spec.admissionCommit(record, { previous, next });
13842
+ } catch (error) {
13843
+ this.runSlotLimiter.release(runId);
13844
+ this.runSlotLimiter.acquire(previous.runId);
13845
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
13846
+ throw error;
13847
+ }
13848
+ this.cleanupRunResources(previous.runId);
13849
+ this.notifyTerminalWaiters(previous.runId);
13850
+ const controller = new AbortController();
13851
+ forwardParentAbortSignal(controller, spec.parentSignal);
13852
+ return this.attachRun(record, spec, controller);
13853
+ }
13734
13854
  async restoreRun(spec) {
13735
13855
  if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13736
13856
  return this.withRunControlLock(spec.runId, async () => {
@@ -13854,7 +13974,7 @@ var DefaultRunSupervisor = class {
13854
13974
  return this.withRunControlLock(input.runId, async () => {
13855
13975
  const handle = this.getHandle(input.runId);
13856
13976
  const record = await this.registryStore.load(input.runId);
13857
- if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
13977
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
13858
13978
  throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
13859
13979
  }
13860
13980
  await persistRunTransition(this.registryStore, record, {
@@ -13995,7 +14115,7 @@ var DefaultRunSupervisor = class {
13995
14115
  }
13996
14116
  const awaitingUserWithoutClaim = { ...awaitingUser };
13997
14117
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
13998
- await persistRunTransition(this.registryStore, record, {
14118
+ const nextRecord = {
13999
14119
  ...record,
14000
14120
  status: "running",
14001
14121
  updatedAt: this.now(),
@@ -14005,6 +14125,10 @@ var DefaultRunSupervisor = class {
14005
14125
  metadata: {
14006
14126
  ...record.metadata ?? {},
14007
14127
  ...execution ? { executionId: execution.executionId } : {},
14128
+ ...execution?.inputEventIds ? { resumeInputs: {
14129
+ eventIds: [...execution.inputEventIds],
14130
+ checkpointRevision: pendingInteraction.checkpointRevision
14131
+ } } : {},
14008
14132
  awaitingUser: {
14009
14133
  ...awaitingUserWithoutClaim,
14010
14134
  interaction: {
@@ -14013,7 +14137,9 @@ var DefaultRunSupervisor = class {
14013
14137
  }
14014
14138
  }
14015
14139
  }
14016
- });
14140
+ };
14141
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
14142
+ else await persistRunTransition(this.registryStore, record, nextRecord);
14017
14143
  const executionController = new AbortController();
14018
14144
  forwardParentAbortSignal(executionController, parentSignal);
14019
14145
  handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
@@ -14179,13 +14305,13 @@ __export(system_reminder_exports, {
14179
14305
 
14180
14306
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
14181
14307
  function createDefaultGraphExecutor(options) {
14182
- const executor = new GraphExecutor(
14308
+ const executor2 = new GraphExecutor(
14183
14309
  options.checkpointer ?? new MemoryCheckpointer(),
14184
14310
  { maxSteps: options.maxSteps ?? 8 }
14185
14311
  );
14186
- executor.registerNode(new UserNode());
14187
- executor.registerNode(options.llmNode);
14188
- executor.registerNode(new ToolNode({
14312
+ executor2.registerNode(new UserNode());
14313
+ executor2.registerNode(options.llmNode);
14314
+ executor2.registerNode(new ToolNode({
14189
14315
  toolRuntime: options.toolRuntime,
14190
14316
  observationPreview: options.observationPreview,
14191
14317
  auditPort: options.auditPort,
@@ -14193,8 +14319,8 @@ function createDefaultGraphExecutor(options) {
14193
14319
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
14194
14320
  modelInputResolver: options.modelInputResolver
14195
14321
  }));
14196
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14197
- return executor;
14322
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14323
+ return executor2;
14198
14324
  }
14199
14325
 
14200
14326
  // src/runtime-kernel/testkit/graphLoopHarness.ts
@@ -14219,7 +14345,7 @@ function createGraphLoopHarness(options) {
14219
14345
  return {
14220
14346
  async run() {
14221
14347
  const checkpointKey = options.runId ?? options.turnId;
14222
- const executor = createDefaultGraphExecutor({
14348
+ const executor2 = createDefaultGraphExecutor({
14223
14349
  llmNode: options.createLlmNode({
14224
14350
  llmCaller: options.llmCaller,
14225
14351
  toolRuntime: options.toolRuntime
@@ -14249,8 +14375,8 @@ function createGraphLoopHarness(options) {
14249
14375
  signal: options.signal ?? options.toolContext.abortSignal,
14250
14376
  executorLocal
14251
14377
  };
14252
- await executor.prime(checkpointKey, local, "user");
14253
- const result = await executor.runUntilYield(checkpointKey);
14378
+ await executor2.prime(checkpointKey, local, "user");
14379
+ const result = await executor2.runUntilYield(checkpointKey);
14254
14380
  return {
14255
14381
  checkpointNodeId: result.checkpoint.nodeId,
14256
14382
  stepCount: result.stepCount,
@@ -14360,6 +14486,7 @@ exports.llm = llm_exports;
14360
14486
  exports.maxStepsForceFinalAnswerTemplate = maxStepsForceFinalAnswerTemplate;
14361
14487
  exports.noopAudit = noopAudit;
14362
14488
  exports.normalizeToolArgs = normalizeToolArgs;
14489
+ exports.parseEngineCheckpoint = parseEngineCheckpoint;
14363
14490
  exports.parseToolModelInputDeclaration = parseToolModelInputDeclaration;
14364
14491
  exports.periodicProgressReflectionTemplate = periodicProgressReflectionTemplate;
14365
14492
  exports.phaseEqualsTrigger = phaseEqualsTrigger;