@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
@@ -2016,6 +2016,7 @@ __export(graph_engine_exports, {
2016
2016
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
2017
2017
  isRunPauseSignal: () => isRunPauseSignal,
2018
2018
  isRuntimeFailureFact: () => isRuntimeFailureFact,
2019
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
2019
2020
  readCheckpointContextUsage: () => readCheckpointContextUsage,
2020
2021
  requireEventStoreId: () => requireEventStoreId,
2021
2022
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -3364,23 +3365,23 @@ var GraphExecutor = class {
3364
3365
  };
3365
3366
  }
3366
3367
  async saveCheckpoint(checkpointKey, state) {
3367
- const checkpoint = this.sanitize({
3368
+ const checkpoint2 = this.sanitize({
3368
3369
  ...state,
3369
3370
  revision: (state.revision ?? 0) + 1
3370
3371
  });
3371
- await this.commitCheckpoint(checkpointKey, checkpoint);
3372
- return checkpoint;
3372
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3373
+ return checkpoint2;
3373
3374
  }
3374
- async commitCheckpoint(checkpointKey, checkpoint) {
3375
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3375
3376
  if (this.executionCheckpointPort) {
3376
- await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3377
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3377
3378
  } else {
3378
- await this.checkpointer.save(checkpointKey, checkpoint);
3379
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3379
3380
  }
3380
3381
  }
3381
3382
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3382
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3383
- return { events, checkpoint, stepCount };
3383
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3384
+ return { events, checkpoint: checkpoint2, stepCount };
3384
3385
  }
3385
3386
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3386
3387
  let state = initialState;
@@ -9228,16 +9229,16 @@ function requireEventStoreId(eventStoreId) {
9228
9229
  }
9229
9230
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9230
9231
  let lastTimestamp = 0;
9231
- let counter = 0;
9232
+ let counter2 = 0;
9232
9233
  return () => {
9233
9234
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9234
9235
  if (timestamp === lastTimestamp) {
9235
- counter += 1;
9236
+ counter2 += 1;
9236
9237
  } else {
9237
9238
  lastTimestamp = timestamp;
9238
- counter = 0;
9239
+ counter2 = 0;
9239
9240
  }
9240
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9241
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9241
9242
  };
9242
9243
  }
9243
9244
 
@@ -9649,6 +9650,76 @@ function assertNonNegativeSafeInteger(value, field) {
9649
9650
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9650
9651
  }
9651
9652
  }
9653
+ var counter = z.number().int().nonnegative();
9654
+ var executor = z.object({
9655
+ stepCount: counter,
9656
+ phase: z.string().optional(),
9657
+ maxSteps: counter.optional(),
9658
+ remainingSteps: z.number().int().optional(),
9659
+ finalStepPolicy: z.enum(["final_answer", "force_tools"]).optional(),
9660
+ finalStepForcedTools: z.array(z.string()).optional(),
9661
+ lastStepsHintThreshold: counter.optional(),
9662
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9663
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9664
+ runLockedModelId: z.string().optional(),
9665
+ lastSuccessfulLlmModelId: z.string().optional(),
9666
+ llmInvocationKind: z.enum(["user_initiated", "continuation"]).optional(),
9667
+ llmInvocationCount: counter.optional(),
9668
+ lockRequestedModelId: z.boolean().optional(),
9669
+ contextCompaction: z.object({
9670
+ attemptCount: counter,
9671
+ committedCount: counter,
9672
+ lastCommittedFingerprint: z.string().optional()
9673
+ }).strict().optional()
9674
+ }).strict();
9675
+ var checkpoint = z.object({
9676
+ nodeId: z.string().min(1),
9677
+ schemaVersion: z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9678
+ revision: counter.optional(),
9679
+ executionStatus: z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9680
+ local: z.object({
9681
+ runId: RunIdSchema.optional(),
9682
+ parentRunId: RunIdSchema.optional(),
9683
+ conversationId: z.string().optional(),
9684
+ turnId: z.string().optional(),
9685
+ request: SerializableJsonRecord.optional(),
9686
+ history: z.array(RuntimeEvent).optional(),
9687
+ newEvents: z.array(RuntimeEvent).optional(),
9688
+ executorLocal: executor.optional(),
9689
+ pendingToolCalls: z.array(z.object({
9690
+ id: ToolCallIdSchema,
9691
+ type: z.literal("function"),
9692
+ function: z.object({ name: z.string().min(1), arguments: z.string() }).strict()
9693
+ }).strict()).optional(),
9694
+ executingToolCallId: ToolCallIdSchema.optional(),
9695
+ toolBatchCompletionMode: z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9696
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9697
+ lastToolResult: SerializableJsonRecord.optional(),
9698
+ finalAnswer: z.string().optional(),
9699
+ answerId: z.string().optional(),
9700
+ chunkSeq: counter.optional(),
9701
+ contextUsage: ContextUsageSnapshot.optional()
9702
+ }).passthrough().optional()
9703
+ }).strict();
9704
+ function parseEngineCheckpoint(value) {
9705
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9706
+ for (const key of [
9707
+ "memory",
9708
+ "signal",
9709
+ "toolContext",
9710
+ "runtimeEventSink",
9711
+ "runtimeEventCommitPort",
9712
+ "runtimeFailureFactSink",
9713
+ "summarizationCallbacks",
9714
+ "commitExecutionBoundary",
9715
+ "toolRecoveryPort"
9716
+ ]) {
9717
+ if (result.local && Object.hasOwn(result.local, key)) {
9718
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9719
+ }
9720
+ }
9721
+ return result;
9722
+ }
9652
9723
 
