@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
package/CHANGELOG.md CHANGED
@@ -14,6 +14,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
14
14
 
15
15
  ## [Unreleased]
16
16
 
17
+ ## [0.34.0] - 2026-09-11
18
+
19
+ ### Added
20
+
21
+ - Atomic Host admission hooks for initial requests, replacement of settled paused runs,
22
+ and human-interaction responses. Failed replacement leaves the original run resumable.
23
+ - Paused activation can require the previous execution identity as well as the timestamp,
24
+ rejecting stale commands even when multiple transitions occur within one millisecond.
25
+ - Public `graph.parseEngineCheckpoint` validates stored execution state without Host casts
26
+ or copied framework schemas, including budget, event and tool-call fields.
27
+
28
+ ### Clarified
29
+
30
+ - Graph result `stepCount` is the current execution's increment; durable cumulative steps
31
+ remain in the checkpoint. A yielded checkpoint continues with zero new execution steps.
32
+
17
33
  ## [0.33.0] - 2026-09-11
18
34
 
19
35
  ### Added
package/dist/cli.cjs CHANGED
@@ -1905,6 +1905,7 @@ __export(graph_engine_exports, {
1905
1905
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
1906
1906
  isRunPauseSignal: () => isRunPauseSignal,
1907
1907
  isRuntimeFailureFact: () => isRuntimeFailureFact,
1908
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
1908
1909
  readCheckpointContextUsage: () => readCheckpointContextUsage,
1909
1910
  requireEventStoreId: () => requireEventStoreId,
1910
1911
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -3253,23 +3254,23 @@ var GraphExecutor = class {
3253
3254
  };
3254
3255
  }
3255
3256
  async saveCheckpoint(checkpointKey, state) {
3256
- const checkpoint = this.sanitize({
3257
+ const checkpoint2 = this.sanitize({
3257
3258
  ...state,
3258
3259
  revision: (state.revision ?? 0) + 1
3259
3260
  });
3260
- await this.commitCheckpoint(checkpointKey, checkpoint);
3261
- return checkpoint;
3261
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3262
+ return checkpoint2;
3262
3263
  }
3263
- async commitCheckpoint(checkpointKey, checkpoint) {
3264
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3264
3265
  if (this.executionCheckpointPort) {
3265
- await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3266
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3266
3267
  } else {
3267
- await this.checkpointer.save(checkpointKey, checkpoint);
3268
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3268
3269
  }
3269
3270
  }
3270
3271
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3271
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3272
- return { events, checkpoint, stepCount };
3272
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3273
+ return { events, checkpoint: checkpoint2, stepCount };
3273
3274
  }
3274
3275
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3275
3276
  let state = initialState;
@@ -9117,16 +9118,16 @@ function requireEventStoreId(eventStoreId) {
9117
9118
  }
9118
9119
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9119
9120
  let lastTimestamp = 0;
9120
- let counter = 0;
9121
+ let counter2 = 0;
9121
9122
  return () => {
9122
9123
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9123
9124
  if (timestamp === lastTimestamp) {
9124
- counter += 1;
9125
+ counter2 += 1;
9125
9126
  } else {
9126
9127
  lastTimestamp = timestamp;
9127
- counter = 0;
9128
+ counter2 = 0;
9128
9129
  }
9129
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9130
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9130
9131
  };
9131
9132
  }
9132
9133
 
@@ -9538,6 +9539,76 @@ function assertNonNegativeSafeInteger(value, field) {
9538
9539
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9539
9540
  }
9540
9541
  }
9542
+ var counter = zod.z.number().int().nonnegative();
9543
+ var executor = zod.z.object({
9544
+ stepCount: counter,
9545
+ phase: zod.z.string().optional(),
9546
+ maxSteps: counter.optional(),
9547
+ remainingSteps: zod.z.number().int().optional(),
9548
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
9549
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
9550
+ lastStepsHintThreshold: counter.optional(),
9551
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9552
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9553
+ runLockedModelId: zod.z.string().optional(),
9554
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
9555
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
9556
+ llmInvocationCount: counter.optional(),
9557
+ lockRequestedModelId: zod.z.boolean().optional(),
9558
+ contextCompaction: zod.z.object({
9559
+ attemptCount: counter,
9560
+ committedCount: counter,
9561
+ lastCommittedFingerprint: zod.z.string().optional()
9562
+ }).strict().optional()
9563
+ }).strict();
9564
+ var checkpoint = zod.z.object({
9565
+ nodeId: zod.z.string().min(1),
9566
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9567
+ revision: counter.optional(),
9568
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9569
+ local: zod.z.object({
9570
+ runId: RunIdSchema.optional(),
9571
+ parentRunId: RunIdSchema.optional(),
9572
+ conversationId: zod.z.string().optional(),
9573
+ turnId: zod.z.string().optional(),
9574
+ request: SerializableJsonRecord.optional(),
9575
+ history: zod.z.array(RuntimeEvent).optional(),
9576
+ newEvents: zod.z.array(RuntimeEvent).optional(),
9577
+ executorLocal: executor.optional(),
9578
+ pendingToolCalls: zod.z.array(zod.z.object({
9579
+ id: ToolCallIdSchema,
9580
+ type: zod.z.literal("function"),
9581
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
9582
+ }).strict()).optional(),
9583
+ executingToolCallId: ToolCallIdSchema.optional(),
9584
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9585
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9586
+ lastToolResult: SerializableJsonRecord.optional(),
9587
+ finalAnswer: zod.z.string().optional(),
9588
+ answerId: zod.z.string().optional(),
9589
+ chunkSeq: counter.optional(),
9590
+ contextUsage: ContextUsageSnapshot.optional()
9591
+ }).passthrough().optional()
9592
+ }).strict();
9593
+ function parseEngineCheckpoint(value) {
9594
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9595
+ for (const key of [
9596
+ "memory",
9597
+ "signal",
9598
+ "toolContext",
9599
+ "runtimeEventSink",
9600
+ "runtimeEventCommitPort",
9601
+ "runtimeFailureFactSink",
9602
+ "summarizationCallbacks",
9603
+ "commitExecutionBoundary",
9604
+ "toolRecoveryPort"
9605
+ ]) {
9606
+ if (result.local && Object.hasOwn(result.local, key)) {
9607
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9608
+ }
9609
+ }
9610
+ return result;
9611
+ }
9541
9612
 
