@linnlabs/linnkit 0.43.0 → 0.45.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 (93) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/cli.cjs +152 -6
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +152 -6
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager/profiles/agent/context/config.d.cts +1 -1
  7. package/dist/context-manager/profiles/agent/context/config.d.ts +1 -1
  8. package/dist/context-manager.cjs +37 -4
  9. package/dist/context-manager.cjs.map +1 -1
  10. package/dist/context-manager.js +37 -4
  11. package/dist/context-manager.js.map +1 -1
  12. package/dist/contracts/agentSpec.d.cts +5 -5
  13. package/dist/contracts/agentSpec.d.ts +5 -5
  14. package/dist/contracts/audit.d.cts +10 -10
  15. package/dist/contracts/audit.d.ts +10 -10
  16. package/dist/contracts/contextPolicy.d.cts +14 -14
  17. package/dist/contracts/contextPolicy.d.ts +14 -14
  18. package/dist/contracts/events.d.cts +121 -117
  19. package/dist/contracts/events.d.ts +121 -117
  20. package/dist/contracts/execution.d.cts +2 -2
  21. package/dist/contracts/execution.d.ts +2 -2
  22. package/dist/contracts/llm-retry.d.cts +2 -2
  23. package/dist/contracts/llm-retry.d.ts +2 -2
  24. package/dist/contracts/messages.d.cts +256 -32
  25. package/dist/contracts/messages.d.ts +256 -32
  26. package/dist/contracts/sse.d.cts +161 -97
  27. package/dist/contracts/sse.d.ts +161 -97
  28. package/dist/contracts/sub-run-trace-payload.d.cts +8 -8
  29. package/dist/contracts/sub-run-trace-payload.d.ts +8 -8
  30. package/dist/contracts/token-accounting.d.cts +12 -12
  31. package/dist/contracts/token-accounting.d.ts +12 -12
  32. package/dist/contracts.cjs +19 -2
  33. package/dist/contracts.cjs.map +1 -1
  34. package/dist/contracts.d.cts +1 -1
  35. package/dist/contracts.d.ts +1 -1
  36. package/dist/contracts.js +19 -3
  37. package/dist/contracts.js.map +1 -1
  38. package/dist/index.cjs +154 -6
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.js +154 -6
  41. package/dist/index.js.map +1 -1
  42. package/dist/quickstart.cjs +152 -6
  43. package/dist/quickstart.cjs.map +1 -1
  44. package/dist/quickstart.js +152 -6
  45. package/dist/quickstart.js.map +1 -1
  46. package/dist/runtime-kernel/events/agentEvents.d.cts +2 -2
  47. package/dist/runtime-kernel/events/agentEvents.d.ts +2 -2
  48. package/dist/runtime-kernel/events.cjs +29 -2
  49. package/dist/runtime-kernel/events.cjs.map +1 -1
  50. package/dist/runtime-kernel/events.js +29 -2
  51. package/dist/runtime-kernel/events.js.map +1 -1
  52. package/dist/runtime-kernel/graph-engine/definitions/pendingUserInput.d.cts +27 -0
  53. package/dist/runtime-kernel/graph-engine/definitions/pendingUserInput.d.ts +27 -0
  54. package/dist/runtime-kernel/graph-engine/engine.d.cts +1 -1
  55. package/dist/runtime-kernel/graph-engine/engine.d.ts +1 -1
  56. package/dist/runtime-kernel/graph-engine/index.d.cts +1 -0
  57. package/dist/runtime-kernel/graph-engine/index.d.ts +1 -0
  58. package/dist/runtime-kernel/graph-engine/nodes/toolNode.d.cts +3 -0
  59. package/dist/runtime-kernel/graph-engine/nodes/toolNode.d.ts +3 -0
  60. package/dist/runtime-kernel/graph-engine/types.d.cts +3 -0
  61. package/dist/runtime-kernel/graph-engine/types.d.ts +3 -0
  62. package/dist/runtime-kernel.cjs +152 -6
  63. package/dist/runtime-kernel.cjs.map +1 -1
  64. package/dist/runtime-kernel.d.cts +1 -0
  65. package/dist/runtime-kernel.d.ts +1 -0
  66. package/dist/runtime-kernel.js +152 -6
  67. package/dist/runtime-kernel.js.map +1 -1
  68. package/dist/testkit/agent-harness/scriptedInferenceHarness.d.cts +24 -6
  69. package/dist/testkit/agent-harness/scriptedInferenceHarness.d.ts +24 -6
  70. package/dist/testkit/scenario/graphScenario.d.cts +89 -0
  71. package/dist/testkit/scenario/graphScenario.d.ts +89 -0
  72. package/dist/testkit/scenario/pendingUserInputQueue.d.cts +26 -0
  73. package/dist/testkit/scenario/pendingUserInputQueue.d.ts +26 -0
  74. package/dist/testkit/scenario/runtimeEventRecorder.d.cts +36 -0
  75. package/dist/testkit/scenario/runtimeEventRecorder.d.ts +36 -0
  76. package/dist/testkit/scenario/scriptedToolRuntime.d.cts +51 -0
  77. package/dist/testkit/scenario/scriptedToolRuntime.d.ts +51 -0
  78. package/dist/testkit/scenario/steeringInvariants.d.cts +33 -0
  79. package/dist/testkit/scenario/steeringInvariants.d.ts +33 -0
  80. package/dist/testkit/scenario/timeline.d.cts +27 -0
  81. package/dist/testkit/scenario/timeline.d.ts +27 -0
  82. package/dist/testkit.cjs +722 -19
  83. package/dist/testkit.cjs.map +1 -1
  84. package/dist/testkit.d.cts +7 -1
  85. package/dist/testkit.d.ts +7 -1
  86. package/dist/testkit.js +714 -20
  87. package/dist/testkit.js.map +1 -1
  88. package/docs/integration/README.md +1 -0
  89. package/docs/integration/mid-run-user-input.md +73 -0
  90. package/docs/integration/realtime.md +4 -0
  91. package/docs/integration/run-supervisor.md +1 -0
  92. package/docs/integration/testing.md +40 -4
  93. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -12,6 +12,67 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
