@linnlabs/linnkit 0.33.0 → 0.35.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 (43) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/cli.cjs +155 -28
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +155 -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 +175 -43
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.js +175 -43
  13. package/dist/index.js.map +1 -1
  14. package/dist/quickstart.cjs +155 -28
  15. package/dist/quickstart.cjs.map +1 -1
  16. package/dist/quickstart.js +155 -28
  17. package/dist/quickstart.js.map +1 -1
  18. package/dist/runtime-kernel/child-runs/childRunInvoker.d.cts +5 -0
  19. package/dist/runtime-kernel/child-runs/childRunInvoker.d.ts +5 -0
  20. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.cts +6 -0
  21. package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.ts +6 -0
  22. package/dist/runtime-kernel/graph-engine/index.d.cts +1 -0
  23. package/dist/runtime-kernel/graph-engine/index.d.ts +1 -0
  24. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +22 -4
  25. package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +22 -4
  26. package/dist/runtime-kernel/run-supervisor/index.d.cts +1 -1
  27. package/dist/runtime-kernel/run-supervisor/index.d.ts +1 -1
  28. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +2 -1
  29. package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +2 -1
  30. package/dist/runtime-kernel.cjs +172 -40
  31. package/dist/runtime-kernel.cjs.map +1 -1
  32. package/dist/runtime-kernel.d.cts +1 -0
  33. package/dist/runtime-kernel.d.ts +1 -0
  34. package/dist/runtime-kernel.js +172 -41
  35. package/dist/runtime-kernel.js.map +1 -1
  36. package/dist/testkit.cjs +172 -40
  37. package/dist/testkit.cjs.map +1 -1
  38. package/dist/testkit.js +172 -40
  39. package/dist/testkit.js.map +1 -1
  40. package/docs/integration/child-runs.md +8 -0
  41. package/docs/integration/persistence.md +1 -0
  42. package/docs/integration/run-supervisor.md +3 -0
  43. package/package.json +2 -2
@@ -2018,6 +2018,7 @@ __export(graph_engine_exports, {
2018
2018
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
2019
2019
  isRunPauseSignal: () => isRunPauseSignal,
2020
2020
  isRuntimeFailureFact: () => isRuntimeFailureFact,
2021
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
2021
2022
  readCheckpointContextUsage: () => readCheckpointContextUsage,
2022
2023
  requireEventStoreId: () => requireEventStoreId,
2023
2024
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -3366,23 +3367,23 @@ var GraphExecutor = class {
3366
3367
  };
3367
3368
  }
3368
3369
  async saveCheckpoint(checkpointKey, state) {
3369
- const checkpoint = this.sanitize({
3370
+ const checkpoint2 = this.sanitize({
3370
3371
  ...state,
3371
3372
  revision: (state.revision ?? 0) + 1
3372
3373
  });
3373
- await this.commitCheckpoint(checkpointKey, checkpoint);
3374
- return checkpoint;
3374
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3375
+ return checkpoint2;
3375
3376
  }
3376
- async commitCheckpoint(checkpointKey, checkpoint) {
3377
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3377
3378
  if (this.executionCheckpointPort) {
3378
- await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3379
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3379
3380
  } else {
3380
- await this.checkpointer.save(checkpointKey, checkpoint);
3381
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3381
3382
  }
3382
3383
  }
3383
3384
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3384
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3385
- return { events, checkpoint, stepCount };
3385
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3386
+ return { events, checkpoint: checkpoint2, stepCount };
3386
3387
  }
3387
3388
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3388
3389
  let state = initialState;
@@ -9230,16 +9231,16 @@ function requireEventStoreId(eventStoreId) {
9230
9231
  }
9231
9232
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9232
9233
  let lastTimestamp = 0;
9233
- let counter = 0;
9234
+ let counter2 = 0;
9234
9235
  return () => {
9235
9236
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9236
9237
  if (timestamp === lastTimestamp) {
9237
- counter += 1;
9238
+ counter2 += 1;
9238
9239
  } else {
9239
9240
  lastTimestamp = timestamp;
9240
- counter = 0;
9241
+ counter2 = 0;
9241
9242
  }
9242
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9243
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9243
9244
  };
9244
9245
  }
9245
9246
 
@@ -9651,6 +9652,76 @@ function assertNonNegativeSafeInteger(value, field) {
9651
9652
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9652
9653
  }
9653
9654
  }
