@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
@@ -70,6 +70,7 @@ export { ModelReasoningConfig, REASONING_EFFORTS, ReasoningEffort, isValidReason
70
70
  export { ModelResolver } from './runtime-kernel/llm/modelResolver.cjs';
71
71
  export { ObservationPreviewContext, ObservationPreviewMeta, ObservationPreviewPort, ObservationPreviewResult, ToolCatalogPort, ToolExecutionPort, ToolExecutionResult, ToolRuntimeDefinition, ToolRuntimePort, ToolSchemaBuildRequest } from './runtime-kernel/tools/ports.cjs';
72
72
  export { PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, PrimaryPromptCapacityErrorMetadata } from './runtime-kernel/graph-engine/definitions/primaryPromptCapacityError.cjs';
73
+ export { PendingUserInput, PendingUserInputPort } from './runtime-kernel/graph-engine/definitions/pendingUserInput.cjs';
73
74
  export { PrimaryPromptCapacityAdmission, evaluatePrimaryPromptCapacity } from './runtime-kernel/graph-engine/functions/evaluatePrimaryPromptCapacity.cjs';
74
75
  export { ProviderContinuation } from './contracts/provider-continuation.cjs';
75
76
  export { RuntimeEventSubRunTracePublisher, RuntimeEventSubRunTracePublisherOptions } from './runtime-kernel/child-run-trace/runtimeEventSubRunTracePublisher.cjs';
@@ -70,6 +70,7 @@ export { ModelReasoningConfig, REASONING_EFFORTS, ReasoningEffort, isValidReason
70
70
  export { ModelResolver } from './runtime-kernel/llm/modelResolver.js';
71
71
  export { ObservationPreviewContext, ObservationPreviewMeta, ObservationPreviewPort, ObservationPreviewResult, ToolCatalogPort, ToolExecutionPort, ToolExecutionResult, ToolRuntimeDefinition, ToolRuntimePort, ToolSchemaBuildRequest } from './runtime-kernel/tools/ports.js';
72
72
  export { PRIMARY_PROMPT_CAPACITY_ERROR_CODE, PrimaryPromptCapacityError, PrimaryPromptCapacityErrorMetadata } from './runtime-kernel/graph-engine/definitions/primaryPromptCapacityError.js';
73
+ export { PendingUserInput, PendingUserInputPort } from './runtime-kernel/graph-engine/definitions/pendingUserInput.js';
73
74
  export { PrimaryPromptCapacityAdmission, evaluatePrimaryPromptCapacity } from './runtime-kernel/graph-engine/functions/evaluatePrimaryPromptCapacity.js';
74
75
  export { ProviderContinuation } from './contracts/provider-continuation.js';
75
76
  export { RuntimeEventSubRunTracePublisher, RuntimeEventSubRunTracePublisherOptions } from './runtime-kernel/child-run-trace/runtimeEventSubRunTracePublisher.js';
@@ -900,6 +900,10 @@ var UserInputMessage = BaseMessage.extend({
900
900
  type: z.literal("user_input"),
901
901
  attachments: RuntimeResourceRefs.optional()
902
902
  });
903
+ var UserSteerMessage = BaseMessage.extend({
904
+ role: z.literal("user"),
905
+ type: z.literal("user_steer")
906
+ });
903
907
  var UserContextMessage = BaseMessage.extend({
904
908
  role: z.literal("user"),
905
909
  // 产品上下文种类由 Host fence metadata 表达,不进入框架消息枚举。
@@ -908,7 +912,7 @@ var UserContextMessage = BaseMessage.extend({
908
912
  "task_request"
909
913
  ])
910
914
  });
911
- var UserMessage = z.union([UserInputMessage, UserContextMessage]);
915
+ var UserMessage = z.union([UserInputMessage, UserSteerMessage, UserContextMessage]);
912
916
  var AssistantMessage = BaseMessage.extend({
913
917
  role: z.literal("assistant"),
914
918
  type: z.enum(["thought", "final_answer", "tool_code", "tool_calls", "task_completion"])
@@ -1510,7 +1514,12 @@ var RuntimeEventShape = z.discriminatedUnion("type", [
1510
1514
  content: z.string(),
1511
1515
  raw_content: z.string().optional(),
1512
1516
  source: z.enum(["user", "editor", "system"]).default("user"),
1513
- attachments: RuntimeResourceRefs.optional()
1517
+ attachments: RuntimeResourceRefs.optional(),
1518
+ /**
1519
+ * 运行中途送达的用户输入(插话)。缺省表示运行起点的输入。
1520
+ * 上下文里投影为 `user_steer`,不改变“当前轮从哪条 user_input 开始”的判定。
1521
+ */
1522
+ delivery: z.literal("mid_run").optional()
1514
1523
  }),
1515
1524
  BaseEvent.extend({
1516
1525
  type: z.literal("thought"),
@@ -1970,6 +1979,11 @@ z.object({
1970
1979
  run_id: RunIdSchema,
1971
1980
  execution_id: ExecutionIdSchema
1972
1981
  });
1982
+ var SSEUserInputEvent = BaseSSEEvent.extend({
1983
+ type: z.literal("user_input"),
1984
+ content: z.string(),
1985
+ delivery: z.literal("mid_run")
1986
+ });
1973
1987
  var SSEThoughtEvent = BaseSSEEvent.extend({
1974
1988
  type: z.literal("thought"),
1975
1989
  thought_message_id: ThoughtMessageIdSchema.optional(),
@@ -2124,6 +2138,7 @@ var SSESummarizationErrorEvent = BaseSSEEvent.extend({
2124
2138
  error: z.string()
2125
2139
  });
2126
2140
  z.discriminatedUnion("type", [
2141
+ SSEUserInputEvent,
2127
2142
  SSEThoughtEvent,
2128
2143
  SSEFinalAnswerChunkEvent,
2129
2144
  SSEFinalAnswerResetEvent,
@@ -2446,6 +2461,7 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2446
2461
  "runtimeEventCommitPort",
2447
2462
  "commitExecutionBoundary",
2448
2463
  "toolRecoveryPort",
2464
+ "pendingUserInputPort",
2449
2465
  "runtimeFailureFactSink",
2450
2466
  "signal",
2451
2467
  "summarizationCallbacks",
@@ -6656,6 +6672,8 @@ function describeRuntimeEventLifecycle(event) {
6656
6672
  case "run_execution_metrics":
6657
6673
  case "history_summary":
6658
6674
  return "event_bus_sse";
6675
+ case "user_input":
6676
+ return event.type === "user_input" && event.delivery === "mid_run" ? "event_bus_sse" : "none";
6659
6677
  case "audit_envelope":
6660
6678
  return "none";
6661
6679
  default:
@@ -7099,6 +7117,16 @@ function requireEventTimestamp(value) {
7099
7117
  function applyRuntimeEventToMemory(event, memory) {
7100
7118
  switch (event.type) {
7101
7119
  case "user_input": {
7120
+ if (event.delivery === "mid_run") {
7121
+ memory.appendMessage({
7122
+ id: event.id,
7123
+ role: "user",
7124
+ type: "user_steer",
7125
+ content: event.content,
7126
+ timestamp: event.timestamp
7127
+ });
7128
+ break;
7129
+ }
7102
7130
  memory.addUserMessage(event.content, event.id, event.attachments);
7103
7131
  break;
7104
7132
  }
@@ -8775,9 +8803,49 @@ function recordToolProtocolError(params) {
8775
8803
  }
8776
8804
 
8777
8805
  // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8806
+ var DEFAULT_TOOL_ABORT_GRACE_MS = 3e3;
8807
+ function settleToolWithinAbortGrace(input) {
8808
+ const { execution, signal, graceMs } = input;
8809
+ if (!signal) return execution;
8810
+ return new Promise((resolve, reject) => {
8811
+ let timer;
8812
+ const cleanup = () => {
8813
+ if (timer !== void 0) clearTimeout(timer);
8814
+ signal.removeEventListener("abort", startGrace);
8815
+ };
8816
+ function startGrace() {
8817
+ timer = setTimeout(() => {
8818
+ cleanup();
8819
+ execution.catch(() => void 0);
8820
+ input.onAbandon?.();
8821
+ const error = new Error("Tool did not stop within the abort grace period; its late outcome is discarded.");
8822
+ error.name = "AbortError";
8823
+ reject(error);
8824
+ }, graceMs);
8825
+ }
8826
+ if (signal.aborted) startGrace();
8827
+ else signal.addEventListener("abort", startGrace, { once: true });
8828
+ execution.then(
8829
+ (value) => {
8830
+ cleanup();
8831
+ resolve(value);
8832
+ },
8833
+ (error) => {
8834
+ cleanup();
8835
+ reject(error);
8836
+ }
8837
+ );
8838
+ });
8839
+ }
8778
8840
  async function executeRecoverableTool(input) {
8779
8841
  const local = input.state.local;
8780
- if (!local?.commitExecutionBoundary) return input.execute();
8842
+ const run = () => settleToolWithinAbortGrace({
8843
+ execution: input.execute(),
8844
+ signal: local?.signal,
8845
+ graceMs: input.abortGraceMs ?? DEFAULT_TOOL_ABORT_GRACE_MS,
8846
+ onAbandon: input.onAbandon
8847
+ });
8848
+ if (!local?.commitExecutionBoundary) return run();
8781
8849
  if (local.executingToolCallId) {
8782
8850
  if (local.executingToolCallId !== input.call.id) {
8783
8851
  throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
@@ -8790,7 +8858,7 @@ async function executeRecoverableTool(input) {
8790
8858
  }
8791
8859
  local.executingToolCallId = input.call.id;
8792
8860
  await local.commitExecutionBoundary(input.state);
8793
- const result = await input.execute();
8861
+ const result = await run();
8794
8862
  if (!result.success && isRunPauseSignal(local.signal)) {
8795
8863
  const error = new Error("Tool execution paused before its outcome was confirmed");
8796
8864
  error.name = "AbortError";
@@ -8806,6 +8874,62 @@ async function commitToolBoundary(state, result) {
8806
8874
  await state.local.commitExecutionBoundary(state);
8807
8875
  }
8808
8876
 
8877
+ // src/runtime-kernel/graph-engine/nodes/toolNode.pendingUserInput.ts
8878
+ function isPendingUserInputPort(value) {
8879
+ return !!value && typeof value === "object" && typeof Reflect.get(value, "claim") === "function" && typeof Reflect.get(value, "confirm") === "function" && typeof Reflect.get(value, "release") === "function";
8880
+ }
8881
+ function readRemainingSteps(state) {
8882
+ const value = state.local?.executorLocal?.remainingSteps;
8883
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
8884
+ }
8885
+ function readIdentity(value, field) {
8886
+ if (typeof value !== "string" || value.trim().length === 0) {
8887
+ throw new Error(`ToolNode pending user input requires ${field}`);
8888
+ }
8889
+ return value;
8890
+ }
8891
+ async function claimPendingUserInputs(state, result) {
8892
+ if (result.kind !== "route" || result.nextNodeId !== "llm") return void 0;
8893
+ const local = state.local;
8894
+ const port = local?.pendingUserInputPort;
8895
+ if (!isPendingUserInputPort(port)) return void 0;
8896
+ const signal = local?.signal;
8897
+ if (signal?.aborted || isRunPauseSignal(signal)) return void 0;
8898
+ const remainingSteps = readRemainingSteps(state);
8899
+ if (remainingSteps !== void 0 && remainingSteps < 1) return void 0;
8900
+ const inputs = await port.claim();
8901
+ if (inputs.length === 0) return void 0;
8902
+ const ids = inputs.map((input) => input.id);
8903
+ try {
8904
+ const conversationId = readIdentity(local?.conversationId, "conversationId");
8905
+ const turnId = readIdentity(local?.turnId, "turnId");
8906
+ const sink = requireRuntimeEventSink(local);
8907
+ const events = inputs.map((input) => sink(
8908
+ createUserInputEvent(readIdentity(input.id, "input id"), conversationId, turnId, input.content, {
8909
+ timestamp: input.timestamp ?? Date.now(),
8910
+ delivery: "mid_run"
8911
+ }),
8912
+ "ToolNode.pending_user_input"
8913
+ ));
8914
+ state.local = {
8915
+ ...state.local,
8916
+ history: appendWorkingHistory(parseRuntimeEvents(state.local?.history ?? []), events)
8917
+ };
8918
+ return {
8919
+ events,
8920
+ confirm: async () => {
8921
+ await port.confirm(ids);
8922
+ },
8923
+ release: async () => {
8924
+ await port.release(ids);
8925
+ }
8926
+ };
8927
+ } catch (error) {
8928
+ await port.release(ids);
8929
+ throw error;
8930
+ }
8931
+ }
8932
+
8809
8933
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
8810
8934
  var logger11 = new Logger("ToolNode");
8811
8935
  function isAbortSignal(value) {
@@ -8854,7 +8978,9 @@ var ToolNode = class {
8854
8978
  auditPort;
8855
8979
  modelInputResolver;
8856
8980
  idempotencyInFlight = /* @__PURE__ */ new Map();
8981
+ abortGraceMs;
8857
8982
  constructor(dependencies) {
8983
+ this.abortGraceMs = dependencies.abortGraceMs;
8858
8984
  this.toolRuntime = dependencies.toolRuntime;
8859
8985
  this.observationPreview = dependencies.observationPreview;
8860
8986
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
@@ -8973,7 +9099,19 @@ var ToolNode = class {
8973
9099
  });
8974
9100
  throw result.error;
8975
9101
  }
8976
- await commitToolBoundary(state, result);
9102
+ const steering = await claimPendingUserInputs(state, result);
9103
+ if (steering) {
9104
+ result = { ...result, events: [...result.events ?? [], ...steering.events] };
9105
+ try {
9106
+ await commitToolBoundary(state, result);
9107
+ } catch (error) {
9108
+ await steering.release();
9109
+ throw error;
9110
+ }
9111
+ await steering.confirm();
9112
+ } else {
9113
+ await commitToolBoundary(state, result);
9114
+ }
8977
9115
  if (Array.isArray(result.events) && result.events.length > 0) {
8978
9116
  events.push(...result.events);
8979
9117
  }
@@ -9060,6 +9198,13 @@ var ToolNode = class {
9060
9198
  state,
9061
9199
  call,
9062
9200
  context: prepared.toolContext,
9201
+ abortGraceMs: this.abortGraceMs,
9202
+ 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", {
9203
+ toolName: execution.toolName,
9204
+ toolCallId: execution.toolCallId,
9205
+ conversationId: prepared.conversationId,
9206
+ turnId: prepared.turnId
9207
+ }),
9063
9208
  execute: () => executeToolWithIdempotency({
9064
9209
  idempotencyKey: execution.idempotencyKey,
9065
9210
  inFlight: this.idempotencyInFlight,
@@ -9731,7 +9876,8 @@ function parseEngineCheckpoint(value) {
9731
9876
  "runtimeFailureFactSink",
9732
9877
  "summarizationCallbacks",
9733
9878
  "commitExecutionBoundary",
9734
- "toolRecoveryPort"
9879
+ "toolRecoveryPort",
9880
+ "pendingUserInputPort"
9735
9881
  ]) {
9736
9882
  if (result.local && Object.hasOwn(result.local, key)) {
9737
9883
  throw new Error(`Checkpoint must not contain execution capability: ${key}`);