9653
9724
  // src/runtime-kernel/execution/index.ts
9654
9725
  var execution_exports = {};
@@ -9899,14 +9970,14 @@ var EventBusEventPersistence = class {
9899
9970
  checkpointWritesActive;
9900
9971
  checkpointEvents = [];
9901
9972
  /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9902
- async commitCheckpoint(checkpointKey, checkpoint) {
9973
+ async commitCheckpoint(checkpointKey, checkpoint2) {
9903
9974
  const writer = this.options.checkpointWriter;
9904
9975
  if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9905
9976
  const events = this.checkpointEvents;
9906
9977
  this.checkpointEvents = [];
9907
9978
  await this.enqueueWrite(() => writer({
9908
9979
  checkpointKey,
9909
- checkpoint,
9980
+ checkpoint: checkpoint2,
9910
9981
  events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9911
9982
  }));
9912
9983
  }
@@ -12219,7 +12290,15 @@ function createRunConcurrencyKeyRegistry() {
12219
12290
  runIdByKey.delete(concurrencyKey);
12220
12291
  }
12221
12292
  }
12222
- return { acquire, release };
12293
+ function transfer(previous, next, concurrencyKey) {
12294
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
12295
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
12296
+ }
12297
+ keyByRunId.delete(previous);
12298
+ keyByRunId.set(next, concurrencyKey);
12299
+ runIdByKey.set(concurrencyKey, next);
12300
+ }
12301
+ return { acquire, release, transfer };
12223
12302
  }
12224
12303
 
12225
12304
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -12468,6 +12547,9 @@ var DefaultRunSupervisor = class {
12468
12547
  });
12469
12548
  }