9542
9613
  // src/runtime-kernel/execution/index.ts
9543
9614
  var execution_exports = {};
@@ -9788,14 +9859,14 @@ var EventBusEventPersistence = class {
9788
9859
  checkpointWritesActive;
9789
9860
  checkpointEvents = [];
9790
9861
  /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9791
- async commitCheckpoint(checkpointKey, checkpoint) {
9862
+ async commitCheckpoint(checkpointKey, checkpoint2) {
9792
9863
  const writer = this.options.checkpointWriter;
9793
9864
  if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9794
9865
  const events = this.checkpointEvents;
9795
9866
  this.checkpointEvents = [];
9796
9867
  await this.enqueueWrite(() => writer({
9797
9868
  checkpointKey,
9798
- checkpoint,
9869
+ checkpoint: checkpoint2,
9799
9870
  events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9800
9871
  }));
9801
9872
  }
@@ -12108,7 +12179,15 @@ function createRunConcurrencyKeyRegistry() {
12108
12179
  runIdByKey.delete(concurrencyKey);
12109
12180
  }
12110
12181
  }
12111
- return { acquire, release };
12182
+ function transfer(previous, next, concurrencyKey) {
12183
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
12184
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
12185
+ }
12186
+ keyByRunId.delete(previous);
12187
+ keyByRunId.set(next, concurrencyKey);
12188
+ runIdByKey.set(concurrencyKey, next);
12189
+ }
12190
+ return { acquire, release, transfer };
12112
12191
  }
12113
12192
 
12114
12193
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -12357,6 +12436,9 @@ var DefaultRunSupervisor = class {
12357
12436
  });
12358
12437
  }