12
12
 
13
13
  ---
14
14
 
15
+ ## [0.45.0] - 2026-11-21
16
+
17
+ ### Added
18
+
19
+ - Abort grace period for tools. After a pause or cancel signal, `ToolNode`
20
+ waits at most `abortGraceMs` (new optional `ToolNodeDependencies` field,
21
+ default 3000 ms) for the running tool to
22
+ finish. A tool that ignores the signal is then treated as an `AbortError`,
23
+ exactly like a tool that honoured it: a pause leaves the call for
24
+ reconciliation before continuing, a cancel settles it as cancelled. Its late
25
+ result is discarded and never reaches history. The deadline starts only when
26
+ the signal fires and does not limit normal tool run time. Previously a
27
+ pause could stay unsettled (`status=paused`, no `pausedAt`) for as long as
28
+ such a tool ran, holding the conversation's concurrency slot.
29
+
30
+ ---
31
+
32
+ ## [0.44.0] - 2026-11-18
33
+
34
+ ### Added
35
+
36
+ - Mid-run user input. A Host can give the Graph an optional
37
+ `pendingUserInputPort` (`PendingUserInput` / `PendingUserInputPort` in the
38
+ graph exports). After a tool batch settles and before the run returns to the
39
+ model, `ToolNode` claims the pending inputs, publishes each as a `user_input`
40
+ fact with `delivery: 'mid_run'` after all the batch's tool outputs, and
41
+ commits them with the same tool boundary. It confirms after the commit and
42
+ releases them back to the Host if the commit fails. Nothing is claimed when
43
+ the batch does not return to the model, when a pause or cancel signal has
44
+ arrived, or when no step is left for another model call. Child runs should
45
+ not receive the port. Hosts without the port behave as before.
46
+ - `user_input.delivery` (optional, `'mid_run'`) and the `AiMessage` type
47
+ `user_steer`. A mid-run input enters the context as `user_steer` and is sent
48
+ to the model as an ordinary user message. The start of the current turn is
49
+ still the run's starting `user_input`, so current-turn fence assembly and
50
+ cleanup, tool history grouping and working-memory protection are unchanged.
51
+ Steers in the current run are core context and are protected from
52
+ compaction; steers from earlier runs are treated as historical user text.
53
+ - `SSEUserInputEvent` in the `SSEEvent` union. A mid-run `user_input` goes to
54
+ the realtime channel (`shouldEmitRuntimeEventToSse` is true) and
55
+ `runtimeEventToSSEEvent` projects it with the user's text and
56
+ `delivery: 'mid_run'`, so clients learn where a steer was delivered while
57
+ the run is still going. Starting inputs are still not sent back. Clients
58
+ that switch exhaustively over `SSEEvent['type']` need a `user_input` case.
59
+ - testkit: `createGraphScenario` runs the real Graph in memory (LlmNode,
60
+ ToolNode, WaitUserNode, the event bus, the persistence queue and a JSON
61
+ round-trip of every checkpoint) with a scripted model, scripted tools and an
62
+ in-memory steering queue. A scenario can start several runs in one
63
+ conversation, steer, pause, continue or cancel at any point, and returns the
64
+ run status instead of throwing. Supporting exports:
65
+ `createScriptedToolRuntime`, `createPendingUserInputQueue`,
66
+ `createRuntimeEventRecorder`, `formatRuntimeTimeline`,
67
+ `formatModelMessages`, `userInputText`, and the steering invariants
68
+ `validateSteeringInvariants` / `assertSteeringInvariants` (S1–S5).
69
+ - testkit: `createScriptedInferenceHarness` also accepts a function that
70
+ chooses each turn from the request, awaits an async `assertCall`, exposes
71
+ `getInferencePort()`, and lets a scripted tool call omit `id` (generated per
72
+ call) and pass `arguments` as an object instead of `argumentsJson`.
73
+
74
+ ---
75
+
15
76
  ## [0.43.0] - 2026-11-12
