@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
package/dist/cli.js CHANGED
@@ -1902,6 +1902,7 @@ __export(graph_engine_exports, {
1902
1902
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
1903
1903
  isRunPauseSignal: () => isRunPauseSignal,
1904
1904
  isRuntimeFailureFact: () => isRuntimeFailureFact,
1905
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
1905
1906
  readCheckpointContextUsage: () => readCheckpointContextUsage,
1906
1907
  requireEventStoreId: () => requireEventStoreId,
1907
1908
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -3250,23 +3251,23 @@ var GraphExecutor = class {
3250
3251
  };
3251
3252
  }
3252
3253
  async saveCheckpoint(checkpointKey, state) {
3253
- const checkpoint = this.sanitize({
3254
+ const checkpoint2 = this.sanitize({
3254
3255
  ...state,
3255
3256
  revision: (state.revision ?? 0) + 1
3256
3257
  });
3257
- await this.commitCheckpoint(checkpointKey, checkpoint);
3258
- return checkpoint;
3258
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3259
+ return checkpoint2;
3259
3260
  }
3260
- async commitCheckpoint(checkpointKey, checkpoint) {
3261
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3261
3262
  if (this.executionCheckpointPort) {
3262
- await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3263
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3263
3264
  } else {
3264
- await this.checkpointer.save(checkpointKey, checkpoint);
3265
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3265
3266
  }
3266
3267
  }
3267
3268
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3268
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3269
- return { events, checkpoint, stepCount };
3269
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3270
+ return { events, checkpoint: checkpoint2, stepCount };
3270
3271
  }
3271
3272
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3272
3273
  let state = initialState;
@@ -9114,16 +9115,16 @@ function requireEventStoreId(eventStoreId) {
9114
9115
  }
9115
9116
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9116
9117
  let lastTimestamp = 0;
9117
- let counter = 0;
9118
+ let counter2 = 0;
9118
9119
  return () => {
9119
9120
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9120
9121
  if (timestamp === lastTimestamp) {
9121
- counter += 1;
9122
+ counter2 += 1;
9122
9123
  } else {
9123
9124
  lastTimestamp = timestamp;
9124
- counter = 0;
9125
+ counter2 = 0;
9125
9126
  }
9126
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9127
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9127
9128
  };
9128
9129
  }
9129
9130
 
@@ -9535,6 +9536,76 @@ function assertNonNegativeSafeInteger(value, field) {
9535
9536
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9536
9537
  }
9537
9538
  }
9539
+ var counter = z.number().int().nonnegative();
9540
+ var executor = z.object({
9541
+ stepCount: counter,
9542
+ phase: z.string().optional(),
9543
+ maxSteps: counter.optional(),
9544
+ remainingSteps: z.number().int().optional(),
9545
+ finalStepPolicy: z.enum(["final_answer", "force_tools"]).optional(),
9546
+ finalStepForcedTools: z.array(z.string()).optional(),
9547
+ lastStepsHintThreshold: counter.optional(),
9548
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9549
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9550
+ runLockedModelId: z.string().optional(),
9551
+ lastSuccessfulLlmModelId: z.string().optional(),
9552
+ llmInvocationKind: z.enum(["user_initiated", "continuation"]).optional(),
9553
+ llmInvocationCount: counter.optional(),
9554
+ lockRequestedModelId: z.boolean().optional(),
9555
+ contextCompaction: z.object({
9556
+ attemptCount: counter,
9557
+ committedCount: counter,
9558
+ lastCommittedFingerprint: z.string().optional()
9559
+ }).strict().optional()
9560
+ }).strict();
9561
+ var checkpoint = z.object({
9562
+ nodeId: z.string().min(1),
9563
+ schemaVersion: z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9564
+ revision: counter.optional(),
9565
+ executionStatus: z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9566
+ local: z.object({
9567
+ runId: RunIdSchema.optional(),
9568
+ parentRunId: RunIdSchema.optional(),
9569
+ conversationId: z.string().optional(),
9570
+ turnId: z.string().optional(),
9571
+ request: SerializableJsonRecord.optional(),
9572
+ history: z.array(RuntimeEvent).optional(),
9573
+ newEvents: z.array(RuntimeEvent).optional(),
9574
+ executorLocal: executor.optional(),
9575
+ pendingToolCalls: z.array(z.object({
9576
+ id: ToolCallIdSchema,
9577
+ type: z.literal("function"),
9578
+ function: z.object({ name: z.string().min(1), arguments: z.string() }).strict()
9579
+ }).strict()).optional(),
9580
+ executingToolCallId: ToolCallIdSchema.optional(),
9581
+ toolBatchCompletionMode: z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9582
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9583
+ lastToolResult: SerializableJsonRecord.optional(),
9584
+ finalAnswer: z.string().optional(),
9585
+ answerId: z.string().optional(),
9586
+ chunkSeq: counter.optional(),
9587
+ contextUsage: ContextUsageSnapshot.optional()
9588
+ }).passthrough().optional()
9589
+ }).strict();
9590
+ function parseEngineCheckpoint(value) {
9591
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9592
+ for (const key of [
9593
+ "memory",
9594
+ "signal",
9595
+ "toolContext",
9596
+ "runtimeEventSink",
9597
+ "runtimeEventCommitPort",
9598
+ "runtimeFailureFactSink",
9599
+ "summarizationCallbacks",
9600
+ "commitExecutionBoundary",
9601
+ "toolRecoveryPort"
9602
+ ]) {
9603
+ if (result.local && Object.hasOwn(result.local, key)) {
9604
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9605
+ }
9606
+ }
9607
+ return result;
9608
+ }
9538
9609
 
