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