UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

411 lines (410 loc) • 15 kB
import { Readable } from "node:stream"; import { StringDecoder } from "node:string_decoder"; import { deliverEngineNotice } from "./engine-notice.js"; import { createSentCredentialStream } from "./protocol-http-auth.js"; import { egressSafeCut, egressText } from "./untrusted-egress.js"; import { foldToOneLine, inlineUntrusted } from "./untrusted-text.js"; export const MCP_STDERR_HOLD_CHARS = 65_536; export const MCP_STDERR_CONTEXT_CHARS = 4_096; export const MCP_STDERR_NOTICE_CHARS = 2_048; export const MCP_STDERR_NOTICE_LINES = 32; export const MCP_STDERR_BACKLOG_CHARS = 262_144; const STEP_CHARS = 16_384; const SLICE_MS = 8; const JUDGE_EVERY_STEP_UP_TO = 4_096; const SETTLE_MS = 250; const SETTLE_QUIET_MS = 25; const SETTLE_CHECK_MS = 5; function lineAt(text, at) { const start = at === 0 ? 0 : text.lastIndexOf("\n", at - 1) + 1; const end = text.indexOf("\n", at); return text.slice(start, end < 0 ? text.length : end + 1); } function wordLines(text) { const words = /[^\S\n]*\S/y; let n = 0; for (let start = 0; start < text.length;) { words.lastIndex = start; if (words.test(text)) n++; const end = text.indexOf("\n", start); if (end < 0) break; start = end + 1; } return n; } export function followMcpServerStderr(transport, server, seat, credentials) { const stream = transport.stderr; if (!(stream instanceof Readable)) throw new Error(`MCP server "${inlineUntrusted(server, 160)}": the stdio transport holds no stderr stream to read — not started`); const reading = readMcpServerStderr(stream, server, seat, credentials); stream.on("unpipe", (source) => source.resume()); stream.on("pipe", (source) => { source.on("error", reading.end); if (stream.destroyed) source.unpipe(); }); return reading; } export function readMcpServerStderr(stream, server, seat, credentials) { const name = inlineUntrusted(server, 160); let readings; let echoed = false; try { readings = { asWritten: createSentCredentialStream(credentials), folded: createSentCredentialStream(credentials), leaving: createSentCredentialStream(credentials) }; if (readings.asWritten.holdback === 0) readings = undefined; } catch { echoed = true; } const readFor = (matcher, text) => { if (echoed || matcher === undefined || text.length === 0) return; try { matcher.push(Buffer.from(text, "utf8")); if (matcher.hits > 0) echoed = true; } catch { echoed = true; } }; let halfWritten = ""; const readWritten = (text) => { const words = halfWritten + text; const last = words.charCodeAt(words.length - 1); halfWritten = last >= 0xd800 && last <= 0xdbff ? words.slice(-1) : ""; readFor(readings?.asWritten, halfWritten === "" ? words : words.slice(0, -1)); }; const readFolded = (run) => { if (echoed || readings === undefined) return; const lines = run.split("\n").filter((l) => /\S/.test(l)).map((l) => foldToOneLine(l.endsWith("\r") ? l.slice(0, -1) : l)); if (lines.length > 0) readFor(readings.folded, `${lines.join("\n")}\n`); }; const endFor = (matcher) => { if (echoed || matcher === undefined) return; try { matcher.end(); if (matcher.hits > 0) echoed = true; } catch { echoed = true; } }; const decoder = new StringDecoder("utf8"); let judged = ""; let opening = ""; let held = ""; let heldWhenJudged = 0; let toLineEnd = false; let overLongBreaks; let overLongEndsLine = true; const backlog = []; let backlogChars = 0; let taken = 0; let paused = false; let reading = true; let truncated = false; let ended = false; let whole = false; let turn; let caughtUp; let settled; let shownLines = 0; let withheldLines = 0; const tail = []; let tailChars = 0; const remember = (text) => { judged = (judged + text).replace(/\s{2,}/g, (run) => (run.includes("\n") ? "\n" : run[0])).slice(-MCP_STDERR_CONTEXT_CHARS); }; const withhold = (text) => { if (text.length === 0) return; let breaks = overLongBreaks ?? 0; for (let at = text.indexOf("\n"); at >= 0; at = text.indexOf("\n", at + 1)) breaks++; overLongBreaks = breaks; overLongEndsLine = text.endsWith("\n"); remember(text); }; const endWithheld = () => { if (overLongBreaks !== undefined) withheldLines += overLongBreaks + (overLongEndsLine ? 0 : 1); overLongBreaks = undefined; overLongEndsLine = true; }; const carry = (shown) => { const lines = shown.split("\n"); const picked = []; let pickedChars = 0; let count = 0; let full = false; for (let i = lines.length - 1; i >= 0; i--) { const raw = lines[i]; if (!/\S/.test(raw)) continue; count++; if (full) continue; const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw; const kept = inlineUntrusted(line, MCP_STDERR_NOTICE_CHARS); if (picked.length > 0 && (picked.length >= MCP_STDERR_NOTICE_LINES || pickedChars + kept.length > MCP_STDERR_NOTICE_CHARS)) { full = true; continue; } picked.push(kept); pickedChars += kept.length; } picked.reverse(); if (full) { tail.splice(0, tail.length, ...picked); tailChars = pickedChars; } else { tail.push(...picked); tailChars += pickedChars; while (tail.length > MCP_STDERR_NOTICE_LINES || (tail.length > 1 && tailChars > MCP_STDERR_NOTICE_CHARS)) tailChars -= tail.shift().length; } return count; }; const judge = (final) => { if (toLineEnd) { const lineEnd = held.indexOf("\n") + 1; const rest = lineEnd > 0 ? held.slice(0, lineEnd) : held; withhold(rest); held = held.slice(rest.length); if (lineEnd === 0 && !final) return; toLineEnd = false; endWithheld(); } if (held.length > MCP_STDERR_HOLD_CHARS && final) { withhold(held); held = ""; } const lines = final && whole ? held.length : held.lastIndexOf("\n") + 1; if (lines > 0 && (final || lines <= JUDGE_EVERY_STEP_UP_TO || lines >= 2 * heldWhenJudged || held.length > MCP_STDERR_HOLD_CHARS)) { const before = opening + judged; const { cut, shown } = egressSafeCut(before + held.slice(0, lines), before.length, final); const out = cut - before.length; if (out > 0) { const run = held.slice(0, out); readFolded(run); const told = carry(shown); shownLines += told; withheldLines += Math.max(0, wordLines(run) - told); remember(run); held = held.slice(out); opening = ""; } heldWhenJudged = held.lastIndexOf("\n") + 1; } if (held.length > MCP_STDERR_HOLD_CHARS) { const text = opening + judged + held; const { open } = egressSafeCut(text, text.length, false); opening = open === undefined ? "" : lineAt(text, open).slice(0, MCP_STDERR_CONTEXT_CHARS); toLineEnd = !held.endsWith("\n"); withhold(held); held = ""; heldWhenJudged = 0; } if (final && held.length > 0) { if (/\S/.test(held)) withhold(held); held = ""; } if (!toLineEnd || final) endWithheld(); }; const feed = (text) => { readWritten(text); for (let at = 0; at < text.length;) { const room = MCP_STDERR_HOLD_CHARS + 1 - held.length; held += text.slice(at, at + room); at += room; judge(false); } }; const giveUp = () => { readWritten(backlog.join("")); withhold(held + backlog.join("")); held = ""; backlog.length = 0; backlogChars = 0; endWithheld(); stopReading(); }; const put = (text) => { if (text.length === 0) return; const last = backlog.length - 1; if (last >= 0 && backlog[last].length < STEP_CHARS) backlog[last] += text; else backlog.push(text); backlogChars += text.length; }; const takeStep = () => { let text = ""; while (backlog.length > 0 && text.length < STEP_CHARS) { const head = backlog[0]; const room = STEP_CHARS - text.length; if (head.length <= room) { text += head; backlog.shift(); } else { text += head.slice(0, room); backlog[0] = head.slice(room); } } backlogChars -= text.length; return text; }; const step = () => { turn = undefined; const began = performance.now(); try { while (backlogChars > 0) { feed(takeStep()); if (performance.now() - began >= SLICE_MS) break; } } catch { giveUp(); } if (paused && reading && backlogChars <= MCP_STDERR_BACKLOG_CHARS / 2) { paused = false; stream.resume(); } if (backlogChars > 0) turn = setImmediate(step); else { const done = caughtUp; caughtUp = undefined; done?.(); } }; const onData = (chunk) => { taken += chunk.length; put(typeof chunk === "string" ? chunk : decoder.write(chunk)); if (backlogChars > MCP_STDERR_BACKLOG_CHARS && !paused) { paused = true; stream.pause(); } if (turn === undefined && backlogChars > 0) turn = setImmediate(step); }; const stopReading = () => { reading = false; stream.off("data", onData); paused = false; stream.resume(); }; const end = () => { if (ended) return; ended = true; put(decoder.end()); if (turn === undefined && backlogChars > 0) turn = setImmediate(step); }; const accountOf = (whole) => { const lines = shownLines + withheldLines; const carried = whole ? [] : tail; return { lines, carried, withheld: whole ? lines : withheldLines, notShown: lines - carried.length }; }; const headOf = (outcome, whole) => { const { lines, carried, withheld, notShown } = accountOf(whole); const parts = [`${lines} ${lines === 1 ? "line" : "lines"}`]; if (whole) parts.push(`${lines === 1 ? "it" : "all of them"} withheld unshown (a credential this dial handed the server stands in what it wrote, or what it wrote could not be checked for one)`); else if (withheld > 0) parts.push(`${withheld} of them withheld unshown (a credential, a key block not closed before the dial settled, a last line not ended when it settled, or a run past ${MCP_STDERR_HOLD_CHARS} characters)`); if (notShown > withheld) parts.push(`${notShown - withheld} earlier not shown`); if (truncated) parts.push("and more was still arriving when the dial settled: it was not read"); const when = outcome === "connected" ? "while connecting (once the connection is up its stderr is not read)" : "before the connection failed"; return `[mcp:${name}] stderr ${when}: ${parts.join(", ")}${carried.length === 0 ? "" : ` — the last ${carried.length === 1 ? "one" : carried.length}:`}`; }; const bodyOf = (carried) => carried.map((l) => `\n ${l}`).join(""); const noticeOf = (outcome, whole) => { const { lines, carried, withheld, notShown } = accountOf(whole); return { code: "mcp.server_stderr", message: `${headOf(outcome, whole)}${bodyOf(carried)}`, detail: { server, outcome, lines, notShown, withheld, truncated } }; }; const headerOnly = () => { readFor(readings?.asWritten, halfWritten); endFor(readings?.asWritten); endFor(readings?.folded); if (echoed || readings === undefined || tail.length === 0) return echoed; try { readFor(readings.leaving, egressText("same-principal", bodyOf(tail))); endFor(readings.leaving); } catch { echoed = true; } return echoed; }; const settle = (outcome) => { if (settled !== undefined) return settled; settled = (async () => { if (outcome !== "stopped") { const deadline = performance.now() + SETTLE_MS; let quietSince = performance.now(); for (let seen = taken; performance.now() - quietSince < SETTLE_QUIET_MS;) { if (performance.now() >= deadline) { truncated = true; break; } await new Promise((resolve) => setTimeout(resolve, SETTLE_CHECK_MS)); if (taken !== seen || paused) { seen = taken; quietSince = performance.now(); } } } while (stream.read() !== null) ; if (outcome !== "stopped") await new Promise((resolve) => setImmediate(resolve)); stopReading(); end(); if (backlogChars > 0) { await new Promise((resolve) => { caughtUp = resolve; if (turn === undefined) turn = setImmediate(step); }); } try { judge(true); } catch { giveUp(); } if (outcome !== "stopped" && shownLines + withheldLines > 0) deliverEngineNotice(seat, noticeOf(outcome, headerOnly())); })(); return settled; }; stream.on("data", onData); stream.on("end", () => { whole = reading; end(); }); stream.on("close", end); stream.on("error", end); return { settle, end }; }