@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/dist/testkit.cjs CHANGED
@@ -1090,6 +1090,10 @@ var UserInputMessage = BaseMessage.extend({
1090
1090
  type: zod.z.literal("user_input"),
1091
1091
  attachments: RuntimeResourceRefs.optional()
1092
1092
  });
1093
+ var UserSteerMessage = BaseMessage.extend({
1094
+ role: zod.z.literal("user"),
1095
+ type: zod.z.literal("user_steer")
1096
+ });
1093
1097
  var UserContextMessage = BaseMessage.extend({
1094
1098
  role: zod.z.literal("user"),
1095
1099
  // 产品上下文种类由 Host fence metadata 表达,不进入框架消息枚举。
@@ -1098,7 +1102,7 @@ var UserContextMessage = BaseMessage.extend({
1098
1102
  "task_request"
1099
1103
  ])
1100
1104
  });
1101
- var UserMessage = zod.z.union([UserInputMessage, UserContextMessage]);
1105
+ var UserMessage = zod.z.union([UserInputMessage, UserSteerMessage, UserContextMessage]);
1102
1106
  var AssistantMessage = BaseMessage.extend({
1103
1107
  role: zod.z.literal("assistant"),
1104
1108
  type: zod.z.enum(["thought", "final_answer", "tool_code", "tool_calls", "task_completion"])
@@ -1700,7 +1704,12 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
1700
1704
  content: zod.z.string(),
1701
1705
  raw_content: zod.z.string().optional(),
1702
1706
  source: zod.z.enum(["user", "editor", "system"]).default("user"),
1703
- attachments: RuntimeResourceRefs.optional()
1707
+ attachments: RuntimeResourceRefs.optional(),
1708
+ /**
1709
+ * 运行中途送达的用户输入(插话)。缺省表示运行起点的输入。
1710
+ * 上下文里投影为 `user_steer`,不改变“当前轮从哪条 user_input 开始”的判定。
1711
+ */
1712
+ delivery: zod.z.literal("mid_run").optional()
1704
1713
  }),