12359
12438
  async registerRun(spec) {
12439
+ if (spec.replacesPausedRun) {
12440
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
12441
+ }
12360
12442
  const runId = spec.runId ?? this.runIdFactory();
12361
12443
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
12362
12444
  throw new RunAlreadyRegisteredError(runId);
@@ -12367,13 +12449,51 @@ var DefaultRunSupervisor = class {
12367
12449
  forwardParentAbortSignal(controller, spec.parentSignal);
12368
12450
  const record = createInitialRunRecord({ runId, spec, startedAt });
12369
12451
  try {
12370
- await this.registryStore.save(record);
12452
+ if (spec.admissionCommit) await spec.admissionCommit(record);
12453
+ else await this.registryStore.save(record);
12371
12454
  } catch (error) {
12372
12455
  this.releaseRunAdmission(runId);
12373
12456
  throw error;
12374
12457
  }
12375
12458
  return this.attachRun(record, spec, controller);
12376
12459
  }
12460
+ async registerPausedReplacement(spec) {
12461
+ const target = spec.replacesPausedRun;
12462
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
12463
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
12464
+ }
12465
+ this.getHandle(target.runId);
12466
+ const previous = await this.registryStore.load(target.runId);
12467
+ 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) {
12468
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
12469
+ }
12470
+ const runId = spec.runId ?? this.runIdFactory();
12471
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
12472
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
12473
+ this.runSlotLimiter.release(previous.runId);
12474
+ this.runSlotLimiter.acquire(runId);
12475
+ const now = this.now();
12476
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
12477
+ const next = {
12478
+ ...previous,
12479
+ status: "cancelled",
12480
+ updatedAt: now,
12481
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
12482
+ };
12483
+ try {
12484
+ await spec.admissionCommit(record, { previous, next });
12485
+ } catch (error) {
12486
+ this.runSlotLimiter.release(runId);
12487
+ this.runSlotLimiter.acquire(previous.runId);
12488
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
12489
+ throw error;
12490
+ }
12491
+ this.cleanupRunResources(previous.runId);
12492
+ this.notifyTerminalWaiters(previous.runId);
12493
+ const controller = new AbortController();
12494
+ forwardParentAbortSignal(controller, spec.parentSignal);
12495
+ return this.attachRun(record, spec, controller);
12496
+ }
12377
12497
  async restoreRun(spec) {
12378
12498
  if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12379
12499
  return this.withRunControlLock(spec.runId, async () => {
@@ -12497,7 +12617,7 @@ var DefaultRunSupervisor = class {
12497
12617
  return this.withRunControlLock(input.runId, async () => {
12498
12618
  const handle = this.getHandle(input.runId);
12499
12619
  const record = await this.registryStore.load(input.runId);
12500
- if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
12620
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
12501
12621
  throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12502
12622
  }
12503
12623
  await persistRunTransition(this.registryStore, record, {
@@ -12638,7 +12758,7 @@ var DefaultRunSupervisor = class {
12638
12758
  }
12639
12759
  const awaitingUserWithoutClaim = { ...awaitingUser };
12640
12760
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12641
- await persistRunTransition(this.registryStore, record, {
12761
+ const nextRecord = {
12642
12762
  ...record,
12643
12763
  status: "running",
12644
12764
  updatedAt: this.now(),
@@ -12648,6 +12768,10 @@ var DefaultRunSupervisor = class {
12648
12768
  metadata: {
12649
12769
  ...record.metadata ?? {},
12650
12770
  ...execution ? { executionId: execution.executionId } : {},
12771
+ ...execution?.inputEventIds ? { resumeInputs: {
12772
+ eventIds: [...execution.inputEventIds],
12773
+ checkpointRevision: pendingInteraction.checkpointRevision
12774
+ } } : {},
12651
12775
  awaitingUser: {
12652
12776
  ...awaitingUserWithoutClaim,
12653
12777
  interaction: {
@@ -12656,7 +12780,9 @@ var DefaultRunSupervisor = class {
12656
12780
  }
12657
12781
  }
12658
12782
  }
12659
- });
12783
+ };
12784
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
12785
+ else await persistRunTransition(this.registryStore, record, nextRecord);
12660
12786
  const executionController = new AbortController();
12661
12787
  forwardParentAbortSignal(executionController, parentSignal);
12662
12788
  handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
@@ -12727,13 +12853,13 @@ createConsoleAudit();
12727
12853
 
12728
12854
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
12729
12855
  function createDefaultGraphExecutor(options) {
12730
- const executor = new GraphExecutor(
12856
+ const executor2 = new GraphExecutor(
12731
12857
  options.checkpointer ?? new MemoryCheckpointer(),
12732
12858
  { maxSteps: options.maxSteps ?? 8 }
12733
12859
  );
12734
- executor.registerNode(new UserNode());
12735
- executor.registerNode(options.llmNode);
12736
- executor.registerNode(new ToolNode({
12860
+ executor2.registerNode(new UserNode());
12861
+ executor2.registerNode(options.llmNode);
12862
+ executor2.registerNode(new ToolNode({
12737
12863
  toolRuntime: options.toolRuntime,
12738
12864
  observationPreview: options.observationPreview,
12739
12865
  auditPort: options.auditPort,
@@ -12741,8 +12867,8 @@ function createDefaultGraphExecutor(options) {
12741
12867
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
12742
12868
  modelInputResolver: options.modelInputResolver
12743
12869
  }));
12744
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12745
- return executor;
12870
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12871
+ return executor2;
12746
12872
  }
12747
12873
 
12748
12874
  // src/quickstart/functions/contextTrace.ts
@@ -13021,7 +13147,7 @@ async function runAgent(agent, options) {
13021
13147
  contextBuilder: new QuickstartContextBuilder(agent),
13022
13148
  telemetryPort
13023
13149
  });
13024
- const executor = createDefaultGraphExecutor({
13150
+ const executor2 = createDefaultGraphExecutor({
13025
13151
  llmNode: new LlmNode({ reasoner }),
13026
13152
  toolRuntime,
13027
13153
  observationPreview: createNoopObservationPreview(),
@@ -13057,7 +13183,7 @@ async function runAgent(agent, options) {
13057
13183
  };
13058
13184
  await handle.markRunning({ currentNode: "user" });
13059
13185
  try {
13060
- await executor.prime(checkpointKey, {
13186
+ await executor2.prime(checkpointKey, {
13061
13187
  conversationId,
13062
13188
  turnId,
13063
13189
  request: {
@@ -13074,7 +13200,7 @@ async function runAgent(agent, options) {
13074
13200
  signal: handle.signal,
13075
13201
  runtimeEventSink: (event, source) => publisher.publish(event, source)
13076
13202
  });
13077
- const result = await executor.runUntilYield(checkpointKey);
13203
+ const result = await executor2.runUntilYield(checkpointKey);
13078
13204
  await Promise.all([callbackTail, persistenceTail]);
13079
13205
  await handle.markCompleted({
13080
13206
  currentNode: result.checkpoint.nodeId,