16
77
 
17
78
  ### Fixed
package/dist/cli.cjs CHANGED
@@ -346,6 +346,10 @@ var UserInputMessage = BaseMessage.extend({
346
346
  type: zod.z.literal("user_input"),
347
347
  attachments: RuntimeResourceRefs.optional()
348
348
  });
349
+ var UserSteerMessage = BaseMessage.extend({
350
+ role: zod.z.literal("user"),
351
+ type: zod.z.literal("user_steer")
352
+ });
349
353
  var UserContextMessage = BaseMessage.extend({
350
354
  role: zod.z.literal("user"),
351
355
  // 产品上下文种类由 Host fence metadata 表达,不进入框架消息枚举。
@@ -354,7 +358,7 @@ var UserContextMessage = BaseMessage.extend({
354
358
  "task_request"
355
359
  ])
356
360
  });
357
- var UserMessage = zod.z.union([UserInputMessage, UserContextMessage]);
361
+ var UserMessage = zod.z.union([UserInputMessage, UserSteerMessage, UserContextMessage]);
358
362
  var AssistantMessage = BaseMessage.extend({
359
363
  role: zod.z.literal("assistant"),
360
364
  type: zod.z.enum(["thought", "final_answer", "tool_code", "tool_calls", "task_completion"])
@@ -971,7 +975,12 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
971
975
  content: zod.z.string(),
972
976
  raw_content: zod.z.string().optional(),
973
977
  source: zod.z.enum(["user", "editor", "system"]).default("user"),
974
- attachments: RuntimeResourceRefs.optional()
978
+ attachments: RuntimeResourceRefs.optional(),
979
+ /**
980
+ * 运行中途送达的用户输入(插话)。缺省表示运行起点的输入。
981
+ * 上下文里投影为 `user_steer`,不改变“当前轮从哪条 user_input 开始”的判定。
982
+ */
983
+ delivery: zod.z.literal("mid_run").optional()
975
984
  }),
