Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 4d33757a86c4dedfc817fe21d1994daf5af70cca
parent bdea6e6a92323877394d9233156937cb2c01c5bb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 00:28:04 -0500

umtool: `umtool model-log` never sends a recorded text's control sequences to the terminal -- ESC, C0, DEL, C1 and bidi controls are printed as escapes; --json escapes what JSON.stringify leaves

A recorded prompt or answer is a model's (or a transcript's) text: an ESC in
it could clear the screen, set the title or rewrite what the operator reads.
Every line printed for a person goes through terminalSafe (\n and \t stay).
JSON.stringify escapes C0 only, so --json goes through terminalSafeJson: DEL,
C1 (U+009B is a CSI to some terminals) and bidi controls become \u.... -- the
same document. Tests in common (the two functions) and over the CLI.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/lib/llm/callLog.test.ts | 23+++++++++++++++++++++++
Mcommon/lib/llm/callLog.ts | 20++++++++++++++++++++
Mumtool/bin/model-log.ts | 45++++++++++++++++++++++++++-------------------
Mumtool/lib/research/model-log.test.ts | 30++++++++++++++++++++++++++++++
4 files changed, 99 insertions(+), 19 deletions(-)

diff --git a/common/lib/llm/callLog.test.ts b/common/lib/llm/callLog.test.ts @@ -16,6 +16,8 @@ import { phaseOrder, scrubText, summarizeCalls, + terminalSafe, + terminalSafeJson, } from "./callLog"; import { CallSlot, ModelLogWriter, modelLogFilesIn, processScrub, readModelCallText, readModelLog, recordModelCall, recordSessionAnswer, runWithModelLog } from "./callLog-server"; import { Meter } from "./meter"; @@ -250,3 +252,24 @@ test("processScrub: a variable of the environment named like a credential is a s for (const k of Object.keys(vars)) delete env[k]; } }); + +test("terminalSafe: a recorded text cannot drive a terminal -- ESC, C0, DEL, C1 and bidi controls are printed as escapes; \\n, \\t and ordinary text stay", () => { + assert.equal(terminalSafe("a\x1b[2Jb"), "a\\x1b[2Jb"); + assert.equal(terminalSafe("\x1b]0;title\x07"), "\\x1b]0;title\\x07"); + assert.equal(terminalSafe("over\rwritten\b\x00\x7f"), "over\\x0dwritten\\x08\\x00\\x7f"); + assert.equal(terminalSafe("c1 \u009b31m \u0090 \u009d"), "c1 \\x9b31m \\x90 \\x9d"); + assert.equal(terminalSafe("rtl \u202e \u2066 \u2028"), "rtl \\u202e \\u2066 \\u2028"); + const plain = "line one\n\ttabbed — “quoted” é 日本語 🙂"; + assert.equal(terminalSafe(plain), plain); + // Nothing a terminal acts on is left, whatever the input. + let all = ""; + for (let i = 0; i < 0x100; i++) all += String.fromCharCode(i); + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(terminalSafe(all))); +}); + +test("terminalSafeJson: printed JSON carries no DEL, C1 or bidi control, and parses to the same value", () => { + const v = { answer: "csi \u009b31m del \x7f esc \x1b[2J rtl \u202e\nnext\tline", n: 1 }; + const out = terminalSafeJson(JSON.stringify(v, null, 2)); + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202e]/.test(out), out); + assert.deepEqual(JSON.parse(out), v); +}); diff --git a/common/lib/llm/callLog.ts b/common/lib/llm/callLog.ts @@ -131,6 +131,26 @@ export function scrubText(text: string, s: Scrub = {}): string { return out.replace(HOME_PATH, "<path>"); } +// A recorded text printed to a terminal (`umtool model-log`): what a model +// answered, or a transcript said, must not drive the operator's terminal. Every +// control character but \n and \t -- ESC and the rest of C0, DEL, C1 (a CSI or +// OSC in one byte) -- is printed as its escape (\x1b), and the characters that +// reorder or hide text (bidi controls, the line and paragraph separators) as +// \u…. JSON printed to a terminal goes through `terminalSafeJson`: +// JSON.stringify escapes C0 only, and leaves DEL, C1 (U+009B is a CSI to some +// terminals) and the bidi controls as they are; there they become JSON's own +// \u…. escapes, so the document parses to the same text. +const TERMINAL_UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069]/g; +export function terminalSafe(text: string): string { + return text.replace(TERMINAL_UNSAFE, (ch) => { + const n = ch.charCodeAt(0); + return n <= 0xff ? `\\x${n.toString(16).padStart(2, "0")}` : `\\u${n.toString(16).padStart(4, "0")}`; + }); +} +export function terminalSafeJson(json: string): string { + return json.replace(TERMINAL_UNSAFE, (ch) => (ch === "\n" || ch === "\t" ? ch : `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`)); +} + // An answer as the record keeps it: a string as it is, anything else as JSON. export function answerText(answer: unknown): string { if (typeof answer === "string") return answer; diff --git a/umtool/bin/model-log.ts b/umtool/bin/model-log.ts @@ -9,7 +9,12 @@ // every model call of the iteration's runs (or the job's), by phase: // the seconds, what code did and why, what was asked, what came back, // and each item's fate; --call prints one call's whole text -import { CALL_OUTCOMES, callMatches, phaseLabel, phaseOrder, summarizeCalls, type CallOutcome, type ModelCall } from "yt-dlp-transcript-common/lib/llm/callLog"; +// +// Every line printed for a person goes through `say`: a recorded prompt or +// answer is a model's (or a transcript's) text, and an ESC in it would be the +// terminal's to obey. --json prints JSON through `sayJson`, which escapes what +// JSON.stringify leaves (DEL, C1, bidi controls) as \u…: the same document. +import { CALL_OUTCOMES, callMatches, phaseLabel, phaseOrder, summarizeCalls, terminalSafe, terminalSafeJson, type CallOutcome, type ModelCall } from "yt-dlp-transcript-common/lib/llm/callLog"; import { readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; import { ModelLogError, jobLogOf, modelLogFilesOf, readModelCall, type ModelLogSource } from "../lib/model-log"; @@ -23,8 +28,10 @@ const val = (f: string) => { const json = has("--json"); const positional = args.filter((a, i) => !a.startsWith("--") && !VALUED.includes(args[i - 1] ?? "")); const USAGE = "usage: umtool model-log <article> <n> | --job <jobId> [--phase P] [--outcome kept|dropped|rewritten|n/a] [--task T] [--run K] [--call <run.call>] [--json]"; +const say = (line: string) => process.stdout.write(`${terminalSafe(line)}\n`); +const sayJson = (v: unknown) => process.stdout.write(`${terminalSafeJson(JSON.stringify(v, null, 2))}\n`); const die = (msg: string, code = 2): never => { - console.error(`umtool model-log: ${msg}`); + console.error(terminalSafe(`umtool model-log: ${msg}`)); process.exit(code); }; @@ -45,16 +52,16 @@ try { if (id) { const { call, text } = await readModelCall(src, id); if (json) { - console.log(JSON.stringify({ call, text }, null, 2)); + sayJson({ call, text }); process.exit(0); } - console.log(`${where} · call ${call.id} · ${call.phase}${call.label ? ` · ${call.label}` : ""} · ${call.model} (${call.route}) · ${secs(call.seconds)} · ${call.decision.outcome}${call.decision.why ? `: ${call.decision.why}` : ""}`); - for (const it of call.items ?? []) console.log(` ${it.outcome.padEnd(9)} ${one(it.text)}${it.why ? ` — ${it.why}` : ""}`); - if (!text) console.log("\n(this call's text was not kept)"); + say(`${where} · call ${call.id} · ${call.phase}${call.label ? ` · ${call.label}` : ""} · ${call.model} (${call.route}) · ${secs(call.seconds)} · ${call.decision.outcome}${call.decision.why ? `: ${call.decision.why}` : ""}`); + for (const it of call.items ?? []) say(` ${it.outcome.padEnd(9)} ${one(it.text)}${it.why ? ` — ${it.why}` : ""}`); + if (!text) say("\n(this call's text was not kept)"); else { - if (text.system) console.log(`\n── system ──\n${text.system}`); - console.log(`\n── asked ──\n${text.prompt}${text.promptCut ? "\n… (cut at 40,000 characters)" : ""}`); - console.log(`\n── came back ──\n${text.answer}${text.answerCut ? "\n… (cut at 40,000 characters)" : ""}`); + if (text.system) say(`\n── system ──\n${text.system}`); + say(`\n── asked ──\n${text.prompt}${text.promptCut ? "\n… (cut at 40,000 characters)" : ""}`); + say(`\n── came back ──\n${text.answer}${text.answerCut ? "\n… (cut at 40,000 characters)" : ""}`); } process.exit(0); } @@ -68,27 +75,27 @@ try { const shown = scoped.filter((c) => callMatches(c, { ...(phase ? { phase } : {}), ...(outcome ? { outcome: outcome as CallOutcome } : {}) })); const summary = summarizeCalls(scoped); if (json) { - console.log(JSON.stringify({ source: src, runs: log.runs, summary, calls: shown }, null, 2)); + sayJson({ source: src, runs: log.runs, summary, calls: shown }); process.exit(0); } if (!scoped.length) { - console.log(`${where}: no model call recorded`); + say(`${where}: no model call recorded`); process.exit(0); } - console.log(`${where} · ${summary.calls} call${summary.calls === 1 ? "" : "s"} · ${secs(summary.seconds)} · ${summary.models.map((m) => `${m.model} (${m.route}, ${m.calls})`).join(", ")}${summary.failed ? ` · ${summary.failed} failed` : ""}`); + say(`${where} · ${summary.calls} call${summary.calls === 1 ? "" : "s"} · ${secs(summary.seconds)} · ${summary.models.map((m) => `${m.model} (${m.route}, ${m.calls})`).join(", ")}${summary.failed ? ` · ${summary.failed} failed` : ""}`); const runs = log.runs.filter((r) => scoped.some((c) => c.run === r.run)); - if (runs.length > 1) console.log(`runs: ${runs.map((r) => `${r.run} ${r.task} ${r.at.slice(0, 16)}`).join(" · ")}`); + if (runs.length > 1) say(`runs: ${runs.map((r) => `${r.run} ${r.task} ${r.at.slice(0, 16)}`).join(" · ")}`); for (const p of phaseOrder(shown.map((c) => c.phase))) { const list: ModelCall[] = shown.filter((c) => c.phase === p); - console.log(`\n${phaseLabel(p)} · ${list.length} call${list.length === 1 ? "" : "s"} · ${secs(list.reduce((s, c) => s + c.seconds, 0))}`); + say(`\n${phaseLabel(p)} · ${list.length} call${list.length === 1 ? "" : "s"} · ${secs(list.reduce((s, c) => s + c.seconds, 0))}`); for (const c of list) { - console.log(` ${c.id.padEnd(6)} ${secs(c.seconds).padStart(7)} ${c.decision.outcome.padEnd(9)} ${c.label ?? ""}${c.decision.why ? ` — ${c.decision.why}` : ""}`); - console.log(` asked: ${one(c.promptHead).slice(0, 160)}`); - console.log(` back: ${c.error ? `FAILED ${one(c.error)}` : one(c.answerHead).slice(0, 160)}`); - for (const it of c.items ?? []) if (!outcome || it.outcome === outcome) console.log(` ${it.outcome.padEnd(9)} ${one(it.text).slice(0, 140)}${it.why ? ` — ${it.why}` : ""}`); + say(` ${c.id.padEnd(6)} ${secs(c.seconds).padStart(7)} ${c.decision.outcome.padEnd(9)} ${c.label ?? ""}${c.decision.why ? ` — ${c.decision.why}` : ""}`); + say(` asked: ${one(c.promptHead).slice(0, 160)}`); + say(` back: ${c.error ? `FAILED ${one(c.error)}` : one(c.answerHead).slice(0, 160)}`); + for (const it of c.items ?? []) if (!outcome || it.outcome === outcome) say(` ${it.outcome.padEnd(9)} ${one(it.text).slice(0, 140)}${it.why ? ` — ${it.why}` : ""}`); } } - console.log(`\nthe whole text of one: umtool model-log ${"job" in src ? `--job ${src.job}` : `${src.article} ${src.n}`} --call <id>`); + say(`\nthe whole text of one: umtool model-log ${"job" in src ? `--job ${src.job}` : `${src.article} ${src.n}`} --call <id>`); } catch (e) { die((e as Error).message, e instanceof ModelLogError && e.status === 400 ? 2 : 1); } diff --git a/umtool/lib/research/model-log.test.ts b/umtool/lib/research/model-log.test.ts @@ -48,6 +48,17 @@ before(async () => { ]); }); await w.flush(); + // A second iteration whose model answered with terminal control sequences. + const dir2 = path.join(articles, "mlog", "iterations", "2"); + await mkdir(dir2, { recursive: true }); + await writeFile(path.join(dir2, "iteration.json"), JSON.stringify({ format: "archilyzer-iteration", version: 1, article: "mlog", n: 2, kind: "sweep", parent: null, copyOf: null, model: "qwen3:8b", question: "q", status: "done", usage: {}, steps: [], createdAt: at, updatedAt: at })); + const w2 = new ModelLogWriter({ files: modelLogFilesIn(dir2), task: "sweep", model: "qwen3:8b", where: { article: "mlog", iteration: 2 }, scrub: {} }); + const slot2 = new CallSlot(); + await runWithModelLog(w2, async () => { + recordModelCall({ phase: "reading", label: "extract \x1b[31mred", model: "qwen3:8b", route: "local", system: "Read.\x1b[2J", prompt: "asked \x1b]0;owned\x07 this\nsecond line\tkept", answer: "back \x1b[2J\x1b[H wiped \u009b31m and\rover", seconds: 1 }, slot2); + slot2.decide("dropped", "why \x1b[1mbold", [{ text: "item \x1b[5mblink", outcome: "dropped", why: "because \x07bell" }]); + }); + await w2.flush(); // The job's pointer (what a report-draft job beside its iteration writes). const usage = path.join(tmp, ".generation", "usage.jsonl"); await mkdir(path.join(tmp, ".generation", "calls", "job-7"), { recursive: true }); @@ -101,3 +112,22 @@ test("--job: a job's calls, through its pointer to the iteration it ran on", asy assert.match(none.out, /job job-unknown: no model call recorded/); assert.equal((await cli("nope")).code, 2, "usage"); }); + +test("a recorded text cannot drive the terminal: control sequences are printed as escapes, in the list and in --call; --json is JSON", async () => { + const raw = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/; + const list = await cli("mlog", "2"); + assert.equal(list.code, 0, list.err); + assert.ok(!raw.test(list.out), JSON.stringify(list.out)); + assert.match(list.out, /extract \\x1b\[31mred — why \\x1b\[1mbold/); + assert.match(list.out, /dropped +item \\x1b\[5mblink — because \\x07bell/); + const one = await cli("mlog", "2", "--call", "1.1"); + assert.equal(one.code, 0, one.err); + assert.ok(!raw.test(one.out), JSON.stringify(one.out)); + assert.match(one.out, /── system ──\nRead\.\\x1b\[2J/); + assert.match(one.out, /── asked ──\nasked \\x1b\]0;owned\\x07 this\nsecond line\tkept/, "newlines and tabs stay"); + assert.match(one.out, /── came back ──\nback \\x1b\[2J\\x1b\[H wiped \\x9b31m and\\x0dover/); + // --json: the text as recorded, in JSON's own escapes -- no raw control byte either. + const j = await cli("mlog", "2", "--call", "1.1", "--json"); + assert.ok(!raw.test(j.out)); + assert.equal(JSON.parse(j.out).text.answer, "back \x1b[2J\x1b[H wiped \u009b31m and\rover"); +});