@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
186 lines • 8.25 kB
JavaScript
/**
* The `media_placeholders` transform (one choke point, not five).
*
* A client that advertised `MEDIA_PLACEHOLDERS_CAPABILITY` must never receive
* `{type:"image", data:<base64>}` inside a tool result — four inline images once
* overflowed a 4 MiB socket queue and froze the desktop. Rather than patching each
* wire path that can carry a tool result (`message_start`/`message_end`,
* `turn_end.toolResults`, `agent_end`, `entry_appended`, and the `get_messages`,
* `get_entries`, `get_tree`, `get_state`, `open_session` responses — a list that has
* already been wrong once), every record is funnelled through this pure transform at
* `SessionEventWriter.enqueue`.
*
* Two hard rules:
* - Type-gate the media walk. JSON-value normalization is shared with writer
* acceptance; media projection itself never walks `message_update` partials.
* - Copy-on-write. Responses hand out live agent state by reference
* (`success(id, "get_messages", { messages: session.messages })`), so the input graph
* is never mutated and unchanged JSON sub-trees keep their identity. When nothing changed
* the SAME record reference comes back, which lets the caller reuse the line it
* already serialized.
*
* User-authored images (`prompt.images`) stay intact: they are bounded by the client
* that sent them; the fan-out hazard is tool output.
*/
import { normalizeJsonValue } from "./json-normal-value.js";
/** Record types that can carry a tool result somewhere in their payload. */
const MEDIA_BEARING_RECORD_TYPES = new Set([
"tool_execution_end",
"message_start",
"message_end",
"turn_end",
"agent_end",
"entry_appended",
]);
/** Response commands whose payload can carry a tool result. */
const MEDIA_BEARING_RESPONSE_COMMANDS = new Set([
"get_messages",
"get_entries",
"get_tree",
"get_state",
"open_session",
"claim_session",
]);
/**
* Decoded byte length of a base64 string, derived from its length alone.
*
* Decoding a multi-MiB payload just to report its size would defeat the purpose of
* omitting it.
*/
export function base64ByteLength(data) {
const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
return Math.max(0, Math.floor((data.length * 3) / 4) - padding);
}
function isPlainObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isInlineImage(value) {
return isPlainObject(value) && value.type === "image" && typeof value.data === "string";
}
/** Replace inline images in one tool-result content array; same reference when none. */
function omitContentImages(content, toolCallId, persist) {
let replaced;
for (let index = 0; index < content.length; index++) {
const block = content[index];
if (!isInlineImage(block))
continue;
replaced ??= [...content];
const ref = { toolCallId, contentIndex: index };
// The bytes reach disk before the placeholder that names them leaves this function.
replaced[index] = {
type: "image_ref",
mimeType: typeof block.mimeType === "string" ? block.mimeType : "application/octet-stream",
byteLength: base64ByteLength(block.data),
ref,
...persist?.(ref, block),
};
}
return replaced ?? content;
}
/** A toolResult message whose content array carries images, rebuilt without them. */
function omitToolResultImages(message, persist) {
const content = message.content;
const toolCallId = typeof message.toolCallId === "string" ? message.toolCallId : "";
if (!Array.isArray(content))
return message;
const omitted = omitContentImages(content, toolCallId, persist);
return omitted === content ? message : { ...message, content: omitted };
}
/** Enter a container (scrubbing a toolResult on entry, so persister calls stay in pre-order), or undefined for a leaf. */
function enter(value, key, persist) {
if (Array.isArray(value))
return { key, value, index: 0 };
if (!isPlainObject(value))
return undefined;
const scrubbed = value.role === "toolResult" ? omitToolResultImages(value, persist) : value;
const entries = Object.entries(scrubbed).filter(([name, child]) => (name !== "content" || scrubbed === value) && (isPlainObject(child) || Array.isArray(child)));
return scrubbed === value
? { key, value, scrubbed, entries, index: 0 }
: { key, value, scrubbed, entries, index: 0, replaced: { ...scrubbed } };
}
/**
* Copy-on-write walk. Every object with `role:"toolResult"` has its content array
* scrubbed, wherever it sits (message arrays, `turn_end.toolResults`, session entries,
* tree nodes, `state.entries`). Unchanged sub-trees are returned by reference.
*
* The walk keeps its own stack instead of recursing, so a record of any depth the JSON engine can serialize passes
* (a recursive walk overflowed from about 3,000 levels on Node, below the engine's ~6,185; senpi#4272 RULING-68).
* A cycle is refused as native JSON refuses it.
*/
function walk(root, persist) {
const first = enter(root, 0, persist);
if (!first)
return root;
const stack = [first];
const ancestors = new Set([first.value]);
for (;;) {
const top = stack[stack.length - 1];
if ("entries" in top ? top.index < top.entries.length : top.index < top.value.length) {
const [key, child] = "entries" in top
? top.entries[top.index]
: [top.index, top.value[top.index]];
top.index++;
const frame = enter(child, key, persist);
if (!frame)
continue;
if (ancestors.has(frame.value))
throw new TypeError("Converting circular structure to JSON");
ancestors.add(frame.value);
stack.push(frame);
continue;
}
stack.pop();
ancestors.delete(top.value);
const result = top.replaced ?? top.value;
const parent = stack[stack.length - 1];
if (!parent)
return result;
if (result === top.value)
continue;
if ("entries" in parent)
(parent.replaced ??= { ...parent.scrubbed })[top.key] = result;
else
(parent.replaced ??= [...parent.value])[top.key] = result;
}
}
/** `tool_execution_end.result.content` is not a toolResult message; scrub it explicitly. */
function omitToolExecutionEndImages(record, persist) {
const result = record.result;
if (!isPlainObject(result) || !Array.isArray(result.content))
return record;
const toolCallId = typeof record.toolCallId === "string" ? record.toolCallId : "";
const omitted = omitContentImages(result.content, toolCallId, persist);
return omitted === result.content ? record : { ...record, result: { ...result, content: omitted } };
}
/** True when this record type can carry a tool result at all (cheap gate). */
export function carriesMedia(record) {
if (typeof record.type !== "string")
return false;
if (MEDIA_BEARING_RECORD_TYPES.has(record.type))
return true;
return record.type === "response" && typeof record.command === "string"
? MEDIA_BEARING_RESPONSE_COMMANDS.has(record.command)
: false;
}
/**
* Replace inline tool-result images with `image_ref` placeholders.
*
* Returns the SAME reference when nothing changed, so the caller can skip the second
* serialization entirely.
*/
export function omitInlineMedia(record, persist) {
const { value, changed } = normalizeJsonValue(record);
if (!changed)
return omitNormalInlineMedia(record, persist);
return omitNormalInlineMedia(value, persist);
}
/** `omitInlineMedia` for a value that is already JSON-normal: type gate first, no normalization walk. */
export function omitNormalInlineMedia(record, persist) {
const typed = record;
if (!carriesMedia(typed))
return record;
const scrubbed = typed.type === "tool_execution_end" ? omitToolExecutionEndImages(typed, persist) : typed;
const walked = walk(scrubbed, persist);
return (walked === typed ? record : walked);
}
//# sourceMappingURL=media-placeholders.js.map