@linnlabs/linnkit 0.42.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 +64 -0
- package/dist/cli.cjs +113 -5
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +113 -5
- 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/events.d.cts +4 -0
- package/dist/contracts/events.d.ts +4 -0
- package/dist/contracts/messages.d.cts +226 -2
- package/dist/contracts/messages.d.ts +226 -2
- package/dist/contracts/sse.d.cts +65 -1
- package/dist/contracts/sse.d.ts +65 -1
- 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 +115 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +115 -5
- package/dist/index.js.map +1 -1
- package/dist/quickstart.cjs +113 -5
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.js +113 -5
- package/dist/quickstart.js.map +1 -1
- 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 +2 -1
- package/dist/runtime-kernel/graph-engine/engine.d.ts +2 -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 +113 -5
- 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 +113 -5
- 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 +683 -18
- 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 +675 -19
- 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/docs/integration/tool-development-guide.md +1 -0
- package/package.json +2 -2
package/dist/testkit.cjs
CHANGED
|
@@ -1090,6 +1090,10 @@ var UserInputMessage = BaseMessage.extend({
|
|
|
1090
1090
|
type: zod.z.literal("user_input"),
|
|
1091
1091
|
attachments: RuntimeResourceRefs.optional()
|
|
1092
1092
|
});
|
|
1093
|
+
var UserSteerMessage = BaseMessage.extend({
|
|
1094
|
+
role: zod.z.literal("user"),
|
|
1095
|
+
type: zod.z.literal("user_steer")
|
|
1096
|
+
});
|
|
1093
1097
|
var UserContextMessage = BaseMessage.extend({
|
|
1094
1098
|
role: zod.z.literal("user"),
|
|
1095
1099
|
// 产品上下文种类由 Host fence metadata 表达,不进入框架消息枚举。
|
|
@@ -1098,7 +1102,7 @@ var UserContextMessage = BaseMessage.extend({
|
|
|
1098
1102
|
"task_request"
|
|
1099
1103
|
])
|
|
1100
1104
|
});
|
|
1101
|
-
var UserMessage = zod.z.union([UserInputMessage, UserContextMessage]);
|
|
1105
|
+
var UserMessage = zod.z.union([UserInputMessage, UserSteerMessage, UserContextMessage]);
|
|
1102
1106
|
var AssistantMessage = BaseMessage.extend({
|
|
1103
1107
|
role: zod.z.literal("assistant"),
|
|
1104
1108
|
type: zod.z.enum(["thought", "final_answer", "tool_code", "tool_calls", "task_completion"])
|
|
@@ -1700,7 +1704,12 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
|
|
|
1700
1704
|
content: zod.z.string(),
|
|
1701
1705
|
raw_content: zod.z.string().optional(),
|
|
1702
1706
|
source: zod.z.enum(["user", "editor", "system"]).default("user"),
|
|
1703
|
-
attachments: RuntimeResourceRefs.optional()
|
|
1707
|
+
attachments: RuntimeResourceRefs.optional(),
|
|
1708
|
+
/**
|
|
1709
|
+
* 运行中途送达的用户输入(插话)。缺省表示运行起点的输入。
|
|
1710
|
+
* 上下文里投影为 `user_steer`,不改变“当前轮从哪条 user_input 开始”的判定。
|
|
1711
|
+
*/
|
|
1712
|
+
delivery: zod.z.literal("mid_run").optional()
|
|
1704
1713
|
}),
|
|
1705
1714
|
BaseEvent.extend({
|
|
1706
1715
|
type: zod.z.literal("thought"),
|
|
@@ -2160,6 +2169,11 @@ zod.z.object({
|
|
|
2160
2169
|
run_id: RunIdSchema,
|
|
2161
2170
|
execution_id: ExecutionIdSchema
|
|
2162
2171
|
});
|
|
2172
|
+
var SSEUserInputEvent = BaseSSEEvent.extend({
|
|
2173
|
+
type: zod.z.literal("user_input"),
|
|
2174
|
+
content: zod.z.string(),
|
|
2175
|
+
delivery: zod.z.literal("mid_run")
|
|
2176
|
+
});
|
|
2163
2177
|
var SSEThoughtEvent = BaseSSEEvent.extend({
|
|
2164
2178
|
type: zod.z.literal("thought"),
|
|
2165
2179
|
thought_message_id: ThoughtMessageIdSchema.optional(),
|
|
@@ -2314,6 +2328,7 @@ var SSESummarizationErrorEvent = BaseSSEEvent.extend({
|
|
|
2314
2328
|
error: zod.z.string()
|
|
2315
2329
|
});
|
|
2316
2330
|
zod.z.discriminatedUnion("type", [
|
|
2331
|
+
SSEUserInputEvent,
|
|
2317
2332
|
SSEThoughtEvent,
|
|
2318
2333
|
SSEFinalAnswerChunkEvent,
|
|
2319
2334
|
SSEFinalAnswerResetEvent,
|
|
@@ -2636,6 +2651,7 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
|
|
|
2636
2651
|
"runtimeEventCommitPort",
|
|
2637
2652
|
"commitExecutionBoundary",
|
|
2638
2653
|
"toolRecoveryPort",
|
|
2654
|
+
"pendingUserInputPort",
|
|
2639
2655
|
"runtimeFailureFactSink",
|
|
2640
2656
|
"signal",
|
|
2641
2657
|
"summarizationCallbacks",
|
|
@@ -3199,6 +3215,16 @@ function mergeResumeSessionLocal(persistedLocal, localPatch) {
|
|
|
3199
3215
|
}
|
|
3200
3216
|
};
|
|
3201
3217
|
}
|
|
3218
|
+
function resolveResumeNodeId(local, requested) {
|
|
3219
|
+
const pending = local?.pendingToolCalls;
|
|
3220
|
+
if (!Array.isArray(pending) || pending.length === 0) return requested ?? "llm";
|
|
3221
|
+
if (requested !== void 0 && requested !== "tool") {
|
|
3222
|
+
throw new Error(
|
|
3223
|
+
`Graph resume must first run ${pending.length} pending tool call(s) from the interrupted batch: requested node=${requested}`
|
|
3224
|
+
);
|
|
3225
|
+
}
|
|
3226
|
+
return "tool";
|
|
3227
|
+
}
|
|
3202
3228
|
var GraphExecutor = class {
|
|
3203
3229
|
constructor(checkpointer, config = {}) {
|
|
3204
3230
|
this.checkpointer = checkpointer;
|
|
@@ -3311,13 +3337,14 @@ var GraphExecutor = class {
|
|
|
3311
3337
|
);
|
|
3312
3338
|
}
|
|
3313
3339
|
const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
|
|
3340
|
+
const nodeId = resolveResumeNodeId(resumedLocal, input.nodeId);
|
|
3314
3341
|
if (this.executionCheckpointPort && current.local?.executorLocal) {
|
|
3315
3342
|
resumedLocal.executorLocal = { ...current.local.executorLocal };
|
|
3316
3343
|
}
|
|
3317
3344
|
this.ephemeralLocals.set(checkpointKey, resumedLocal);
|
|
3318
3345
|
await this.commitCheckpoint(checkpointKey, {
|
|
3319
3346
|
...current,
|
|
3320
|
-
nodeId
|
|
3347
|
+
nodeId,
|
|
3321
3348
|
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3322
3349
|
revision: currentRevision + 1,
|
|
3323
3350
|
local: sanitizeCheckpointLocal(resumedLocal)
|
|
@@ -6835,6 +6862,8 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
6835
6862
|
case "run_execution_metrics":
|
|
6836
6863
|
case "history_summary":
|
|
6837
6864
|
return "event_bus_sse";
|
|
6865
|
+
case "user_input":
|
|
6866
|
+
return event.type === "user_input" && event.delivery === "mid_run" ? "event_bus_sse" : "none";
|
|
6838
6867
|
case "audit_envelope":
|
|
6839
6868
|
return "none";
|
|
6840
6869
|
default:
|
|
@@ -7278,6 +7307,16 @@ function requireEventTimestamp(value) {
|
|
|
7278
7307
|
function applyRuntimeEventToMemory(event, memory) {
|
|
7279
7308
|
switch (event.type) {
|
|
7280
7309
|
case "user_input": {
|
|
7310
|
+
if (event.delivery === "mid_run") {
|
|
7311
|
+
memory.appendMessage({
|
|
7312
|
+
id: event.id,
|
|
7313
|
+
role: "user",
|
|
7314
|
+
type: "user_steer",
|
|
7315
|
+
content: event.content,
|
|
7316
|
+
timestamp: event.timestamp
|
|
7317
|
+
});
|
|
7318
|
+
break;
|
|
7319
|
+
}
|
|
7281
7320
|
memory.addUserMessage(event.content, event.id, event.attachments);
|
|
7282
7321
|
break;
|
|
7283
7322
|
}
|
|
@@ -8985,6 +9024,62 @@ async function commitToolBoundary(state, result) {
|
|
|
8985
9024
|
await state.local.commitExecutionBoundary(state);
|
|
8986
9025
|
}
|
|
8987
9026
|
|
|
9027
|
+
// src/runtime-kernel/graph-engine/nodes/toolNode.pendingUserInput.ts
|
|
9028
|
+
function isPendingUserInputPort(value) {
|
|
9029
|
+
return !!value && typeof value === "object" && typeof Reflect.get(value, "claim") === "function" && typeof Reflect.get(value, "confirm") === "function" && typeof Reflect.get(value, "release") === "function";
|
|
9030
|
+
}
|
|
9031
|
+
function readRemainingSteps(state) {
|
|
9032
|
+
const value = state.local?.executorLocal?.remainingSteps;
|
|
9033
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
9034
|
+
}
|
|
9035
|
+
function readIdentity(value, field) {
|
|
9036
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
9037
|
+
throw new Error(`ToolNode pending user input requires ${field}`);
|
|
9038
|
+
}
|
|
9039
|
+
return value;
|
|
9040
|
+
}
|
|
9041
|
+
async function claimPendingUserInputs(state, result) {
|
|
9042
|
+
if (result.kind !== "route" || result.nextNodeId !== "llm") return void 0;
|
|
9043
|
+
const local = state.local;
|
|
9044
|
+
const port = local?.pendingUserInputPort;
|
|
9045
|
+
if (!isPendingUserInputPort(port)) return void 0;
|
|
9046
|
+
const signal = local?.signal;
|
|
9047
|
+
if (signal?.aborted || isRunPauseSignal(signal)) return void 0;
|
|
9048
|
+
const remainingSteps = readRemainingSteps(state);
|
|
9049
|
+
if (remainingSteps !== void 0 && remainingSteps < 1) return void 0;
|
|
9050
|
+
const inputs = await port.claim();
|
|
9051
|
+
if (inputs.length === 0) return void 0;
|
|
9052
|
+
const ids = inputs.map((input) => input.id);
|
|
9053
|
+
try {
|
|
9054
|
+
const conversationId = readIdentity(local?.conversationId, "conversationId");
|
|
9055
|
+
const turnId = readIdentity(local?.turnId, "turnId");
|
|
9056
|
+
const sink = requireRuntimeEventSink(local);
|
|
9057
|
+
const events = inputs.map((input) => sink(
|
|
9058
|
+
createUserInputEvent(readIdentity(input.id, "input id"), conversationId, turnId, input.content, {
|
|
9059
|
+
timestamp: input.timestamp ?? Date.now(),
|
|
9060
|
+
delivery: "mid_run"
|
|
9061
|
+
}),
|
|
9062
|
+
"ToolNode.pending_user_input"
|
|
9063
|
+
));
|
|
9064
|
+
state.local = {
|
|
9065
|
+
...state.local,
|
|
9066
|
+
history: appendWorkingHistory(parseRuntimeEvents(state.local?.history ?? []), events)
|
|
9067
|
+
};
|
|
9068
|
+
return {
|
|
9069
|
+
events,
|
|
9070
|
+
confirm: async () => {
|
|
9071
|
+
await port.confirm(ids);
|
|
9072
|
+
},
|
|
9073
|
+
release: async () => {
|
|
9074
|
+
await port.release(ids);
|
|
9075
|
+
}
|
|
9076
|
+
};
|
|
9077
|
+
} catch (error) {
|
|
9078
|
+
await port.release(ids);
|
|
9079
|
+
throw error;
|
|
9080
|
+
}
|
|
9081
|
+
}
|
|
9082
|
+
|
|
8988
9083
|
// src/runtime-kernel/graph-engine/nodes/toolNode.ts
|
|
8989
9084
|
var logger11 = new Logger("ToolNode");
|
|
8990
9085
|
function isAbortSignal(value) {
|
|
@@ -9152,7 +9247,19 @@ var ToolNode = class {
|
|
|
9152
9247
|
});
|
|
9153
9248
|
throw result.error;
|
|
9154
9249
|
}
|
|
9155
|
-
await
|
|
9250
|
+
const steering = await claimPendingUserInputs(state, result);
|
|
9251
|
+
if (steering) {
|
|
9252
|
+
result = { ...result, events: [...result.events ?? [], ...steering.events] };
|
|
9253
|
+
try {
|
|
9254
|
+
await commitToolBoundary(state, result);
|
|
9255
|
+
} catch (error) {
|
|
9256
|
+
await steering.release();
|
|
9257
|
+
throw error;
|
|
9258
|
+
}
|
|
9259
|
+
await steering.confirm();
|
|
9260
|
+
} else {
|
|
9261
|
+
await commitToolBoundary(state, result);
|
|
9262
|
+
}
|
|
9156
9263
|
if (Array.isArray(result.events) && result.events.length > 0) {
|
|
9157
9264
|
events.push(...result.events);
|
|
9158
9265
|
}
|
|
@@ -9910,7 +10017,8 @@ function parseEngineCheckpoint(value) {
|
|
|
9910
10017
|
"runtimeFailureFactSink",
|
|
9911
10018
|
"summarizationCallbacks",
|
|
9912
10019
|
"commitExecutionBoundary",
|
|
9913
|
-
"toolRecoveryPort"
|
|
10020
|
+
"toolRecoveryPort",
|
|
10021
|
+
"pendingUserInputPort"
|
|
9914
10022
|
]) {
|
|
9915
10023
|
if (result.local && Object.hasOwn(result.local, key)) {
|
|
9916
10024
|
throw new Error(`Checkpoint must not contain execution capability: ${key}`);
|
|
@@ -14743,31 +14851,37 @@ function createScriptedModelCatalog() {
|
|
|
14743
14851
|
getModelsByUIVisibility: () => []
|
|
14744
14852
|
};
|
|
14745
14853
|
}
|
|
14854
|
+
function argumentsJsonOf(toolCall) {
|
|
14855
|
+
if (toolCall.argumentsJson !== void 0) return toolCall.argumentsJson;
|
|
14856
|
+
return JSON.stringify(toolCall.arguments ?? {});
|
|
14857
|
+
}
|
|
14746
14858
|
function parseArguments(toolCall) {
|
|
14747
|
-
const parsed = JSON.parse(toolCall
|
|
14859
|
+
const parsed = JSON.parse(argumentsJsonOf(toolCall));
|
|
14748
14860
|
const record = toSerializableJsonRecord(parsed);
|
|
14749
14861
|
if (!record) {
|
|
14750
14862
|
throw new Error(`[scriptedInferenceHarness] ${toolCall.name} arguments \u5FC5\u987B\u662F JSON object\u3002`);
|
|
14751
14863
|
}
|
|
14752
14864
|
return record;
|
|
14753
14865
|
}
|
|
14754
|
-
function createScriptedInferenceHarness(
|
|
14755
|
-
const streamTurns = [...
|
|
14866
|
+
function createScriptedInferenceHarness(script, options = {}) {
|
|
14867
|
+
const streamTurns = typeof script === "function" ? void 0 : [...script];
|
|
14868
|
+
const respond = typeof script === "function" ? script : void 0;
|
|
14756
14869
|
const calls = [];
|
|
14757
14870
|
const inferencePort = {
|
|
14758
14871
|
async *stream(request) {
|
|
14759
|
-
const turn = streamTurns.shift();
|
|
14760
|
-
if (!turn) {
|
|
14761
|
-
throw new Error("[scriptedInferenceHarness] \u6CA1\u6709\u53EF\u6D88\u8D39\u7684 scripted turn\uFF0C\u8BF7\u8865\u9F50\u811A\u672C\u3002");
|
|
14762
|
-
}
|
|
14763
14872
|
const call = {
|
|
14764
14873
|
request,
|
|
14765
14874
|
modelId: request.model_id,
|
|
14766
14875
|
messages: request.messages,
|
|
14767
14876
|
options: callOptions(request)
|
|
14768
14877
|
};
|
|
14878
|
+
const callIndex = calls.length;
|
|
14879
|
+
const turn = respond ? await respond(call, callIndex) : streamTurns?.shift();
|
|
14880
|
+
if (!turn) {
|
|
14881
|
+
throw new Error("[scriptedInferenceHarness] \u6CA1\u6709\u53EF\u6D88\u8D39\u7684 scripted turn\uFF0C\u8BF7\u8865\u9F50\u811A\u672C\u3002");
|
|
14882
|
+
}
|
|
14769
14883
|
calls.push(call);
|
|
14770
|
-
turn.assertCall?.(call);
|
|
14884
|
+
await turn.assertCall?.(call);
|
|
14771
14885
|
yield { type: "start", model_id: request.model_id, attempt_id: request.invocation.attempt_id };
|
|
14772
14886
|
if (turn.failure) {
|
|
14773
14887
|
yield { type: "failure", ...turn.failure };
|
|
@@ -14804,23 +14918,24 @@ function createScriptedInferenceHarness(turns, options = {}) {
|
|
|
14804
14918
|
}
|
|
14805
14919
|
for (const [position, toolCall] of (turn.toolCalls ?? []).entries()) {
|
|
14806
14920
|
const index = toolCall.index ?? position;
|
|
14921
|
+
const id = toolCall.id ?? `call_${callIndex + 1}_${position + 1}`;
|
|
14807
14922
|
yield {
|
|
14808
14923
|
type: "tool_call_start",
|
|
14809
14924
|
index,
|
|
14810
14925
|
part_index: nextAssistantPartIndex++,
|
|
14811
|
-
id
|
|
14926
|
+
id,
|
|
14812
14927
|
name: toolCall.name
|
|
14813
14928
|
};
|
|
14814
14929
|
yield {
|
|
14815
14930
|
type: "tool_argument_delta",
|
|
14816
14931
|
index,
|
|
14817
|
-
json_delta: toolCall
|
|
14932
|
+
json_delta: argumentsJsonOf(toolCall)
|
|
14818
14933
|
};
|
|
14819
14934
|
yield {
|
|
14820
14935
|
type: "tool_call_end",
|
|
14821
14936
|
index,
|
|
14822
14937
|
call: {
|
|
14823
|
-
id
|
|
14938
|
+
id,
|
|
14824
14939
|
name: toolCall.name,
|
|
14825
14940
|
arguments: parseArguments(toolCall),
|
|
14826
14941
|
...toolCall.continuations?.length ? { continuation: toolCall.continuations } : {}
|
|
@@ -14847,8 +14962,9 @@ function createScriptedInferenceHarness(turns, options = {}) {
|
|
|
14847
14962
|
getCalls: () => [...calls],
|
|
14848
14963
|
getConsumedTurnCount: () => calls.length,
|
|
14849
14964
|
getLlmCaller: () => llmCaller,
|
|
14965
|
+
getInferencePort: () => inferencePort,
|
|
14850
14966
|
assertAllTurnsConsumed() {
|
|
14851
|
-
if (streamTurns.length > 0) {
|
|
14967
|
+
if (streamTurns && streamTurns.length > 0) {
|
|
14852
14968
|
throw new Error(
|
|
14853
14969
|
`[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`
|
|
14854
14970
|
);
|
|
@@ -14919,6 +15035,8 @@ var MessageFormatter = class {
|
|
|
14919
15035
|
content,
|
|
14920
15036
|
...message.attachments ? { attachments: message.attachments } : {}
|
|
14921
15037
|
};
|
|
15038
|
+
case "user_steer":
|
|
15039
|
+
return { role: "user", content };
|
|
14922
15040
|
case "context_injection": {
|
|
14923
15041
|
const fenceKind = metadata?.fenceKind;
|
|
14924
15042
|
if (!fenceKind) {
|
|
@@ -14971,7 +15089,10 @@ var MessageFormatter = class {
|
|
|
14971
15089
|
}
|
|
14972
15090
|
}
|
|
14973
15091
|
};
|
|
14974
|
-
new MessageFormatter();
|
|
15092
|
+
var messageFormatter = new MessageFormatter();
|
|
15093
|
+
function formatAgentLlmMessages(messages, options = {}) {
|
|
15094
|
+
return messageFormatter.format(messages, { nativeTools: true, ...options });
|
|
15095
|
+
}
|
|
14975
15096
|
zod.z.object({
|
|
14976
15097
|
systemPrompt: zod.z.string(),
|
|
14977
15098
|
messages: zod.z.array(AiMessage)
|
|
@@ -15113,6 +15234,7 @@ function convertAiMessageToEvent(message, context) {
|
|
|
15113
15234
|
type: "user_input",
|
|
15114
15235
|
content: message.content,
|
|
15115
15236
|
source: "user",
|
|
15237
|
+
...message.type === "user_steer" ? { delivery: "mid_run" } : {},
|
|
15116
15238
|
...message.type === "user_input" && message.attachments ? { attachments: message.attachments } : {}
|
|
15117
15239
|
};
|
|
15118
15240
|
return event;
|
|
@@ -16283,6 +16405,540 @@ function createMockTokenizerPort(options = {}) {
|
|
|
16283
16405
|
};
|
|
16284
16406
|
}
|
|
16285
16407
|
|
|
16408
|
+
// src/testkit/scenario/pendingUserInputQueue.ts
|
|
16409
|
+
function createPendingUserInputQueue() {
|
|
16410
|
+
let pending = [];
|
|
16411
|
+
const claimed = /* @__PURE__ */ new Map();
|
|
16412
|
+
const delivered = [];
|
|
16413
|
+
let sequence = 0;
|
|
16414
|
+
const port = {
|
|
16415
|
+
claim() {
|
|
16416
|
+
const taken = pending;
|
|
16417
|
+
pending = [];
|
|
16418
|
+
for (const input of taken) claimed.set(input.id, input);
|
|
16419
|
+
return taken;
|
|
16420
|
+
},
|
|
16421
|
+
confirm(ids) {
|
|
16422
|
+
for (const id of ids) {
|
|
16423
|
+
const input = claimed.get(id);
|
|
16424
|
+
if (!input) continue;
|
|
16425
|
+
claimed.delete(id);
|
|
16426
|
+
delivered.push(input);
|
|
16427
|
+
}
|
|
16428
|
+
},
|
|
16429
|
+
release(ids) {
|
|
16430
|
+
const returned = ids.flatMap((id) => {
|
|
16431
|
+
const input = claimed.get(id);
|
|
16432
|
+
claimed.delete(id);
|
|
16433
|
+
return input ? [input] : [];
|
|
16434
|
+
});
|
|
16435
|
+
pending = [...returned, ...pending];
|
|
16436
|
+
}
|
|
16437
|
+
};
|
|
16438
|
+
return {
|
|
16439
|
+
port,
|
|
16440
|
+
submit(content, options = {}) {
|
|
16441
|
+
sequence += 1;
|
|
16442
|
+
const id = options.id ?? `steer_${sequence}`;
|
|
16443
|
+
pending.push({ id, content, timestamp: options.timestamp ?? Date.now() });
|
|
16444
|
+
return id;
|
|
16445
|
+
},
|
|
16446
|
+
withdraw(id) {
|
|
16447
|
+
if (pending.some((input) => input.id === id)) {
|
|
16448
|
+
pending = pending.filter((input) => input.id !== id);
|
|
16449
|
+
return "withdrawn";
|
|
16450
|
+
}
|
|
16451
|
+
if (claimed.has(id)) return "claimed";
|
|
16452
|
+
if (delivered.some((input) => input.id === id)) return "delivered";
|
|
16453
|
+
return "unknown";
|
|
16454
|
+
},
|
|
16455
|
+
drain() {
|
|
16456
|
+
const taken = pending;
|
|
16457
|
+
pending = [];
|
|
16458
|
+
return taken;
|
|
16459
|
+
},
|
|
16460
|
+
pending: () => [...pending],
|
|
16461
|
+
claimed: () => [...claimed.values()],
|
|
16462
|
+
delivered: () => [...delivered]
|
|
16463
|
+
};
|
|
16464
|
+
}
|
|
16465
|
+
|
|
16466
|
+
// src/testkit/scenario/runtimeEventRecorder.ts
|
|
16467
|
+
function routingIdentityOf(options) {
|
|
16468
|
+
const child = options.parentRunId !== void 0;
|
|
16469
|
+
return {
|
|
16470
|
+
run_id: RunIdSchema.parse(options.runId ?? "run"),
|
|
16471
|
+
...child ? { parent_run_id: RunIdSchema.parse(options.parentRunId) } : {},
|
|
16472
|
+
lane: options.lane ?? (child ? "child" : "foreground"),
|
|
16473
|
+
visibility: options.visibility ?? (child ? "parent-trace" : "conversation")
|
|
16474
|
+
};
|
|
16475
|
+
}
|
|
16476
|
+
function createRuntimeEventRecorder(options = {}) {
|
|
16477
|
+
const sequencer = new execution_exports.EventSequencer(options.conversationId ?? "conversation");
|
|
16478
|
+
const eventBus = new execution_exports.EventBus(sequencer.getExecutionId());
|
|
16479
|
+
const events = [];
|
|
16480
|
+
eventBus.on("event", (envelope) => events.push(envelope.payload));
|
|
16481
|
+
const publisher = new execution_exports.RuntimeEventPublisher(eventBus, sequencer, routingIdentityOf(options));
|
|
16482
|
+
return {
|
|
16483
|
+
sink: (event, source) => publisher.publish(event, source),
|
|
16484
|
+
events,
|
|
16485
|
+
eventBus,
|
|
16486
|
+
sequencer,
|
|
16487
|
+
publisher,
|
|
16488
|
+
publisherFor: (identity) => new execution_exports.RuntimeEventPublisher(eventBus, sequencer, identity),
|
|
16489
|
+
close: () => eventBus.close()
|
|
16490
|
+
};
|
|
16491
|
+
}
|
|
16492
|
+
|
|
16493
|
+
// src/testkit/scenario/scriptedToolRuntime.ts
|
|
16494
|
+
var EMPTY_PARAMETERS = { type: "object", properties: {} };
|
|
16495
|
+
function specOf(entry) {
|
|
16496
|
+
return typeof entry === "function" ? { run: entry } : entry;
|
|
16497
|
+
}
|
|
16498
|
+
function toResult(outcome, toolName, durationMs) {
|
|
16499
|
+
if (typeof outcome === "string") {
|
|
16500
|
+
return { success: true, result: JSON.stringify({ data: {}, observation: outcome }), durationMs };
|
|
16501
|
+
}
|
|
16502
|
+
if (outcome.error !== void 0) {
|
|
16503
|
+
return {
|
|
16504
|
+
success: false,
|
|
16505
|
+
error: outcome.error,
|
|
16506
|
+
...outcome.errorCode ? { errorCode: outcome.errorCode } : {},
|
|
16507
|
+
errorKind: "execution",
|
|
16508
|
+
durationMs
|
|
16509
|
+
};
|
|
16510
|
+
}
|
|
16511
|
+
return {
|
|
16512
|
+
success: true,
|
|
16513
|
+
result: JSON.stringify({ data: outcome.data ?? {}, observation: outcome.observation ?? `${toolName} done` }),
|
|
16514
|
+
durationMs
|
|
16515
|
+
};
|
|
16516
|
+
}
|
|
16517
|
+
function createScriptedToolRuntime(tools = {}) {
|
|
16518
|
+
const specs = new Map(Object.entries(tools).map(([name, entry]) => [name, specOf(entry)]));
|
|
16519
|
+
const executions = [];
|
|
16520
|
+
const counts = /* @__PURE__ */ new Map();
|
|
16521
|
+
return {
|
|
16522
|
+
executions,
|
|
16523
|
+
getToolSchemas() {
|
|
16524
|
+
return [...specs].map(([name, spec]) => ({
|
|
16525
|
+
type: "function",
|
|
16526
|
+
function: {
|
|
16527
|
+
name,
|
|
16528
|
+
description: spec.description ?? `scripted tool ${name}`,
|
|
16529
|
+
parameters: spec.parameters ?? EMPTY_PARAMETERS
|
|
16530
|
+
}
|
|
16531
|
+
}));
|
|
16532
|
+
},
|
|
16533
|
+
getToolDefinition(toolName) {
|
|
16534
|
+
const spec = specs.get(toolName);
|
|
16535
|
+
if (!spec) return void 0;
|
|
16536
|
+
return {
|
|
16537
|
+
parameters: spec.parameters ?? EMPTY_PARAMETERS,
|
|
16538
|
+
...spec.validateArguments ? { validateArguments: spec.validateArguments } : {}
|
|
16539
|
+
};
|
|
16540
|
+
},
|
|
16541
|
+
async executeTool(toolName, args, context) {
|
|
16542
|
+
const spec = specs.get(toolName);
|
|
16543
|
+
if (!spec) throw new Error(`[scriptedToolRuntime] \u672A\u767B\u8BB0\u7684\u5DE5\u5177\uFF1A${toolName}`);
|
|
16544
|
+
const count = (counts.get(toolName) ?? 0) + 1;
|
|
16545
|
+
counts.set(toolName, count);
|
|
16546
|
+
const execution = { toolName, args, startedAt: Date.now() };
|
|
16547
|
+
executions.push(execution);
|
|
16548
|
+
try {
|
|
16549
|
+
const outcome = spec.run ? await spec.run({ toolName, args, context, count }) : `${toolName} done`;
|
|
16550
|
+
execution.finishedAt = Date.now();
|
|
16551
|
+
const result = toResult(outcome, toolName, execution.finishedAt - execution.startedAt);
|
|
16552
|
+
execution.outcome = result.success ? "success" : "error";
|
|
16553
|
+
return result;
|
|
16554
|
+
} catch (error) {
|
|
16555
|
+
execution.finishedAt = Date.now();
|
|
16556
|
+
execution.outcome = "threw";
|
|
16557
|
+
throw error;
|
|
16558
|
+
}
|
|
16559
|
+
}
|
|
16560
|
+
};
|
|
16561
|
+
}
|
|
16562
|
+
|
|
16563
|
+
// src/testkit/scenario/timeline.ts
|
|
16564
|
+
var DEFAULT_HIDDEN = /* @__PURE__ */ new Set([
|
|
16565
|
+
"run_execution_metrics",
|
|
16566
|
+
"context_usage_snapshot",
|
|
16567
|
+
"audit_envelope",
|
|
16568
|
+
"tool_process",
|
|
16569
|
+
"final_answer_chunk",
|
|
16570
|
+
"final_answer_reset"
|
|
16571
|
+
]);
|
|
16572
|
+
function clip(text, max) {
|
|
16573
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
16574
|
+
return JSON.stringify(flat.length > max ? `${flat.slice(0, max)}\u2026` : flat);
|
|
16575
|
+
}
|
|
16576
|
+
function userInputText(event) {
|
|
16577
|
+
return event.raw_content ?? event.content;
|
|
16578
|
+
}
|
|
16579
|
+
function describe(event, max) {
|
|
16580
|
+
switch (event.type) {
|
|
16581
|
+
case "user_input":
|
|
16582
|
+
return `${event.delivery === "mid_run" ? "steer" : "user"} ${clip(userInputText(event), max)}`;
|
|
16583
|
+
case "thought":
|
|
16584
|
+
return `thought ${clip(event.content, max)}`;
|
|
16585
|
+
case "tool_call_decision":
|
|
16586
|
+
return `call ${event.tool_name}#${event.tool_call_id}`;
|
|
16587
|
+
case "tool_output":
|
|
16588
|
+
return `result ${event.tool_name}#${event.tool_call_id} ${event.status} ${clip(event.observation ?? "", max)}`;
|
|
16589
|
+
case "final_answer":
|
|
16590
|
+
return `answer ${clip(event.content, max)}${event.completion_reason && event.completion_reason !== "terminal" ? ` (${event.completion_reason})` : ""}`;
|
|
16591
|
+
case "error":
|
|
16592
|
+
return `error ${event.error_code ?? ""} ${clip(event.error, max)}`.replace(" ", " ");
|
|
16593
|
+
case "requires_user_interaction":
|
|
16594
|
+
return `wait_user ${event.interaction_status}`;
|
|
16595
|
+
case "llm_retry":
|
|
16596
|
+
return "llm_retry";
|
|
16597
|
+
default:
|
|
16598
|
+
return event.type;
|
|
16599
|
+
}
|
|
16600
|
+
}
|
|
16601
|
+
function formatRuntimeTimeline(events, options = {}) {
|
|
16602
|
+
const max = options.maxText ?? 40;
|
|
16603
|
+
const keep = options.types ? new Set(options.types) : void 0;
|
|
16604
|
+
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));
|
|
16605
|
+
}
|
|
16606
|
+
function textOf(blocks) {
|
|
16607
|
+
return blocks.map((block) => block.type === "text" ? block.text ?? "" : `[${block.type}]`).join("");
|
|
16608
|
+
}
|
|
16609
|
+
function formatModelMessages(call, options = {}) {
|
|
16610
|
+
const max = options.maxText ?? 40;
|
|
16611
|
+
return call.messages.map((message) => {
|
|
16612
|
+
switch (message.role) {
|
|
16613
|
+
case "system":
|
|
16614
|
+
return "system";
|
|
16615
|
+
case "user":
|
|
16616
|
+
return `user ${clip(textOf(message.content), max)}`;
|
|
16617
|
+
case "tool":
|
|
16618
|
+
return `tool #${message.tool_call_id} ${clip(textOf(message.content), max)}`;
|
|
16619
|
+
case "assistant": {
|
|
16620
|
+
const parts = message.parts.map((part) => {
|
|
16621
|
+
if (part.type === "text") return clip(part.text, max);
|
|
16622
|
+
if (part.type === "tool_call") return `call ${part.call.name}#${part.call.id}`;
|
|
16623
|
+
return "reasoning";
|
|
16624
|
+
});
|
|
16625
|
+
return `assistant ${parts.join(" ")}`;
|
|
16626
|
+
}
|
|
16627
|
+
}
|
|
16628
|
+
});
|
|
16629
|
+
}
|
|
16630
|
+
|
|
16631
|
+
// src/testkit/scenario/steeringInvariants.ts
|
|
16632
|
+
function isSteer(event) {
|
|
16633
|
+
return event.type === "user_input" && event.delivery === "mid_run";
|
|
16634
|
+
}
|
|
16635
|
+
function messageIndexOfText(call, text) {
|
|
16636
|
+
return call.messages.flatMap((message, index) => {
|
|
16637
|
+
if (message.role !== "user") return [];
|
|
16638
|
+
const body = message.content.map((block) => block.type === "text" ? block.text : "").join("");
|
|
16639
|
+
return body.includes(text) ? [index] : [];
|
|
16640
|
+
});
|
|
16641
|
+
}
|
|
16642
|
+
function toolMessageIndex(call, toolCallId) {
|
|
16643
|
+
return call.messages.findIndex((message) => message.role === "tool" && message.tool_call_id === toolCallId);
|
|
16644
|
+
}
|
|
16645
|
+
function validateSteeringInvariants(context, options = {}) {
|
|
16646
|
+
const disabled = new Set(options.disabled ?? []);
|
|
16647
|
+
const failures = [];
|
|
16648
|
+
const fail = (id, message) => {
|
|
16649
|
+
if (!disabled.has(id)) failures.push({ id, message });
|
|
16650
|
+
};
|
|
16651
|
+
const { history, modelCalls } = context;
|
|
16652
|
+
const steers = history.filter(isSteer);
|
|
16653
|
+
const seen = /* @__PURE__ */ new Map();
|
|
16654
|
+
for (const steer of steers) seen.set(steer.id, (seen.get(steer.id) ?? 0) + 1);
|
|
16655
|
+
for (const [id, count] of seen) {
|
|
16656
|
+
if (count > 1) fail("S1_STEER_UNIQUE", `\u63D2\u8BDD ${id} \u5728\u5386\u53F2\u91CC\u51FA\u73B0\u4E86 ${count} \u6B21`);
|
|
16657
|
+
}
|
|
16658
|
+
for (const steer of steers) {
|
|
16659
|
+
const text = userInputText(steer);
|
|
16660
|
+
const position = history.findIndex((event) => event.id === steer.id);
|
|
16661
|
+
const before = history.slice(0, position);
|
|
16662
|
+
const decided = /* @__PURE__ */ new Set();
|
|
16663
|
+
const settled = /* @__PURE__ */ new Set();
|
|
16664
|
+
let lastToolOutputId;
|
|
16665
|
+
for (const event of before) {
|
|
16666
|
+
if (event.type === "user_input" && event.delivery !== "mid_run") {
|
|
16667
|
+
decided.clear();
|
|
16668
|
+
settled.clear();
|
|
16669
|
+
lastToolOutputId = void 0;
|
|
16670
|
+
}
|
|
16671
|
+
if (event.type === "tool_call_decision") decided.add(event.tool_call_id);
|
|
16672
|
+
if (event.type === "tool_output") {
|
|
16673
|
+
settled.add(event.tool_call_id);
|
|
16674
|
+
lastToolOutputId = event.tool_call_id;
|
|
16675
|
+
}
|
|
16676
|
+
}
|
|
16677
|
+
const unsettled = [...decided].filter((id) => !settled.has(id));
|
|
16678
|
+
if (unsettled.length > 0 || lastToolOutputId === void 0) {
|
|
16679
|
+
fail(
|
|
16680
|
+
"S2_STEER_AT_BATCH_BOUNDARY",
|
|
16681
|
+
`\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`
|
|
16682
|
+
);
|
|
16683
|
+
continue;
|
|
16684
|
+
}
|
|
16685
|
+
const nextCallIndex = modelCalls.findIndex((call) => toolMessageIndex(call, lastToolOutputId) >= 0);
|
|
16686
|
+
if (nextCallIndex < 0) {
|
|
16687
|
+
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`);
|
|
16688
|
+
continue;
|
|
16689
|
+
}
|
|
16690
|
+
const nextCall = modelCalls[nextCallIndex];
|
|
16691
|
+
const at = messageIndexOfText(nextCall, text);
|
|
16692
|
+
const toolAt = toolMessageIndex(nextCall, lastToolOutputId);
|
|
16693
|
+
if (at.length === 0) {
|
|
16694
|
+
fail("S3_STEER_IN_NEXT_MODEL_CALL", `\u7B2C ${nextCallIndex + 1} \u6B21\u6A21\u578B\u8C03\u7528\u6CA1\u6709\u6536\u5230\u63D2\u8BDD ${steer.id}`);
|
|
16695
|
+
} else if (at[0] < toolAt) {
|
|
16696
|
+
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`);
|
|
16697
|
+
}
|
|
16698
|
+
for (const [index, call] of modelCalls.entries()) {
|
|
16699
|
+
const hits = messageIndexOfText(call, text).length;
|
|
16700
|
+
if (hits > 1) {
|
|
16701
|
+
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`);
|
|
16702
|
+
}
|
|
16703
|
+
if (index > nextCallIndex && hits === 0) {
|
|
16704
|
+
fail("S5_STEER_KEPT_IN_LATER_CALLS", `\u7B2C ${index + 1} \u6B21\u6A21\u578B\u8C03\u7528\u4E22\u4E86\u63D2\u8BDD ${steer.id}`);
|
|
16705
|
+
}
|
|
16706
|
+
}
|
|
16707
|
+
}
|
|
16708
|
+
return failures;
|
|
16709
|
+
}
|
|
16710
|
+
function assertSteeringInvariants(context, options = {}) {
|
|
16711
|
+
const failures = validateSteeringInvariants(context, options);
|
|
16712
|
+
if (failures.length > 0) {
|
|
16713
|
+
throw new Error(`[steeringInvariants] ${failures.map((f) => `${f.id}: ${f.message}`).join("\n")}`);
|
|
16714
|
+
}
|
|
16715
|
+
}
|
|
16716
|
+
|
|
16717
|
+
// src/testkit/scenario/graphScenario.ts
|
|
16718
|
+
var defaultContextBuilder = {
|
|
16719
|
+
async build({ history }) {
|
|
16720
|
+
return { llmMessages: formatAgentLlmMessages(convertEventsToAiMessages(history)) };
|
|
16721
|
+
}
|
|
16722
|
+
};
|
|
16723
|
+
var passthroughPreview = {
|
|
16724
|
+
async truncateObservation(params) {
|
|
16725
|
+
return { truncated: false, preview: params.text };
|
|
16726
|
+
}
|
|
16727
|
+
};
|
|
16728
|
+
function createGraphScenario(options) {
|
|
16729
|
+
const conversationId = options.conversationId ?? "conversation";
|
|
16730
|
+
const model = createScriptedInferenceHarness(options.model);
|
|
16731
|
+
const tools = createScriptedToolRuntime(options.tools ?? {});
|
|
16732
|
+
const steering = createPendingUserInputQueue();
|
|
16733
|
+
const checkpointer = new MemoryCheckpointer();
|
|
16734
|
+
const eventStore = new MemoryEventStore();
|
|
16735
|
+
const nextEventStoreId = createMonotonicEventStoreIdFactory();
|
|
16736
|
+
const live = [];
|
|
16737
|
+
const seed = [...options.history ?? []];
|
|
16738
|
+
const runs = /* @__PURE__ */ new Map();
|
|
16739
|
+
let current;
|
|
16740
|
+
let runCount = 0;
|
|
16741
|
+
const reasoner = new GraphAgentExecutor({
|
|
16742
|
+
llmCaller: model.getLlmCaller(),
|
|
16743
|
+
toolRuntime: tools,
|
|
16744
|
+
contextBuilder: options.contextBuilder ?? defaultContextBuilder,
|
|
16745
|
+
...options.tokenizer ? { tokenizer: options.tokenizer } : {}
|
|
16746
|
+
});
|
|
16747
|
+
const graph = new GraphExecutor(checkpointer, {
|
|
16748
|
+
maxSteps: options.maxSteps ?? 16,
|
|
16749
|
+
executionCheckpointPort: {
|
|
16750
|
+
commit: (key, state) => {
|
|
16751
|
+
const run = runs.get(key);
|
|
16752
|
+
if (!run) throw new Error(`[graphScenario] \u672A\u77E5\u8FD0\u884C\uFF1A${key}`);
|
|
16753
|
+
return run.persistence.commitCheckpoint(key, state);
|
|
16754
|
+
}
|
|
16755
|
+
}
|
|
16756
|
+
});
|
|
16757
|
+
graph.registerNode(new LlmNode({ reasoner }));
|
|
16758
|
+
graph.registerNode(new ToolNode({
|
|
16759
|
+
toolRuntime: tools,
|
|
16760
|
+
observationPreview: options.observationPreview ?? passthroughPreview
|
|
16761
|
+
}));
|
|
16762
|
+
graph.registerNode(new WaitUserNode({}));
|
|
16763
|
+
function openRun(runId, turnId) {
|
|
16764
|
+
const sequencer = new execution_exports.EventSequencer(conversationId);
|
|
16765
|
+
const eventBus = new execution_exports.EventBus(sequencer.getExecutionId());
|
|
16766
|
+
eventBus.on("event", (envelope) => live.push(envelope.payload));
|
|
16767
|
+
const publisher = new execution_exports.RuntimeEventPublisher(
|
|
16768
|
+
eventBus,
|
|
16769
|
+
sequencer,
|
|
16770
|
+
routingIdentityOf({ runId })
|
|
16771
|
+
);
|
|
16772
|
+
const persistence = new execution_exports.EventBusEventPersistence({
|
|
16773
|
+
eventBus,
|
|
16774
|
+
eventStore,
|
|
16775
|
+
nextEventStoreId,
|
|
16776
|
+
async checkpointWriter({ checkpointKey, checkpoint: checkpoint2, events }) {
|
|
16777
|
+
await options.beforeCheckpointWrite?.({ checkpointKey, events: events.map((item) => item.event) });
|
|
16778
|
+
const stored = JSON.parse(JSON.stringify(checkpoint2));
|
|
16779
|
+
await checkpointer.save(checkpointKey, parseEngineCheckpoint(stored));
|
|
16780
|
+
for (const event of events) await eventStore.append(event);
|
|
16781
|
+
}
|
|
16782
|
+
});
|
|
16783
|
+
persistence.connect();
|
|
16784
|
+
const run = {
|
|
16785
|
+
runId,
|
|
16786
|
+
turnId,
|
|
16787
|
+
eventBus,
|
|
16788
|
+
sink: (event, source) => publisher.publish(event, source),
|
|
16789
|
+
persistence,
|
|
16790
|
+
controller: new AbortController(),
|
|
16791
|
+
open: true
|
|
16792
|
+
};
|
|
16793
|
+
runs.set(runId, run);
|
|
16794
|
+
return run;
|
|
16795
|
+
}
|
|
16796
|
+
async function closeRun(run) {
|
|
16797
|
+
if (!run.open) return;
|
|
16798
|
+
run.open = false;
|
|
16799
|
+
run.persistence.finishCheckpointWrites();
|
|
16800
|
+
try {
|
|
16801
|
+
await run.persistence.drain();
|
|
16802
|
+
} finally {
|
|
16803
|
+
run.eventBus.close();
|
|
16804
|
+
}
|
|
16805
|
+
}
|
|
16806
|
+
function capabilities(run) {
|
|
16807
|
+
const toolContext = {
|
|
16808
|
+
runId: RunIdSchema.parse(run.runId),
|
|
16809
|
+
conversationId,
|
|
16810
|
+
turnId: run.turnId,
|
|
16811
|
+
abortSignal: run.controller.signal
|
|
16812
|
+
};
|
|
16813
|
+
return {
|
|
16814
|
+
signal: run.controller.signal,
|
|
16815
|
+
toolContext,
|
|
16816
|
+
runtimeEventSink: run.sink,
|
|
16817
|
+
pendingUserInputPort: steering.port
|
|
16818
|
+
};
|
|
16819
|
+
}
|
|
16820
|
+
async function settle(run, operation) {
|
|
16821
|
+
current = run;
|
|
16822
|
+
let status;
|
|
16823
|
+
let error;
|
|
16824
|
+
try {
|
|
16825
|
+
const checkpoint2 = await operation();
|
|
16826
|
+
status = checkpoint2.executionStatus === "awaiting_user" ? "awaiting_user" : "yielded";
|
|
16827
|
+
} catch (caught) {
|
|
16828
|
+
const signal = run.controller.signal;
|
|
16829
|
+
if (signal.aborted) {
|
|
16830
|
+
status = isRunPauseSignal(signal) ? "paused" : "cancelled";
|
|
16831
|
+
} else {
|
|
16832
|
+
status = "failed";
|
|
16833
|
+
error = caught;
|
|
16834
|
+
}
|
|
16835
|
+
} finally {
|
|
16836
|
+
current = void 0;
|
|
16837
|
+
}
|
|
16838
|
+
if (status === "paused" || status === "awaiting_user") {
|
|
16839
|
+
await run.persistence.drain().catch(() => void 0);
|
|
16840
|
+
} else {
|
|
16841
|
+
await closeRun(run).catch((caught) => {
|
|
16842
|
+
status = "failed";
|
|
16843
|
+
error ??= caught;
|
|
16844
|
+
});
|
|
16845
|
+
}
|
|
16846
|
+
return {
|
|
16847
|
+
runId: run.runId,
|
|
16848
|
+
status,
|
|
16849
|
+
...error !== void 0 ? { error } : {},
|
|
16850
|
+
undeliveredSteers: steering.drain()
|
|
16851
|
+
};
|
|
16852
|
+
}
|
|
16853
|
+
async function history() {
|
|
16854
|
+
for (const run of runs.values()) {
|
|
16855
|
+
if (run.open) await run.persistence.drain().catch(() => void 0);
|
|
16856
|
+
}
|
|
16857
|
+
return [...seed, ...(await eventStore.range(conversationId)).map((item) => item.event)];
|
|
16858
|
+
}
|
|
16859
|
+
let lastPaused;
|
|
16860
|
+
return {
|
|
16861
|
+
conversationId,
|
|
16862
|
+
model,
|
|
16863
|
+
tools,
|
|
16864
|
+
steering,
|
|
16865
|
+
live,
|
|
16866
|
+
async start(input) {
|
|
16867
|
+
const { query, runId: requestedRunId, request } = typeof input === "string" ? { query: input, runId: void 0, request: void 0 } : input;
|
|
16868
|
+
runCount += 1;
|
|
16869
|
+
const runId = requestedRunId ?? `run_${runCount}`;
|
|
16870
|
+
const turnId = `turn_${runCount}`;
|
|
16871
|
+
const prior = await history();
|
|
16872
|
+
const run = openRun(runId, turnId);
|
|
16873
|
+
const userInput = run.sink(
|
|
16874
|
+
createUserInputEvent(`user_${runId}`, conversationId, turnId, query),
|
|
16875
|
+
"graphScenario.user_input"
|
|
16876
|
+
);
|
|
16877
|
+
const toolNames = Object.keys(options.tools ?? {});
|
|
16878
|
+
const outcome = await settle(run, async () => (await graph.startSession(runId, {
|
|
16879
|
+
...capabilities(run),
|
|
16880
|
+
runId: RunIdSchema.parse(runId),
|
|
16881
|
+
conversationId,
|
|
16882
|
+
turnId,
|
|
16883
|
+
history: [...prior, userInput],
|
|
16884
|
+
request: {
|
|
16885
|
+
query,
|
|
16886
|
+
promptKey: "agent",
|
|
16887
|
+
model_id: "scripted-model",
|
|
16888
|
+
enableTools: toolNames.length > 0,
|
|
16889
|
+
availableTools: toolNames,
|
|
16890
|
+
...request
|
|
16891
|
+
}
|
|
16892
|
+
}, "llm")).checkpoint);
|
|
16893
|
+
lastPaused = outcome.status === "paused" ? run : void 0;
|
|
16894
|
+
return outcome;
|
|
16895
|
+
},
|
|
16896
|
+
async continue() {
|
|
16897
|
+
const run = lastPaused;
|
|
16898
|
+
if (!run) throw new Error("[graphScenario] \u6CA1\u6709\u6682\u505C\u4E2D\u7684\u8FD0\u884C\u53EF\u4EE5\u7EE7\u7EED");
|
|
16899
|
+
const saved = await checkpointer.load(run.runId);
|
|
16900
|
+
if (!saved?.revision) throw new Error(`[graphScenario] \u8FD0\u884C ${run.runId} \u6CA1\u6709\u65AD\u70B9`);
|
|
16901
|
+
run.controller = new AbortController();
|
|
16902
|
+
const outcome = await settle(run, async () => (await graph.continueSession(run.runId, {
|
|
16903
|
+
expectedRevision: saved.revision ?? 0,
|
|
16904
|
+
capabilities: capabilities(run)
|
|
16905
|
+
})).checkpoint);
|
|
16906
|
+
lastPaused = outcome.status === "paused" ? run : void 0;
|
|
16907
|
+
return outcome;
|
|
16908
|
+
},
|
|
16909
|
+
steer: (content, steerOptions) => steering.submit(content, steerOptions),
|
|
16910
|
+
pause() {
|
|
16911
|
+
if (!current) throw new Error("[graphScenario] \u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u53EF\u4EE5\u6682\u505C");
|
|
16912
|
+
current.controller.abort(new RunPauseRequested());
|
|
16913
|
+
},
|
|
16914
|
+
cancel() {
|
|
16915
|
+
if (!current) throw new Error("[graphScenario] \u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u53EF\u4EE5\u53D6\u6D88");
|
|
16916
|
+
current.controller.abort(new Error("Run cancelled by scenario"));
|
|
16917
|
+
},
|
|
16918
|
+
history,
|
|
16919
|
+
checkpoint: async (runId) => checkpointer.load(runId ?? [...runs.keys()].at(-1) ?? ""),
|
|
16920
|
+
timeline: async (timelineOptions) => formatRuntimeTimeline(await history(), timelineOptions),
|
|
16921
|
+
modelCalls: () => model.getCalls(),
|
|
16922
|
+
async assertInvariants(invariantOptions) {
|
|
16923
|
+
const events = await history();
|
|
16924
|
+
const ids = events.map((event) => event.id);
|
|
16925
|
+
const duplicated = ids.filter((id, index) => ids.indexOf(id) !== index);
|
|
16926
|
+
try {
|
|
16927
|
+
if (duplicated.length > 0) throw new Error(`[graphScenario] \u5386\u53F2\u91CC\u6709\u91CD\u590D\u4E8B\u4EF6\uFF1A${duplicated.join(", ")}`);
|
|
16928
|
+
assertSteeringInvariants({ history: events, modelCalls: model.getCalls() }, invariantOptions);
|
|
16929
|
+
} catch (error) {
|
|
16930
|
+
const timeline = formatRuntimeTimeline(events).map((line) => ` ${line}`).join("\n");
|
|
16931
|
+
throw new Error(`${error instanceof Error ? error.message : String(error)}
|
|
16932
|
+
\u65F6\u95F4\u7EBF\uFF1A
|
|
16933
|
+
${timeline}`);
|
|
16934
|
+
}
|
|
16935
|
+
},
|
|
16936
|
+
async close() {
|
|
16937
|
+
for (const run of runs.values()) await closeRun(run).catch(() => void 0);
|
|
16938
|
+
}
|
|
16939
|
+
};
|
|
16940
|
+
}
|
|
16941
|
+
|
|
16286
16942
|
// src/testkit/tool-fixtures/toolContext.ts
|
|
16287
16943
|
function createToolContextFixture(options = {}) {
|
|
16288
16944
|
const persistedHistoryEvents = options.persistedHistoryEvents ?? options.historyEvents ?? [];
|
|
@@ -16309,22 +16965,31 @@ function createToolContextFixture(options = {}) {
|
|
|
16309
16965
|
|
|
16310
16966
|
exports.assertContextPolicyInvariants = assertContextPolicyInvariants;
|
|
16311
16967
|
exports.assertRunInvariants = assertRunInvariants;
|
|
16968
|
+
exports.assertSteeringInvariants = assertSteeringInvariants;
|
|
16312
16969
|
exports.assertions = assertions_exports;
|
|
16313
16970
|
exports.createCollectingAuditPort = createCollectingAuditPort;
|
|
16314
16971
|
exports.createDefaultGraphExecutor = createDefaultGraphExecutor;
|
|
16315
16972
|
exports.createGraphLoopHarness = createGraphLoopHarness;
|
|
16973
|
+
exports.createGraphScenario = createGraphScenario;
|
|
16316
16974
|
exports.createMockTelemetryPort = createMockTelemetryPort;
|
|
16317
16975
|
exports.createMockTokenizerPort = createMockTokenizerPort;
|
|
16976
|
+
exports.createPendingUserInputQueue = createPendingUserInputQueue;
|
|
16318
16977
|
exports.createReplayHarness = createReplayHarness;
|
|
16319
16978
|
exports.createRunSupervisorHarness = createRunSupervisorHarness;
|
|
16979
|
+
exports.createRuntimeEventRecorder = createRuntimeEventRecorder;
|
|
16320
16980
|
exports.createScriptedInferenceHarness = createScriptedInferenceHarness;
|
|
16981
|
+
exports.createScriptedToolRuntime = createScriptedToolRuntime;
|
|
16321
16982
|
exports.createToolContextFixture = createToolContextFixture;
|
|
16322
16983
|
exports.expectFinalStepForcedTools = expectFinalStepForcedTools;
|
|
16323
16984
|
exports.expectMessagesContainText = expectMessagesContainText;
|
|
16324
16985
|
exports.expectMessagesContainToolResult = expectMessagesContainToolResult;
|
|
16325
16986
|
exports.expectRunEndedWithFinalAnswer = expectRunEndedWithFinalAnswer;
|
|
16326
16987
|
exports.expectToolOutputFedBackToHistory = expectToolOutputFedBackToHistory;
|
|
16988
|
+
exports.formatModelMessages = formatModelMessages;
|
|
16989
|
+
exports.formatRuntimeTimeline = formatRuntimeTimeline;
|
|
16990
|
+
exports.userInputText = userInputText;
|
|
16327
16991
|
exports.validateContextPolicyInvariants = validateContextPolicyInvariants;
|
|
16328
16992
|
exports.validateRunInvariants = validateRunInvariants;
|
|
16993
|
+
exports.validateSteeringInvariants = validateSteeringInvariants;
|
|
16329
16994
|
//# sourceMappingURL=testkit.cjs.map
|
|
16330
16995
|
//# sourceMappingURL=testkit.cjs.map
|