9539
9610
  // src/runtime-kernel/execution/index.ts
9540
9611
  var execution_exports = {};
@@ -9785,14 +9856,14 @@ var EventBusEventPersistence = class {
9785
9856
  checkpointWritesActive;
9786
9857
  checkpointEvents = [];
9787
9858
  /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
9788
- async commitCheckpoint(checkpointKey, checkpoint) {
9859
+ async commitCheckpoint(checkpointKey, checkpoint2) {
9789
9860
  const writer = this.options.checkpointWriter;
9790
9861
  if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
9791
9862
  const events = this.checkpointEvents;
9792
9863
  this.checkpointEvents = [];
9793
9864
  await this.enqueueWrite(() => writer({
9794
9865
  checkpointKey,
9795
- checkpoint,
9866
+ checkpoint: checkpoint2,
9796
9867
  events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
9797
9868
  }));
9798
9869
  }
@@ -12105,7 +12176,15 @@ function createRunConcurrencyKeyRegistry() {
12105
12176
  runIdByKey.delete(concurrencyKey);
12106
12177
  }
12107
12178
  }
12108
- return { acquire, release };
12179
+ function transfer(previous, next, concurrencyKey) {
12180
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
12181
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
12182
+ }
12183
+ keyByRunId.delete(previous);
12184
+ keyByRunId.set(next, concurrencyKey);
12185
+ runIdByKey.set(concurrencyKey, next);
12186
+ }
12187
+ return { acquire, release, transfer };
12109
12188
  }
12110
12189
 
12111
12190
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -12354,6 +12433,9 @@ var DefaultRunSupervisor = class {
12354
12433
  });
12355
12434
  }