12470
12549
  async registerRun(spec) {
12550
+ if (spec.replacesPausedRun) {
12551
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
12552
+ }
12471
12553
  const runId = spec.runId ?? this.runIdFactory();
12472
12554
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
12473
12555
  throw new RunAlreadyRegisteredError(runId);
@@ -12478,13 +12560,51 @@ var DefaultRunSupervisor = class {
12478
12560
  forwardParentAbortSignal(controller, spec.parentSignal);
12479
12561
  const record = createInitialRunRecord({ runId, spec, startedAt });
12480
12562
  try {
12481
- await this.registryStore.save(record);
12563
+ if (spec.admissionCommit) await spec.admissionCommit(record);
12564
+ else await this.registryStore.save(record);
12482
12565
  } catch (error) {
12483
12566
  this.releaseRunAdmission(runId);
12484
12567
  throw error;
12485
12568
  }
12486
12569
  return this.attachRun(record, spec, controller);
12487
12570
  }
12571
+ async registerPausedReplacement(spec) {
12572
+ const target = spec.replacesPausedRun;
12573
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
12574
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
12575
+ }
12576
+ this.getHandle(target.runId);
12577
+ const previous = await this.registryStore.load(target.runId);
12578
+ 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) {
12579
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
12580
+ }
12581
+ const runId = spec.runId ?? this.runIdFactory();
12582
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
12583
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
12584
+ this.runSlotLimiter.release(previous.runId);
12585
+ this.runSlotLimiter.acquire(runId);
12586
+ const now = this.now();
12587
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
12588
+ const next = {
12589
+ ...previous,
12590
+ status: "cancelled",
12591
+ updatedAt: now,
12592
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
12593
+ };
12594
+ try {
12595
+ await spec.admissionCommit(record, { previous, next });
12596
+ } catch (error) {
12597
+ this.runSlotLimiter.release(runId);
12598
+ this.runSlotLimiter.acquire(previous.runId);
12599
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
12600
+ throw error;
12601
+ }
12602
+ this.cleanupRunResources(previous.runId);
12603
+ this.notifyTerminalWaiters(previous.runId);
12604
+ const controller = new AbortController();
12605
+ forwardParentAbortSignal(controller, spec.parentSignal);
12606
+ return this.attachRun(record, spec, controller);
12607
+ }
12488
12608
  async restoreRun(spec) {
12489
12609
  if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12490
12610
  return this.withRunControlLock(spec.runId, async () => {
@@ -12608,7 +12728,7 @@ var DefaultRunSupervisor = class {
12608
12728
  return this.withRunControlLock(input.runId, async () => {
12609
12729
  const handle = this.getHandle(input.runId);
12610
12730
  const record = await this.registryStore.load(input.runId);
12611
- if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
12731
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
12612
12732
  throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12613
12733
  }
12614
12734
  await persistRunTransition(this.registryStore, record, {
@@ -12749,7 +12869,7 @@ var DefaultRunSupervisor = class {
12749
12869
  }
12750
12870
  const awaitingUserWithoutClaim = { ...awaitingUser };
12751
12871
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12752
- await persistRunTransition(this.registryStore, record, {
12872
+ const nextRecord = {
12753
12873
  ...record,
12754
12874
  status: "running",
12755
12875
  updatedAt: this.now(),
@@ -12759,6 +12879,10 @@ var DefaultRunSupervisor = class {
12759
12879
  metadata: {
12760
12880
  ...record.metadata ?? {},
12761
12881
  ...execution ? { executionId: execution.executionId } : {},
12882
+ ...execution?.inputEventIds ? { resumeInputs: {
12883
+ eventIds: [...execution.inputEventIds],
12884
+ checkpointRevision: pendingInteraction.checkpointRevision
12885
+ } } : {},
12762
12886
  awaitingUser: {
12763
12887
  ...awaitingUserWithoutClaim,
12764
12888
  interaction: {
@@ -12767,7 +12891,9 @@ var DefaultRunSupervisor = class {
12767
12891
  }
12768
12892
  }
12769
12893
  }
12770
- });
12894
+ };
12895
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
12896
+ else await persistRunTransition(this.registryStore, record, nextRecord);
12771
12897
  const executionController = new AbortController();
12772
12898
  forwardParentAbortSignal(executionController, parentSignal);
12773
12899
  handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
@@ -12838,13 +12964,13 @@ createConsoleAudit();
12838
12964
 
12839
12965
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
12840
12966
  function createDefaultGraphExecutor(options) {
12841
- const executor = new GraphExecutor(
12967
+ const executor2 = new GraphExecutor(
12842
12968
  options.checkpointer ?? new MemoryCheckpointer(),
12843
12969
  { maxSteps: options.maxSteps ?? 8 }
12844
12970
  );
12845
- executor.registerNode(new UserNode());
12846
- executor.registerNode(options.llmNode);
12847
- executor.registerNode(new ToolNode({
12971
+ executor2.registerNode(new UserNode());
12972
+ executor2.registerNode(options.llmNode);
12973
+ executor2.registerNode(new ToolNode({
12848
12974
  toolRuntime: options.toolRuntime,
12849
12975
  observationPreview: options.observationPreview,
12850
12976
  auditPort: options.auditPort,
@@ -12852,8 +12978,8 @@ function createDefaultGraphExecutor(options) {
12852
12978
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
12853
12979
  modelInputResolver: options.modelInputResolver
12854
12980
  }));
12855
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12856
- return executor;
12981
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12982
+ return executor2;
12857
12983
  }
12858
12984
 
12859
12985
  // src/quickstart/functions/contextTrace.ts
@@ -13132,7 +13258,7 @@ async function runAgent(agent, options) {
13132
13258
  contextBuilder: new QuickstartContextBuilder(agent),
13133
13259
  telemetryPort
13134
13260
  });
13135
- const executor = createDefaultGraphExecutor({
13261
+ const executor2 = createDefaultGraphExecutor({
13136
13262
  llmNode: new LlmNode({ reasoner }),
13137
13263
  toolRuntime,
13138
13264
  observationPreview: createNoopObservationPreview(),
@@ -13168,7 +13294,7 @@ async function runAgent(agent, options) {
13168
13294
  };
13169
13295
  await handle.markRunning({ currentNode: "user" });
13170
13296
  try {
13171
- await executor.prime(checkpointKey, {
13297
+ await executor2.prime(checkpointKey, {
13172
13298
  conversationId,
13173
13299
  turnId,
13174
13300
  request: {
@@ -13185,7 +13311,7 @@ async function runAgent(agent, options) {
13185
13311
  signal: handle.signal,
13186
13312
  runtimeEventSink: (event, source) => publisher.publish(event, source)
13187
13313
  });
13188
- const result = await executor.runUntilYield(checkpointKey);
13314
+ const result = await executor2.runUntilYield(checkpointKey);
13189
13315
  await Promise.all([callbackTail, persistenceTail]);
13190
13316
  await handle.markCompleted({
13191
13317
  currentNode: result.checkpoint.nodeId,