Qoder Ultimate sent two native tool calls at tool_calls[].index 0, each
with its own id and name. events() kept one call per upstream index, so
the second call's arguments were sent as more of the first:
{"key":"A"}{"key":"B"}, which the client refused as unparseable JSON.
A fragment with a non-empty id that differs from the open call's id at
that index now starts a new call with an output index of its own. A
fragment with no id, or the open call's id, still goes on with the open
call (OpenAI's argument fragments, and relays that repeat the id). A call
pushed aside before it got a name still counts as nameless (#579).
After two ids at one index, id-less fragments go to the newer call; the
report suggested failing there instead, but OpenAI streams each call's
fragments right after its start, so the newest is the one open.
Siblings with the same index-keyed fold, fixed the same way:
- zed 0.1.19: chatWhole (a streamed chat reply folded for stream:false).
- codearts 0.3.7: completionFromChunks.
- zen-free 0.1.27: stream.mjs chatAccumulator, and tool-response.mjs's
chat buffer, which gives each call its own index when two collided.
- page-chat 0.1.13: lib/server.mjs folds through toolCallFolder.
Looked at and left: codearts' stream name restorer and kimi-desktop's
Agent hold pass fragments through unchanged and join no arguments;
zed's streaming path passes Zed's chunks through, and magpie's gateway
already starts a new call on a new id (internal/gateway/chat.go).
Run (WSL magpie-desktop, bun 1.4.2, node 22):
- pedh's repro.mjs with his fixture: [0,0] gave one tool event plus an
args event on 0.2.64; now two tool events (index 0 and 1), each with
valid JSON. [0,1] unchanged.
- HOME=$(mktemp -d) bun test packages/qoder packages/zed
packages/codearts packages/zen-free packages/chat: 987 pass, 0 fail,
1 skip (the epub reader's, as before). bun scripts/check.mjs: every
package and registry.json ok.
Broken by hand:
- qoder back to index-only: 3 of the new tests fail (two ids, id-less
after a second id, streaming adapter).
- qoder starting a call on any fragment without the open id: 8 fail,
the id-less continuation test among them.
- qoder treating any id as new: the repeated-id test fails.
- zed, codearts, zen-free (both) on main's code and chat keyed by index
only: each new collision test fails (5 of 5).
Not tried: a real Qoder account (no Qoder Ultimate here), real Zed,
CodeArts or OpenCode Zen replies with a collision, and the chat page
in a browser.
Reported-by: pedh <pedh@users.noreply.github.com>
919 lines
32 KiB
JavaScript
919 lines
32 KiB
JavaScript
const MAX_BYTES = 32 * 1024 * 1024;
|
|
const encoder = new TextEncoder();
|
|
|
|
class GuardError extends Error {}
|
|
|
|
function headersFor(response) {
|
|
const headers = new Headers(response.headers);
|
|
headers.delete("content-length");
|
|
headers.delete("content-encoding");
|
|
return headers;
|
|
}
|
|
|
|
function failure(protocol, message, stream = false) {
|
|
if (protocol === "anthropic") return { type: "error", error: { type: "api_error", message } };
|
|
if (protocol === "responses") {
|
|
return stream
|
|
? { type: "error", code: "undeclared_tool", message }
|
|
: { error: { type: "upstream_error", code: "undeclared_tool", message } };
|
|
}
|
|
return { error: { message, type: "upstream_error" } };
|
|
}
|
|
|
|
function object(value) {
|
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
}
|
|
|
|
function list(value) {
|
|
if (value == null) return [];
|
|
if (!Array.isArray(value)) throw new GuardError("Invalid upstream tool snapshot");
|
|
return value;
|
|
}
|
|
|
|
// OpenCode's own models call OpenCode's tool names (bash, todowrite,
|
|
// webfetch) whatever the agent declared. A call is given the agent's tool
|
|
// whose name differs only in case, or else only in case and separators
|
|
// (todowrite → todo_write, webfetch → web_fetch), when exactly one does; a
|
|
// name two of the agent's tools fold to is never guessed between.
|
|
const separators = /[\s_.-]/g;
|
|
function foldsTo(declared, key) {
|
|
const folded = new Map();
|
|
for (const name of declared) {
|
|
const k = key(name);
|
|
// A name of separators only folds to nothing, and would be handed any
|
|
// other such call ("_" for "--"): it matches only itself.
|
|
if (!k) continue;
|
|
folded.set(k, folded.has(k) ? null : name);
|
|
}
|
|
return folded;
|
|
}
|
|
|
|
// nameGuard answers the agent's name for a call: the agent's spelling when
|
|
// one folds to it, else the name as the model wrote it. A call of a tool
|
|
// the agent doesn't have (bedit, psh, mcp__netcatcatty__unused) goes to the
|
|
// agent as called, like any other provider's: the agent answers it with
|
|
// its own unknown-tool error, and the model corrects the name and goes on
|
|
// (#209). Leaving it out ended an agent's turn as a plain answer. Only a
|
|
// call with no name answers null, and is left out.
|
|
function nameGuard(policy) {
|
|
const declared = new Set(policy.declared);
|
|
const lower = (name) => name.toLowerCase();
|
|
const bare = (name) => name.toLowerCase().replace(separators, "");
|
|
const byCase = foldsTo(declared, lower);
|
|
const byShape = foldsTo(declared, bare);
|
|
const renamed = policy.renamed ?? new Map();
|
|
return (name) => {
|
|
if (typeof name !== "string" || !name) return null;
|
|
if (renamed.has(name)) return renamed.get(name);
|
|
if (declared.has(name)) return name;
|
|
const match =
|
|
byCase.get(lower(name)) ?? (byCase.has(lower(name)) ? null : byShape.get(bare(name)));
|
|
return match || name;
|
|
};
|
|
}
|
|
|
|
// A call with no name can't be answered by any agent, and failing the
|
|
// reply for it threw away the whole turn (#76). 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 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;
|
|
}
|
|
}
|
|
|
|
// 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");
|
|
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, kept: 0, left: 0 };
|
|
}
|
|
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, holder, key] = stack.pop();
|
|
if (!object(value)) throw new GuardError("Invalid upstream tool snapshot");
|
|
if (
|
|
protocol === "responses" &&
|
|
typeof value.type === "string" &&
|
|
value.type.endsWith("_call") &&
|
|
value.type !== "function_call"
|
|
) {
|
|
throw new GuardError("Unsupported upstream tool call type");
|
|
}
|
|
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 name of arrays) {
|
|
// Text content is not a snapshot container.
|
|
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 name of objects) {
|
|
if (value[name] != null) stack.push([value[name], value, name]);
|
|
}
|
|
}
|
|
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) {
|
|
const result = value ?? 0;
|
|
if (!Number.isSafeInteger(result) || result < 0)
|
|
throw new GuardError("Invalid upstream tool index");
|
|
return result;
|
|
}
|
|
|
|
function appendFunction(target, fragment) {
|
|
if (!object(fragment)) throw new GuardError("Invalid upstream function delta");
|
|
for (const [key, value] of Object.entries(fragment)) {
|
|
if (key === "name" || key === "arguments") {
|
|
// Nullable stream fields carry no new bytes; keep prior fragments intact.
|
|
if (value == null) continue;
|
|
if (typeof value !== "string") throw new GuardError("Invalid upstream function delta");
|
|
target[key] = (target[key] ?? "") + value;
|
|
} else {
|
|
Object.defineProperty(target, key, {
|
|
value,
|
|
writable: true,
|
|
enumerable: true,
|
|
configurable: true,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
function chatBuffer(checkName) {
|
|
const pending = new Map();
|
|
let bytes = 0;
|
|
function charge(state, value) {
|
|
const size = encoder.encode(JSON.stringify(value)).byteLength;
|
|
bytes += size;
|
|
state.bytes += size;
|
|
if (bytes > MAX_BYTES)
|
|
throw new GuardError("Pending upstream tools exceed the 32 MiB buffer limit");
|
|
}
|
|
function stateFor(index, data) {
|
|
if (!pending.has(index)) {
|
|
const metadata = {};
|
|
for (const key of [
|
|
"id",
|
|
"object",
|
|
"created",
|
|
"model",
|
|
"system_fingerprint",
|
|
"service_tier",
|
|
]) {
|
|
if (data[key] !== undefined) metadata[key] = data[key];
|
|
}
|
|
// calls: slot -> call; open: upstream index -> the slot being written
|
|
const state = { calls: new Map(), open: new Map(), slots: 0, collided: false, legacy: null, metadata, bytes: 0 };
|
|
pending.set(index, state);
|
|
charge(state, metadata);
|
|
}
|
|
return pending.get(index);
|
|
}
|
|
// 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) {
|
|
// by index, and in the order they began within one (sort is stable)
|
|
delta.tool_calls = [...state.calls.values()].sort((a, b) => a.index - b.index);
|
|
// two calls that began at one index each get an index of their own
|
|
if (state.collided) delta.tool_calls.forEach((call, i) => (call.index = i));
|
|
}
|
|
if (state.legacy) delta.function_call = state.legacy;
|
|
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) {
|
|
const state = pending.get(index);
|
|
if (state) bytes -= state.bytes;
|
|
pending.delete(index);
|
|
}
|
|
return {
|
|
get size() {
|
|
return pending.size;
|
|
},
|
|
clear() {
|
|
pending.clear();
|
|
bytes = 0;
|
|
},
|
|
apply(data) {
|
|
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);
|
|
for (const fragment of list(delta.tool_calls)) {
|
|
if (!object(fragment) || (fragment.type != null && fragment.type !== "function")) {
|
|
throw new GuardError("Unsupported upstream tool delta");
|
|
}
|
|
charge(state, fragment);
|
|
const index = position(fragment.index);
|
|
// A new id at an index in use is a new call, not more of the open
|
|
// one: two calls at one index ran together as {"a"}{"b"}
|
|
// (plugins#930). No id, or the same one, goes on with it.
|
|
let slot = state.open.get(index);
|
|
const open = slot === undefined ? undefined : state.calls.get(slot);
|
|
if (
|
|
slot === undefined ||
|
|
(typeof fragment.id === "string" &&
|
|
fragment.id &&
|
|
typeof open?.id === "string" &&
|
|
open.id &&
|
|
fragment.id !== open.id)
|
|
) {
|
|
if (slot !== undefined) state.collided = true;
|
|
slot = state.slots++;
|
|
state.open.set(index, slot);
|
|
}
|
|
const previous = state.calls.get(slot) ?? { index, function: {} };
|
|
const value = { ...previous, ...fragment, index, function: previous.function };
|
|
// 空 ID 片段不应抹掉已缓存的有效 ID,同时允许首次 ID 后续到达。
|
|
if (
|
|
typeof previous.id === "string" &&
|
|
previous.id.length > 0 &&
|
|
(fragment.id == null || fragment.id === "")
|
|
) {
|
|
value.id = previous.id;
|
|
}
|
|
if (fragment.function != null) appendFunction(value.function, fragment.function);
|
|
state.calls.set(slot, value);
|
|
}
|
|
if (delta.function_call != null) {
|
|
charge(state, delta.function_call);
|
|
state.legacy ??= {};
|
|
appendFunction(state.legacy, delta.function_call);
|
|
}
|
|
delete delta.tool_calls;
|
|
delete delta.function_call;
|
|
}
|
|
// Validate every finishing choice before publishing any part of this event.
|
|
for (const choice of choices) {
|
|
if (choice.finish_reason == null) continue;
|
|
const index = position(choice.index);
|
|
const state = pending.get(index);
|
|
if (!state) continue;
|
|
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) =>
|
|
choice.finish_reason != null ||
|
|
Object.keys(choice.delta ?? {}).length ||
|
|
Object.keys(choice).some((key) => !["index", "delta", "finish_reason"].includes(key)),
|
|
);
|
|
return { data: data.choices.length || data.usage != null ? data : null, changed: true };
|
|
},
|
|
finish() {
|
|
if (!pending.size) return null;
|
|
const choices = [...pending]
|
|
.sort(([a], [b]) => a - b)
|
|
.map(([index, state]) => ({ index, delta: complete(state, index), finish_reason: null }));
|
|
const metadata = pending.values().next().value.metadata;
|
|
pending.clear();
|
|
bytes = 0;
|
|
return { ...metadata, choices };
|
|
},
|
|
};
|
|
}
|
|
|
|
// 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 {
|
|
value = JSON.parse(text);
|
|
} catch {
|
|
throw new GuardError("Invalid JSON in upstream response");
|
|
}
|
|
if (!object(value)) throw new GuardError("Invalid JSON object in upstream response");
|
|
return value;
|
|
}
|
|
|
|
function encodeEvent(data, name = "") {
|
|
return `${name ? `event: ${name}\n` : ""}data: ${JSON.stringify(data)}\n\n`;
|
|
}
|
|
|
|
function rewrite(frame, data) {
|
|
const lines = frame.lines.filter((line) => line !== "data" && !line.startsWith("data:"));
|
|
lines.push(`data: ${JSON.stringify(data)}`);
|
|
return `${lines.join("\n")}\n\n`;
|
|
}
|
|
|
|
async function* framesFrom(reader) {
|
|
let parts = [];
|
|
let lineBytes = 0;
|
|
let eventBytes = 0;
|
|
let lines = [];
|
|
let rawLines = [];
|
|
let skipLF = false;
|
|
let pendingFrame;
|
|
let firstLine = true;
|
|
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
function append(value) {
|
|
eventBytes += value.byteLength;
|
|
if (eventBytes > MAX_BYTES)
|
|
throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit");
|
|
if (value.byteLength) {
|
|
parts.push(value);
|
|
lineBytes += value.byteLength;
|
|
}
|
|
}
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) {
|
|
if (pendingFrame) {
|
|
yield pendingFrame;
|
|
pendingFrame = null;
|
|
eventBytes = 0;
|
|
}
|
|
if (eventBytes || lineBytes || lines.length)
|
|
throw new GuardError("Upstream SSE ended inside an event");
|
|
return;
|
|
}
|
|
let start = 0;
|
|
if (skipLF && value.length) {
|
|
if (value[0] === 10) {
|
|
eventBytes++;
|
|
if (pendingFrame) pendingFrame.raw += "\n";
|
|
else rawLines[rawLines.length - 1] += "\n";
|
|
start = 1;
|
|
}
|
|
if (eventBytes > MAX_BYTES)
|
|
throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit");
|
|
skipLF = false;
|
|
if (pendingFrame) {
|
|
const frame = pendingFrame;
|
|
pendingFrame = null;
|
|
eventBytes = 0;
|
|
yield frame;
|
|
}
|
|
}
|
|
for (let offset = start; offset < value.length; offset++) {
|
|
if (value[offset] !== 10 && value[offset] !== 13) continue;
|
|
append(value.subarray(start, offset));
|
|
if (++eventBytes > MAX_BYTES)
|
|
throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit");
|
|
const bytes = new Uint8Array(lineBytes);
|
|
let cursor = 0;
|
|
for (const part of parts) {
|
|
bytes.set(part, cursor);
|
|
cursor += part.length;
|
|
}
|
|
let line;
|
|
try {
|
|
line = decoder.decode(bytes);
|
|
} catch {
|
|
throw new GuardError("Invalid UTF-8 in upstream SSE event");
|
|
}
|
|
parts = [];
|
|
lineBytes = 0;
|
|
let rawLine = line + String.fromCharCode(value[offset]);
|
|
if (firstLine) {
|
|
line = line.replace(/^\uFEFF/, "");
|
|
firstLine = false;
|
|
}
|
|
if (value[offset] === 13) {
|
|
if (value[offset + 1] === 10) {
|
|
rawLine += "\n";
|
|
offset++;
|
|
if (++eventBytes > MAX_BYTES)
|
|
throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit");
|
|
} else if (offset + 1 === value.length) skipLF = true;
|
|
}
|
|
start = offset + 1;
|
|
rawLines.push(rawLine);
|
|
if (line) {
|
|
lines.push(line);
|
|
} else {
|
|
const frameLines = lines;
|
|
lines = [];
|
|
let name = "";
|
|
const data = [];
|
|
for (const item of frameLines) {
|
|
const colon = item.indexOf(":");
|
|
const key = colon < 0 ? item : item.slice(0, colon);
|
|
let content = colon < 0 ? "" : item.slice(colon + 1);
|
|
if (content.startsWith(" ")) content = content.slice(1);
|
|
if (key === "event") name = content;
|
|
if (key === "data") data.push(content);
|
|
}
|
|
const frame = {
|
|
lines: frameLines,
|
|
name,
|
|
text: data.join("\n"),
|
|
raw: rawLines.join(""),
|
|
};
|
|
rawLines = [];
|
|
if (skipLF) {
|
|
// Preserve a trailing CRLF even when its LF arrives in the next chunk.
|
|
pendingFrame = frame;
|
|
} else {
|
|
eventBytes = 0;
|
|
yield frame;
|
|
}
|
|
}
|
|
}
|
|
append(value.subarray(start));
|
|
}
|
|
}
|
|
|
|
// A Chat stream Zen closed before its [DONE] (#91: space-bunny-free, about
|
|
// 0.1% of turns) is ended as a turn cut short when it has said something
|
|
// and no tool call of it is pending: each choice still open gets a note
|
|
// saying so and a stop, then [DONE]. Failing it threw away the reasoning
|
|
// and text the agent already had, and a Chat reply through Zen can't be
|
|
// asked to go on from there. A pending call's arguments may be half
|
|
// written, and a reply that said nothing is an empty one, so both still
|
|
// fail, as does one collapsed for a client that doesn't stream, which can
|
|
// still be asked again. Anthropic and Responses streams cut short fail
|
|
// too: magpie's gateway tells such a reply from a whole one itself
|
|
// (#370), and goes on with it where the upstream can (an Anthropic one),
|
|
// which a made-up end here would stop.
|
|
export const cutShortNote =
|
|
"(The reply was cut short: Zen closed the stream before it finished. Ask again to go on.)";
|
|
|
|
function chatTrack() {
|
|
const open = new Set();
|
|
const finished = new Set();
|
|
const wrote = new Set();
|
|
let said = false;
|
|
let meta = null;
|
|
return {
|
|
see(data) {
|
|
if (!object(data)) return;
|
|
meta = {
|
|
id: data.id ?? meta?.id,
|
|
created: data.created ?? meta?.created,
|
|
model: data.model ?? meta?.model,
|
|
};
|
|
for (const choice of Array.isArray(data.choices) ? data.choices : []) {
|
|
if (!object(choice)) continue;
|
|
const index = position(choice.index);
|
|
const delta = object(choice.delta) ? choice.delta : {};
|
|
for (const key of ["content", "reasoning_content", "reasoning"]) {
|
|
if (typeof delta[key] === "string" && delta[key]) said = true;
|
|
}
|
|
if (typeof delta.content === "string" && delta.content) wrote.add(index);
|
|
if (choice.finish_reason != null) {
|
|
finished.add(index);
|
|
open.delete(index);
|
|
} else if (!finished.has(index)) open.add(index);
|
|
}
|
|
},
|
|
// ending answers the frames that end the reply as cut short, or null
|
|
// when it can't be.
|
|
ending() {
|
|
if (!said) return null;
|
|
const choices = [...open]
|
|
.sort((a, b) => a - b)
|
|
.map((index) => ({
|
|
index,
|
|
delta: { content: (wrote.has(index) ? "\n\n" : "") + cutShortNote },
|
|
finish_reason: "stop",
|
|
}));
|
|
const head = {
|
|
id: meta?.id ?? "chatcmpl-cut-short",
|
|
object: "chat.completion.chunk",
|
|
created: meta?.created ?? Math.floor(Date.now() / 1000),
|
|
model: meta?.model ?? "",
|
|
};
|
|
return (choices.length ? encodeEvent({ ...head, choices }) : "") + "data: [DONE]\n\n";
|
|
},
|
|
};
|
|
}
|
|
|
|
function guardedStream(response, protocol, checkName, endCutShort) {
|
|
const source = response.body?.getReader();
|
|
// What came before a stream cut short, for its error to say (#91).
|
|
let bytes = 0;
|
|
let events = 0;
|
|
let replyID;
|
|
const reader = source && {
|
|
async read() {
|
|
const result = await source.read();
|
|
if (result.value) bytes += result.value.byteLength;
|
|
return result;
|
|
},
|
|
releaseLock: () => source.releaseLock(),
|
|
cancel: (reason) => source.cancel(reason),
|
|
};
|
|
const chat = protocol === "chat" ? chatBuffer(checkName) : null;
|
|
const track = chat && endCutShort ? chatTrack() : null;
|
|
const snapshots = chat ? null : snapshotStream(protocol, checkName);
|
|
let frames = reader ? framesFrom(reader) : null;
|
|
let completed = false;
|
|
let stopped = false;
|
|
let released = false;
|
|
let cancellation;
|
|
function release() {
|
|
if (reader && !released) {
|
|
reader.releaseLock();
|
|
released = true;
|
|
}
|
|
chat?.clear();
|
|
frames = null;
|
|
}
|
|
function cancel(reason) {
|
|
cancellation ??= (async () => {
|
|
try {
|
|
await reader?.cancel(reason);
|
|
} finally {
|
|
release();
|
|
}
|
|
})();
|
|
return cancellation;
|
|
}
|
|
return new ReadableStream(
|
|
{
|
|
async pull(controller) {
|
|
try {
|
|
while (!stopped) {
|
|
const next = frames ? await frames.next() : { done: true };
|
|
if (stopped) return;
|
|
if (next.done) {
|
|
const ending = !completed && !chat?.size ? track?.ending() : null;
|
|
if (ending) {
|
|
stopped = true;
|
|
release();
|
|
controller.enqueue(encoder.encode(ending));
|
|
controller.close();
|
|
return;
|
|
}
|
|
if (!completed || chat?.size) {
|
|
const came = [
|
|
replyID ? `reply ${String(replyID).slice(0, 128)}` : "",
|
|
`${events} event${events === 1 ? "" : "s"}`,
|
|
`${bytes} bytes received`,
|
|
chat?.size ? "a tool call unfinished" : "",
|
|
].filter(Boolean);
|
|
throw new GuardError(
|
|
`Upstream SSE ended without a completion marker (${came.join(", ")})`,
|
|
);
|
|
}
|
|
stopped = true;
|
|
release();
|
|
controller.close();
|
|
return;
|
|
}
|
|
const frame = next.value;
|
|
if (frame.name !== "error" && !frame.text.trim()) {
|
|
controller.enqueue(encoder.encode(frame.raw));
|
|
return;
|
|
}
|
|
if (frame.name !== "error" && frame.text.trim() === "[DONE]") {
|
|
if (protocol !== "chat")
|
|
throw new GuardError("Unexpected upstream completion marker");
|
|
const final = chat.finish();
|
|
completed = true;
|
|
controller.enqueue(encoder.encode((final ? encodeEvent(final) : "") + frame.raw));
|
|
return;
|
|
}
|
|
events++;
|
|
const data = frame.name === "error" ? null : parseJSON(frame.text);
|
|
const type = data?.type ?? frame.name;
|
|
replyID = data?.id ?? data?.message?.id ?? data?.response?.id ?? replyID;
|
|
if (
|
|
frame.name === "error" ||
|
|
type === "error" ||
|
|
data?.error ||
|
|
type === "response.failed" ||
|
|
data?.response?.status === "failed"
|
|
) {
|
|
stopped = true;
|
|
try {
|
|
await cancel();
|
|
} catch (cause) {
|
|
controller.error(cause);
|
|
return;
|
|
}
|
|
controller.enqueue(encoder.encode(frame.raw));
|
|
controller.close();
|
|
return;
|
|
}
|
|
const checked = chat ? chat.apply(data) : snapshots.apply(data, type);
|
|
const { changed, data: result, extra = [] } = checked;
|
|
if (result) track?.see(result);
|
|
if (
|
|
(protocol === "responses" &&
|
|
["response.completed", "response.incomplete"].includes(type)) ||
|
|
(protocol === "anthropic" && type === "message_stop")
|
|
)
|
|
completed = true;
|
|
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;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (stopped) return;
|
|
stopped = true;
|
|
if (error instanceof GuardError) {
|
|
try {
|
|
await cancel(error);
|
|
} catch (cause) {
|
|
controller.error(cause);
|
|
return;
|
|
}
|
|
controller.enqueue(
|
|
encoder.encode(
|
|
encodeEvent(
|
|
failure(protocol, error.message, true),
|
|
protocol === "chat" ? "" : "error",
|
|
),
|
|
),
|
|
);
|
|
controller.close();
|
|
} else {
|
|
release();
|
|
controller.error(error);
|
|
}
|
|
}
|
|
},
|
|
async cancel(reason) {
|
|
stopped = true;
|
|
await cancel(reason);
|
|
},
|
|
},
|
|
{ highWaterMark: 0 },
|
|
);
|
|
}
|
|
|
|
// options.endCutShort lets a Chat stream cut short end as one (#91): for a
|
|
// client that streams, which has the reply's start already. A reply
|
|
// collapsed for a client that doesn't stream fails instead, so it can be
|
|
// asked again before anything reached the client.
|
|
export async function guardToolResponse(response, protocol, policy, options = {}) {
|
|
if (!response.ok) return response;
|
|
if (!["chat", "responses", "anthropic"].includes(protocol))
|
|
throw new TypeError(`Unsupported protocol: ${protocol}`);
|
|
const checkName = nameGuard(policy);
|
|
const headers = headersFor(response);
|
|
const contentType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase();
|
|
if (contentType === "text/event-stream") {
|
|
return new Response(guardedStream(response, protocol, checkName, options.endCutShort === true), {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
headers,
|
|
});
|
|
}
|
|
const text = await response.text();
|
|
let value;
|
|
let status = response.status;
|
|
try {
|
|
value = parseJSON(text);
|
|
checkSnapshots(value, protocol, checkName);
|
|
} catch (error) {
|
|
if (!(error instanceof GuardError)) throw error;
|
|
status = 502;
|
|
value = failure(protocol, error.message);
|
|
}
|
|
headers.set("content-type", "application/json");
|
|
return new Response(JSON.stringify(value), { status, headers });
|
|
}
|