12356
12435
  async registerRun(spec) {
12436
+ if (spec.replacesPausedRun) {
12437
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
12438
+ }
12357
12439
  const runId = spec.runId ?? this.runIdFactory();
12358
12440
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
12359
12441
  throw new RunAlreadyRegisteredError(runId);
@@ -12364,13 +12446,51 @@ var DefaultRunSupervisor = class {
12364
12446
  forwardParentAbortSignal(controller, spec.parentSignal);
12365
12447
  const record = createInitialRunRecord({ runId, spec, startedAt });
12366
12448
  try {
12367
- await this.registryStore.save(record);
12449
+ if (spec.admissionCommit) await spec.admissionCommit(record);
12450
+ else await this.registryStore.save(record);
12368
12451
  } catch (error) {
12369
12452
  this.releaseRunAdmission(runId);
12370
12453
  throw error;
12371
12454
  }
12372
12455
  return this.attachRun(record, spec, controller);
12373
12456
  }
12457
+ async registerPausedReplacement(spec) {
12458
+ const target = spec.replacesPausedRun;
12459
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
12460
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
12461
+ }
12462
+ this.getHandle(target.runId);
12463
+ const previous = await this.registryStore.load(target.runId);
12464
+ 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) {
12465
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
12466
+ }
12467
+ const runId = spec.runId ?? this.runIdFactory();
12468
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
12469
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
12470
+ this.runSlotLimiter.release(previous.runId);
12471
+ this.runSlotLimiter.acquire(runId);
12472
+ const now = this.now();
12473
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
12474
+ const next = {
12475
+ ...previous,
12476
+ status: "cancelled",
12477
+ updatedAt: now,
12478
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
12479
+ };
12480
+ try {
12481
+ await spec.admissionCommit(record, { previous, next });
12482
+ } catch (error) {
12483
+ this.runSlotLimiter.release(runId);
12484
+ this.runSlotLimiter.acquire(previous.runId);
12485
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
12486
+ throw error;
12487
+ }
12488
+ this.cleanupRunResources(previous.runId);
12489
+ this.notifyTerminalWaiters(previous.runId);
12490
+ const controller = new AbortController();
12491
+ forwardParentAbortSignal(controller, spec.parentSignal);
12492
+ return this.attachRun(record, spec, controller);
12493
+ }
12374
12494
  async restoreRun(spec) {
12375
12495
  if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
12376
12496
  return this.withRunControlLock(spec.runId, async () => {
@@ -12494,7 +12614,7 @@ var DefaultRunSupervisor = class {
12494
12614
  return this.withRunControlLock(input.runId, async () => {
12495
12615
  const handle = this.getHandle(input.runId);
12496
12616
  const record = await this.registryStore.load(input.runId);
12497
- if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
12617
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
12498
12618
  throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
12499
12619
  }
12500
12620
  await persistRunTransition(this.registryStore, record, {
@@ -12507,6 +12627,7 @@ var DefaultRunSupervisor = class {
12507
12627
  metadata: { ...record.metadata, executionId: input.executionId }
12508
12628
  });
12509
12629
  const controller = new AbortController();
12630
+ forwardParentAbortSignal(controller, input.parentSignal);
12510
12631
  handle.replaceExecutionAbortController(controller, input.executionId);
12511
12632
  handle.attachTransportEventBus(input.eventBus);
12512
12633
  this.controllers.set(input.runId, controller);
@@ -12635,7 +12756,7 @@ var DefaultRunSupervisor = class {
12635
12756
  }
12636
12757
  const awaitingUserWithoutClaim = { ...awaitingUser };
12637
12758
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
12638
- await persistRunTransition(this.registryStore, record, {
12759
+ const nextRecord = {
12639
12760
  ...record,
12640
12761
  status: "running",
12641
12762
  updatedAt: this.now(),
@@ -12645,6 +12766,10 @@ var DefaultRunSupervisor = class {
12645
12766
  metadata: {
12646
12767
  ...record.metadata ?? {},
12647
12768
  ...execution ? { executionId: execution.executionId } : {},
12769
+ ...execution?.inputEventIds ? { resumeInputs: {
12770
+ eventIds: [...execution.inputEventIds],
12771
+ checkpointRevision: pendingInteraction.checkpointRevision
12772
+ } } : {},
12648
12773
  awaitingUser: {
12649
12774
  ...awaitingUserWithoutClaim,
12650
12775
  interaction: {
@@ -12653,7 +12778,9 @@ var DefaultRunSupervisor = class {
12653
12778
  }
12654
12779
  }
12655
12780
  }
12656
- });
12781
+ };
12782
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
12783
+ else await persistRunTransition(this.registryStore, record, nextRecord);
12657
12784
  const executionController = new AbortController();
12658
12785
  forwardParentAbortSignal(executionController, parentSignal);
12659
12786
  handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
@@ -12724,13 +12851,13 @@ createConsoleAudit();
12724
12851
 
12725
12852
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
12726
12853
  function createDefaultGraphExecutor(options) {
12727
- const executor = new GraphExecutor(
12854
+ const executor2 = new GraphExecutor(
12728
12855
  options.checkpointer ?? new MemoryCheckpointer(),
12729
12856
  { maxSteps: options.maxSteps ?? 8 }
12730
12857
  );
12731
- executor.registerNode(new UserNode());
12732
- executor.registerNode(options.llmNode);
12733
- executor.registerNode(new ToolNode({
12858
+ executor2.registerNode(new UserNode());
12859
+ executor2.registerNode(options.llmNode);
12860
+ executor2.registerNode(new ToolNode({
12734
12861
  toolRuntime: options.toolRuntime,
12735
12862
  observationPreview: options.observationPreview,
12736
12863
  auditPort: options.auditPort,
@@ -12738,8 +12865,8 @@ function createDefaultGraphExecutor(options) {
12738
12865
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
12739
12866
  modelInputResolver: options.modelInputResolver
12740
12867
  }));
12741
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12742
- return executor;
12868
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
12869
+ return executor2;
12743
12870
  }
12744
12871
 
12745
12872
  // src/quickstart/functions/contextTrace.ts
@@ -13018,7 +13145,7 @@ async function runAgent(agent, options) {
13018
13145
  contextBuilder: new QuickstartContextBuilder(agent),
13019
13146
  telemetryPort
13020
13147
  });
13021
- const executor = createDefaultGraphExecutor({
13148
+ const executor2 = createDefaultGraphExecutor({
13022
13149
  llmNode: new LlmNode({ reasoner }),
13023
13150
  toolRuntime,
13024
13151
  observationPreview: createNoopObservationPreview(),
@@ -13054,7 +13181,7 @@ async function runAgent(agent, options) {
13054
13181
  };
13055
13182
  await handle.markRunning({ currentNode: "user" });
13056
13183
  try {
13057
- await executor.prime(checkpointKey, {
13184
+ await executor2.prime(checkpointKey, {
13058
13185
  conversationId,
13059
13186
  turnId,
13060
13187
  request: {
@@ -13071,7 +13198,7 @@ async function runAgent(agent, options) {
13071
13198
  signal: handle.signal,
13072
13199
  runtimeEventSink: (event, source) => publisher.publish(event, source)
13073
13200
  });
13074
- const result = await executor.runUntilYield(checkpointKey);
13201
+ const result = await executor2.runUntilYield(checkpointKey);
13075
13202
  await Promise.all([callbackTail, persistenceTail]);
13076
13203
  await handle.markCompleted({
13077
13204
  currentNode: result.checkpoint.nodeId,