@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/dist/testkit.cjs CHANGED
@@ -174,6 +174,7 @@ __export(runtime_kernel_exports, {
174
174
  maxStepsForceFinalAnswerTemplate: () => maxStepsForceFinalAnswerTemplate,
175
175
  noopAudit: () => noopAudit,
176
176
  normalizeToolArgs: () => normalizeToolArgs,
177
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
177
178
  parseToolModelInputDeclaration: () => parseToolModelInputDeclaration,
178
179
  periodicProgressReflectionTemplate: () => periodicProgressReflectionTemplate,
179
180
  phaseEqualsTrigger: () => phaseEqualsTrigger,
@@ -223,6 +224,7 @@ __export(graph_engine_exports, {
223
224
  evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
224
225
  isRunPauseSignal: () => isRunPauseSignal,
225
226
  isRuntimeFailureFact: () => isRuntimeFailureFact,
227
+ parseEngineCheckpoint: () => parseEngineCheckpoint,
226
228
  readCheckpointContextUsage: () => readCheckpointContextUsage,
227
229
  requireEventStoreId: () => requireEventStoreId,
228
230
  resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
@@ -3344,23 +3346,23 @@ var GraphExecutor = class {
3344
3346
  };
3345
3347
  }
3346
3348
  async saveCheckpoint(checkpointKey, state) {
3347
- const checkpoint = this.sanitize({
3349
+ const checkpoint2 = this.sanitize({
3348
3350
  ...state,
3349
3351
  revision: (state.revision ?? 0) + 1
3350
3352
  });
3351
- await this.commitCheckpoint(checkpointKey, checkpoint);
3352
- return checkpoint;
3353
+ await this.commitCheckpoint(checkpointKey, checkpoint2);
3354
+ return checkpoint2;
3353
3355
  }
3354
- async commitCheckpoint(checkpointKey, checkpoint) {
3356
+ async commitCheckpoint(checkpointKey, checkpoint2) {
3355
3357
  if (this.executionCheckpointPort) {
3356
- await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
3358
+ await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
3357
3359
  } else {
3358
- await this.checkpointer.save(checkpointKey, checkpoint);
3360
+ await this.checkpointer.save(checkpointKey, checkpoint2);
3359
3361
  }
3360
3362
  }
3361
3363
  async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
3362
- const checkpoint = await this.saveCheckpoint(checkpointKey, state);
3363
- return { events, checkpoint, stepCount };
3364
+ const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
3365
+ return { events, checkpoint: checkpoint2, stepCount };
3364
3366
  }
3365
3367
  async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
3366
3368
  let state = initialState;
@@ -9487,16 +9489,16 @@ function requireEventStoreId(eventStoreId) {
9487
9489
  }
9488
9490
  function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
9489
9491
  let lastTimestamp = 0;
9490
- let counter = 0;
9492
+ let counter2 = 0;
9491
9493
  return () => {
9492
9494
  const timestamp = Math.max(nowProvider(), lastTimestamp);
9493
9495
  if (timestamp === lastTimestamp) {
9494
- counter += 1;
9496
+ counter2 += 1;
9495
9497
  } else {
9496
9498
  lastTimestamp = timestamp;
9497
- counter = 0;
9499
+ counter2 = 0;
9498
9500
  }
9499
- return `${String(timestamp).padStart(13, "0")}-${String(counter).padStart(4, "0")}`;
9501
+ return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
9500
9502
  };
9501
9503
  }
9502
9504
 
@@ -9908,6 +9910,76 @@ function assertNonNegativeSafeInteger(value, field) {
9908
9910
  throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9909
9911
  }
9910
9912
  }
9913
+ var counter = zod.z.number().int().nonnegative();
9914
+ var executor = zod.z.object({
9915
+ stepCount: counter,
9916
+ phase: zod.z.string().optional(),
9917
+ maxSteps: counter.optional(),
9918
+ remainingSteps: zod.z.number().int().optional(),
9919
+ finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
9920
+ finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
9921
+ lastStepsHintThreshold: counter.optional(),
9922
+ systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
9923
+ toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
9924
+ runLockedModelId: zod.z.string().optional(),
9925
+ lastSuccessfulLlmModelId: zod.z.string().optional(),
9926
+ llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
9927
+ llmInvocationCount: counter.optional(),
9928
+ lockRequestedModelId: zod.z.boolean().optional(),
9929
+ contextCompaction: zod.z.object({
9930
+ attemptCount: counter,
9931
+ committedCount: counter,
9932
+ lastCommittedFingerprint: zod.z.string().optional()
9933
+ }).strict().optional()
9934
+ }).strict();
9935
+ var checkpoint = zod.z.object({
9936
+ nodeId: zod.z.string().min(1),
9937
+ schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
9938
+ revision: counter.optional(),
9939
+ executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
9940
+ local: zod.z.object({
9941
+ runId: RunIdSchema.optional(),
9942
+ parentRunId: RunIdSchema.optional(),
9943
+ conversationId: zod.z.string().optional(),
9944
+ turnId: zod.z.string().optional(),
9945
+ request: SerializableJsonRecord.optional(),
9946
+ history: zod.z.array(RuntimeEvent).optional(),
9947
+ newEvents: zod.z.array(RuntimeEvent).optional(),
9948
+ executorLocal: executor.optional(),
9949
+ pendingToolCalls: zod.z.array(zod.z.object({
9950
+ id: ToolCallIdSchema,
9951
+ type: zod.z.literal("function"),
9952
+ function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
9953
+ }).strict()).optional(),
9954
+ executingToolCallId: ToolCallIdSchema.optional(),
9955
+ toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
9956
+ pendingInteractionSpec: SerializableJsonRecord.optional(),
9957
+ lastToolResult: SerializableJsonRecord.optional(),
9958
+ finalAnswer: zod.z.string().optional(),
9959
+ answerId: zod.z.string().optional(),
9960
+ chunkSeq: counter.optional(),
9961
+ contextUsage: ContextUsageSnapshot.optional()
9962
+ }).passthrough().optional()
9963
+ }).strict();
9964
+ function parseEngineCheckpoint(value) {
9965
+ const result = checkpoint.parse(SerializableJsonRecord.parse(value));
9966
+ for (const key of [
9967
+ "memory",
9968
+ "signal",
9969
+ "toolContext",
9970
+ "runtimeEventSink",
9971
+ "runtimeEventCommitPort",
9972
+ "runtimeFailureFactSink",
9973
+ "summarizationCallbacks",
9974
+ "commitExecutionBoundary",
9975
+ "toolRecoveryPort"
9976
+ ]) {
9977
+ if (result.local && Object.hasOwn(result.local, key)) {
9978
+ throw new Error(`Checkpoint must not contain execution capability: ${key}`);
9979
+ }
9980
+ }
9981
+ return result;
9982
+ }
9911
9983
 
9912
9984
  // src/runtime-kernel/tools/index.ts
9913
9985
  var tools_exports = {};
@@ -10369,14 +10441,14 @@ var EventBusEventPersistence = class {
10369
10441
  checkpointWritesActive;
10370
10442
  checkpointEvents = [];
10371
10443
  /** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
10372
- async commitCheckpoint(checkpointKey, checkpoint) {
10444
+ async commitCheckpoint(checkpointKey, checkpoint2) {
10373
10445
  const writer = this.options.checkpointWriter;
10374
10446
  if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
10375
10447
  const events = this.checkpointEvents;
10376
10448
  this.checkpointEvents = [];
10377
10449
  await this.enqueueWrite(() => writer({
10378
10450
  checkpointKey,
10379
- checkpoint,
10451
+ checkpoint: checkpoint2,
10380
10452
  events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
10381
10453
  }));
10382
10454
  }
@@ -12069,15 +12141,15 @@ function hasSeedHistoryPrefix(history, seedHistory) {
12069
12141
  }
12070
12142
  return true;
12071
12143
  }
12072
- function readCheckpointHistory(checkpoint) {
12073
- if (!checkpoint?.local) return [];
12074
- const history = checkpoint.local.history;
12144
+ function readCheckpointHistory(checkpoint2) {
12145
+ if (!checkpoint2?.local) return [];
12146
+ const history = checkpoint2.local.history;
12075
12147
  if (!Array.isArray(history)) return [];
12076
12148
  return parseRuntimeEvents(history);
12077
12149
  }
12078
12150
  async function recoverChildRunEventsFromCheckpoint(params) {
12079
- const checkpoint = await params.checkpointer.load(params.checkpointKey);
12080
- const history = readCheckpointHistory(checkpoint);
12151
+ const checkpoint2 = await params.checkpointer.load(params.checkpointKey);
12152
+ const history = readCheckpointHistory(checkpoint2);
12081
12153
  if (history.length === 0) {
12082
12154
  return [];
12083
12155
  }
@@ -12373,9 +12445,9 @@ var ChildRunInvoker = class {
12373
12445
  async continueChild(config, runId, conversationId) {
12374
12446
  const persistence = config.persistence;
12375
12447
  if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
12376
- const checkpoint = await persistence.checkpointer.load(runId);
12377
- if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12378
- const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
12448
+ const checkpoint2 = await persistence.checkpointer.load(runId);
12449
+ if (!checkpoint2 || checkpoint2.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
12450
+ const local = readGraphAgentLocal({ ...checkpoint2.local, runtimeEventSink: config.runtimeEventSink });
12379
12451
  const request = local.request;
12380
12452
  if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
12381
12453
  const context = createChildRunToolContext({
@@ -13652,7 +13724,15 @@ function createRunConcurrencyKeyRegistry() {
13652
13724
  runIdByKey.delete(concurrencyKey);
13653
13725
  }
13654
13726
  }
13655
- return { acquire, release };
13727
+ function transfer(previous, next, concurrencyKey) {
13728
+ if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
13729
+ throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
13730
+ }
13731
+ keyByRunId.delete(previous);
13732
+ keyByRunId.set(next, concurrencyKey);
13733
+ runIdByKey.set(concurrencyKey, next);
13734
+ }
13735
+ return { acquire, release, transfer };
13656
13736
  }
13657
13737
 
13658
13738
  // src/runtime-kernel/run-supervisor/functions/runRegistration.ts
@@ -13901,6 +13981,9 @@ var DefaultRunSupervisor = class {
13901
13981
  });
13902
13982
  }
13903
13983
  async registerRun(spec) {
13984
+ if (spec.replacesPausedRun) {
13985
+ return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
13986
+ }
13904
13987
  const runId = spec.runId ?? this.runIdFactory();
13905
13988
  if (this.handles.has(runId) || await this.registryStore.load(runId)) {
13906
13989
  throw new RunAlreadyRegisteredError(runId);
@@ -13911,13 +13994,51 @@ var DefaultRunSupervisor = class {
13911
13994
  forwardParentAbortSignal(controller, spec.parentSignal);
13912
13995
  const record = createInitialRunRecord({ runId, spec, startedAt });
13913
13996
  try {
13914
- await this.registryStore.save(record);
13997
+ if (spec.admissionCommit) await spec.admissionCommit(record);
13998
+ else await this.registryStore.save(record);
13915
13999
  } catch (error) {
13916
14000
  this.releaseRunAdmission(runId);
13917
14001
  throw error;
13918
14002
  }
13919
14003
  return this.attachRun(record, spec, controller);
13920
14004
  }
14005
+ async registerPausedReplacement(spec) {
14006
+ const target = spec.replacesPausedRun;
14007
+ if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
14008
+ throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
14009
+ }
14010
+ this.getHandle(target.runId);
14011
+ const previous = await this.registryStore.load(target.runId);
14012
+ 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) {
14013
+ throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
14014
+ }
14015
+ const runId = spec.runId ?? this.runIdFactory();
14016
+ if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
14017
+ this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
14018
+ this.runSlotLimiter.release(previous.runId);
14019
+ this.runSlotLimiter.acquire(runId);
14020
+ const now = this.now();
14021
+ const record = createInitialRunRecord({ runId, spec, startedAt: now });
14022
+ const next = {
14023
+ ...previous,
14024
+ status: "cancelled",
14025
+ updatedAt: now,
14026
+ errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
14027
+ };
14028
+ try {
14029
+ await spec.admissionCommit(record, { previous, next });
14030
+ } catch (error) {
14031
+ this.runSlotLimiter.release(runId);
14032
+ this.runSlotLimiter.acquire(previous.runId);
14033
+ this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
14034
+ throw error;
14035
+ }
14036
+ this.cleanupRunResources(previous.runId);
14037
+ this.notifyTerminalWaiters(previous.runId);
14038
+ const controller = new AbortController();
14039
+ forwardParentAbortSignal(controller, spec.parentSignal);
14040
+ return this.attachRun(record, spec, controller);
14041
+ }
13921
14042
  async restoreRun(spec) {
13922
14043
  if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
13923
14044
  return this.withRunControlLock(spec.runId, async () => {
@@ -14041,7 +14162,7 @@ var DefaultRunSupervisor = class {
14041
14162
  return this.withRunControlLock(input.runId, async () => {
14042
14163
  const handle = this.getHandle(input.runId);
14043
14164
  const record = await this.registryStore.load(input.runId);
14044
- if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
14165
+ if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
14045
14166
  throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
14046
14167
  }
14047
14168
  await persistRunTransition(this.registryStore, record, {
@@ -14182,7 +14303,7 @@ var DefaultRunSupervisor = class {
14182
14303
  }
14183
14304
  const awaitingUserWithoutClaim = { ...awaitingUser };
14184
14305
  Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
14185
- await persistRunTransition(this.registryStore, record, {
14306
+ const nextRecord = {
14186
14307
  ...record,
14187
14308
  status: "running",
14188
14309
  updatedAt: this.now(),
@@ -14192,6 +14313,10 @@ var DefaultRunSupervisor = class {
14192
14313
  metadata: {
14193
14314
  ...record.metadata ?? {},
14194
14315
  ...execution ? { executionId: execution.executionId } : {},
14316
+ ...execution?.inputEventIds ? { resumeInputs: {
14317
+ eventIds: [...execution.inputEventIds],
14318
+ checkpointRevision: pendingInteraction.checkpointRevision
14319
+ } } : {},
14195
14320
  awaitingUser: {
14196
14321
  ...awaitingUserWithoutClaim,
14197
14322
  interaction: {
@@ -14200,7 +14325,9 @@ var DefaultRunSupervisor = class {
14200
14325
  }
14201
14326
  }
14202
14327
  }
14203
- });
14328
+ };
14329
+ if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
14330
+ else await persistRunTransition(this.registryStore, record, nextRecord);
14204
14331
  const executionController = new AbortController();
14205
14332
  forwardParentAbortSignal(executionController, parentSignal);
14206
14333
  handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
@@ -14366,13 +14493,13 @@ __export(system_reminder_exports, {
14366
14493
 
14367
14494
  // src/runtime-kernel/testkit/defaultGraphExecutor.ts
14368
14495
  function createDefaultGraphExecutor(options) {
14369
- const executor = new GraphExecutor(
14496
+ const executor2 = new GraphExecutor(
14370
14497
  options.checkpointer ?? new MemoryCheckpointer(),
14371
14498
  { maxSteps: options.maxSteps ?? 8 }
14372
14499
  );
14373
- executor.registerNode(new UserNode());
14374
- executor.registerNode(options.llmNode);
14375
- executor.registerNode(new ToolNode({
14500
+ executor2.registerNode(new UserNode());
14501
+ executor2.registerNode(options.llmNode);
14502
+ executor2.registerNode(new ToolNode({
14376
14503
  toolRuntime: options.toolRuntime,
14377
14504
  observationPreview: options.observationPreview,
14378
14505
  auditPort: options.auditPort,
@@ -14380,8 +14507,8 @@ function createDefaultGraphExecutor(options) {
14380
14507
  modelInputCapabilityValidator: options.modelInputCapabilityValidator,
14381
14508
  modelInputResolver: options.modelInputResolver
14382
14509
  }));
14383
- executor.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14384
- return executor;
14510
+ executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
14511
+ return executor2;
14385
14512
  }
14386
14513
 
14387
14514
  // src/runtime-kernel/testkit/graphLoopHarness.ts
@@ -14406,7 +14533,7 @@ function createGraphLoopHarness(options) {
14406
14533
  return {
14407
14534
  async run() {
14408
14535
  const checkpointKey = options.runId ?? options.turnId;
14409
- const executor = createDefaultGraphExecutor({
14536
+ const executor2 = createDefaultGraphExecutor({
14410
14537
  llmNode: options.createLlmNode({
14411
14538
  llmCaller: options.llmCaller,
14412
14539
  toolRuntime: options.toolRuntime
@@ -14436,8 +14563,8 @@ function createGraphLoopHarness(options) {
14436
14563
  signal: options.signal ?? options.toolContext.abortSignal,
14437
14564
  executorLocal
14438
14565
  };
14439
- await executor.prime(checkpointKey, local, "user");
14440
- const result = await executor.runUntilYield(checkpointKey);
14566
+ await executor2.prime(checkpointKey, local, "user");
14567
+ const result = await executor2.runUntilYield(checkpointKey);
14441
14568
  return {
14442
14569
  checkpointNodeId: result.checkpoint.nodeId,
14443
14570
  stepCount: result.stepCount,