1705
1714
  BaseEvent.extend({
1706
1715
  type: zod.z.literal("thought"),
@@ -2160,6 +2169,11 @@ zod.z.object({
2160
2169
  run_id: RunIdSchema,
2161
2170
  execution_id: ExecutionIdSchema
2162
2171
  });
2172
+ var SSEUserInputEvent = BaseSSEEvent.extend({
2173
+ type: zod.z.literal("user_input"),
2174
+ content: zod.z.string(),
2175
+ delivery: zod.z.literal("mid_run")
2176
+ });
2163
2177
  var SSEThoughtEvent = BaseSSEEvent.extend({
2164
2178
  type: zod.z.literal("thought"),
2165
2179
  thought_message_id: ThoughtMessageIdSchema.optional(),
@@ -2314,6 +2328,7 @@ var SSESummarizationErrorEvent = BaseSSEEvent.extend({
2314
2328
  error: zod.z.string()
2315
2329
  });
2316
2330
  zod.z.discriminatedUnion("type", [
2331
+ SSEUserInputEvent,
2317
2332
  SSEThoughtEvent,
2318
2333
  SSEFinalAnswerChunkEvent,
2319
2334
  SSEFinalAnswerResetEvent,
@@ -2636,6 +2651,7 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
2636
2651
  "runtimeEventCommitPort",
2637
2652
  "commitExecutionBoundary",
2638
2653
  "toolRecoveryPort",
2654
+ "pendingUserInputPort",
2639
2655
  "runtimeFailureFactSink",
2640
2656
  "signal",
2641
2657
  "summarizationCallbacks",
@@ -6846,6 +6862,8 @@ function describeRuntimeEventLifecycle(event) {
6846
6862
  case "run_execution_metrics":
6847
6863
  case "history_summary":
6848
6864
  return "event_bus_sse";
6865
+ case "user_input":
6866
+ return event.type === "user_input" && event.delivery === "mid_run" ? "event_bus_sse" : "none";
6849
6867
  case "audit_envelope":
6850
6868
  return "none";
6851
6869
  default:
@@ -7289,6 +7307,16 @@ function requireEventTimestamp(value) {
7289
7307
  function applyRuntimeEventToMemory(event, memory) {
7290
7308
  switch (event.type) {
7291
7309
  case "user_input": {
7310
+ if (event.delivery === "mid_run") {
7311
+ memory.appendMessage({
7312
+ id: event.id,
7313
+ role: "user",
7314
+ type: "user_steer",
7315
+ content: event.content,
7316
+ timestamp: event.timestamp
7317
+ });
7318
+ break;
7319
+ }
7292
7320
  memory.addUserMessage(event.content, event.id, event.attachments);
7293
7321
  break;
7294
7322
  }
@@ -8965,9 +8993,49 @@ function recordToolProtocolError(params) {
8965
8993
  }
8966
8994
 
8967
8995
  // src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
8996
+ var DEFAULT_TOOL_ABORT_GRACE_MS = 3e3;
8997
+ function settleToolWithinAbortGrace(input) {
8998
+ const { execution, signal, graceMs } = input;
8999
+ if (!signal) return execution;
9000
+ return new Promise((resolve, reject) => {
9001
+ let timer;
9002
+ const cleanup = () => {
9003
+ if (timer !== void 0) clearTimeout(timer);
9004
+ signal.removeEventListener("abort", startGrace);
9005
+ };
9006
+ function startGrace() {
9007
+ timer = setTimeout(() => {
9008
+ cleanup();
9009
+ execution.catch(() => void 0);
9010
+ input.onAbandon?.();
9011
+ const error = new Error("Tool did not stop within the abort grace period; its late outcome is discarded.");
9012
+ error.name = "AbortError";
9013
+ reject(error);
9014
+ }, graceMs);
9015
+ }
9016
+ if (signal.aborted) startGrace();
9017
+ else signal.addEventListener("abort", startGrace, { once: true });
9018
+ execution.then(
9019
+ (value) => {
9020
+ cleanup();
9021
+ resolve(value);
9022
+ },
9023
+ (error) => {
9024
+ cleanup();
9025
+ reject(error);
9026
+ }
9027
+ );
9028
+ });
9029
+ }
8968
9030
  async function executeRecoverableTool(input) {
8969
9031
  const local = input.state.local;
8970
- if (!local?.commitExecutionBoundary) return input.execute();
9032
+ const run = () => settleToolWithinAbortGrace({
9033
+ execution: input.execute(),
9034
+ signal: local?.signal,
9035
+ graceMs: input.abortGraceMs ?? DEFAULT_TOOL_ABORT_GRACE_MS,
9036
+ onAbandon: input.onAbandon
9037
+ });
9038
+ if (!local?.commitExecutionBoundary) return run();
8971
9039
  if (local.executingToolCallId) {
8972
9040
  if (local.executingToolCallId !== input.call.id) {
8973
9041
  throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
@@ -8980,7 +9048,7 @@ async function executeRecoverableTool(input) {
8980
9048
  }
8981
9049
  local.executingToolCallId = input.call.id;
8982
9050
  await local.commitExecutionBoundary(input.state);
8983
- const result = await input.execute();
9051
+ const result = await run();
8984
9052
  if (!result.success && isRunPauseSignal(local.signal)) {
8985
9053
  const error = new Error("Tool execution paused before its outcome was confirmed");
8986
9054
  error.name = "AbortError";
@@ -8996,6 +9064,62 @@ async function commitToolBoundary(state, result) {
8996
9064
  await state.local.commitExecutionBoundary(state);
8997
9065
  }
8998
9066
 
9067
+ // src/runtime-kernel/graph-engine/nodes/toolNode.pendingUserInput.ts
9068
+ function isPendingUserInputPort(value) {
9069
+ return !!value && typeof value === "object" && typeof Reflect.get(value, "claim") === "function" && typeof Reflect.get(value, "confirm") === "function" && typeof Reflect.get(value, "release") === "function";
9070
+ }
9071
+ function readRemainingSteps(state) {
9072
+ const value = state.local?.executorLocal?.remainingSteps;
9073
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
9074
+ }
9075
+ function readIdentity(value, field) {
9076
+ if (typeof value !== "string" || value.trim().length === 0) {
9077
+ throw new Error(`ToolNode pending user input requires ${field}`);
9078
+ }
9079
+ return value;
9080
+ }
9081
+ async function claimPendingUserInputs(state, result) {
9082
+ if (result.kind !== "route" || result.nextNodeId !== "llm") return void 0;
9083
+ const local = state.local;
9084
+ const port = local?.pendingUserInputPort;
9085
+ if (!isPendingUserInputPort(port)) return void 0;
9086
+ const signal = local?.signal;
9087
+ if (signal?.aborted || isRunPauseSignal(signal)) return void 0;
9088
+ const remainingSteps = readRemainingSteps(state);
9089
+ if (remainingSteps !== void 0 && remainingSteps < 1) return void 0;
9090
+ const inputs = await port.claim();
9091
+ if (inputs.length === 0) return void 0;
9092
+ const ids = inputs.map((input) => input.id);
9093
+ try {
9094
+ const conversationId = readIdentity(local?.conversationId, "conversationId");
9095
+ const turnId = readIdentity(local?.turnId, "turnId");
9096
+ const sink = requireRuntimeEventSink(local);
9097
+ const events = inputs.map((input) => sink(
9098
+ createUserInputEvent(readIdentity(input.id, "input id"), conversationId, turnId, input.content, {
9099
+ timestamp: input.timestamp ?? Date.now(),
9100
+ delivery: "mid_run"
9101
+ }),
9102
+ "ToolNode.pending_user_input"
9103
+ ));
9104
+ state.local = {
9105
+ ...state.local,
9106
+ history: appendWorkingHistory(parseRuntimeEvents(state.local?.history ?? []), events)
9107
+ };
9108
+ return {
9109
+ events,
9110
+ confirm: async () => {
9111
+ await port.confirm(ids);
9112
+ },
9113
+ release: async () => {
9114
+ await port.release(ids);
9115
+ }
9116
+ };
9117
+ } catch (error) {
9118
+ await port.release(ids);
9119
+ throw error;
9120
+ }
9121
+ }
9122
+
8999
9123
  // src/runtime-kernel/graph-engine/nodes/toolNode.ts
9000
9124
  var logger11 = new Logger("ToolNode");
9001
9125
  function isAbortSignal(value) {
@@ -9044,7 +9168,9 @@ var ToolNode = class {
9044
9168
  auditPort;
9045
9169
  modelInputResolver;
9046
9170
  idempotencyInFlight = /* @__PURE__ */ new Map();
9171
+ abortGraceMs;
9047
9172
  constructor(dependencies) {
9173
+ this.abortGraceMs = dependencies.abortGraceMs;
9048
9174
  this.toolRuntime = dependencies.toolRuntime;
9049
9175
  this.observationPreview = dependencies.observationPreview;
9050
9176
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
@@ -9163,7 +9289,19 @@ var ToolNode = class {
9163
9289
  });
9164
9290
  throw result.error;
9165
9291
  }
9166
- await commitToolBoundary(state, result);
9292
+ const steering = await claimPendingUserInputs(state, result);
9293
+ if (steering) {
9294
+ result = { ...result, events: [...result.events ?? [], ...steering.events] };
9295
+ try {
9296
+ await commitToolBoundary(state, result);
9297
+ } catch (error) {
9298
+ await steering.release();
9299
+ throw error;
9300
+ }
9301
+ await steering.confirm();
9302
+ } else {
9303
+ await commitToolBoundary(state, result);
9304
+ }
9167
9305
  if (Array.isArray(result.events) && result.events.length > 0) {
9168
9306
  events.push(...result.events);
9169
9307
  }
@@ -9250,6 +9388,13 @@ var ToolNode = class {
9250
9388
  state,
9251
9389
  call,
9252
9390
  context: prepared.toolContext,
9391
+ abortGraceMs: this.abortGraceMs,
9392
+ 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", {
9393
+ toolName: execution.toolName,
9394
+ toolCallId: execution.toolCallId,
9395
+ conversationId: prepared.conversationId,
9396
+ turnId: prepared.turnId
9397
+ }),
9253
9398
  execute: () => executeToolWithIdempotency({
9254
9399
  idempotencyKey: execution.idempotencyKey,
9255
9400
  inFlight: this.idempotencyInFlight,
@@ -9921,7 +10066,8 @@ function parseEngineCheckpoint(value) {
9921
10066
  "runtimeFailureFactSink",
9922
10067
  "summarizationCallbacks",
9923
10068
  "commitExecutionBoundary",
9924
- "toolRecoveryPort"
10069
+ "toolRecoveryPort",
10070
+ "pendingUserInputPort"
9925
10071
  ]) {
9926
10072
  if (result.local && Object.hasOwn(result.local, key)) {
9927
10073
  throw new Error(`Checkpoint must not contain execution capability: ${key}`);
@@ -14754,31 +14900,37 @@ function createScriptedModelCatalog() {
14754
14900
  getModelsByUIVisibility: () => []
14755
14901
  };
14756
14902
  }
14903
+ function argumentsJsonOf(toolCall) {
14904
+ if (toolCall.argumentsJson !== void 0) return toolCall.argumentsJson;
14905
+ return JSON.stringify(toolCall.arguments ?? {});
14906
+ }
14757
14907
  function parseArguments(toolCall) {
14758
- const parsed = JSON.parse(toolCall.argumentsJson);
14908
+ const parsed = JSON.parse(argumentsJsonOf(toolCall));
14759
14909
  const record = toSerializableJsonRecord(parsed);
14760
14910
  if (!record) {
14761
14911
  throw new Error(`[scriptedInferenceHarness] ${toolCall.name} arguments \u5FC5\u987B\u662F JSON object\u3002`);
14762
14912
  }
14763
14913
  return record;
14764
14914
  }
14765
- function createScriptedInferenceHarness(turns, options = {}) {
14766
- const streamTurns = [...turns];
14915
+ function createScriptedInferenceHarness(script, options = {}) {
14916
+ const streamTurns = typeof script === "function" ? void 0 : [...script];
14917
+ const respond = typeof script === "function" ? script : void 0;
14767
14918
  const calls = [];
14768
14919
  const inferencePort = {
14769
14920
  async *stream(request) {
14770
- const turn = streamTurns.shift();
14771
- if (!turn) {
14772
- throw new Error("[scriptedInferenceHarness] \u6CA1\u6709\u53EF\u6D88\u8D39\u7684 scripted turn\uFF0C\u8BF7\u8865\u9F50\u811A\u672C\u3002");
14773
- }
14774
14921
  const call = {
14775
14922
  request,
14776
14923
  modelId: request.model_id,
14777
14924
  messages: request.messages,
14778
14925
  options: callOptions(request)
14779
14926
  };
14927
+ const callIndex = calls.length;
14928
+ const turn = respond ? await respond(call, callIndex) : streamTurns?.shift();
14929
+ if (!turn) {
14930
+ throw new Error("[scriptedInferenceHarness] \u6CA1\u6709\u53EF\u6D88\u8D39\u7684 scripted turn\uFF0C\u8BF7\u8865\u9F50\u811A\u672C\u3002");
14931
+ }
14780
14932
  calls.push(call);
14781
- turn.assertCall?.(call);
14933
+ await turn.assertCall?.(call);
14782
14934
  yield { type: "start", model_id: request.model_id, attempt_id: request.invocation.attempt_id };
14783
14935
  if (turn.failure) {
14784
14936
  yield { type: "failure", ...turn.failure };
@@ -14815,23 +14967,24 @@ function createScriptedInferenceHarness(turns, options = {}) {
14815
14967
  }
14816
14968
  for (const [position, toolCall] of (turn.toolCalls ?? []).entries()) {
14817
14969
  const index = toolCall.index ?? position;
14970
+ const id = toolCall.id ?? `call_${callIndex + 1}_${position + 1}`;
14818
14971
  yield {
14819
14972
  type: "tool_call_start",
14820
14973
  index,
14821
14974
  part_index: nextAssistantPartIndex++,
14822
- id: toolCall.id,
14975
+ id,
14823
14976
  name: toolCall.name
14824
14977
  };
14825
14978
  yield {
14826
14979
  type: "tool_argument_delta",
14827
14980
  index,
14828
- json_delta: toolCall.argumentsJson
14981
+ json_delta: argumentsJsonOf(toolCall)
14829
14982
  };
14830
14983
  yield {
14831
14984
  type: "tool_call_end",
14832
14985
  index,
14833
14986
  call: {
14834
- id: toolCall.id,
14987
+ id,
14835
14988
  name: toolCall.name,
14836
14989
  arguments: parseArguments(toolCall),
14837
14990
  ...toolCall.continuations?.length ? { continuation: toolCall.continuations } : {}
@@ -14858,8 +15011,9 @@ function createScriptedInferenceHarness(turns, options = {}) {
14858
15011
  getCalls: () => [...calls],
14859
15012
  getConsumedTurnCount: () => calls.length,
14860
15013
  getLlmCaller: () => llmCaller,
15014
+ getInferencePort: () => inferencePort,
14861
15015
  assertAllTurnsConsumed() {
14862
- if (streamTurns.length > 0) {
15016
+ if (streamTurns && streamTurns.length > 0) {
14863
15017
  throw new Error(
14864
15018
  `[scriptedInferenceHarness] \u4ECD\u6709 ${streamTurns.length} \u4E2A scripted turn \u672A\u88AB\u6D88\u8D39\uFF0C\u8BF7\u68C0\u67E5\u56FE\u6267\u884C\u662F\u5426\u63D0\u524D\u7ED3\u675F\u3002`
14865
15019
  );
@@ -14930,6 +15084,8 @@ var MessageFormatter = class {
14930
15084
  content,
14931
15085
  ...message.attachments ? { attachments: message.attachments } : {}
14932
15086
  };
15087
+ case "user_steer":
15088
+ return { role: "user", content };
14933
15089
  case "context_injection": {
14934
15090
  const fenceKind = metadata?.fenceKind;
14935
15091
  if (!fenceKind) {
@@ -14982,7 +15138,10 @@ var MessageFormatter = class {
14982
15138
  }
14983
15139
  }
14984
15140
  };
14985
- new MessageFormatter();
15141
+ var messageFormatter = new MessageFormatter();
15142
+ function formatAgentLlmMessages(messages, options = {}) {
15143
+ return messageFormatter.format(messages, { nativeTools: true, ...options });
15144
+ }
14986
15145
  zod.z.object({
14987
15146
  systemPrompt: zod.z.string(),
14988
15147
  messages: zod.z.array(AiMessage)
@@ -15124,6 +15283,7 @@ function convertAiMessageToEvent(message, context) {
15124
15283
  type: "user_input",
15125
15284
  content: message.content,
15126
15285
  source: "user",
15286
+ ...message.type === "user_steer" ? { delivery: "mid_run" } : {},
15127
15287
  ...message.type === "user_input" && message.attachments ? { attachments: message.attachments } : {}
15128
15288
  };
15129
15289
  return event;
@@ -16294,6 +16454,540 @@ function createMockTokenizerPort(options = {}) {
16294
16454
  };
16295
16455
  }
16296
16456
 
16457
+ // src/testkit/scenario/pendingUserInputQueue.ts
16458
+ function createPendingUserInputQueue() {
16459
+ let pending = [];
16460
+ const claimed = /* @__PURE__ */ new Map();
16461
+ const delivered = [];
16462
+ let sequence = 0;
16463
+ const port = {
16464
+ claim() {
16465
+ const taken = pending;
16466
+ pending = [];
16467
+ for (const input of taken) claimed.set(input.id, input);
16468
+ return taken;
16469
+ },
16470
+ confirm(ids) {
16471
+ for (const id of ids) {
16472
+ const input = claimed.get(id);
16473
+ if (!input) continue;
16474
+ claimed.delete(id);
16475
+ delivered.push(input);
16476
+ }
16477
+ },
16478
+ release(ids) {
16479
+ const returned = ids.flatMap((id) => {
16480
+ const input = claimed.get(id);
16481
+ claimed.delete(id);
16482
+ return input ? [input] : [];
16483
+ });
16484
+ pending = [...returned, ...pending];
16485
+ }
16486
+ };
16487
+ return {
16488
+ port,
16489
+ submit(content, options = {}) {
16490
+ sequence += 1;
16491
+ const id = options.id ?? `steer_${sequence}`;
16492
+ pending.push({ id, content, timestamp: options.timestamp ?? Date.now() });
16493
+ return id;
16494
+ },
16495
+ withdraw(id) {
16496
+ if (pending.some((input) => input.id === id)) {
16497
+ pending = pending.filter((input) => input.id !== id);
16498
+ return "withdrawn";
16499
+ }
16500
+ if (claimed.has(id)) return "claimed";
16501
+ if (delivered.some((input) => input.id === id)) return "delivered";
16502
+ return "unknown";
16503
+ },
16504
+ drain() {
16505
+ const taken = pending;
16506
+ pending = [];
16507
+ return taken;
16508
+ },
16509
+ pending: () => [...pending],
16510
+ claimed: () => [...claimed.values()],
16511
+ delivered: () => [...delivered]
16512
+ };
16513
+ }
16514
+
16515
+ // src/testkit/scenario/runtimeEventRecorder.ts
16516
+ function routingIdentityOf(options) {
16517
+ const child = options.parentRunId !== void 0;
16518
+ return {
16519
+ run_id: RunIdSchema.parse(options.runId ?? "run"),
16520
+ ...child ? { parent_run_id: RunIdSchema.parse(options.parentRunId) } : {},
16521
+ lane: options.lane ?? (child ? "child" : "foreground"),
16522
+ visibility: options.visibility ?? (child ? "parent-trace" : "conversation")
16523
+ };
16524
+ }
16525
+ function createRuntimeEventRecorder(options = {}) {
16526
+ const sequencer = new execution_exports.EventSequencer(options.conversationId ?? "conversation");
16527
+ const eventBus = new execution_exports.EventBus(sequencer.getExecutionId());
16528
+ const events = [];
16529
+ eventBus.on("event", (envelope) => events.push(envelope.payload));
16530
+ const publisher = new execution_exports.RuntimeEventPublisher(eventBus, sequencer, routingIdentityOf(options));
16531
+ return {
16532
+ sink: (event, source) => publisher.publish(event, source),
16533
+ events,
16534
+ eventBus,
16535
+ sequencer,
16536
+ publisher,
16537
+ publisherFor: (identity) => new execution_exports.RuntimeEventPublisher(eventBus, sequencer, identity),
16538
+ close: () => eventBus.close()
16539
+ };
16540
+ }
16541
+
16542
+ // src/testkit/scenario/scriptedToolRuntime.ts
16543
+ var EMPTY_PARAMETERS = { type: "object", properties: {} };
16544
+ function specOf(entry) {
16545
+ return typeof entry === "function" ? { run: entry } : entry;
16546
+ }
16547
+ function toResult(outcome, toolName, durationMs) {
16548
+ if (typeof outcome === "string") {
16549
+ return { success: true, result: JSON.stringify({ data: {}, observation: outcome }), durationMs };
16550
+ }
16551
+ if (outcome.error !== void 0) {
16552
+ return {
16553
+ success: false,
16554
+ error: outcome.error,
16555
+ ...outcome.errorCode ? { errorCode: outcome.errorCode } : {},
16556
+ errorKind: "execution",
16557
+ durationMs
16558
+ };
16559
+ }
16560
+ return {
16561
+ success: true,
16562
+ result: JSON.stringify({ data: outcome.data ?? {}, observation: outcome.observation ?? `${toolName} done` }),
16563
+ durationMs
16564
+ };
16565
+ }
16566
+ function createScriptedToolRuntime(tools = {}) {
16567
+ const specs = new Map(Object.entries(tools).map(([name, entry]) => [name, specOf(entry)]));
16568
+ const executions = [];
16569
+ const counts = /* @__PURE__ */ new Map();
16570
+ return {
16571
+ executions,
16572
+ getToolSchemas() {
16573
+ return [...specs].map(([name, spec]) => ({
16574
+ type: "function",
16575
+ function: {
16576
+ name,
16577
+ description: spec.description ?? `scripted tool ${name}`,
16578
+ parameters: spec.parameters ?? EMPTY_PARAMETERS
16579
+ }
16580
+ }));
16581
+ },
16582
+ getToolDefinition(toolName) {
16583
+ const spec = specs.get(toolName);
16584
+ if (!spec) return void 0;
16585
+ return {
16586
+ parameters: spec.parameters ?? EMPTY_PARAMETERS,
16587
+ ...spec.validateArguments ? { validateArguments: spec.validateArguments } : {}
16588
+ };
16589
+ },
16590
+ async executeTool(toolName, args, context) {
16591
+ const spec = specs.get(toolName);
16592
+ if (!spec) throw new Error(`[scriptedToolRuntime] \u672A\u767B\u8BB0\u7684\u5DE5\u5177\uFF1A${toolName}`);
16593
+ const count = (counts.get(toolName) ?? 0) + 1;
16594
+ counts.set(toolName, count);
16595
+ const execution = { toolName, args, startedAt: Date.now() };
16596
+ executions.push(execution);
16597
+ try {
16598
+ const outcome = spec.run ? await spec.run({ toolName, args, context, count }) : `${toolName} done`;
16599
+ execution.finishedAt = Date.now();
16600
+ const result = toResult(outcome, toolName, execution.finishedAt - execution.startedAt);
16601
+ execution.outcome = result.success ? "success" : "error";
16602
+ return result;
16603
+ } catch (error) {
16604
+ execution.finishedAt = Date.now();
16605
+ execution.outcome = "threw";
16606
+ throw error;
16607
+ }
16608
+ }
16609
+ };
16610
+ }
16611
+
16612
+ // src/testkit/scenario/timeline.ts
16613
+ var DEFAULT_HIDDEN = /* @__PURE__ */ new Set([
16614
+ "run_execution_metrics",
16615
+ "context_usage_snapshot",
16616
+ "audit_envelope",
16617
+ "tool_process",
16618
+ "final_answer_chunk",
16619
+ "final_answer_reset"
16620
+ ]);
16621
+ function clip(text, max) {
16622
+ const flat = text.replace(/\s+/g, " ").trim();
16623
+ return JSON.stringify(flat.length > max ? `${flat.slice(0, max)}\u2026` : flat);
16624
+ }
16625
+ function userInputText(event) {
16626
+ return event.raw_content ?? event.content;
16627
+ }
16628
+ function describe(event, max) {
16629
+ switch (event.type) {
16630
+ case "user_input":
16631
+ return `${event.delivery === "mid_run" ? "steer" : "user"} ${clip(userInputText(event), max)}`;
16632
+ case "thought":
16633
+ return `thought ${clip(event.content, max)}`;
16634
+ case "tool_call_decision":
16635
+ return `call ${event.tool_name}#${event.tool_call_id}`;
16636
+ case "tool_output":
16637
+ return `result ${event.tool_name}#${event.tool_call_id} ${event.status} ${clip(event.observation ?? "", max)}`;
16638
+ case "final_answer":
16639
+ return `answer ${clip(event.content, max)}${event.completion_reason && event.completion_reason !== "terminal" ? ` (${event.completion_reason})` : ""}`;
16640
+ case "error":
16641
+ return `error ${event.error_code ?? ""} ${clip(event.error, max)}`.replace(" ", " ");
16642
+ case "requires_user_interaction":
16643
+ return `wait_user ${event.interaction_status}`;
16644
+ case "llm_retry":
16645
+ return "llm_retry";
16646
+ default:
16647
+ return event.type;
16648
+ }
16649
+ }
16650
+ function formatRuntimeTimeline(events, options = {}) {
16651
+ const max = options.maxText ?? 40;
16652
+ const keep = options.types ? new Set(options.types) : void 0;
16653
+ return events.filter((event) => keep ? keep.has(event.type) : !DEFAULT_HIDDEN.has(event.type)).filter((event) => !(event.type === "thought" && event.ephemeral)).map((event) => describe(event, max));
16654
+ }
16655
+ function textOf(blocks) {
16656
+ return blocks.map((block) => block.type === "text" ? block.text ?? "" : `[${block.type}]`).join("");
16657
+ }
16658
+ function formatModelMessages(call, options = {}) {
16659
+ const max = options.maxText ?? 40;
16660
+ return call.messages.map((message) => {
16661
+ switch (message.role) {
16662
+ case "system":
16663
+ return "system";
16664
+ case "user":
16665
+ return `user ${clip(textOf(message.content), max)}`;
16666
+ case "tool":
16667
+ return `tool #${message.tool_call_id} ${clip(textOf(message.content), max)}`;
16668
+ case "assistant": {
16669
+ const parts = message.parts.map((part) => {
16670
+ if (part.type === "text") return clip(part.text, max);
16671
+ if (part.type === "tool_call") return `call ${part.call.name}#${part.call.id}`;
16672
+ return "reasoning";
16673
+ });
16674
+ return `assistant ${parts.join(" ")}`;
16675
+ }
16676
+ }
16677
+ });
16678
+ }
16679
+
16680
+ // src/testkit/scenario/steeringInvariants.ts
16681
+ function isSteer(event) {
16682
+ return event.type === "user_input" && event.delivery === "mid_run";
16683
+ }
16684
+ function messageIndexOfText(call, text) {
16685
+ return call.messages.flatMap((message, index) => {
16686
+ if (message.role !== "user") return [];
16687
+ const body = message.content.map((block) => block.type === "text" ? block.text : "").join("");
16688
+ return body.includes(text) ? [index] : [];
16689
+ });
16690
+ }
16691
+ function toolMessageIndex(call, toolCallId) {
16692
+ return call.messages.findIndex((message) => message.role === "tool" && message.tool_call_id === toolCallId);
16693
+ }
16694
+ function validateSteeringInvariants(context, options = {}) {
16695
+ const disabled = new Set(options.disabled ?? []);
16696
+ const failures = [];
16697
+ const fail = (id, message) => {
16698
+ if (!disabled.has(id)) failures.push({ id, message });
16699
+ };
16700
+ const { history, modelCalls } = context;
16701
+ const steers = history.filter(isSteer);
16702
+ const seen = /* @__PURE__ */ new Map();
16703
+ for (const steer of steers) seen.set(steer.id, (seen.get(steer.id) ?? 0) + 1);
16704
+ for (const [id, count] of seen) {
16705
+ if (count > 1) fail("S1_STEER_UNIQUE", `\u63D2\u8BDD ${id} \u5728\u5386\u53F2\u91CC\u51FA\u73B0\u4E86 ${count} \u6B21`);
16706
+ }
16707
+ for (const steer of steers) {
16708
+ const text = userInputText(steer);
16709
+ const position = history.findIndex((event) => event.id === steer.id);
16710
+ const before = history.slice(0, position);
16711
+ const decided = /* @__PURE__ */ new Set();
16712
+ const settled = /* @__PURE__ */ new Set();
16713
+ let lastToolOutputId;
16714
+ for (const event of before) {
16715
+ if (event.type === "user_input" && event.delivery !== "mid_run") {
16716
+ decided.clear();
16717
+ settled.clear();
16718
+ lastToolOutputId = void 0;
16719
+ }
16720
+ if (event.type === "tool_call_decision") decided.add(event.tool_call_id);
16721
+ if (event.type === "tool_output") {
16722
+ settled.add(event.tool_call_id);
16723
+ lastToolOutputId = event.tool_call_id;
16724
+ }
16725
+ }
16726
+ const unsettled = [...decided].filter((id) => !settled.has(id));
16727
+ if (unsettled.length > 0 || lastToolOutputId === void 0) {
16728
+ fail(
16729
+ "S2_STEER_AT_BATCH_BOUNDARY",
16730
+ `\u63D2\u8BDD ${steer.id} \u6CA1\u6709\u6392\u5728\u4E00\u6574\u6279\u5DE5\u5177\u7ED3\u679C\u4E4B\u540E\uFF08\u672A\u7ED3\u7B97\uFF1A${unsettled.join(", ") || "\u65E0\u5DE5\u5177\u7ED3\u679C"}\uFF09`
16731
+ );
16732
+ continue;
16733
+ }
16734
+ const nextCallIndex = modelCalls.findIndex((call) => toolMessageIndex(call, lastToolOutputId) >= 0);
16735
+ if (nextCallIndex < 0) {
16736
+ fail("S3_STEER_IN_NEXT_MODEL_CALL", `\u63D2\u8BDD ${steer.id} \u9001\u8FBE\u540E\u518D\u6CA1\u6709\u6A21\u578B\u8C03\u7528\u5E26\u4E0A\u524D\u4E00\u6279\u5DE5\u5177\u7ED3\u679C`);
16737
+ continue;
16738
+ }
16739
+ const nextCall = modelCalls[nextCallIndex];
16740
+ const at = messageIndexOfText(nextCall, text);
16741
+ const toolAt = toolMessageIndex(nextCall, lastToolOutputId);
16742
+ if (at.length === 0) {
16743
+ fail("S3_STEER_IN_NEXT_MODEL_CALL", `\u7B2C ${nextCallIndex + 1} \u6B21\u6A21\u578B\u8C03\u7528\u6CA1\u6709\u6536\u5230\u63D2\u8BDD ${steer.id}`);
16744
+ } else if (at[0] < toolAt) {
16745
+ fail("S3_STEER_IN_NEXT_MODEL_CALL", `\u7B2C ${nextCallIndex + 1} \u6B21\u6A21\u578B\u8C03\u7528\u91CC\u63D2\u8BDD ${steer.id} \u6392\u5728\u5DE5\u5177\u7ED3\u679C\u4E4B\u524D`);
16746
+ }
16747
+ for (const [index, call] of modelCalls.entries()) {
16748
+ const hits = messageIndexOfText(call, text).length;
16749
+ if (hits > 1) {
16750
+ fail("S4_STEER_ONCE_PER_MODEL_CALL", `\u7B2C ${index + 1} \u6B21\u6A21\u578B\u8C03\u7528\u91CC\u63D2\u8BDD ${steer.id} \u51FA\u73B0\u4E86 ${hits} \u6B21`);
16751
+ }
16752
+ if (index > nextCallIndex && hits === 0) {
16753
+ fail("S5_STEER_KEPT_IN_LATER_CALLS", `\u7B2C ${index + 1} \u6B21\u6A21\u578B\u8C03\u7528\u4E22\u4E86\u63D2\u8BDD ${steer.id}`);
16754
+ }
16755
+ }
16756
+ }
16757
+ return failures;
16758
+ }
16759
+ function assertSteeringInvariants(context, options = {}) {
16760
+ const failures = validateSteeringInvariants(context, options);
16761
+ if (failures.length > 0) {
16762
+ throw new Error(`[steeringInvariants] ${failures.map((f) => `${f.id}: ${f.message}`).join("\n")}`);
16763
+ }
16764
+ }
16765
+
16766
+ // src/testkit/scenario/graphScenario.ts
16767
+ var defaultContextBuilder = {
16768
+ async build({ history }) {
16769
+ return { llmMessages: formatAgentLlmMessages(convertEventsToAiMessages(history)) };
16770
+ }
16771
+ };
16772
+ var passthroughPreview = {
16773
+ async truncateObservation(params) {
16774
+ return { truncated: false, preview: params.text };
16775
+ }
16776
+ };
16777
+ function createGraphScenario(options) {
16778
+ const conversationId = options.conversationId ?? "conversation";
16779
+ const model = createScriptedInferenceHarness(options.model);
16780
+ const tools = createScriptedToolRuntime(options.tools ?? {});
16781
+ const steering = createPendingUserInputQueue();
16782
+ const checkpointer = new MemoryCheckpointer();
16783
+ const eventStore = new MemoryEventStore();
16784
+ const nextEventStoreId = createMonotonicEventStoreIdFactory();
16785
+ const live = [];
16786
+ const seed = [...options.history ?? []];
16787
+ const runs = /* @__PURE__ */ new Map();
16788
+ let current;
16789
+ let runCount = 0;
16790
+ const reasoner = new GraphAgentExecutor({
16791
+ llmCaller: model.getLlmCaller(),
16792
+ toolRuntime: tools,
16793
+ contextBuilder: options.contextBuilder ?? defaultContextBuilder,
16794
+ ...options.tokenizer ? { tokenizer: options.tokenizer } : {}
16795
+ });
16796
+ const graph = new GraphExecutor(checkpointer, {
16797
+ maxSteps: options.maxSteps ?? 16,
16798
+ executionCheckpointPort: {
16799
+ commit: (key, state) => {
16800
+ const run = runs.get(key);
16801
+ if (!run) throw new Error(`[graphScenario] \u672A\u77E5\u8FD0\u884C\uFF1A${key}`);
16802
+ return run.persistence.commitCheckpoint(key, state);
16803
+ }
16804
+ }
16805
+ });
16806
+ graph.registerNode(new LlmNode({ reasoner }));
16807
+ graph.registerNode(new ToolNode({
16808
+ toolRuntime: tools,
16809
+ observationPreview: options.observationPreview ?? passthroughPreview
16810
+ }));
16811
+ graph.registerNode(new WaitUserNode({}));
16812
+ function openRun(runId, turnId) {
16813
+ const sequencer = new execution_exports.EventSequencer(conversationId);
16814
+ const eventBus = new execution_exports.EventBus(sequencer.getExecutionId());
16815
+ eventBus.on("event", (envelope) => live.push(envelope.payload));
16816
+ const publisher = new execution_exports.RuntimeEventPublisher(
16817
+ eventBus,
16818
+ sequencer,
16819
+ routingIdentityOf({ runId })
16820
+ );
16821
+ const persistence = new execution_exports.EventBusEventPersistence({
16822
+ eventBus,
16823
+ eventStore,
16824
+ nextEventStoreId,
16825
+ async checkpointWriter({ checkpointKey, checkpoint: checkpoint2, events }) {
16826
+ await options.beforeCheckpointWrite?.({ checkpointKey, events: events.map((item) => item.event) });
16827
+ const stored = JSON.parse(JSON.stringify(checkpoint2));
16828
+ await checkpointer.save(checkpointKey, parseEngineCheckpoint(stored));
16829
+ for (const event of events) await eventStore.append(event);
16830
+ }
16831
+ });
16832
+ persistence.connect();
16833
+ const run = {
16834
+ runId,
16835
+ turnId,
16836
+ eventBus,
16837
+ sink: (event, source) => publisher.publish(event, source),
16838
+ persistence,
16839
+ controller: new AbortController(),
16840
+ open: true
16841
+ };
16842
+ runs.set(runId, run);
16843
+ return run;
16844
+ }
16845
+ async function closeRun(run) {
16846
+ if (!run.open) return;
16847
+ run.open = false;
16848
+ run.persistence.finishCheckpointWrites();
16849
+ try {
16850
+ await run.persistence.drain();
16851
+ } finally {
16852
+ run.eventBus.close();
16853
+ }
16854
+ }
16855
+ function capabilities(run) {
16856
+ const toolContext = {
16857
+ runId: RunIdSchema.parse(run.runId),
16858
+ conversationId,
16859
+ turnId: run.turnId,
16860
+ abortSignal: run.controller.signal
16861
+ };
16862
+ return {
16863
+ signal: run.controller.signal,
16864
+ toolContext,
16865
+ runtimeEventSink: run.sink,
16866
+ pendingUserInputPort: steering.port
16867
+ };
16868
+ }
16869
+ async function settle(run, operation) {
16870
+ current = run;
16871
+ let status;
16872
+ let error;
16873
+ try {
16874
+ const checkpoint2 = await operation();
16875
+ status = checkpoint2.executionStatus === "awaiting_user" ? "awaiting_user" : "yielded";
16876
+ } catch (caught) {
16877
+ const signal = run.controller.signal;
16878
+ if (signal.aborted) {
16879
+ status = isRunPauseSignal(signal) ? "paused" : "cancelled";
16880
+ } else {
16881
+ status = "failed";
16882
+ error = caught;
16883
+ }
16884
+ } finally {
16885
+ current = void 0;
16886
+ }
16887
+ if (status === "paused" || status === "awaiting_user") {
16888
+ await run.persistence.drain().catch(() => void 0);
16889
+ } else {
16890
+ await closeRun(run).catch((caught) => {
16891
+ status = "failed";
16892
+ error ??= caught;
16893
+ });
16894
+ }
16895
+ return {
16896
+ runId: run.runId,
16897
+ status,
16898
+ ...error !== void 0 ? { error } : {},
16899
+ undeliveredSteers: steering.drain()
16900
+ };
16901
+ }
16902
+ async function history() {
16903
+ for (const run of runs.values()) {
16904
+ if (run.open) await run.persistence.drain().catch(() => void 0);
16905
+ }
16906
+ return [...seed, ...(await eventStore.range(conversationId)).map((item) => item.event)];
16907
+ }
16908
+ let lastPaused;
16909
+ return {
16910
+ conversationId,
16911
+ model,
16912
+ tools,
16913
+ steering,
16914
+ live,
16915
+ async start(input) {
16916
+ const { query, runId: requestedRunId, request } = typeof input === "string" ? { query: input, runId: void 0, request: void 0 } : input;
16917
+ runCount += 1;
16918
+ const runId = requestedRunId ?? `run_${runCount}`;
16919
+ const turnId = `turn_${runCount}`;
16920
+ const prior = await history();
16921
+ const run = openRun(runId, turnId);
16922
+ const userInput = run.sink(
16923
+ createUserInputEvent(`user_${runId}`, conversationId, turnId, query),
16924
+ "graphScenario.user_input"
16925
+ );
16926
+ const toolNames = Object.keys(options.tools ?? {});
16927
+ const outcome = await settle(run, async () => (await graph.startSession(runId, {
16928
+ ...capabilities(run),
16929
+ runId: RunIdSchema.parse(runId),
16930
+ conversationId,
16931
+ turnId,
16932
+ history: [...prior, userInput],
16933
+ request: {
16934
+ query,
16935
+ promptKey: "agent",
16936
+ model_id: "scripted-model",
16937
+ enableTools: toolNames.length > 0,
16938
+ availableTools: toolNames,
16939
+ ...request
16940
+ }
16941
+ }, "llm")).checkpoint);
16942
+ lastPaused = outcome.status === "paused" ? run : void 0;
16943
+ return outcome;
16944
+ },
16945
+ async continue() {
16946
+ const run = lastPaused;
16947
+ if (!run) throw new Error("[graphScenario] \u6CA1\u6709\u6682\u505C\u4E2D\u7684\u8FD0\u884C\u53EF\u4EE5\u7EE7\u7EED");
16948
+ const saved = await checkpointer.load(run.runId);
16949
+ if (!saved?.revision) throw new Error(`[graphScenario] \u8FD0\u884C ${run.runId} \u6CA1\u6709\u65AD\u70B9`);
16950
+ run.controller = new AbortController();
16951
+ const outcome = await settle(run, async () => (await graph.continueSession(run.runId, {
16952
+ expectedRevision: saved.revision ?? 0,
16953
+ capabilities: capabilities(run)
16954
+ })).checkpoint);
16955
+ lastPaused = outcome.status === "paused" ? run : void 0;
16956
+ return outcome;
16957
+ },
16958
+ steer: (content, steerOptions) => steering.submit(content, steerOptions),
16959
+ pause() {
16960
+ if (!current) throw new Error("[graphScenario] \u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u53EF\u4EE5\u6682\u505C");
16961
+ current.controller.abort(new RunPauseRequested());
16962
+ },
16963
+ cancel() {
16964
+ if (!current) throw new Error("[graphScenario] \u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u53EF\u4EE5\u53D6\u6D88");
16965
+ current.controller.abort(new Error("Run cancelled by scenario"));
16966
+ },
16967
+ history,
16968
+ checkpoint: async (runId) => checkpointer.load(runId ?? [...runs.keys()].at(-1) ?? ""),
16969
+ timeline: async (timelineOptions) => formatRuntimeTimeline(await history(), timelineOptions),
16970
+ modelCalls: () => model.getCalls(),
16971
+ async assertInvariants(invariantOptions) {
16972
+ const events = await history();
16973
+ const ids = events.map((event) => event.id);
16974
+ const duplicated = ids.filter((id, index) => ids.indexOf(id) !== index);
16975
+ try {
16976
+ if (duplicated.length > 0) throw new Error(`[graphScenario] \u5386\u53F2\u91CC\u6709\u91CD\u590D\u4E8B\u4EF6\uFF1A${duplicated.join(", ")}`);
16977
+ assertSteeringInvariants({ history: events, modelCalls: model.getCalls() }, invariantOptions);
16978
+ } catch (error) {
16979
+ const timeline = formatRuntimeTimeline(events).map((line) => ` ${line}`).join("\n");
16980
+ throw new Error(`${error instanceof Error ? error.message : String(error)}
16981
+ \u65F6\u95F4\u7EBF\uFF1A
16982
+ ${timeline}`);
16983
+ }
16984
+ },
16985
+ async close() {
16986
+ for (const run of runs.values()) await closeRun(run).catch(() => void 0);
16987
+ }
16988
+ };
16989
+ }
16990
+
16297
16991
  // src/testkit/tool-fixtures/toolContext.ts
16298
16992
  function createToolContextFixture(options = {}) {
16299
16993
  const persistedHistoryEvents = options.persistedHistoryEvents ?? options.historyEvents ?? [];
@@ -16320,22 +17014,31 @@ function createToolContextFixture(options = {}) {
16320
17014
 
16321
17015
  exports.assertContextPolicyInvariants = assertContextPolicyInvariants;
16322
17016
  exports.assertRunInvariants = assertRunInvariants;
17017
+ exports.assertSteeringInvariants = assertSteeringInvariants;
16323
17018
  exports.assertions = assertions_exports;
16324
17019
  exports.createCollectingAuditPort = createCollectingAuditPort;
16325
17020
  exports.createDefaultGraphExecutor = createDefaultGraphExecutor;
16326
17021
  exports.createGraphLoopHarness = createGraphLoopHarness;
17022
+ exports.createGraphScenario = createGraphScenario;
16327
17023
  exports.createMockTelemetryPort = createMockTelemetryPort;
16328
17024
  exports.createMockTokenizerPort = createMockTokenizerPort;
17025
+ exports.createPendingUserInputQueue = createPendingUserInputQueue;
16329
17026
  exports.createReplayHarness = createReplayHarness;
16330
17027
  exports.createRunSupervisorHarness = createRunSupervisorHarness;
17028
+ exports.createRuntimeEventRecorder = createRuntimeEventRecorder;
16331
17029
  exports.createScriptedInferenceHarness = createScriptedInferenceHarness;
17030
+ exports.createScriptedToolRuntime = createScriptedToolRuntime;
16332
17031
  exports.createToolContextFixture = createToolContextFixture;
16333
17032
  exports.expectFinalStepForcedTools = expectFinalStepForcedTools;
16334
17033
  exports.expectMessagesContainText = expectMessagesContainText;
16335
17034
  exports.expectMessagesContainToolResult = expectMessagesContainToolResult;
16336
17035
  exports.expectRunEndedWithFinalAnswer = expectRunEndedWithFinalAnswer;
16337
17036
  exports.expectToolOutputFedBackToHistory = expectToolOutputFedBackToHistory;
17037
+ exports.formatModelMessages = formatModelMessages;
17038
+ exports.formatRuntimeTimeline = formatRuntimeTimeline;
17039
+ exports.userInputText = userInputText;
16338
17040
  exports.validateContextPolicyInvariants = validateContextPolicyInvariants;
16339
17041
  exports.validateRunInvariants = validateRunInvariants;
17042
+ exports.validateSteeringInvariants = validateSteeringInvariants;
16340
17043
  //# sourceMappingURL=testkit.cjs.map
16341
17044
  //# sourceMappingURL=testkit.cjs.map