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