zen-free 0.1.3: a call of a tool the agent doesn't have is left out with a note, not a failed turn (#76, tkhs101)
#76: Zen's free models sometimes call a tool by a name the agent never declared (tkhs101's table: bedit, bcp, ash, mcp__netcatcatty__unused, beside declared edit, bash, mcp__netcatty-external__list_hosts). The guard answered each with "Upstream called a tool not declared by the client", which failed the whole turn. The rows without a name are from before 0.1.1 (published 10-10 11:51 UTC), which added the name. Now such a call (or one with no name) is left out of the reply instead: - chat: dropped from tool_calls/function_call; the reply's content says "(The model called a tool this agent doesn't have: "bedit". The call was left out.)"; kept calls are renumbered from 0; finish_reason becomes "stop" when no call is left, including a repeated finish. - responses: the function_call item becomes a message item with the note (added, text deltas, done, and in response.completed); its argument events are not passed on. - anthropic: the tool_use block becomes a text block with the note; its input deltas are not passed on; stop_reason tool_use becomes end_turn when no call is left. A call of an unsupported type (custom tools, non-object input) still fails as before. Run: - bun test packages/zen-free: 155 pass, 0 fail; node --test packages/zen-free/*.test.mjs: 155/155; bun scripts/check.mjs zen-free. - The new tests on the old tool-response.mjs: 35 fail. - Breaking the finish rewrite by hand: 5 fail. - Chat stream fixtures use the shape a live step-5-preview-free stream sent (name whole in the first delta, arguments in pieces, two tool_calls finishes). Zen sends names whole, so the names in #76 are the model's own; a real misnamed call was not reproduced live.
This commit is contained in:
@@ -41,5 +41,6 @@ The agent's tools are preserved. Zen's models often call OpenCode's own
|
||||
tool names; such a call is given the agent's tool whose name differs only
|
||||
in case (`bash` to `Bash`), or else only in case and `_`/`-` (`todowrite`
|
||||
to `todo_write`, `webfetch` to `web_fetch`), when exactly one does. A
|
||||
call with no such tool returns an error that names it. Tools run in the
|
||||
agent.
|
||||
call with no such tool (or with no name) is left out of the reply, and
|
||||
the reply's text says which name was left out; a turn whose every call
|
||||
was left out ends as an ordinary answer. Tools run in the agent.
|
||||
|
||||
@@ -22,9 +22,11 @@ async function fixture(t, input = {}) {
|
||||
res.writeHead(state.modelsStatus, { "content-type": "application/json" });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
data: (state.ids ?? ["chat-free", "responses-free", "messages-free", "paid"]).map((id) => ({
|
||||
id,
|
||||
})),
|
||||
data: (state.ids ?? ["chat-free", "responses-free", "messages-free", "paid"]).map(
|
||||
(id) => ({
|
||||
id,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
} else if (req.url === "/catalog") {
|
||||
@@ -119,12 +121,16 @@ for (const { protocol, path, model } of protocols) {
|
||||
assert.equal((tool.parameters ?? tool.input_schema).additionalProperties, false);
|
||||
assert.deepEqual((tool.parameters ?? tool.input_schema).properties, {});
|
||||
}
|
||||
// A call of a tool the agent doesn't have is left out, said in
|
||||
// the reply's text, and the turn ends as a stop rather than
|
||||
// failing (#76).
|
||||
state.reply = toolReply(protocol, "edit", upstreamSSE);
|
||||
const error = await send();
|
||||
if (!stream || !upstreamSSE) assert.equal(error.status, 502);
|
||||
const rejected = await error.text();
|
||||
assert.match(rejected, /error/);
|
||||
assert.doesNotMatch(rejected, /"name"\s*:\s*"edit"/);
|
||||
const left = await send();
|
||||
assert.equal(left.status, 200);
|
||||
const text = await left.text();
|
||||
assert.doesNotMatch(text, /"name"\s*:\s*"edit"/);
|
||||
assert.doesNotMatch(text, /"error"|"tool_calls"|"tool_use"|"function_call"/);
|
||||
assert.match(text, /a tool this agent doesn't have: \\"edit\\"/);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -142,8 +148,10 @@ test("keeps declared tools isolated between requests using the same loader", asy
|
||||
});
|
||||
assert.equal((await send(declaredTools("chat"))).status, 200);
|
||||
const blocked = await send([]);
|
||||
assert.equal(blocked.status, 502);
|
||||
assert.doesNotMatch(await blocked.text(), /"name"\s*:\s*"Bash"/);
|
||||
assert.equal(blocked.status, 200);
|
||||
const text = await blocked.text();
|
||||
assert.doesNotMatch(text, /"name"\s*:\s*"Bash"/);
|
||||
assert.match(text, /a tool this agent doesn't have: \\"bash\\"/);
|
||||
});
|
||||
|
||||
for (const [input, supplied, expected] of [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zen-free-auth",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "OpenCode Zen free models through the public credential, with native streaming protocols",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -45,6 +45,8 @@ function foldsTo(declared, key) {
|
||||
return folded;
|
||||
}
|
||||
|
||||
// nameGuard answers the agent's name for a call, or null for a call of no
|
||||
// tool the agent has (a missing name included).
|
||||
function nameGuard(policy) {
|
||||
const declared = new Set(policy.declared);
|
||||
const lower = (name) => name.toLowerCase();
|
||||
@@ -52,49 +54,135 @@ function nameGuard(policy) {
|
||||
const byCase = foldsTo(declared, lower);
|
||||
const byShape = foldsTo(declared, bare);
|
||||
return (name) => {
|
||||
if (typeof name !== "string" || !name) throw new GuardError("Missing upstream tool name");
|
||||
if (typeof name !== "string" || !name) return null;
|
||||
if (declared.has(name)) return name;
|
||||
const match = byCase.get(lower(name)) ?? (byCase.has(lower(name)) ? null : byShape.get(bare(name)));
|
||||
if (match) return match;
|
||||
throw new GuardError(
|
||||
`Upstream called a tool not declared by the client: ${JSON.stringify(name.slice(0, 128))}`,
|
||||
);
|
||||
const match =
|
||||
byCase.get(lower(name)) ?? (byCase.has(lower(name)) ? null : byShape.get(bare(name)));
|
||||
return match || null;
|
||||
};
|
||||
}
|
||||
|
||||
function checkFunction(value, checkName) {
|
||||
if (!object(value)) throw new GuardError("Invalid upstream function call");
|
||||
const name = checkName(value.name);
|
||||
const changed = name !== value.name;
|
||||
value.name = name;
|
||||
return changed;
|
||||
// The models also call tools no agent has: bedit, bcp, ash, a mangled
|
||||
// mcp__netcatcatty__unused (#76). Such a call can't be run or named onto
|
||||
// one the agent has, and failing the reply for it threw away the whole
|
||||
// turn. It is left out instead, and the reply says so in its text, where
|
||||
// the agent's user and the model's next turn both read it. A reply left
|
||||
// with no call ends as a plain stop.
|
||||
export function droppedNote(name) {
|
||||
return typeof name === "string" && name
|
||||
? `(The model called a tool this agent doesn't have: ${JSON.stringify(name.slice(0, 128))}. The call was left out.)`
|
||||
: "(The model called a tool without a name. The call was left out.)";
|
||||
}
|
||||
|
||||
function checkChatMessage(message, checkName) {
|
||||
if (!object(message)) return false;
|
||||
let changed = false;
|
||||
if (message.function_call != null) changed = checkFunction(message.function_call, checkName);
|
||||
for (const call of list(message.tool_calls)) {
|
||||
if (!object(call) || (call.type != null && call.type !== "function")) {
|
||||
throw new GuardError("Unsupported upstream tool call");
|
||||
}
|
||||
changed = checkFunction(call.function, checkName) || changed;
|
||||
function appendNotes(message, notes) {
|
||||
const text = notes.join("\n\n");
|
||||
if (typeof message.content === "string" && message.content) {
|
||||
message.content = `${message.content}\n\n${text}`;
|
||||
} else if (Array.isArray(message.content)) {
|
||||
message.content.push({ type: "text", text });
|
||||
} else {
|
||||
message.content = text;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
// checkChatMessage renames message's calls to the agent's tools and leaves
|
||||
// out the rest, answering the notes for those left out.
|
||||
function checkChatMessage(message, checkName) {
|
||||
const result = { changed: false, notes: [] };
|
||||
if (!object(message)) return result;
|
||||
if (message.function_call != null) {
|
||||
const value = message.function_call;
|
||||
if (!object(value)) throw new GuardError("Invalid upstream function call");
|
||||
const name = checkName(value.name);
|
||||
if (name == null) {
|
||||
result.notes.push(droppedNote(value.name));
|
||||
delete message.function_call;
|
||||
result.changed = true;
|
||||
} else if (name !== value.name) {
|
||||
value.name = name;
|
||||
result.changed = true;
|
||||
}
|
||||
}
|
||||
if (message.tool_calls != null) {
|
||||
const calls = list(message.tool_calls);
|
||||
const kept = [];
|
||||
for (const call of calls) {
|
||||
if (!object(call) || (call.type != null && call.type !== "function")) {
|
||||
throw new GuardError("Unsupported upstream tool call");
|
||||
}
|
||||
if (!object(call.function)) throw new GuardError("Invalid upstream function call");
|
||||
const name = checkName(call.function.name);
|
||||
if (name == null) {
|
||||
result.notes.push(droppedNote(call.function.name));
|
||||
result.changed = true;
|
||||
continue;
|
||||
}
|
||||
if (name !== call.function.name) {
|
||||
call.function.name = name;
|
||||
result.changed = true;
|
||||
}
|
||||
kept.push(call);
|
||||
}
|
||||
if (kept.length !== calls.length) {
|
||||
if (kept.length) message.tool_calls = kept;
|
||||
else delete message.tool_calls;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const callFinish = new Set(["tool_calls", "function_call"]);
|
||||
function hasCalls(message) {
|
||||
return message.function_call != null || (message.tool_calls?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
function isCall(protocol, value) {
|
||||
return (
|
||||
(protocol === "responses" && value.type === "function_call") ||
|
||||
(protocol === "anthropic" && ["tool_use", "server_tool_use"].includes(value.type))
|
||||
);
|
||||
}
|
||||
|
||||
// What a call left out of a Responses or Messages reply becomes: text
|
||||
// saying so, in the call's place, so no later index moves.
|
||||
function inPlaceOf(protocol, call, note) {
|
||||
if (protocol === "anthropic") return { type: "text", text: note };
|
||||
return {
|
||||
type: "message",
|
||||
id: typeof call.id === "string" && call.id ? call.id : `msg_${call.call_id ?? "dropped"}`,
|
||||
role: "assistant",
|
||||
status: call.status ?? "completed",
|
||||
content: [{ type: "output_text", text: note, annotations: [] }],
|
||||
};
|
||||
}
|
||||
|
||||
// checkSnapshots checks every call in a reply or event: renamed to the
|
||||
// agent's tool, or (Responses, Messages) put in place of by a note. It
|
||||
// answers whether data changed, how many calls it kept and how many it
|
||||
// left out.
|
||||
function checkSnapshots(data, protocol, checkName) {
|
||||
let changed = false;
|
||||
if (protocol === "chat") {
|
||||
for (const choice of list(data.choices)) {
|
||||
if (!object(choice)) throw new GuardError("Invalid upstream choice");
|
||||
changed = checkChatMessage(choice.message, checkName) || changed;
|
||||
const message = choice.message;
|
||||
const checked = checkChatMessage(message, checkName);
|
||||
changed = checked.changed || changed;
|
||||
if (checked.notes.length) {
|
||||
appendNotes(message, checked.notes);
|
||||
if (!hasCalls(message) && callFinish.has(choice.finish_reason))
|
||||
choice.finish_reason = "stop";
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
return { changed, kept: 0, left: 0 };
|
||||
}
|
||||
const stack = [data];
|
||||
let kept = 0;
|
||||
let left = 0;
|
||||
if (!object(data)) throw new GuardError("Invalid upstream tool snapshot");
|
||||
// Each entry is a value and where it sits, so a call can be replaced.
|
||||
const stack = [[data, null, null]];
|
||||
while (stack.length) {
|
||||
const value = stack.pop();
|
||||
const [value, holder, key] = stack.pop();
|
||||
if (!object(value)) throw new GuardError("Invalid upstream tool snapshot");
|
||||
if (
|
||||
protocol === "responses" &&
|
||||
@@ -104,25 +192,44 @@ function checkSnapshots(data, protocol, checkName) {
|
||||
) {
|
||||
throw new GuardError("Unsupported upstream tool call type");
|
||||
}
|
||||
if (
|
||||
(protocol === "responses" && value.type === "function_call") ||
|
||||
(protocol === "anthropic" && ["tool_use", "server_tool_use"].includes(value.type))
|
||||
) {
|
||||
changed = checkFunction(value, checkName) || changed;
|
||||
if (isCall(protocol, value)) {
|
||||
const name = checkName(value.name);
|
||||
if (name == null) {
|
||||
if (!holder) throw new GuardError(droppedNote(value.name));
|
||||
holder[key] = inPlaceOf(protocol, value, droppedNote(value.name));
|
||||
changed = true;
|
||||
left++;
|
||||
continue;
|
||||
}
|
||||
if (name !== value.name) {
|
||||
value.name = name;
|
||||
changed = true;
|
||||
}
|
||||
kept++;
|
||||
}
|
||||
const arrays = protocol === "responses" ? ["output", "content"] : ["content"];
|
||||
const objects =
|
||||
protocol === "responses" ? ["response", "item", "part"] : ["message", "content_block"];
|
||||
for (const key of arrays) {
|
||||
for (const name of arrays) {
|
||||
// Text content is not a snapshot container.
|
||||
if (typeof value[key] === "string") continue;
|
||||
for (const item of list(value[key])) stack.push(item);
|
||||
if (typeof value[name] === "string") continue;
|
||||
const items = list(value[name]);
|
||||
for (let i = 0; i < items.length; i++) stack.push([items[i], items, i]);
|
||||
}
|
||||
for (const key of objects) {
|
||||
if (value[key] != null) stack.push(value[key]);
|
||||
for (const name of objects) {
|
||||
if (value[name] != null) stack.push([value[name], value, name]);
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
if (
|
||||
protocol === "anthropic" &&
|
||||
left &&
|
||||
!kept &&
|
||||
data.type === "message" &&
|
||||
data.stop_reason === "tool_use"
|
||||
) {
|
||||
data.stop_reason = "end_turn";
|
||||
}
|
||||
return { changed, kept, left };
|
||||
}
|
||||
|
||||
function position(value) {
|
||||
@@ -178,13 +285,24 @@ function chatBuffer(checkName) {
|
||||
}
|
||||
return pending.get(index);
|
||||
}
|
||||
function complete(state) {
|
||||
// Choices that streamed text, and those whose every call was left out
|
||||
// (whose later "tool_calls" finish is a stop).
|
||||
const wrote = new Set();
|
||||
const ended = new Set();
|
||||
function complete(state, index) {
|
||||
const delta = {};
|
||||
if (state.calls.size) {
|
||||
delta.tool_calls = [...state.calls].sort(([a], [b]) => a - b).map(([, value]) => value);
|
||||
}
|
||||
if (state.legacy) delta.function_call = state.legacy;
|
||||
checkChatMessage(delta, checkName);
|
||||
const { notes } = checkChatMessage(delta, checkName);
|
||||
if (notes.length) {
|
||||
delta.tool_calls?.forEach((call, i) => {
|
||||
call.index = i;
|
||||
});
|
||||
delta.content = (wrote.has(index) ? "\n\n" : "") + notes.join("\n\n");
|
||||
if (!hasCalls(delta)) ended.add(index);
|
||||
}
|
||||
return delta;
|
||||
}
|
||||
function remove(index) {
|
||||
@@ -201,11 +319,12 @@ function chatBuffer(checkName) {
|
||||
bytes = 0;
|
||||
},
|
||||
apply(data) {
|
||||
let changed = checkSnapshots(data, "chat", checkName);
|
||||
let { changed } = checkSnapshots(data, "chat", checkName);
|
||||
const choices = list(data.choices);
|
||||
for (const choice of choices) {
|
||||
const delta = choice.delta;
|
||||
if (!object(delta)) continue;
|
||||
if (typeof delta.content === "string" && delta.content) wrote.add(position(choice.index));
|
||||
if (delta.tool_calls == null && delta.function_call == null) continue;
|
||||
changed = true;
|
||||
const state = stateFor(position(choice.index), data);
|
||||
@@ -234,10 +353,20 @@ function chatBuffer(checkName) {
|
||||
const index = position(choice.index);
|
||||
const state = pending.get(index);
|
||||
if (!state) continue;
|
||||
choice.delta = { ...choice.delta, ...complete(state) };
|
||||
const own = object(choice.delta) ? choice.delta : {};
|
||||
const delta = complete(state, index);
|
||||
if (typeof own.content === "string" && delta.content)
|
||||
delta.content = own.content + delta.content;
|
||||
choice.delta = { ...own, ...delta };
|
||||
remove(index);
|
||||
changed = true;
|
||||
}
|
||||
for (const choice of choices) {
|
||||
if (callFinish.has(choice.finish_reason) && ended.has(position(choice.index))) {
|
||||
choice.finish_reason = "stop";
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) return { data, changed: false };
|
||||
data.choices = choices.filter(
|
||||
(choice) =>
|
||||
@@ -251,7 +380,7 @@ function chatBuffer(checkName) {
|
||||
if (!pending.size) return null;
|
||||
const choices = [...pending]
|
||||
.sort(([a], [b]) => a - b)
|
||||
.map(([index, state]) => ({ index, delta: complete(state), finish_reason: null }));
|
||||
.map(([index, state]) => ({ index, delta: complete(state, index), finish_reason: null }));
|
||||
const metadata = pending.values().next().value.metadata;
|
||||
pending.clear();
|
||||
bytes = 0;
|
||||
@@ -260,6 +389,99 @@ function chatBuffer(checkName) {
|
||||
};
|
||||
}
|
||||
|
||||
// snapshotStream checks a Responses or Messages stream event by event. A
|
||||
// call left out is streamed as text in its place: its item or block starts
|
||||
// as text carrying the note, and its arguments are never sent. A message
|
||||
// whose every call was left out stops as a turn's end, not as tool use.
|
||||
function snapshotStream(protocol, checkName) {
|
||||
const left = new Map(); // output_index or content block index → true
|
||||
const leftIDs = new Set(); // Responses item ids left out
|
||||
let kept = 0;
|
||||
let dropped = 0;
|
||||
return {
|
||||
apply(data, type) {
|
||||
if (protocol === "responses") {
|
||||
const item = data.item;
|
||||
if (
|
||||
type === "response.output_item.added" &&
|
||||
object(item) &&
|
||||
item.type === "function_call" &&
|
||||
checkName(item.name) == null
|
||||
) {
|
||||
const note = droppedNote(item.name);
|
||||
const message = inPlaceOf(protocol, item, note);
|
||||
left.set(data.output_index, true);
|
||||
leftIDs.add(message.id);
|
||||
if (typeof item.id === "string") leftIDs.add(item.id);
|
||||
dropped++;
|
||||
const where = { item_id: message.id, output_index: data.output_index, content_index: 0 };
|
||||
const part = { type: "output_text", text: "", annotations: [] };
|
||||
return {
|
||||
changed: true,
|
||||
data: { ...data, item: { ...message, status: "in_progress", content: [] } },
|
||||
extra: [
|
||||
{ type: "response.content_part.added", ...where, part },
|
||||
{ type: "response.output_text.delta", ...where, delta: note },
|
||||
{ type: "response.output_text.done", ...where, text: note },
|
||||
{ type: "response.content_part.done", ...where, part: { ...part, text: note } },
|
||||
],
|
||||
};
|
||||
}
|
||||
if (
|
||||
typeof type === "string" &&
|
||||
type.startsWith("response.function_call_arguments.") &&
|
||||
((data.output_index != null && left.has(data.output_index)) || leftIDs.has(data.item_id))
|
||||
) {
|
||||
return { changed: true, data: null };
|
||||
}
|
||||
} else {
|
||||
if (type === "message_start") {
|
||||
left.clear();
|
||||
kept = 0;
|
||||
dropped = 0;
|
||||
}
|
||||
const block = data.content_block;
|
||||
if (
|
||||
type === "content_block_start" &&
|
||||
object(block) &&
|
||||
isCall(protocol, block) &&
|
||||
checkName(block.name) == null
|
||||
) {
|
||||
left.set(data.index, true);
|
||||
dropped++;
|
||||
return {
|
||||
changed: true,
|
||||
data: { ...data, content_block: { type: "text", text: "" } },
|
||||
extra: [
|
||||
{
|
||||
type: "content_block_delta",
|
||||
index: data.index,
|
||||
delta: { type: "text_delta", text: droppedNote(block.name) },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (type === "content_block_delta" && left.has(data.index))
|
||||
return { changed: true, data: null };
|
||||
if (
|
||||
type === "message_delta" &&
|
||||
object(data.delta) &&
|
||||
data.delta.stop_reason === "tool_use" &&
|
||||
dropped &&
|
||||
!kept
|
||||
) {
|
||||
data.delta.stop_reason = "end_turn";
|
||||
return { changed: true, data };
|
||||
}
|
||||
}
|
||||
const checked = checkSnapshots(data, protocol, checkName);
|
||||
kept += checked.kept;
|
||||
dropped += checked.left;
|
||||
return { changed: checked.changed, data };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parseJSON(text) {
|
||||
let value;
|
||||
try {
|
||||
@@ -402,6 +624,7 @@ async function* framesFrom(reader) {
|
||||
function guardedStream(response, protocol, checkName) {
|
||||
const reader = response.body?.getReader();
|
||||
const chat = protocol === "chat" ? chatBuffer(checkName) : null;
|
||||
const snapshots = chat ? null : snapshotStream(protocol, checkName);
|
||||
let frames = reader ? framesFrom(reader) : null;
|
||||
let completed = false;
|
||||
let stopped = false;
|
||||
@@ -473,23 +696,18 @@ function guardedStream(response, protocol, checkName) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
let changed;
|
||||
let result = data;
|
||||
if (chat) {
|
||||
const checked = chat.apply(data);
|
||||
changed = checked.changed;
|
||||
result = checked.data;
|
||||
} else {
|
||||
changed = checkSnapshots(data, protocol, checkName);
|
||||
}
|
||||
const checked = chat ? chat.apply(data) : snapshots.apply(data, type);
|
||||
const { changed, data: result, extra = [] } = checked;
|
||||
if (
|
||||
(protocol === "responses" &&
|
||||
["response.completed", "response.incomplete"].includes(type)) ||
|
||||
(protocol === "anthropic" && type === "message_stop")
|
||||
)
|
||||
completed = true;
|
||||
if (result) {
|
||||
controller.enqueue(encoder.encode(changed ? rewrite(frame, result) : frame.raw));
|
||||
if (result || extra.length) {
|
||||
const own = !result ? "" : changed ? rewrite(frame, result) : frame.raw;
|
||||
const added = extra.map((value) => encodeEvent(value, value.type)).join("");
|
||||
controller.enqueue(encoder.encode(own + added));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { guardToolResponse } from "./tool-response.mjs";
|
||||
import { droppedNote, guardToolResponse } from "./tool-response.mjs";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
@@ -83,6 +83,167 @@ function namesIn(protocol, data) {
|
||||
protocol === "responses" ? (data.response ?? data).output : (data.message ?? data).content
|
||||
).map((value) => value.name);
|
||||
}
|
||||
// The calls a reply (JSON, or every SSE frame's data) hands the agent, and
|
||||
// the text it says.
|
||||
function callsIn(protocol, values) {
|
||||
return values.flatMap((data) => {
|
||||
if (protocol === "chat")
|
||||
return (data.choices ?? [])
|
||||
.flatMap((choice) => (choice.message ?? choice.delta)?.tool_calls ?? [])
|
||||
.map((value) => value.function.name);
|
||||
const items =
|
||||
protocol === "responses"
|
||||
? [...((data.response ?? data).output ?? []), ...(data.item ? [data.item] : [])]
|
||||
: [
|
||||
...((data.message ?? data).content ?? []),
|
||||
...(data.content_block ? [data.content_block] : []),
|
||||
];
|
||||
return items
|
||||
.filter((item) => ["function_call", "tool_use", "server_tool_use"].includes(item.type))
|
||||
.map((item) => item.name);
|
||||
});
|
||||
}
|
||||
function textIn(protocol, values) {
|
||||
if (protocol === "chat")
|
||||
return values
|
||||
.flatMap((data) => data.choices ?? [])
|
||||
.map((choice) => (choice.message ?? choice.delta)?.content ?? "")
|
||||
.join("");
|
||||
// A stream's text is its deltas; a reply or snapshot's is its text parts.
|
||||
const deltas = values.filter((data) =>
|
||||
protocol === "responses"
|
||||
? data.type === "response.output_text.delta"
|
||||
: data.type === "content_block_delta" && data.delta?.type === "text_delta",
|
||||
);
|
||||
if (deltas.length)
|
||||
return deltas.map((data) => (protocol === "responses" ? data.delta : data.delta.text)).join("");
|
||||
const snapshot = values
|
||||
.map((data) =>
|
||||
protocol === "responses" ? (data.response ?? data).output : (data.message ?? data).content,
|
||||
)
|
||||
.filter(Array.isArray)
|
||||
.at(-1);
|
||||
return (snapshot ?? [])
|
||||
.flatMap((item) =>
|
||||
protocol === "responses"
|
||||
? item.type === "message"
|
||||
? item.content.map((part) => part.text)
|
||||
: []
|
||||
: item.type === "text"
|
||||
? [item.text]
|
||||
: [],
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
const frameData = (text) =>
|
||||
parse(text)
|
||||
.map((frame) => frame.data)
|
||||
.filter((data) => data && data !== "[DONE]");
|
||||
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
// One call streamed the way Zen streams it. Chat's is step-5-preview-free's
|
||||
// own shape (2026-10-11): the name whole in the first delta with empty
|
||||
// arguments, the arguments in pieces, and two tool_calls finishes.
|
||||
function toolStream(protocol, name) {
|
||||
if (protocol === "chat") {
|
||||
const id = { id: "chatcmpl-1", model: "step-5-preview-free" };
|
||||
return (
|
||||
event({ ...id, choices: [{ index: 0, delta: { role: "assistant", content: "" } }] }) +
|
||||
event({
|
||||
...id,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
tool_calls: [
|
||||
{
|
||||
index: 0,
|
||||
id: "call_773767abbc494d2a82872502",
|
||||
type: "function",
|
||||
function: { name, arguments: "" },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
}) +
|
||||
["", "{", '"command": "ls"', "}"]
|
||||
.map((part) =>
|
||||
event({
|
||||
...id,
|
||||
choices: [
|
||||
{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: part } }] } },
|
||||
],
|
||||
}),
|
||||
)
|
||||
.join("") +
|
||||
event({ ...id, choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }) +
|
||||
event({
|
||||
...id,
|
||||
choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 5 },
|
||||
}) +
|
||||
"data: [DONE]\n\n"
|
||||
);
|
||||
}
|
||||
if (protocol === "responses") {
|
||||
const item = { id: "fc_1", type: "function_call", call_id: "call_1", name, arguments: "" };
|
||||
const done = { ...item, arguments: '{"command":"ls"}', status: "completed" };
|
||||
const where = { item_id: "fc_1", output_index: 0 };
|
||||
return [
|
||||
{ type: "response.created", response: { id: "r1", status: "in_progress", output: [] } },
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
output_index: 0,
|
||||
item: { ...item, status: "in_progress" },
|
||||
},
|
||||
{ type: "response.function_call_arguments.delta", ...where, delta: '{"command":' },
|
||||
{ type: "response.function_call_arguments.delta", ...where, delta: '"ls"}' },
|
||||
{ type: "response.function_call_arguments.done", ...where, arguments: '{"command":"ls"}' },
|
||||
{ type: "response.output_item.done", output_index: 0, item: done },
|
||||
{ type: "response.completed", response: { id: "r1", status: "completed", output: [done] } },
|
||||
]
|
||||
.map((value) => event(value, value.type))
|
||||
.join("");
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "message_start",
|
||||
message: { id: "m1", type: "message", role: "assistant", content: [] },
|
||||
},
|
||||
{
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: { type: "tool_use", id: "t1", name, input: {} },
|
||||
},
|
||||
{
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: { type: "input_json_delta", partial_json: '{"command":' },
|
||||
},
|
||||
{
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: { type: "input_json_delta", partial_json: '"ls"}' },
|
||||
},
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 5 } },
|
||||
{ type: "message_stop" },
|
||||
]
|
||||
.map((value) => event(value, value.type))
|
||||
.join("");
|
||||
}
|
||||
// An event no undeclared name can explain: a call of a kind the agent
|
||||
// can't be handed, beside a declared one.
|
||||
function badMixed(protocol) {
|
||||
if (protocol === "chat")
|
||||
return chat({ tool_calls: [call("Read"), { ...call("x", 1), type: "custom" }] }, "tool_calls");
|
||||
if (protocol === "responses")
|
||||
return {
|
||||
type: "response.completed",
|
||||
response: { output: [tool(protocol, "Read"), { type: "custom_tool_call", name: "x" }] },
|
||||
};
|
||||
return { type: "message_start", message: { content: [tool(protocol, "Read"), 5] } };
|
||||
}
|
||||
function sse(text, { chunkSize = 31, headers = {}, status = 200 } = {}) {
|
||||
const bytes = encoder.encode(text);
|
||||
let offset = 0;
|
||||
@@ -191,23 +352,72 @@ for (const protocol of protocols) {
|
||||
}
|
||||
});
|
||||
|
||||
test(`${protocol}: JSON refuses unknown, non-injected, ambiguous and semantic aliases atomically`, async () => {
|
||||
test(`${protocol}: JSON leaves out unknown, non-injected, ambiguous and semantic aliases, and says so (#76)`, async () => {
|
||||
for (const [name, rules] of [
|
||||
["unknown", policy],
|
||||
["shell", policy],
|
||||
["bash", { declared: new Set(["Bash", "BASH"]), injected: new Set(["bash"]) }],
|
||||
["todowrite", { declared: new Set(["todo_write", "todo-write"]), injected: new Set() }],
|
||||
["bash", { declared: new Set(), injected: new Set(["bash"]) }],
|
||||
["bash", { declared: new Set(["Read", "Bash", "BASH"]), injected: new Set(["bash"]) }],
|
||||
[
|
||||
"todowrite",
|
||||
{ declared: new Set(["Read", "todo_write", "todo-write"]), injected: new Set() },
|
||||
],
|
||||
["bash", { declared: new Set(["Read"]), injected: new Set(["bash"]) }],
|
||||
]) {
|
||||
const response = await guardToolResponse(
|
||||
Response.json(snapshot(protocol, ["Read", name])),
|
||||
protocol,
|
||||
rules,
|
||||
);
|
||||
assert.equal(response.status, 502);
|
||||
assert.equal(response.status, 200);
|
||||
const body = await response.json();
|
||||
assertError(protocol, body, false);
|
||||
assert.equal(body.choices ?? body.output ?? body.content, undefined);
|
||||
assert.deepEqual(callsIn(protocol, [body]), ["Read"]);
|
||||
assert.equal(textIn(protocol, [body]), droppedNote(name));
|
||||
}
|
||||
});
|
||||
|
||||
// #76, tkhs101's table of 2026-10-10: the names step-5-preview-free
|
||||
// called that DSH has no tool for, and no spelling of one either. Each
|
||||
// failed the whole turn; each is now left out with the turn going on.
|
||||
test(`${protocol}: the names from #76's table are left out, not failed on`, async () => {
|
||||
const rules = {
|
||||
declared: new Set([
|
||||
"bash",
|
||||
"read",
|
||||
"edit",
|
||||
"glob",
|
||||
"grep",
|
||||
"write",
|
||||
"todo_write",
|
||||
"mcp__netcatty-external__list_hosts",
|
||||
]),
|
||||
injected: new Set(),
|
||||
};
|
||||
for (const name of ["bedit", "bcp", "ash", "mcp__netcatcatty__unused"]) {
|
||||
const json = await guardToolResponse(
|
||||
Response.json(snapshot(protocol, ["bash", name])),
|
||||
protocol,
|
||||
rules,
|
||||
);
|
||||
assert.equal(json.status, 200);
|
||||
const body = await json.json();
|
||||
assert.deepEqual(callsIn(protocol, [body]), ["bash"]);
|
||||
assert.equal(textIn(protocol, [body]), droppedNote(name));
|
||||
for (const upstream of [
|
||||
event(streamSnapshot(protocol, [name])) + terminal(protocol),
|
||||
toolStream(protocol, name),
|
||||
]) {
|
||||
const streamed = await guardToolResponse(sse(upstream), protocol, rules);
|
||||
assert.equal(streamed.status, 200);
|
||||
const values = frameData(await streamed.text());
|
||||
assert.ok(!values.some((data) => data.type === "error" || data.error));
|
||||
assert.deepEqual(callsIn(protocol, values), []);
|
||||
assert.match(
|
||||
textIn(protocol, values),
|
||||
new RegExp(`^(\\n\\n)?${escape(droppedNote(name))}`),
|
||||
);
|
||||
assert.ok(!JSON.stringify(values).includes(`"${name}"`));
|
||||
assert.doesNotMatch(JSON.stringify(values), /"(?:tool_calls|tool_use|function_call)"/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -215,7 +425,17 @@ for (const protocol of protocols) {
|
||||
// todo_write; step-5-preview-free opens with OpenCode's todowrite.
|
||||
test(`${protocol}: an OpenCode tool name is given the agent's own spelling of it (#76)`, async () => {
|
||||
const rules = {
|
||||
declared: new Set(["bash", "read", "edit", "glob", "grep", "write", "todo_write", "web_fetch", "TodoRead"]),
|
||||
declared: new Set([
|
||||
"bash",
|
||||
"read",
|
||||
"edit",
|
||||
"glob",
|
||||
"grep",
|
||||
"write",
|
||||
"todo_write",
|
||||
"web_fetch",
|
||||
"TodoRead",
|
||||
]),
|
||||
injected: new Set(),
|
||||
};
|
||||
for (const [asked, given] of [
|
||||
@@ -243,21 +463,27 @@ for (const protocol of protocols) {
|
||||
}
|
||||
});
|
||||
|
||||
test(`${protocol}: a refused call names the tool (#76)`, async () => {
|
||||
test(`${protocol}: a call left out is named in the reply's text (#76)`, async () => {
|
||||
const json = await guardToolResponse(
|
||||
Response.json(snapshot(protocol, ["subagent"])),
|
||||
protocol,
|
||||
policy,
|
||||
);
|
||||
const body = await json.json();
|
||||
assert.match(body.message ?? body.error?.message, /: "subagent"$/);
|
||||
assert.equal(textIn(protocol, [await json.json()]), droppedNote("subagent"));
|
||||
const streamed = await guardToolResponse(
|
||||
sse(event(streamSnapshot(protocol, ["subagent"])) + terminal(protocol)),
|
||||
protocol,
|
||||
policy,
|
||||
);
|
||||
const frame = parse(await streamed.text())[0].data;
|
||||
assert.match(frame.message ?? frame.error?.message, /: "subagent"$/);
|
||||
assert.equal(textIn(protocol, frameData(await streamed.text())), droppedNote("subagent"));
|
||||
assert.equal(
|
||||
droppedNote("x".repeat(300)),
|
||||
`(The model called a tool this agent doesn't have: "${"x".repeat(128)}". The call was left out.)`,
|
||||
);
|
||||
assert.equal(
|
||||
droppedNote(""),
|
||||
"(The model called a tool without a name. The call was left out.)",
|
||||
);
|
||||
});
|
||||
|
||||
test(`${protocol}: exact matches win over ambiguous casing`, async () => {
|
||||
@@ -294,21 +520,33 @@ for (const protocol of protocols) {
|
||||
});
|
||||
|
||||
test(`${protocol}: bad mixed SSE snapshot never leaks a tool and cancels immediately`, async () => {
|
||||
let cancelled = false;
|
||||
const source = openSource(
|
||||
event(badMixed(protocol)) + event({ sentinel: "must not escape" }),
|
||||
() => {
|
||||
cancelled = true;
|
||||
},
|
||||
);
|
||||
const result = await guardToolResponse(source.response, protocol, policy);
|
||||
const frames = parse(await withTimeout(result.text()));
|
||||
assert.equal(frames.length, 1);
|
||||
assertError(protocol, frames[0].data);
|
||||
if (protocol !== "chat") assert.equal(frames[0].name, "error");
|
||||
assert.equal(cancelled, true);
|
||||
assert.equal(source.response.body.locked, false);
|
||||
});
|
||||
|
||||
test(`${protocol}: a mixed SSE snapshot hands on the declared call and leaves out the rest (#76)`, async () => {
|
||||
for (const name of ["unknown", "shell", "todowrite"]) {
|
||||
let cancelled = false;
|
||||
const source = openSource(
|
||||
event(streamSnapshot(protocol, ["Read", name])) + event({ sentinel: "must not escape" }),
|
||||
() => {
|
||||
cancelled = true;
|
||||
},
|
||||
const result = await guardToolResponse(
|
||||
sse(event(streamSnapshot(protocol, ["Read", name])) + terminal(protocol)),
|
||||
protocol,
|
||||
policy,
|
||||
);
|
||||
const result = await guardToolResponse(source.response, protocol, policy);
|
||||
const frames = parse(await withTimeout(result.text()));
|
||||
assert.equal(frames.length, 1);
|
||||
assertError(protocol, frames[0].data);
|
||||
if (protocol !== "chat") assert.equal(frames[0].name, "error");
|
||||
assert.equal(cancelled, true);
|
||||
assert.equal(source.response.body.locked, false);
|
||||
const values = frameData(await result.text());
|
||||
assert.ok(!values.some((data) => data.type === "error" || data.error));
|
||||
assert.deepEqual(callsIn(protocol, values), ["Read"]);
|
||||
assert.equal(textIn(protocol, values), droppedNote(name));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -348,10 +586,10 @@ for (const protocol of protocols) {
|
||||
);
|
||||
}
|
||||
rawFrames.push(
|
||||
'\uFEFFevent:error\r\ndata: not JSON 中文🙂\r\ndata: second line\r\n\r\n',
|
||||
'event: error\ndata: {broken\n\n',
|
||||
'event: error\ndata: [DONE]\n\n',
|
||||
'event: error\n\n',
|
||||
"\uFEFFevent:error\r\ndata: not JSON 中文🙂\r\ndata: second line\r\n\r\n",
|
||||
"event: error\ndata: {broken\n\n",
|
||||
"event: error\ndata: [DONE]\n\n",
|
||||
"event: error\n\n",
|
||||
);
|
||||
for (const raw of rawFrames) {
|
||||
for (const newline of ["\r\n", "\n", "\r"]) {
|
||||
@@ -477,7 +715,7 @@ for (const protocol of protocols) {
|
||||
test(`${protocol}: cancel failures propagate rather than being swallowed`, async () => {
|
||||
const cause = new Error("cancel failed");
|
||||
for (const badTool of [false, true]) {
|
||||
const source = openSource(event(streamSnapshot(protocol, ["unknown"])), () => {
|
||||
const source = openSource(event(badMixed(protocol)), () => {
|
||||
throw cause;
|
||||
});
|
||||
const result = await guardToolResponse(source.response, protocol, policy);
|
||||
@@ -507,14 +745,31 @@ test("chat: JSON checks every choice, legacy function_call and missing tool name
|
||||
policy,
|
||||
);
|
||||
assert.equal((await result.json()).choices[0].message.function_call.name, "Read");
|
||||
for (const message of [
|
||||
{ function_call: { name: "unknown" } },
|
||||
{ tool_calls: [{ type: "function", function: {} }] },
|
||||
{ tool_calls: [{ type: "custom", custom: { name: "unknown" } }] },
|
||||
for (const [message, name] of [
|
||||
[{ function_call: { name: "unknown" } }, "unknown"],
|
||||
[{ tool_calls: [{ type: "function", function: {} }] }, undefined],
|
||||
]) {
|
||||
const source = Response.json({ choices: [{ message: { content: "ok" } }, { message }] });
|
||||
assert.equal((await guardToolResponse(source, "chat", policy)).status, 502);
|
||||
const source = Response.json({
|
||||
choices: [
|
||||
{ message: { content: "ok" } },
|
||||
{
|
||||
index: 1,
|
||||
message,
|
||||
finish_reason: message.function_call ? "function_call" : "tool_calls",
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await guardToolResponse(source, "chat", policy);
|
||||
assert.equal(result.status, 200);
|
||||
const [first, second] = (await result.json()).choices;
|
||||
assert.deepEqual(first.message, { content: "ok" });
|
||||
assert.deepEqual(second.message, { content: droppedNote(name) });
|
||||
assert.equal(second.finish_reason, "stop");
|
||||
}
|
||||
const custom = Response.json({
|
||||
choices: [{ message: { tool_calls: [{ type: "custom", custom: { name: "unknown" } }] } }],
|
||||
});
|
||||
assert.equal((await guardToolResponse(custom, "chat", policy)).status, 502);
|
||||
});
|
||||
|
||||
test("Responses: nested JSON responses and all streaming snapshots are checked", async () => {
|
||||
@@ -544,8 +799,17 @@ test("Responses: nested JSON responses and all streaming snapshots are checked",
|
||||
);
|
||||
const frames = parse(await result.text());
|
||||
if (name === "unknown") {
|
||||
assert.equal(frames.length, 1);
|
||||
assertError("responses", frames[0].data);
|
||||
const raw = frames.map((frame) => frame.data);
|
||||
assert.ok(!raw.some((data) => data.type === "error" || data.error));
|
||||
assert.deepEqual(callsIn("responses", raw), []);
|
||||
const message = raw[0].item ?? raw[0].response.output[0];
|
||||
assert.equal(message.type, "message");
|
||||
assert.equal(message.id, "msg_call");
|
||||
const said =
|
||||
type === "response.output_item.added"
|
||||
? textIn("responses", raw)
|
||||
: message.content[0].text;
|
||||
assert.equal(said, droppedNote("unknown"));
|
||||
} else
|
||||
assert.equal(frames[0].data.item?.name ?? frames[0].data.response.output[0].name, "Read");
|
||||
}
|
||||
@@ -561,7 +825,9 @@ test("Anthropic: content_block_start, message_start and server_tool_use are guar
|
||||
"anthropic",
|
||||
policy,
|
||||
);
|
||||
assert.equal(json.status, name === "bash" ? 200 : 502);
|
||||
assert.equal(json.status, 200);
|
||||
if (name === "unknown")
|
||||
assert.deepEqual((await json.json()).content, [{ type: "text", text: droppedNote(name) }]);
|
||||
for (const data of [
|
||||
{ type: "content_block_start", index: 0, content_block: block },
|
||||
{ type: "message_start", message: { content: [block] } },
|
||||
@@ -573,8 +839,10 @@ test("Anthropic: content_block_start, message_start and server_tool_use are guar
|
||||
);
|
||||
const frames = parse(await response.text());
|
||||
if (name === "unknown") {
|
||||
assert.equal(frames.length, 1);
|
||||
assertError("anthropic", frames[0].data);
|
||||
const values = frames.map((frame) => frame.data);
|
||||
assert.ok(!values.some((value) => value.type === "error"));
|
||||
assert.deepEqual(callsIn("anthropic", values), []);
|
||||
assert.equal(textIn("anthropic", values), droppedNote(name));
|
||||
} else
|
||||
assert.equal(
|
||||
frames[0].data.content_block?.name ?? frames[0].data.message.content[0].name,
|
||||
@@ -674,7 +942,7 @@ test("chat: one chunk containing many text events still obeys downstream backpre
|
||||
const source = openSource(
|
||||
event(chat({ content: "one" })) +
|
||||
event(chat({ content: "two" })) +
|
||||
event(chat({ tool_calls: [call("unknown")] }, "tool_calls")),
|
||||
event(chat({ tool_calls: [{ ...call("unknown"), type: "custom" }] }, "tool_calls")),
|
||||
() => {
|
||||
cancelled = true;
|
||||
},
|
||||
@@ -777,7 +1045,7 @@ test("cumulative pending chat tools are limited across choices and calls", async
|
||||
assert.ok(pulls <= 33);
|
||||
});
|
||||
|
||||
test("chat: DONE validates all pending choices atomically and rejects missing final names", async () => {
|
||||
test("chat: each pending choice is settled on its own, an unknown or missing final name left out", async () => {
|
||||
for (const ending of [
|
||||
terminal("chat"),
|
||||
event({
|
||||
@@ -785,7 +1053,7 @@ test("chat: DONE validates all pending choices atomically and rejects missing fi
|
||||
{ index: 0, delta: {}, finish_reason: "tool_calls" },
|
||||
{ index: 1, delta: {}, finish_reason: "tool_calls" },
|
||||
],
|
||||
}),
|
||||
}) + terminal("chat"),
|
||||
]) {
|
||||
for (const name of ["unknown", ""]) {
|
||||
const text =
|
||||
@@ -793,14 +1061,73 @@ test("chat: DONE validates all pending choices atomically and rejects missing fi
|
||||
event(chat({ tool_calls: [call(name)] }, null, 1)) +
|
||||
ending;
|
||||
const response = await guardToolResponse(sse(text), "chat", policy);
|
||||
const frames = parse(await response.text());
|
||||
assert.equal(frames.length, 1);
|
||||
assertError("chat", frames[0].data);
|
||||
const values = frameData(await response.text());
|
||||
assert.ok(!values.some((data) => data.error));
|
||||
const choices = values.flatMap((data) => data.choices ?? []);
|
||||
const of = (index) => choices.filter((choice) => choice.index === index);
|
||||
assert.deepEqual(callsIn("chat", [{ choices: of(0) }]), ["Bash"]);
|
||||
assert.deepEqual(callsIn("chat", [{ choices: of(1) }]), []);
|
||||
assert.equal(textIn("chat", [{ choices: of(1) }]), droppedNote(name));
|
||||
const finishes = (index) =>
|
||||
of(index)
|
||||
.map((choice) => choice.finish_reason)
|
||||
.filter(Boolean);
|
||||
if (ending !== terminal("chat")) {
|
||||
assert.deepEqual(finishes(0), ["tool_calls"]);
|
||||
assert.deepEqual(finishes(1), ["stop"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("SSE: ambiguous injected names fail in every protocol", async () => {
|
||||
test("chat: a choice whose every call was left out finishes as a stop, again and again (#76)", async () => {
|
||||
// step-5-preview-free sends its tool_calls finish twice, the second with
|
||||
// usage (seen 2026-10-11); neither may tell the agent to run a tool.
|
||||
const response = await guardToolResponse(sse(toolStream("chat", "bedit")), "chat", policy);
|
||||
const values = frameData(await response.text());
|
||||
const finishes = values
|
||||
.flatMap((data) => data.choices ?? [])
|
||||
.map((choice) => choice.finish_reason)
|
||||
.filter(Boolean);
|
||||
assert.deepEqual(finishes, ["stop", "stop"]);
|
||||
assert.equal(textIn("chat", values), droppedNote("bedit"));
|
||||
assert.ok(values.some((data) => data.usage?.completion_tokens === 5));
|
||||
});
|
||||
|
||||
test("chat: the note follows the text the model wrote before its call", async () => {
|
||||
const text =
|
||||
event(chat({ content: "Fixing the stray heredoc marker." })) +
|
||||
event(chat({ tool_calls: [call("bedit")] }, "tool_calls")) +
|
||||
terminal("chat");
|
||||
const response = await guardToolResponse(sse(text), "chat", policy);
|
||||
assert.equal(
|
||||
textIn("chat", frameData(await response.text())),
|
||||
`Fixing the stray heredoc marker.\n\n${droppedNote("bedit")}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("chat: a call kept beside one left out is numbered from 0", async () => {
|
||||
const text =
|
||||
event(chat({ tool_calls: [call("bedit", 0), call("read", 1, '{"path":"a"}')] }, "tool_calls")) +
|
||||
terminal("chat");
|
||||
const response = await guardToolResponse(sse(text), "chat", policy);
|
||||
const values = frameData(await response.text());
|
||||
const calls = values
|
||||
.flatMap((data) => data.choices ?? [])
|
||||
.flatMap((c) => c.delta?.tool_calls ?? []);
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
index: 0,
|
||||
id: "call-1",
|
||||
type: "function",
|
||||
function: { name: "Read", arguments: '{"path":"a"}' },
|
||||
},
|
||||
]);
|
||||
const finishes = values.flatMap((data) => data.choices ?? []).map((c) => c.finish_reason);
|
||||
assert.ok(finishes.includes("tool_calls"));
|
||||
});
|
||||
|
||||
test("SSE: ambiguous injected names are left out in every protocol", async () => {
|
||||
const rules = { declared: new Set(["Bash", "BASH"]), injected: new Set(["bash"]) };
|
||||
for (const protocol of protocols) {
|
||||
const response = await guardToolResponse(
|
||||
@@ -808,12 +1135,92 @@ test("SSE: ambiguous injected names fail in every protocol", async () => {
|
||||
protocol,
|
||||
rules,
|
||||
);
|
||||
const frames = parse(await response.text());
|
||||
assert.equal(frames.length, 1);
|
||||
assertError(protocol, frames[0].data);
|
||||
const values = frameData(await response.text());
|
||||
assert.ok(!values.some((data) => data.type === "error" || data.error));
|
||||
assert.deepEqual(callsIn(protocol, values), []);
|
||||
assert.equal(textIn(protocol, values), droppedNote("bash"));
|
||||
}
|
||||
});
|
||||
|
||||
test("Responses and Messages: a streamed call left out comes as text in its place", async () => {
|
||||
const responses = frameData(
|
||||
await (
|
||||
await guardToolResponse(sse(toolStream("responses", "bcp")), "responses", policy)
|
||||
).text(),
|
||||
);
|
||||
assert.deepEqual(
|
||||
responses.map((data) => data.type),
|
||||
[
|
||||
"response.created",
|
||||
"response.output_item.added",
|
||||
"response.content_part.added",
|
||||
"response.output_text.delta",
|
||||
"response.output_text.done",
|
||||
"response.content_part.done",
|
||||
"response.output_item.done",
|
||||
"response.completed",
|
||||
],
|
||||
);
|
||||
const note = droppedNote("bcp");
|
||||
const message = { type: "message", id: "fc_1", role: "assistant", status: "completed" };
|
||||
assert.deepEqual(responses[6].item, {
|
||||
...message,
|
||||
content: [{ type: "output_text", text: note, annotations: [] }],
|
||||
});
|
||||
assert.deepEqual(responses[7].response.output, [responses[6].item]);
|
||||
for (const data of responses.slice(2, 6)) {
|
||||
assert.equal(data.item_id, "fc_1");
|
||||
assert.equal(data.output_index, 0);
|
||||
}
|
||||
const messages = frameData(
|
||||
await (
|
||||
await guardToolResponse(sse(toolStream("anthropic", "ash")), "anthropic", policy)
|
||||
).text(),
|
||||
);
|
||||
assert.deepEqual(
|
||||
messages.map((data) => data.type),
|
||||
[
|
||||
"message_start",
|
||||
"content_block_start",
|
||||
"content_block_delta",
|
||||
"content_block_stop",
|
||||
"message_delta",
|
||||
"message_stop",
|
||||
],
|
||||
);
|
||||
assert.deepEqual(messages[1].content_block, { type: "text", text: "" });
|
||||
assert.deepEqual(messages[2].delta, { type: "text_delta", text: droppedNote("ash") });
|
||||
assert.equal(messages[4].delta.stop_reason, "end_turn");
|
||||
});
|
||||
|
||||
test("Messages: a kept call keeps the tool_use stop beside one left out", async () => {
|
||||
const text = [
|
||||
{
|
||||
type: "message_start",
|
||||
message: { id: "m1", type: "message", role: "assistant", content: [] },
|
||||
},
|
||||
{
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: { type: "tool_use", id: "a", name: "ash", input: {} },
|
||||
},
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{
|
||||
type: "content_block_start",
|
||||
index: 1,
|
||||
content_block: { type: "tool_use", id: "b", name: "bash", input: {} },
|
||||
},
|
||||
{ type: "content_block_stop", index: 1 },
|
||||
{ type: "message_delta", delta: { stop_reason: "tool_use" } },
|
||||
{ type: "message_stop" },
|
||||
]
|
||||
.map((value) => event(value, value.type))
|
||||
.join("");
|
||||
const values = frameData(await (await guardToolResponse(sse(text), "anthropic", policy)).text());
|
||||
assert.deepEqual(callsIn("anthropic", values), ["Bash"]);
|
||||
assert.equal(values.find((data) => data.type === "message_delta").delta.stop_reason, "tool_use");
|
||||
});
|
||||
|
||||
test("downstream cancellation interrupts a pending upstream read", async () => {
|
||||
for (const protocol of protocols) {
|
||||
let cancelReason;
|
||||
@@ -866,18 +1273,22 @@ test("chat: completed tool buffers release their cumulative budget", async () =>
|
||||
|
||||
// 64 MiB through the guard: seconds of work, more under load, so it isn't
|
||||
// held to bun's 5 s default (it timed out on a machine at load 110)
|
||||
test("SSE event byte limit includes both bytes of CRLF even across chunks", { timeout: 60_000 }, async () => {
|
||||
const prefix = 'data: {"text":"';
|
||||
const suffix = '"}\r\n\r\n';
|
||||
const text = prefix + "x".repeat(32 * 1024 * 1024 + 1 - prefix.length - suffix.length) + suffix;
|
||||
for (const chunkSize of [1024 * 1024, text.length - 1]) {
|
||||
const result = await guardToolResponse(sse(text, { chunkSize }), "chat", policy);
|
||||
const frames = parse(await result.text());
|
||||
assert.equal(frames.length, 1);
|
||||
assertError("chat", frames[0].data);
|
||||
assert.match(frames[0].data.error.message, /32 MiB|limit/i);
|
||||
}
|
||||
});
|
||||
test(
|
||||
"SSE event byte limit includes both bytes of CRLF even across chunks",
|
||||
{ timeout: 60_000 },
|
||||
async () => {
|
||||
const prefix = 'data: {"text":"';
|
||||
const suffix = '"}\r\n\r\n';
|
||||
const text = prefix + "x".repeat(32 * 1024 * 1024 + 1 - prefix.length - suffix.length) + suffix;
|
||||
for (const chunkSize of [1024 * 1024, text.length - 1]) {
|
||||
const result = await guardToolResponse(sse(text, { chunkSize }), "chat", policy);
|
||||
const frames = parse(await result.text());
|
||||
assert.equal(frames.length, 1);
|
||||
assertError("chat", frames[0].data);
|
||||
assert.match(frames[0].data.error.message, /32 MiB|limit/i);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("text streams larger than 32 MiB are not subject to the pending-tool limit", async () => {
|
||||
let count = 0;
|
||||
|
||||
Reference in New Issue
Block a user