@linnlabs/linnkit 0.43.0 → 0.44.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 +44 -0
- package/dist/cli.cjs +101 -4
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +101 -4
- 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 +103 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +103 -4
- package/dist/index.js.map +1 -1
- package/dist/quickstart.cjs +101 -4
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.js +101 -4
- 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/types.d.cts +3 -0
- package/dist/runtime-kernel/graph-engine/types.d.ts +3 -0
- package/dist/runtime-kernel.cjs +101 -4
- 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 +101 -4
- 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 +671 -17
- 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 +663 -18
- 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/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
|
}
|
|
@@ -8994,6 +9022,62 @@ async function commitToolBoundary(state, result) {
|
|
|
8994
9022
|
await state.local.commitExecutionBoundary(state);
|
|
8995
9023
|
}
|
|
8996
9024
|
|
|
9025
|
+
// src/runtime-kernel/graph-engine/nodes/toolNode.pendingUserInput.ts
|
|
9026
|
+
function isPendingUserInputPort(value) {
|
|
9027
|
+
return !!value && typeof value === "object" && typeof Reflect.get(value, "claim") === "function" && typeof Reflect.get(value, "confirm") === "function" && typeof Reflect.get(value, "release") === "function";
|
|
9028
|
+
}
|
|
9029
|
+
function readRemainingSteps(state) {
|
|
9030
|
+
const value = state.local?.executorLocal?.remainingSteps;
|
|
9031
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
9032
|
+
}
|
|
9033
|
+
function readIdentity(value, field) {
|
|
9034
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
9035
|
+
throw new Error(`ToolNode pending user input requires ${field}`);
|
|
9036
|
+
}
|
|
9037
|
+
return value;
|
|
9038
|
+
}
|
|
9039
|
+
async function claimPendingUserInputs(state, result) {
|
|
9040
|
+
if (result.kind !== "route" || result.nextNodeId !== "llm") return void 0;
|
|
9041
|
+
const local = state.local;
|
|
9042
|
+
const port = local?.pendingUserInputPort;
|
|
9043
|
+
if (!isPendingUserInputPort(port)) return void 0;
|
|
9044
|
+
const signal = local?.signal;
|
|
9045
|
+
if (signal?.aborted || isRunPauseSignal(signal)) return void 0;
|
|
9046
|
+
const remainingSteps = readRemainingSteps(state);
|
|
9047
|
+
if (remainingSteps !== void 0 && remainingSteps < 1) return void 0;
|
|
9048
|
+
const inputs = await port.claim();
|
|
9049
|
+
if (inputs.length === 0) return void 0;
|
|
9050
|
+
const ids = inputs.map((input) => input.id);
|
|
9051
|
+
try {
|
|
9052
|
+
const conversationId = readIdentity(local?.conversationId, "conversationId");
|
|
9053
|
+
const turnId = readIdentity(local?.turnId, "turnId");
|
|
9054
|
+
const sink = requireRuntimeEventSink(local);
|
|
9055
|
+
const events = inputs.map((input) => sink(
|
|
9056
|
+
createUserInputEvent(readIdentity(input.id, "input id"), conversationId, turnId, input.content, {
|
|
9057
|
+
timestamp: input.timestamp ?? Date.now(),
|
|
9058
|
+
delivery: "mid_run"
|
|
9059
|
+
}),
|
|
9060
|
+
"ToolNode.pending_user_input"
|
|
9061
|
+
));
|
|
9062
|
+
state.local = {
|
|
9063
|
+
...state.local,
|
|
9064
|
+
history: appendWorkingHistory(parseRuntimeEvents(state.local?.history ?? []), events)
|
|
9065
|
+
};
|
|
9066
|
+
return {
|
|
9067
|
+
events,
|
|
9068
|
+
confirm: async () => {
|
|
9069
|
+
await port.confirm(ids);
|
|
9070
|
+
},
|
|
9071
|
+
release: async () => {
|
|
9072
|
+
await port.release(ids);
|
|
9073
|
+
}
|
|
9074
|
+
};
|
|
9075
|
+
} catch (error) {
|
|
9076
|
+
await port.release(ids);
|
|
9077
|
+
throw error;
|
|
9078
|
+
}
|
|
9079
|
+
}
|
|
9080
|
+
|
|
8997
9081
|
// src/runtime-kernel/graph-engine/nodes/toolNode.ts
|
|
8998
9082
|
var logger11 = new Logger("ToolNode");
|
|
8999
9083
|
function isAbortSignal(value) {
|
|
@@ -9161,7 +9245,19 @@ var ToolNode = class {
|
|
|
9161
9245
|
});
|
|
9162
9246
|
throw result.error;
|
|
9163
9247
|
}
|
|
9164
|
-
await
|
|
9248
|
+
const steering = await claimPendingUserInputs(state, result);
|
|
9249
|
+
if (steering) {
|
|
9250
|
+
result = { ...result, events: [...result.events ?? [], ...steering.events] };
|
|
9251
|
+
try {
|
|
9252
|
+
await commitToolBoundary(state, result);
|
|
9253
|
+
} catch (error) {
|
|
9254
|
+
await steering.release();
|
|
9255
|
+
throw error;
|
|
9256
|
+
}
|
|
9257
|
+
await steering.confirm();
|
|
9258
|
+
} else {
|
|
9259
|
+
await commitToolBoundary(state, result);
|
|
9260
|
+
}
|
|
9165
9261
|
if (Array.isArray(result.events) && result.events.length > 0) {
|
|
9166
9262
|
events.push(...result.events);
|
|
9167
9263
|
}
|
|
@@ -9919,7 +10015,8 @@ function parseEngineCheckpoint(value) {
|
|
|
9919
10015
|
"runtimeFailureFactSink",
|
|
9920
10016
|
"summarizationCallbacks",
|
|
9921
10017
|
"commitExecutionBoundary",
|
|
9922
|
-
"toolRecoveryPort"
|
|
10018
|
+
"toolRecoveryPort",
|
|
10019
|
+
"pendingUserInputPort"
|
|
9923
10020
|
]) {
|
|
9924
10021
|
if (result.local && Object.hasOwn(result.local, key)) {
|
|
9925
10022
|
throw new Error(`Checkpoint must not contain execution capability: ${key}`);
|
|
@@ -14752,31 +14849,37 @@ function createScriptedModelCatalog() {
|
|
|
14752
14849
|
getModelsByUIVisibility: () => []
|
|
14753
14850
|
};
|
|
14754
14851
|
}
|
|
14852
|
+
function argumentsJsonOf(toolCall) {
|
|
14853
|
+
if (toolCall.argumentsJson !== void 0) return toolCall.argumentsJson;
|
|
14854
|
+
return JSON.stringify(toolCall.arguments ?? {});
|
|
14855
|
+
}
|
|
14755
14856
|
function parseArguments(toolCall) {
|
|
14756
|
-
const parsed = JSON.parse(toolCall
|
|
14857
|
+
const parsed = JSON.parse(argumentsJsonOf(toolCall));
|
|
14757
14858
|
const record = toSerializableJsonRecord(parsed);
|
|
14758
14859
|
if (!record) {
|
|
14759
14860
|
throw new Error(`[scriptedInferenceHarness] ${toolCall.name} arguments \u5FC5\u987B\u662F JSON object\u3002`);
|
|
14760
14861
|
}
|
|
14761
14862
|
return record;
|
|
14762
14863
|
}
|
|
14763
|
-
function createScriptedInferenceHarness(
|
|
14764
|
-
const streamTurns = [...
|
|
14864
|
+
function createScriptedInferenceHarness(script, options = {}) {
|
|
14865
|
+
const streamTurns = typeof script === "function" ? void 0 : [...script];
|
|
14866
|
+
const respond = typeof script === "function" ? script : void 0;
|
|
14765
14867
|
const calls = [];
|
|
14766
14868
|
const inferencePort = {
|
|
14767
14869
|
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
14870
|
const call = {
|
|
14773
14871
|
request,
|
|
14774
14872
|
modelId: request.model_id,
|
|
14775
14873
|
messages: request.messages,
|
|
14776
14874
|
options: callOptions(request)
|
|
14777
14875
|
};
|
|
14876
|
+
const callIndex = calls.length;
|
|
14877
|
+
const turn = respond ? await respond(call, callIndex) : streamTurns?.shift();
|
|
14878
|
+
if (!turn) {
|
|
14879
|
+
throw new Error("[scriptedInferenceHarness] \u6CA1\u6709\u53EF\u6D88\u8D39\u7684 scripted turn\uFF0C\u8BF7\u8865\u9F50\u811A\u672C\u3002");
|
|
14880
|
+
}
|
|
14778
14881
|
calls.push(call);
|
|
14779
|
-
turn.assertCall?.(call);
|
|
14882
|
+
await turn.assertCall?.(call);
|
|
14780
14883
|
yield { type: "start", model_id: request.model_id, attempt_id: request.invocation.attempt_id };
|
|
14781
14884
|
if (turn.failure) {
|
|
14782
14885
|
yield { type: "failure", ...turn.failure };
|
|
@@ -14813,23 +14916,24 @@ function createScriptedInferenceHarness(turns, options = {}) {
|
|
|
14813
14916
|
}
|
|
14814
14917
|
for (const [position, toolCall] of (turn.toolCalls ?? []).entries()) {
|
|
14815
14918
|
const index = toolCall.index ?? position;
|
|
14919
|
+
const id = toolCall.id ?? `call_${callIndex + 1}_${position + 1}`;
|
|
14816
14920
|
yield {
|
|
14817
14921
|
type: "tool_call_start",
|
|
14818
14922
|
index,
|
|
14819
14923
|
part_index: nextAssistantPartIndex++,
|
|
14820
|
-
id
|
|
14924
|
+
id,
|
|
14821
14925
|
name: toolCall.name
|
|
14822
14926
|
};
|
|
14823
14927
|
yield {
|
|
14824
14928
|
type: "tool_argument_delta",
|
|
14825
14929
|
index,
|
|
14826
|
-
json_delta: toolCall
|
|
14930
|
+
json_delta: argumentsJsonOf(toolCall)
|
|
14827
14931
|
};
|
|
14828
14932
|
yield {
|
|
14829
14933
|
type: "tool_call_end",
|
|
14830
14934
|
index,
|
|
14831
14935
|
call: {
|
|
14832
|
-
id
|
|
14936
|
+
id,
|
|
14833
14937
|
name: toolCall.name,
|
|
14834
14938
|
arguments: parseArguments(toolCall),
|
|
14835
14939
|
...toolCall.continuations?.length ? { continuation: toolCall.continuations } : {}
|
|
@@ -14856,8 +14960,9 @@ function createScriptedInferenceHarness(turns, options = {}) {
|
|
|
14856
14960
|
getCalls: () => [...calls],
|
|
14857
14961
|
getConsumedTurnCount: () => calls.length,
|
|
14858
14962
|
getLlmCaller: () => llmCaller,
|
|
14963
|
+
getInferencePort: () => inferencePort,
|
|
14859
14964
|
assertAllTurnsConsumed() {
|
|
14860
|
-
if (streamTurns.length > 0) {
|
|
14965
|
+
if (streamTurns && streamTurns.length > 0) {
|
|
14861
14966
|
throw new Error(
|
|
14862
14967
|
`[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
14968
|
);
|
|
@@ -14928,6 +15033,8 @@ var MessageFormatter = class {
|
|
|
14928
15033
|
content,
|
|
14929
15034
|
...message.attachments ? { attachments: message.attachments } : {}
|
|
14930
15035
|
};
|
|
15036
|
+
case "user_steer":
|
|
15037
|
+
return { role: "user", content };
|
|
14931
15038
|
case "context_injection": {
|
|
14932
15039
|
const fenceKind = metadata?.fenceKind;
|
|
14933
15040
|
if (!fenceKind) {
|
|
@@ -14980,7 +15087,10 @@ var MessageFormatter = class {
|
|
|
14980
15087
|
}
|
|
14981
15088
|
}
|
|
14982
15089
|
};
|
|
14983
|
-
new MessageFormatter();
|
|
15090
|
+
var messageFormatter = new MessageFormatter();
|
|
15091
|
+
function formatAgentLlmMessages(messages, options = {}) {
|
|
15092
|
+
return messageFormatter.format(messages, { nativeTools: true, ...options });
|
|
15093
|
+
}
|
|
14984
15094
|
z.object({
|
|
14985
15095
|
systemPrompt: z.string(),
|
|
14986
15096
|
messages: z.array(AiMessage)
|
|
@@ -15122,6 +15232,7 @@ function convertAiMessageToEvent(message, context) {
|
|
|
15122
15232
|
type: "user_input",
|
|
15123
15233
|
content: message.content,
|
|
15124
15234
|
source: "user",
|
|
15235
|
+
...message.type === "user_steer" ? { delivery: "mid_run" } : {},
|
|
15125
15236
|
...message.type === "user_input" && message.attachments ? { attachments: message.attachments } : {}
|
|
15126
15237
|
};
|
|
15127
15238
|
return event;
|
|
@@ -16292,6 +16403,540 @@ function createMockTokenizerPort(options = {}) {
|
|
|
16292
16403
|
};
|
|
16293
16404
|
}
|
|
16294
16405
|
|
|
16406
|
+
// src/testkit/scenario/pendingUserInputQueue.ts
|
|
16407
|
+
function createPendingUserInputQueue() {
|
|
16408
|
+
let pending = [];
|
|
16409
|
+
const claimed = /* @__PURE__ */ new Map();
|
|
16410
|
+
const delivered = [];
|
|
16411
|
+
let sequence = 0;
|
|
16412
|
+
const port = {
|
|
16413
|
+
claim() {
|
|
16414
|
+
const taken = pending;
|
|
16415
|
+
pending = [];
|
|
16416
|
+
for (const input of taken) claimed.set(input.id, input);
|
|
16417
|
+
return taken;
|
|
16418
|
+
},
|
|
16419
|
+
confirm(ids) {
|
|
16420
|
+
for (const id of ids) {
|
|
16421
|
+
const input = claimed.get(id);
|
|
16422
|
+
if (!input) continue;
|
|
16423
|
+
claimed.delete(id);
|
|
16424
|
+
delivered.push(input);
|
|
16425
|
+
}
|
|
16426
|
+
},
|
|
16427
|
+
release(ids) {
|
|
16428
|
+
const returned = ids.flatMap((id) => {
|
|
16429
|
+
const input = claimed.get(id);
|
|
16430
|
+
claimed.delete(id);
|
|
16431
|
+
return input ? [input] : [];
|
|
16432
|
+
});
|
|
16433
|
+
pending = [...returned, ...pending];
|
|
16434
|
+
}
|
|
16435
|
+
};
|
|
16436
|
+
return {
|
|
16437
|
+
port,
|
|
16438
|
+
submit(content, options = {}) {
|
|
16439
|
+
sequence += 1;
|
|
16440
|
+
const id = options.id ?? `steer_${sequence}`;
|
|
16441
|
+
pending.push({ id, content, timestamp: options.timestamp ?? Date.now() });
|
|
16442
|
+
return id;
|
|
16443
|
+
},
|
|
16444
|
+
withdraw(id) {
|
|
16445
|
+
if (pending.some((input) => input.id === id)) {
|
|
16446
|
+
pending = pending.filter((input) => input.id !== id);
|
|
16447
|
+
return "withdrawn";
|
|
16448
|
+
}
|
|
16449
|
+
if (claimed.has(id)) return "claimed";
|
|
16450
|
+
if (delivered.some((input) => input.id === id)) return "delivered";
|
|
16451
|
+
return "unknown";
|
|
16452
|
+
},
|
|
16453
|
+
drain() {
|
|
16454
|
+
const taken = pending;
|
|
16455
|
+
pending = [];
|
|
16456
|
+
return taken;
|
|
16457
|
+
},
|
|
16458
|
+
pending: () => [...pending],
|
|
16459
|
+
claimed: () => [...claimed.values()],
|
|
16460
|
+
delivered: () => [...delivered]
|
|
16461
|
+
};
|
|
16462
|
+
}
|
|
16463
|
+
|
|
16464
|
+
// src/testkit/scenario/runtimeEventRecorder.ts
|
|
16465
|
+
function routingIdentityOf(options) {
|
|
16466
|
+
const child = options.parentRunId !== void 0;
|
|
16467
|
+
return {
|
|
16468
|
+
run_id: RunIdSchema.parse(options.runId ?? "run"),
|
|
16469
|
+
...child ? { parent_run_id: RunIdSchema.parse(options.parentRunId) } : {},
|
|
16470
|
+
lane: options.lane ?? (child ? "child" : "foreground"),
|
|
16471
|
+
visibility: options.visibility ?? (child ? "parent-trace" : "conversation")
|
|
16472
|
+
};
|
|
16473
|
+
}
|
|
16474
|
+
function createRuntimeEventRecorder(options = {}) {
|
|
16475
|
+
const sequencer = new execution_exports.EventSequencer(options.conversationId ?? "conversation");
|
|
16476
|
+
const eventBus = new execution_exports.EventBus(sequencer.getExecutionId());
|
|
16477
|
+
const events = [];
|
|
16478
|
+
eventBus.on("event", (envelope) => events.push(envelope.payload));
|
|
16479
|
+
const publisher = new execution_exports.RuntimeEventPublisher(eventBus, sequencer, routingIdentityOf(options));
|
|
16480
|
+
return {
|
|
16481
|
+
sink: (event, source) => publisher.publish(event, source),
|
|
16482
|
+
events,
|
|
16483
|
+
eventBus,
|
|
16484
|
+
sequencer,
|
|
16485
|
+
publisher,
|
|
16486
|
+
publisherFor: (identity) => new execution_exports.RuntimeEventPublisher(eventBus, sequencer, identity),
|
|
16487
|
+
close: () => eventBus.close()
|
|
16488
|
+
};
|
|
16489
|
+
}
|
|
16490
|
+
|
|
16491
|
+
// src/testkit/scenario/scriptedToolRuntime.ts
|
|
16492
|
+
var EMPTY_PARAMETERS = { type: "object", properties: {} };
|
|
16493
|
+
function specOf(entry) {
|
|
16494
|
+
return typeof entry === "function" ? { run: entry } : entry;
|
|
16495
|
+
}
|
|
16496
|
+
function toResult(outcome, toolName, durationMs) {
|
|
16497
|
+
if (typeof outcome === "string") {
|
|
16498
|
+
return { success: true, result: JSON.stringify({ data: {}, observation: outcome }), durationMs };
|
|
16499
|
+
}
|
|
16500
|
+
if (outcome.error !== void 0) {
|
|
16501
|
+
return {
|
|
16502
|
+
success: false,
|
|
16503
|
+
error: outcome.error,
|
|
16504
|
+
...outcome.errorCode ? { errorCode: outcome.errorCode } : {},
|
|
16505
|
+
errorKind: "execution",
|
|
16506
|
+
durationMs
|
|
16507
|
+
};
|
|
16508
|
+
}
|
|
16509
|
+
return {
|
|
16510
|
+
success: true,
|
|
16511
|
+
result: JSON.stringify({ data: outcome.data ?? {}, observation: outcome.observation ?? `${toolName} done` }),
|
|
16512
|
+
durationMs
|
|
16513
|
+
};
|
|
16514
|
+
}
|
|
16515
|
+
function createScriptedToolRuntime(tools = {}) {
|
|
16516
|
+
const specs = new Map(Object.entries(tools).map(([name, entry]) => [name, specOf(entry)]));
|
|
16517
|
+
const executions = [];
|
|
16518
|
+
const counts = /* @__PURE__ */ new Map();
|
|
16519
|
+
return {
|
|
16520
|
+
executions,
|
|
16521
|
+
getToolSchemas() {
|
|
16522
|
+
return [...specs].map(([name, spec]) => ({
|
|
16523
|
+
type: "function",
|
|
16524
|
+
function: {
|
|
16525
|
+
name,
|
|
16526
|
+
description: spec.description ?? `scripted tool ${name}`,
|
|
16527
|
+
parameters: spec.parameters ?? EMPTY_PARAMETERS
|
|
16528
|
+
}
|
|
16529
|
+
}));
|
|
16530
|
+
},
|
|
16531
|
+
getToolDefinition(toolName) {
|
|
16532
|
+
const spec = specs.get(toolName);
|
|
16533
|
+
if (!spec) return void 0;
|
|
16534
|
+
return {
|
|
16535
|
+
parameters: spec.parameters ?? EMPTY_PARAMETERS,
|
|
16536
|
+
...spec.validateArguments ? { validateArguments: spec.validateArguments } : {}
|
|
16537
|
+
};
|
|
16538
|
+
},
|
|
16539
|
+
async executeTool(toolName, args, context) {
|
|
16540
|
+
const spec = specs.get(toolName);
|
|
16541
|
+
if (!spec) throw new Error(`[scriptedToolRuntime] \u672A\u767B\u8BB0\u7684\u5DE5\u5177\uFF1A${toolName}`);
|
|
16542
|
+
const count = (counts.get(toolName) ?? 0) + 1;
|
|
16543
|
+
counts.set(toolName, count);
|
|
16544
|
+
const execution = { toolName, args, startedAt: Date.now() };
|
|
16545
|
+
executions.push(execution);
|
|
16546
|
+
try {
|
|
16547
|
+
const outcome = spec.run ? await spec.run({ toolName, args, context, count }) : `${toolName} done`;
|
|
16548
|
+
execution.finishedAt = Date.now();
|
|
16549
|
+
const result = toResult(outcome, toolName, execution.finishedAt - execution.startedAt);
|
|
16550
|
+
execution.outcome = result.success ? "success" : "error";
|
|
16551
|
+
return result;
|
|
16552
|
+
} catch (error) {
|
|
16553
|
+
execution.finishedAt = Date.now();
|
|
16554
|
+
execution.outcome = "threw";
|
|
16555
|
+
throw error;
|
|
16556
|
+
}
|
|
16557
|
+
}
|
|
16558
|
+
};
|
|
16559
|
+
}
|
|
16560
|
+
|
|
16561
|
+
// src/testkit/scenario/timeline.ts
|
|
16562
|
+
var DEFAULT_HIDDEN = /* @__PURE__ */ new Set([
|
|
16563
|
+
"run_execution_metrics",
|
|
16564
|
+
"context_usage_snapshot",
|
|
16565
|
+
"audit_envelope",
|
|
16566
|
+
"tool_process",
|
|
16567
|
+
"final_answer_chunk",
|
|
16568
|
+
"final_answer_reset"
|
|
16569
|
+
]);
|
|
16570
|
+
function clip(text, max) {
|
|
16571
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
16572
|
+
return JSON.stringify(flat.length > max ? `${flat.slice(0, max)}\u2026` : flat);
|
|
16573
|
+
}
|
|
16574
|
+
function userInputText(event) {
|
|
16575
|
+
return event.raw_content ?? event.content;
|
|
16576
|
+
}
|
|
16577
|
+
function describe(event, max) {
|
|
16578
|
+
switch (event.type) {
|
|
16579
|
+
case "user_input":
|
|
16580
|
+
return `${event.delivery === "mid_run" ? "steer" : "user"} ${clip(userInputText(event), max)}`;
|
|
16581
|
+
case "thought":
|
|
16582
|
+
return `thought ${clip(event.content, max)}`;
|
|
16583
|
+
case "tool_call_decision":
|
|
16584
|
+
return `call ${event.tool_name}#${event.tool_call_id}`;
|
|
16585
|
+
case "tool_output":
|
|
16586
|
+
return `result ${event.tool_name}#${event.tool_call_id} ${event.status} ${clip(event.observation ?? "", max)}`;
|
|
16587
|
+
case "final_answer":
|
|
16588
|
+
return `answer ${clip(event.content, max)}${event.completion_reason && event.completion_reason !== "terminal" ? ` (${event.completion_reason})` : ""}`;
|
|
16589
|
+
case "error":
|
|
16590
|
+
return `error ${event.error_code ?? ""} ${clip(event.error, max)}`.replace(" ", " ");
|
|
16591
|
+
case "requires_user_interaction":
|
|
16592
|
+
return `wait_user ${event.interaction_status}`;
|
|
16593
|
+
case "llm_retry":
|
|
16594
|
+
return "llm_retry";
|
|
16595
|
+
default:
|
|
16596
|
+
return event.type;
|
|
16597
|
+
}
|
|
16598
|
+
}
|
|
16599
|
+
function formatRuntimeTimeline(events, options = {}) {
|
|
16600
|
+
const max = options.maxText ?? 40;
|
|
16601
|
+
const keep = options.types ? new Set(options.types) : void 0;
|
|
16602
|
+
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));
|
|
16603
|
+
}
|
|
16604
|
+
function textOf(blocks) {
|
|
16605
|
+
return blocks.map((block) => block.type === "text" ? block.text ?? "" : `[${block.type}]`).join("");
|
|
16606
|
+
}
|
|
16607
|
+
function formatModelMessages(call, options = {}) {
|
|
16608
|
+
const max = options.maxText ?? 40;
|
|
16609
|
+
return call.messages.map((message) => {
|
|
16610
|
+
switch (message.role) {
|
|
16611
|
+
case "system":
|
|
16612
|
+
return "system";
|
|
16613
|
+
case "user":
|
|
16614
|
+
return `user ${clip(textOf(message.content), max)}`;
|
|
16615
|
+
case "tool":
|
|
16616
|
+
return `tool #${message.tool_call_id} ${clip(textOf(message.content), max)}`;
|
|
16617
|
+
case "assistant": {
|
|
16618
|
+
const parts = message.parts.map((part) => {
|
|
16619
|
+
if (part.type === "text") return clip(part.text, max);
|
|
16620
|
+
if (part.type === "tool_call") return `call ${part.call.name}#${part.call.id}`;
|
|
16621
|
+
return "reasoning";
|
|
16622
|
+
});
|
|
16623
|
+
return `assistant ${parts.join(" ")}`;
|
|
16624
|
+
}
|
|
16625
|
+
}
|
|
16626
|
+
});
|
|
16627
|
+
}
|
|
16628
|
+
|
|
16629
|
+
// src/testkit/scenario/steeringInvariants.ts
|
|
16630
|
+
function isSteer(event) {
|
|
16631
|
+
return event.type === "user_input" && event.delivery === "mid_run";
|
|
16632
|
+
}
|
|
16633
|
+
function messageIndexOfText(call, text) {
|
|
16634
|
+
return call.messages.flatMap((message, index) => {
|
|
16635
|
+
if (message.role !== "user") return [];
|
|
16636
|
+
const body = message.content.map((block) => block.type === "text" ? block.text : "").join("");
|
|
16637
|
+
return body.includes(text) ? [index] : [];
|
|
16638
|
+
});
|
|
16639
|
+
}
|
|
16640
|
+
function toolMessageIndex(call, toolCallId) {
|
|
16641
|
+
return call.messages.findIndex((message) => message.role === "tool" && message.tool_call_id === toolCallId);
|
|
16642
|
+
}
|
|
16643
|
+
function validateSteeringInvariants(context, options = {}) {
|
|
16644
|
+
const disabled = new Set(options.disabled ?? []);
|
|
16645
|
+
const failures = [];
|
|
16646
|
+
const fail = (id, message) => {
|
|
16647
|
+
if (!disabled.has(id)) failures.push({ id, message });
|
|
16648
|
+
};
|
|
16649
|
+
const { history, modelCalls } = context;
|
|
16650
|
+
const steers = history.filter(isSteer);
|
|
16651
|
+
const seen = /* @__PURE__ */ new Map();
|
|
16652
|
+
for (const steer of steers) seen.set(steer.id, (seen.get(steer.id) ?? 0) + 1);
|
|
16653
|
+
for (const [id, count] of seen) {
|
|
16654
|
+
if (count > 1) fail("S1_STEER_UNIQUE", `\u63D2\u8BDD ${id} \u5728\u5386\u53F2\u91CC\u51FA\u73B0\u4E86 ${count} \u6B21`);
|
|
16655
|
+
}
|
|
16656
|
+
for (const steer of steers) {
|
|
16657
|
+
const text = userInputText(steer);
|
|
16658
|
+
const position = history.findIndex((event) => event.id === steer.id);
|
|
16659
|
+
const before = history.slice(0, position);
|
|
16660
|
+
const decided = /* @__PURE__ */ new Set();
|
|
16661
|
+
const settled = /* @__PURE__ */ new Set();
|
|
16662
|
+
let lastToolOutputId;
|
|
16663
|
+
for (const event of before) {
|
|
16664
|
+
if (event.type === "user_input" && event.delivery !== "mid_run") {
|
|
16665
|
+
decided.clear();
|
|
16666
|
+
settled.clear();
|
|
16667
|
+
lastToolOutputId = void 0;
|
|
16668
|
+
}
|
|
16669
|
+
if (event.type === "tool_call_decision") decided.add(event.tool_call_id);
|
|
16670
|
+
if (event.type === "tool_output") {
|
|
16671
|
+
settled.add(event.tool_call_id);
|
|
16672
|
+
lastToolOutputId = event.tool_call_id;
|
|
16673
|
+
}
|
|
16674
|
+
}
|
|
16675
|
+
const unsettled = [...decided].filter((id) => !settled.has(id));
|
|
16676
|
+
if (unsettled.length > 0 || lastToolOutputId === void 0) {
|
|
16677
|
+
fail(
|
|
16678
|
+
"S2_STEER_AT_BATCH_BOUNDARY",
|
|
16679
|
+
`\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`
|
|
16680
|
+
);
|
|
16681
|
+
continue;
|
|
16682
|
+
}
|
|
16683
|
+
const nextCallIndex = modelCalls.findIndex((call) => toolMessageIndex(call, lastToolOutputId) >= 0);
|
|
16684
|
+
if (nextCallIndex < 0) {
|
|
16685
|
+
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`);
|
|
16686
|
+
continue;
|
|
16687
|
+
}
|
|
16688
|
+
const nextCall = modelCalls[nextCallIndex];
|
|
16689
|
+
const at = messageIndexOfText(nextCall, text);
|
|
16690
|
+
const toolAt = toolMessageIndex(nextCall, lastToolOutputId);
|
|
16691
|
+
if (at.length === 0) {
|
|
16692
|
+
fail("S3_STEER_IN_NEXT_MODEL_CALL", `\u7B2C ${nextCallIndex + 1} \u6B21\u6A21\u578B\u8C03\u7528\u6CA1\u6709\u6536\u5230\u63D2\u8BDD ${steer.id}`);
|
|
16693
|
+
} else if (at[0] < toolAt) {
|
|
16694
|
+
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`);
|
|
16695
|
+
}
|
|
16696
|
+
for (const [index, call] of modelCalls.entries()) {
|
|
16697
|
+
const hits = messageIndexOfText(call, text).length;
|
|
16698
|
+
if (hits > 1) {
|
|
16699
|
+
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`);
|
|
16700
|
+
}
|
|
16701
|
+
if (index > nextCallIndex && hits === 0) {
|
|
16702
|
+
fail("S5_STEER_KEPT_IN_LATER_CALLS", `\u7B2C ${index + 1} \u6B21\u6A21\u578B\u8C03\u7528\u4E22\u4E86\u63D2\u8BDD ${steer.id}`);
|
|
16703
|
+
}
|
|
16704
|
+
}
|
|
16705
|
+
}
|
|
16706
|
+
return failures;
|
|
16707
|
+
}
|
|
16708
|
+
function assertSteeringInvariants(context, options = {}) {
|
|
16709
|
+
const failures = validateSteeringInvariants(context, options);
|
|
16710
|
+
if (failures.length > 0) {
|
|
16711
|
+
throw new Error(`[steeringInvariants] ${failures.map((f) => `${f.id}: ${f.message}`).join("\n")}`);
|
|
16712
|
+
}
|
|
16713
|
+
}
|
|
16714
|
+
|
|
16715
|
+
// src/testkit/scenario/graphScenario.ts
|
|
16716
|
+
var defaultContextBuilder = {
|
|
16717
|
+
async build({ history }) {
|
|
16718
|
+
return { llmMessages: formatAgentLlmMessages(convertEventsToAiMessages(history)) };
|
|
16719
|
+
}
|
|
16720
|
+
};
|
|
16721
|
+
var passthroughPreview = {
|
|
16722
|
+
async truncateObservation(params) {
|
|
16723
|
+
return { truncated: false, preview: params.text };
|
|
16724
|
+
}
|
|
16725
|
+
};
|
|
16726
|
+
function createGraphScenario(options) {
|
|
16727
|
+
const conversationId = options.conversationId ?? "conversation";
|
|
16728
|
+
const model = createScriptedInferenceHarness(options.model);
|
|
16729
|
+
const tools = createScriptedToolRuntime(options.tools ?? {});
|
|
16730
|
+
const steering = createPendingUserInputQueue();
|
|
16731
|
+
const checkpointer = new MemoryCheckpointer();
|
|
16732
|
+
const eventStore = new MemoryEventStore();
|
|
16733
|
+
const nextEventStoreId = createMonotonicEventStoreIdFactory();
|
|
16734
|
+
const live = [];
|
|
16735
|
+
const seed = [...options.history ?? []];
|
|
16736
|
+
const runs = /* @__PURE__ */ new Map();
|
|
16737
|
+
let current;
|
|
16738
|
+
let runCount = 0;
|
|
16739
|
+
const reasoner = new GraphAgentExecutor({
|
|
16740
|
+
llmCaller: model.getLlmCaller(),
|
|
16741
|
+
toolRuntime: tools,
|
|
16742
|
+
contextBuilder: options.contextBuilder ?? defaultContextBuilder,
|
|
16743
|
+
...options.tokenizer ? { tokenizer: options.tokenizer } : {}
|
|
16744
|
+
});
|
|
16745
|
+
const graph = new GraphExecutor(checkpointer, {
|
|
16746
|
+
maxSteps: options.maxSteps ?? 16,
|
|
16747
|
+
executionCheckpointPort: {
|
|
16748
|
+
commit: (key, state) => {
|
|
16749
|
+
const run = runs.get(key);
|
|
16750
|
+
if (!run) throw new Error(`[graphScenario] \u672A\u77E5\u8FD0\u884C\uFF1A${key}`);
|
|
16751
|
+
return run.persistence.commitCheckpoint(key, state);
|
|
16752
|
+
}
|
|
16753
|
+
}
|
|
16754
|
+
});
|
|
16755
|
+
graph.registerNode(new LlmNode({ reasoner }));
|
|
16756
|
+
graph.registerNode(new ToolNode({
|
|
16757
|
+
toolRuntime: tools,
|
|
16758
|
+
observationPreview: options.observationPreview ?? passthroughPreview
|
|
16759
|
+
}));
|
|
16760
|
+
graph.registerNode(new WaitUserNode({}));
|
|
16761
|
+
function openRun(runId, turnId) {
|
|
16762
|
+
const sequencer = new execution_exports.EventSequencer(conversationId);
|
|
16763
|
+
const eventBus = new execution_exports.EventBus(sequencer.getExecutionId());
|
|
16764
|
+
eventBus.on("event", (envelope) => live.push(envelope.payload));
|
|
16765
|
+
const publisher = new execution_exports.RuntimeEventPublisher(
|
|
16766
|
+
eventBus,
|
|
16767
|
+
sequencer,
|
|
16768
|
+
routingIdentityOf({ runId })
|
|
16769
|
+
);
|
|
16770
|
+
const persistence = new execution_exports.EventBusEventPersistence({
|
|
16771
|
+
eventBus,
|
|
16772
|
+
eventStore,
|
|
16773
|
+
nextEventStoreId,
|
|
16774
|
+
async checkpointWriter({ checkpointKey, checkpoint: checkpoint2, events }) {
|
|
16775
|
+
await options.beforeCheckpointWrite?.({ checkpointKey, events: events.map((item) => item.event) });
|
|
16776
|
+
const stored = JSON.parse(JSON.stringify(checkpoint2));
|
|
16777
|
+
await checkpointer.save(checkpointKey, parseEngineCheckpoint(stored));
|
|
16778
|
+
for (const event of events) await eventStore.append(event);
|
|
16779
|
+
}
|
|
16780
|
+
});
|
|
16781
|
+
persistence.connect();
|
|
16782
|
+
const run = {
|
|
16783
|
+
runId,
|
|
16784
|
+
turnId,
|
|
16785
|
+
eventBus,
|
|
16786
|
+
sink: (event, source) => publisher.publish(event, source),
|
|
16787
|
+
persistence,
|
|
16788
|
+
controller: new AbortController(),
|
|
16789
|
+
open: true
|
|
16790
|
+
};
|
|
16791
|
+
runs.set(runId, run);
|
|
16792
|
+
return run;
|
|
16793
|
+
}
|
|
16794
|
+
async function closeRun(run) {
|
|
16795
|
+
if (!run.open) return;
|
|
16796
|
+
run.open = false;
|
|
16797
|
+
run.persistence.finishCheckpointWrites();
|
|
16798
|
+
try {
|
|
16799
|
+
await run.persistence.drain();
|
|
16800
|
+
} finally {
|
|
16801
|
+
run.eventBus.close();
|
|
16802
|
+
}
|
|
16803
|
+
}
|
|
16804
|
+
function capabilities(run) {
|
|
16805
|
+
const toolContext = {
|
|
16806
|
+
runId: RunIdSchema.parse(run.runId),
|
|
16807
|
+
conversationId,
|
|
16808
|
+
turnId: run.turnId,
|
|
16809
|
+
abortSignal: run.controller.signal
|
|
16810
|
+
};
|
|
16811
|
+
return {
|
|
16812
|
+
signal: run.controller.signal,
|
|
16813
|
+
toolContext,
|
|
16814
|
+
runtimeEventSink: run.sink,
|
|
16815
|
+
pendingUserInputPort: steering.port
|
|
16816
|
+
};
|
|
16817
|
+
}
|
|
16818
|
+
async function settle(run, operation) {
|
|
16819
|
+
current = run;
|
|
16820
|
+
let status;
|
|
16821
|
+
let error;
|
|
16822
|
+
try {
|
|
16823
|
+
const checkpoint2 = await operation();
|
|
16824
|
+
status = checkpoint2.executionStatus === "awaiting_user" ? "awaiting_user" : "yielded";
|
|
16825
|
+
} catch (caught) {
|
|
16826
|
+
const signal = run.controller.signal;
|
|
16827
|
+
if (signal.aborted) {
|
|
16828
|
+
status = isRunPauseSignal(signal) ? "paused" : "cancelled";
|
|
16829
|
+
} else {
|
|
16830
|
+
status = "failed";
|
|
16831
|
+
error = caught;
|
|
16832
|
+
}
|
|
16833
|
+
} finally {
|
|
16834
|
+
current = void 0;
|
|
16835
|
+
}
|
|
16836
|
+
if (status === "paused" || status === "awaiting_user") {
|
|
16837
|
+
await run.persistence.drain().catch(() => void 0);
|
|
16838
|
+
} else {
|
|
16839
|
+
await closeRun(run).catch((caught) => {
|
|
16840
|
+
status = "failed";
|
|
16841
|
+
error ??= caught;
|
|
16842
|
+
});
|
|
16843
|
+
}
|
|
16844
|
+
return {
|
|
16845
|
+
runId: run.runId,
|
|
16846
|
+
status,
|
|
16847
|
+
...error !== void 0 ? { error } : {},
|
|
16848
|
+
undeliveredSteers: steering.drain()
|
|
16849
|
+
};
|
|
16850
|
+
}
|
|
16851
|
+
async function history() {
|
|
16852
|
+
for (const run of runs.values()) {
|
|
16853
|
+
if (run.open) await run.persistence.drain().catch(() => void 0);
|
|
16854
|
+
}
|
|
16855
|
+
return [...seed, ...(await eventStore.range(conversationId)).map((item) => item.event)];
|
|
16856
|
+
}
|
|
16857
|
+
let lastPaused;
|
|
16858
|
+
return {
|
|
16859
|
+
conversationId,
|
|
16860
|
+
model,
|
|
16861
|
+
tools,
|
|
16862
|
+
steering,
|
|
16863
|
+
live,
|
|
16864
|
+
async start(input) {
|
|
16865
|
+
const { query, runId: requestedRunId, request } = typeof input === "string" ? { query: input, runId: void 0, request: void 0 } : input;
|
|
16866
|
+
runCount += 1;
|
|
16867
|
+
const runId = requestedRunId ?? `run_${runCount}`;
|
|
16868
|
+
const turnId = `turn_${runCount}`;
|
|
16869
|
+
const prior = await history();
|
|
16870
|
+
const run = openRun(runId, turnId);
|
|
16871
|
+
const userInput = run.sink(
|
|
16872
|
+
createUserInputEvent(`user_${runId}`, conversationId, turnId, query),
|
|
16873
|
+
"graphScenario.user_input"
|
|
16874
|
+
);
|
|
16875
|
+
const toolNames = Object.keys(options.tools ?? {});
|
|
16876
|
+
const outcome = await settle(run, async () => (await graph.startSession(runId, {
|
|
16877
|
+
...capabilities(run),
|
|
16878
|
+
runId: RunIdSchema.parse(runId),
|
|
16879
|
+
conversationId,
|
|
16880
|
+
turnId,
|
|
16881
|
+
history: [...prior, userInput],
|
|
16882
|
+
request: {
|
|
16883
|
+
query,
|
|
16884
|
+
promptKey: "agent",
|
|
16885
|
+
model_id: "scripted-model",
|
|
16886
|
+
enableTools: toolNames.length > 0,
|
|
16887
|
+
availableTools: toolNames,
|
|
16888
|
+
...request
|
|
16889
|
+
}
|
|
16890
|
+
}, "llm")).checkpoint);
|
|
16891
|
+
lastPaused = outcome.status === "paused" ? run : void 0;
|
|
16892
|
+
return outcome;
|
|
16893
|
+
},
|
|
16894
|
+
async continue() {
|
|
16895
|
+
const run = lastPaused;
|
|
16896
|
+
if (!run) throw new Error("[graphScenario] \u6CA1\u6709\u6682\u505C\u4E2D\u7684\u8FD0\u884C\u53EF\u4EE5\u7EE7\u7EED");
|
|
16897
|
+
const saved = await checkpointer.load(run.runId);
|
|
16898
|
+
if (!saved?.revision) throw new Error(`[graphScenario] \u8FD0\u884C ${run.runId} \u6CA1\u6709\u65AD\u70B9`);
|
|
16899
|
+
run.controller = new AbortController();
|
|
16900
|
+
const outcome = await settle(run, async () => (await graph.continueSession(run.runId, {
|
|
16901
|
+
expectedRevision: saved.revision ?? 0,
|
|
16902
|
+
capabilities: capabilities(run)
|
|
16903
|
+
})).checkpoint);
|
|
16904
|
+
lastPaused = outcome.status === "paused" ? run : void 0;
|
|
16905
|
+
return outcome;
|
|
16906
|
+
},
|
|
16907
|
+
steer: (content, steerOptions) => steering.submit(content, steerOptions),
|
|
16908
|
+
pause() {
|
|
16909
|
+
if (!current) throw new Error("[graphScenario] \u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u53EF\u4EE5\u6682\u505C");
|
|
16910
|
+
current.controller.abort(new RunPauseRequested());
|
|
16911
|
+
},
|
|
16912
|
+
cancel() {
|
|
16913
|
+
if (!current) throw new Error("[graphScenario] \u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u53EF\u4EE5\u53D6\u6D88");
|
|
16914
|
+
current.controller.abort(new Error("Run cancelled by scenario"));
|
|
16915
|
+
},
|
|
16916
|
+
history,
|
|
16917
|
+
checkpoint: async (runId) => checkpointer.load(runId ?? [...runs.keys()].at(-1) ?? ""),
|
|
16918
|
+
timeline: async (timelineOptions) => formatRuntimeTimeline(await history(), timelineOptions),
|
|
16919
|
+
modelCalls: () => model.getCalls(),
|
|
16920
|
+
async assertInvariants(invariantOptions) {
|
|
16921
|
+
const events = await history();
|
|
16922
|
+
const ids = events.map((event) => event.id);
|
|
16923
|
+
const duplicated = ids.filter((id, index) => ids.indexOf(id) !== index);
|
|
16924
|
+
try {
|
|
16925
|
+
if (duplicated.length > 0) throw new Error(`[graphScenario] \u5386\u53F2\u91CC\u6709\u91CD\u590D\u4E8B\u4EF6\uFF1A${duplicated.join(", ")}`);
|
|
16926
|
+
assertSteeringInvariants({ history: events, modelCalls: model.getCalls() }, invariantOptions);
|
|
16927
|
+
} catch (error) {
|
|
16928
|
+
const timeline = formatRuntimeTimeline(events).map((line) => ` ${line}`).join("\n");
|
|
16929
|
+
throw new Error(`${error instanceof Error ? error.message : String(error)}
|
|
16930
|
+
\u65F6\u95F4\u7EBF\uFF1A
|
|
16931
|
+
${timeline}`);
|
|
16932
|
+
}
|
|
16933
|
+
},
|
|
16934
|
+
async close() {
|
|
16935
|
+
for (const run of runs.values()) await closeRun(run).catch(() => void 0);
|
|
16936
|
+
}
|
|
16937
|
+
};
|
|
16938
|
+
}
|
|
16939
|
+
|
|
16295
16940
|
// src/testkit/tool-fixtures/toolContext.ts
|
|
16296
16941
|
function createToolContextFixture(options = {}) {
|
|
16297
16942
|
const persistedHistoryEvents = options.persistedHistoryEvents ?? options.historyEvents ?? [];
|
|
@@ -16316,6 +16961,6 @@ function createToolContextFixture(options = {}) {
|
|
|
16316
16961
|
return context;
|
|
16317
16962
|
}
|
|
16318
16963
|
|
|
16319
|
-
export { assertContextPolicyInvariants, assertRunInvariants, assertions_exports as assertions, createCollectingAuditPort, createDefaultGraphExecutor, createGraphLoopHarness, createMockTelemetryPort, createMockTokenizerPort, createReplayHarness, createRunSupervisorHarness, createScriptedInferenceHarness, createToolContextFixture, expectFinalStepForcedTools, expectMessagesContainText, expectMessagesContainToolResult, expectRunEndedWithFinalAnswer, expectToolOutputFedBackToHistory, validateContextPolicyInvariants, validateRunInvariants };
|
|
16964
|
+
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
16965
|
//# sourceMappingURL=testkit.js.map
|
|
16321
16966
|
//# sourceMappingURL=testkit.js.map
|