9655
+ var counter = zod.z.number().int().nonnegative();
9656
+ var executor = zod.z.object({
9657
+ stepCount: counter,
9658
+ phase: zod.z.string().optional(),
9659
+ maxSteps: counter.optional(),
9660
+ remainingSteps: zod.z.number().int().optional(),
9661
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
9662
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
9663
+ lastStepsHintThreshold: counter.optional(),
9664
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9665
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9666
+ runLockedModelId: zod.z.string().optional(),
9667
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
9668
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
9669
+ llmInvocationCount: counter.optional(),
9670
+ lockRequestedModelId: zod.z.boolean().optional(),
9671
+ contextCompaction: zod.z.object({
9672
+ attemptCount: counter,
9673
+ committedCount: counter,
9674
+ lastCommittedFingerprint: zod.z.string().optional()
9675
+ }).strict().optional()
9676
+ }).strict();
9677
+ var checkpoint = zod.z.object({
9678
+ nodeId: zod.z.string().min(1),
9679
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9680
+ revision: counter.optional(),
9681
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9682
+ local: zod.z.object({
9683
+ runId: RunIdSchema.optional(),
9684
+ parentRunId: RunIdSchema.optional(),
9685
+ conversationId: zod.z.string().optional(),
9686
+ turnId: zod.z.string().optional(),
9687
+ request: SerializableJsonRecord.optional(),
9688
+ history: zod.z.array(RuntimeEvent).optional(),
9689
+ newEvents: zod.z.array(RuntimeEvent).optional(),
9690
+ executorLocal: executor.optional(),
9691
+ pendingToolCalls: zod.z.array(zod.z.object({
9692
+ id: ToolCallIdSchema,
9693
+ type: zod.z.literal("function"),
9694
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
9695
+ }).strict()).optional(),
9696
+ executingToolCallId: ToolCallIdSchema.optional(),
9697
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9698
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9699
+ lastToolResult: SerializableJsonRecord.optional(),
9700
+ finalAnswer: zod.z.string().optional(),
9701
+ answerId: zod.z.string().optional(),
9702
+ chunkSeq: counter.optional(),
9703
+ contextUsage: ContextUsageSnapshot.optional()
9704
+ }).passthrough().optional()
9705
+ }).strict();
9706
+ function parseEngineCheckpoint(value) {
9707
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9708
+ for (const key of [
9709
+ "memory",
9710
+ "signal",
9711
+ "toolContext",
9712
+ "runtimeEventSink",
9713
+ "runtimeEventCommitPort",
9714
+ "runtimeFailureFactSink",
9715
+ "summarizationCallbacks",
9716
+ "commitExecutionBoundary",
9717
+ "toolRecoveryPort"
9718
+ ]) {
9719
+ if (result.local && Object.hasOwn(result.local, key)) {
9720
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9721
+ }
9722
+ }
9723
+ return result;
9724
+ }
9654
9725
 
9655
9726
  // src/runtime-kernel/execution/index.ts
9656
9727
  var execution_exports = {};
@@ -9901,14 +9972,14 @@ var EventBusEventPersistence = class {
9901
9972
  checkpointWritesActive;
9902
9973
  checkpointEvents = [];
9903
9974
  /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9904
- async commitCheckpoint(checkpointKey, checkpoint) {
9975
+ async commitCheckpoint(checkpointKey, checkpoint2) {
9905
9976
  const writer = this.options.checkpointWriter;
9906
9977
  if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9907
9978
  const events = this.checkpointEvents;
9908
9979
  this.checkpointEvents = [];
9909
9980
  await this.enqueueWrite(() => writer({
9910
9981
  checkpointKey,
9911
- checkpoint,
9982
+ checkpoint: checkpoint2,
9912
9983
  events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9913
9984
  }));
9914
9985
  }
@@ -12221,7 +12292,15 @@ function createRunConcurrencyKeyRegistry() {
12221
12292
  runIdByKey.delete(concurrencyKey);
12222
12293
  }
12223
12294
  }
12224
- return { acquire, release };
12295
+ function transfer(previous, next, concurrencyKey) {
12296
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
12297
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
12298
+ }
12299
+ keyByRunId.delete(previous);
12300
+ keyByRunId.set(next, concurrencyKey);
12301
+ runIdByKey.set(concurrencyKey, next);
12302
+ }
12303
+ return { acquire, release, transfer };
12225
12304
  }