976
985
  BaseEvent.extend({
977
986
  type: zod.z.literal("thought"),
@@ -1418,6 +1427,11 @@ zod.z.object({
1418
1427
  run_id: RunIdSchema,
1419
1428
  execution_id: ExecutionIdSchema
1420
1429
  });
1430
+ var SSEUserInputEvent = BaseSSEEvent.extend({
1431
+ type: zod.z.literal("user_input"),
1432
+ content: zod.z.string(),
1433
+ delivery: zod.z.literal("mid_run")
1434
+ });
1421
1435
  var SSEThoughtEvent = BaseSSEEvent.extend({
1422
1436
  type: zod.z.literal("thought"),
1423
1437
  thought_message_id: ThoughtMessageIdSchema.optional(),
@@ -1572,6 +1586,7 @@ var SSESummarizationErrorEvent = BaseSSEEvent.extend({
1572
1586
  error: zod.z.string()
1573
1587
  });
1574
1588
  zod.z.discriminatedUnion("type", [
1589
+ SSEUserInputEvent,
1575
1590
  SSEThoughtEvent,
1576
1591
  SSEFinalAnswerChunkEvent,
1577
1592
  SSEFinalAnswerResetEvent,
@@ -2542,6 +2557,7 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2542
2557
  "runtimeEventCommitPort",
2543
2558
  "commitExecutionBoundary",
2544
2559
  "toolRecoveryPort",
2560
+ "pendingUserInputPort",
2545
2561
  "runtimeFailureFactSink",
2546
2562
  "signal",
2547
2563
  "summarizationCallbacks",
@@ -6534,6 +6550,8 @@ function describeRuntimeEventLifecycle(event) {
6534
6550
  case "run_execution_metrics":
6535
6551
  case "history_summary":
6536
6552
  return "event_bus_sse";
6553
+ case "user_input":
6554
+ return event.type === "user_input" && event.delivery === "mid_run" ? "event_bus_sse" : "none";
6537
6555
  case "audit_envelope":
6538
6556
  return "none";
6539
6557
  default:
@@ -6977,6 +6995,16 @@ function requireEventTimestamp(value) {
6977
6995
  function applyRuntimeEventToMemory(event, memory) {
6978
6996
  switch (event.type) {
6979
6997
  case "user_input": {
6998
+ if (event.delivery === "mid_run") {
6999
+ memory.appendMessage({
7000
+ id: event.id,
7001
+ role: "user",
7002
+ type: "user_steer",
7003
+ content: event.content,
7004
+ timestamp: event.timestamp
7005
+ });
7006
+ break;
7007
+ }
6980
7008
  memory.addUserMessage(event.content, event.id, event.attachments);
6981
7009
  break;
6982
7010
  }
@@ -8593,9 +8621,49 @@ function recordToolProtocolError(params) {
8593
8621
  }
8594
8622
 
8595
8623
  // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8624
+ var DEFAULT_TOOL_ABORT_GRACE_MS = 3e3;
8625
+ function settleToolWithinAbortGrace(input) {
8626
+ const { execution, signal, graceMs } = input;
8627
+ if (!signal) return execution;
8628
+ return new Promise((resolve5, reject) => {
8629
+ let timer;
8630
+ const cleanup = () => {
8631
+ if (timer !== void 0) clearTimeout(timer);
8632
+ signal.removeEventListener("abort", startGrace);
8633
+ };
8634
+ function startGrace() {
8635
+ timer = setTimeout(() => {
8636
+ cleanup();
8637
+ execution.catch(() => void 0);
8638
+ input.onAbandon?.();
8639
+ const error = new Error("Tool did not stop within the abort grace period; its late outcome is discarded.");
8640
+ error.name = "AbortError";
8641
+ reject(error);
8642
+ }, graceMs);
8643
+ }
8644
+ if (signal.aborted) startGrace();
8645
+ else signal.addEventListener("abort", startGrace, { once: true });
8646
+ execution.then(
8647
+ (value) => {
8648
+ cleanup();
8649
+ resolve5(value);
8650
+ },
8651
+ (error) => {
8652
+ cleanup();
8653
+ reject(error);
8654
+ }
8655
+ );
8656
+ });
8657
+ }
8596
8658
  async function executeRecoverableTool(input) {
8597
8659
  const local = input.state.local;
8598
- if (!local?.commitExecutionBoundary) return input.execute();
8660
+ const run = () => settleToolWithinAbortGrace({
8661
+ execution: input.execute(),
8662
+ signal: local?.signal,
8663
+ graceMs: input.abortGraceMs ?? DEFAULT_TOOL_ABORT_GRACE_MS,
8664
+ onAbandon: input.onAbandon
8665
+ });
8666
+ if (!local?.commitExecutionBoundary) return run();
8599
8667
  if (local.executingToolCallId) {
8600
8668
  if (local.executingToolCallId !== input.call.id) {
8601
8669
  throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
@@ -8608,7 +8676,7 @@ async function executeRecoverableTool(input) {
8608
8676
  }
8609
8677
  local.executingToolCallId = input.call.id;
8610
8678
  await local.commitExecutionBoundary(input.state);
8611
- const result = await input.execute();
8679
+ const result = await run();
8612
8680
  if (!result.success && isRunPauseSignal(local.signal)) {
8613
8681
  const error = new Error("Tool execution paused before its outcome was confirmed");
8614
8682
  error.name = "AbortError";
@@ -8624,6 +8692,62 @@ async function commitToolBoundary(state, result) {
8624
8692
  await state.local.commitExecutionBoundary(state);
8625
8693
  }
8626
8694
 
8695
+ // src/runtime-kernel/graph-engine/nodes/toolNode.pendingUserInput.ts
8696
+ function isPendingUserInputPort(value) {
8697
+ return !!value && typeof value === "object" && typeof Reflect.get(value, "claim") === "function" && typeof Reflect.get(value, "confirm") === "function" && typeof Reflect.get(value, "release") === "function";
8698
+ }
8699
+ function readRemainingSteps(state) {
8700
+ const value = state.local?.executorLocal?.remainingSteps;
8701
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
8702
+ }
8703
+ function readIdentity(value, field) {
8704
+ if (typeof value !== "string" || value.trim().length === 0) {
8705
+ throw new Error(`ToolNode pending user input requires ${field}`);
8706
+ }
8707
+ return value;
8708
+ }
8709
+ async function claimPendingUserInputs(state, result) {
8710
+ if (result.kind !== "route" || result.nextNodeId !== "llm") return void 0;
8711
+ const local = state.local;
8712
+ const port = local?.pendingUserInputPort;
8713
+ if (!isPendingUserInputPort(port)) return void 0;
8714
+ const signal = local?.signal;
8715
+ if (signal?.aborted || isRunPauseSignal(signal)) return void 0;
8716
+ const remainingSteps = readRemainingSteps(state);
8717
+ if (remainingSteps !== void 0 && remainingSteps < 1) return void 0;
8718
+ const inputs = await port.claim();
8719
+ if (inputs.length === 0) return void 0;
8720
+ const ids = inputs.map((input) => input.id);
8721
+ try {
8722
+ const conversationId = readIdentity(local?.conversationId, "conversationId");
8723
+ const turnId = readIdentity(local?.turnId, "turnId");
8724
+ const sink = requireRuntimeEventSink(local);
8725
+ const events = inputs.map((input) => sink(
8726
+ createUserInputEvent(readIdentity(input.id, "input id"), conversationId, turnId, input.content, {
8727
+ timestamp: input.timestamp ?? Date.now(),
8728
+ delivery: "mid_run"
8729
+ }),
8730
+ "ToolNode.pending_user_input"
8731
+ ));
8732
+ state.local = {
8733
+ ...state.local,
8734
+ history: appendWorkingHistory(parseRuntimeEvents(state.local?.history ?? []), events)
8735
+ };
8736
+ return {
8737
+ events,
8738
+ confirm: async () => {
8739
+ await port.confirm(ids);
8740
+ },
8741
+ release: async () => {
8742
+ await port.release(ids);
8743
+ }
8744
+ };
8745
+ } catch (error) {
8746
+ await port.release(ids);
8747
+ throw error;
8748
+ }
8749
+ }
8750
+
8627
8751
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8628
8752
  var logger11 = new Logger("ToolNode");
8629
8753
  function isAbortSignal(value) {
@@ -8672,7 +8796,9 @@ var ToolNode = class {
8672
8796
  auditPort;
8673
8797
  modelInputResolver;
8674
8798
  idempotencyInFlight = /* @__PURE__ */ new Map();
8799
+ abortGraceMs;
8675
8800
  constructor(dependencies) {
8801
+ this.abortGraceMs = dependencies.abortGraceMs;
8676
8802
  this.toolRuntime = dependencies.toolRuntime;
8677
8803
  this.observationPreview = dependencies.observationPreview;
8678
8804
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
@@ -8791,7 +8917,19 @@ var ToolNode = class {
8791
8917
  });
8792
8918
  throw result.error;
8793
8919
  }
8794
- await commitToolBoundary(state, result);
8920
+ const steering = await claimPendingUserInputs(state, result);
8921
+ if (steering) {
8922
+ result = { ...result, events: [...result.events ?? [], ...steering.events] };
8923
+ try {
8924
+ await commitToolBoundary(state, result);
8925
+ } catch (error) {
8926
+ await steering.release();
8927
+ throw error;
8928
+ }
8929
+ await steering.confirm();
8930
+ } else {
8931
+ await commitToolBoundary(state, result);
8932
+ }
8795
8933
  if (Array.isArray(result.events) && result.events.length > 0) {
8796
8934
  events.push(...result.events);
8797
8935
  }
@@ -8878,6 +9016,13 @@ var ToolNode = class {
8878
9016
  state,
8879
9017
  call,
8880
9018
  context: prepared.toolContext,
9019
+ abortGraceMs: this.abortGraceMs,
9020
+ onAbandon: () => logger11.warn("[ToolNode] \u5DE5\u5177\u672A\u5728\u505C\u6B62\u671F\u9650\u5185\u7ED3\u675F\uFF0C\u6309\u4E2D\u65AD\u5904\u7406\u5E76\u4E22\u5F03\u8FDF\u5230\u7ED3\u679C", {
9021
+ toolName: execution.toolName,
9022
+ toolCallId: execution.toolCallId,
9023
+ conversationId: prepared.conversationId,
9024
+ turnId: prepared.turnId
9025
+ }),
8881
9026
  execute: () => executeToolWithIdempotency({
8882
9027
  idempotencyKey: execution.idempotencyKey,
8883
9028
  inFlight: this.idempotencyInFlight,
@@ -9549,7 +9694,8 @@ function parseEngineCheckpoint(value) {
9549
9694
  "runtimeFailureFactSink",
9550
9695
  "summarizationCallbacks",
9551
9696
  "commitExecutionBoundary",
9552
- "toolRecoveryPort"
9697
+ "toolRecoveryPort",
9698
+ "pendingUserInputPort"
9553
9699
  ]) {
9554
9700
  if (result.local && Object.hasOwn(result.local, key)) {
9555
9701
  throw new Error(`Checkpoint must not contain execution capability: ${key}`);