12226
12305
 
12227
12306
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -12470,6 +12549,9 @@ var DefaultRunSupervisor = class {
12470
12549
  });
12471
12550
  }
12472
12551
  async registerRun(spec) {
12552
+ if (spec.replacesPausedRun) {
12553
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
12554
+ }
12473
12555
  const runId = spec.runId ?? this.runIdFactory();
12474
12556
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
12475
12557
  throw new RunAlreadyRegisteredError(runId);
@@ -12480,13 +12562,51 @@ var DefaultRunSupervisor = class {
12480
12562
  forwardParentAbortSignal(controller, spec.parentSignal);
12481
12563
  const record = createInitialRunRecord({ runId, spec, startedAt });
12482
12564
  try {
12483
- await this.registryStore.save(record);
12565
+ if (spec.admissionCommit) await spec.admissionCommit(record);
12566
+ else await this.registryStore.save(record);
12484
12567
  } catch (error) {
12485
12568
  this.releaseRunAdmission(runId);
12486
12569
  throw error;
12487
12570
  }
12488
12571
  return this.attachRun(record, spec, controller);
12489
12572
  }
12573
+ async registerPausedReplacement(spec) {
12574
+ const target = spec.replacesPausedRun;
12575
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
12576
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
12577
+ }
12578
+ this.getHandle(target.runId);
12579
+ const previous = await this.registryStore.load(target.runId);
12580
+ 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) {
12581
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
12582
+ }
12583
+ const runId = spec.runId ?? this.runIdFactory();
12584
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
12585
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
12586
+ this.runSlotLimiter.release(previous.runId);
12587
+ this.runSlotLimiter.acquire(runId);
12588
+ const now = this.now();
12589
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
12590
+ const next = {
12591
+ ...previous,
12592
+ status: "cancelled",
12593
+ updatedAt: now,
12594
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
12595
+ };
12596
+ try {
12597
+ await spec.admissionCommit(record, { previous, next });
12598
+ } catch (error) {
12599
+ this.runSlotLimiter.release(runId);
12600
+ this.runSlotLimiter.acquire(previous.runId);
12601
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
12602
+ throw error;
12603
+ }
12604
+ this.cleanupRunResources(previous.runId);
12605
+ this.notifyTerminalWaiters(previous.runId);
12606
+ const controller = new AbortController();
12607
+ forwardParentAbortSignal(controller, spec.parentSignal);
12608
+ return this.attachRun(record, spec, controller);
12609
+ }
12490
12610
  async restoreRun(spec) {
12491
12611
  if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12492
12612
  return this.withRunControlLock(spec.runId, async () => {
@@ -12610,7 +12730,7 @@ var DefaultRunSupervisor = class {
12610
12730
  return this.withRunControlLock(input.runId, async () => {
12611
12731
  const handle = this.getHandle(input.runId);
12612
12732
  const record = await this.registryStore.load(input.runId);
12613
- if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
12733
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
12614
12734
  throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12615
12735
  }
12616
12736
  await persistRunTransition(this.registryStore, record, {
@@ -12623,6 +12743,7 @@ var DefaultRunSupervisor = class {
12623
12743
  metadata: { ...record.metadata, executionId: input.executionId }
12624
12744
  });
12625
12745
  const controller = new AbortController();
12746
+ forwardParentAbortSignal(controller, input.parentSignal);
12626
12747
  handle.replaceExecutionAbortController(controller, input.executionId);
12627
12748
  handle.attachTransportEventBus(input.eventBus);
12628
12749
  this.controllers.set(input.runId, controller);
@@ -12751,7 +12872,7 @@ var DefaultRunSupervisor = class {
12751
12872
  }
12752
12873
  const awaitingUserWithoutClaim = { ...awaitingUser };
12753
12874
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12754
- await persistRunTransition(this.registryStore, record, {
12875
+ const nextRecord = {
12755
12876
  ...record,
12756
12877
  status: "running",
12757
12878
  updatedAt: this.now(),
@@ -12761,6 +12882,10 @@ var DefaultRunSupervisor = class {
12761
12882
  metadata: {
12762
12883
  ...record.metadata ?? {},
12763
12884
  ...execution ? { executionId: execution.executionId } : {},
12885
+ ...execution?.inputEventIds ? { resumeInputs: {
12886
+ eventIds: [...execution.inputEventIds],
12887
+ checkpointRevision: pendingInteraction.checkpointRevision
12888
+ } } : {},
12764
12889
  awaitingUser: {
12765
12890
  ...awaitingUserWithoutClaim,
12766
12891
  interaction: {
@@ -12769,7 +12894,9 @@ var DefaultRunSupervisor = class {
12769
12894
  }
12770
12895
  }
12771
12896
  }
12772
- });
12897
+ };
12898
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
12899
+ else await persistRunTransition(this.registryStore, record, nextRecord);
12773
12900
  const executionController = new AbortController();
12774
12901
  forwardParentAbortSignal(executionController, parentSignal);
12775
12902
  handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
@@ -12840,13 +12967,13 @@ createConsoleAudit();
12840
12967
 
12841
12968
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
12842
12969
  function createDefaultGraphExecutor(options) {
12843
- const executor = new GraphExecutor(
12970
+ const executor2 = new GraphExecutor(
12844
12971
  options.checkpointer ?? new MemoryCheckpointer(),
12845
12972
  { maxSteps: options.maxSteps ?? 8 }
12846
12973
  );
12847
- executor.registerNode(new UserNode());
12848
- executor.registerNode(options.llmNode);
12849
- executor.registerNode(new ToolNode({
12974
+ executor2.registerNode(new UserNode());
12975
+ executor2.registerNode(options.llmNode);
12976
+ executor2.registerNode(new ToolNode({
12850
12977
  toolRuntime: options.toolRuntime,
12851
12978
  observationPreview: options.observationPreview,
12852
12979
  auditPort: options.auditPort,
@@ -12854,8 +12981,8 @@ function createDefaultGraphExecutor(options) {
12854
12981
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
12855
12982
  modelInputResolver: options.modelInputResolver
12856
12983
  }));
12857
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12858
- return executor;
12984
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12985
+ return executor2;
12859
12986
  }
12860
12987
 
12861
12988
  // src/quickstart/functions/contextTrace.ts
@@ -13134,7 +13261,7 @@ async function runAgent(agent, options) {
13134
13261
  contextBuilder: new QuickstartContextBuilder(agent),
13135
13262
  telemetryPort
13136
13263
  });
13137
- const executor = createDefaultGraphExecutor({
13264
+ const executor2 = createDefaultGraphExecutor({
13138
13265
  llmNode: new LlmNode({ reasoner }),
13139
13266
  toolRuntime,
13140
13267
  observationPreview: createNoopObservationPreview(),
@@ -13170,7 +13297,7 @@ async function runAgent(agent, options) {
13170
13297
  };
13171
13298
  await handle.markRunning({ currentNode: "user" });
13172
13299
  try {
13173
- await executor.prime(checkpointKey, {
13300
+ await executor2.prime(checkpointKey, {
13174
13301
  conversationId,
13175
13302
  turnId,
13176
13303
  request: {
@@ -13187,7 +13314,7 @@ async function runAgent(agent, options) {
13187
13314
  signal: handle.signal,
13188
13315
  runtimeEventSink: (event, source) => publisher.publish(event, source)
13189
13316
  });
13190
- const result = await executor.runUntilYield(checkpointKey);
13317
+ const result = await executor2.runUntilYield(checkpointKey);
13191
13318
  await Promise.all([callbackTail, persistenceTail]);
13192
13319
  await handle.markCompleted({
13193
13320
  currentNode: result.checkpoint.nodeId,