@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
901 lines (900 loc) • 47.1 kB
JavaScript
import { constants } from "node:fs";
import { open } from "node:fs/promises";
import { codexThreadPreview } from "./codex-threads.js";
import { classifyClaudeInput } from "./input-classification.js";
import { readPaneText } from "./pane-text.js";
import { object, objects } from "./protocol.js";
import { withTranscriptIndex } from "./transcript-index.js";
import { stripTerminal } from "../terminal-text.js";
/** Harnesses whose preview text is the reply's own Markdown, from their deltas. */
const STREAMED_SOURCES = new Set(["codex", "opencode", "phren"]);
export const PREVIEW_INTERVAL_MS = 500;
const MAX_TEXT = 32_768;
// A JSON-escaped UTF-16 code unit takes at most six bytes, plus metadata.
const MAX_PREVIEW_BYTES = MAX_TEXT * 6 + 1_024;
/** Only the last Claude reply after the current prompt is eligible. A missing
* prompt anchor is deliberately silent: scrollback could belong to an old turn,
* unless `inTurn` (the turn already landed an entry, so the screen is its own
* output and the prompt scrolled off above it). */
export function claudePanePreview(rendered, prompt, previous = "", inTurn = false) {
const screen = claudeReplyRegion(rendered.split("\n"));
if (!screen)
return "";
const raw = screen.map(stripTerminal);
// What the phone shows: the line with Claude's bold as Markdown. Detection
// below reads the plain line.
const marked = screen.map(line => claudeBoldMarkdown(line).replace(/[\u2500-\u257f]/g, "").trimEnd());
// The rule above the input box can carry the session title
// ("───── Docs refresh ─"); it ends the reply, it is never part of it.
// A narrow pane leaves the titled rule a single dash ("…title… ─"), so a
// line that ends in a rule dash right above the input prompt ends it too.
const lines = raw.map((line, index) => (/[─━═]{3,}/.test(line) && !/^\s*[│┃║]/.test(line))
|| (/[─━═]\s*$/.test(line) && /^\s*[❯>]\s*$/.test(raw[index + 1] ?? "")) ? "❯" : line.replace(/[\u2500-\u257f]/g, "").trimEnd());
const firstPrompt = prompt.trim().split(/\r?\n/)[0]?.trim();
// No verified textual anchor means no pane preview, including reconnects.
if (!firstPrompt)
return "";
let start = -1;
for (let i = 0; i < lines.length; i++) {
if (!/^\s*[❯>]\s*\S/.test(lines[i]))
continue;
const shown = lines[i].replace(/^\s*[❯>]\s*/, "").trim();
if (shown === firstPrompt || (shown.length >= 12 && firstPrompt.startsWith(shown)))
start = i + 1;
}
// Once anchored, a reply can scroll its prompt off screen. Extend only
// through a matching text overlap; unrelated terminal lines cannot replace it.
// In the turn but not anchored (its prompt scrolled off, or drawn otherwise than written, as "/review" or a
// pasted-text placeholder): the newest prompt row with turn output under it (a block, the spinner, thinking)
// is this turn's, and everything above it is an older turn. The composer and a permission dialog's
// options have none under them.
const command = /<command-name>([^<]+)<\/command-name>/.exec(prompt)?.[1];
if (start < 0 && inTurn && !previous && command) {
const output = (line) => /^\s*[⏺●✻✽✶✢✳✦·∴⠁-⣿]/u.test(line) || !!parseClaudeSpinnerLine(line);
for (let i = lines.length - 1; i >= 0; i--) {
if (lines[i].replace(/^\s*[❯>]\s*/, "").trim() !== command || !lines.slice(i + 1).some(output))
continue;
// Nothing written under this turn's prompt yet: no reply to show.
if (!lines.slice(i + 1).some(line => /^\s*[⏺●]/.test(line)))
return "";
start = i + 1;
break;
}
}
if (start < 0 && !previous && lines.some(line => /^\s*[❯>]\s*\S/.test(line)))
return "";
const scrolled = start < 0;
if (scrolled && !previous && !inTurn)
return "";
const reply = [], shown = [];
// Scrolled past its ⏺, a reply already previewed continues from the top; without one, the top of the
// screen may be tool output, so only a ⏺ text block starts a reply. A marker alone cannot establish
// authorship: notices and tools share it, so each is classified before a reply can start.
let block = scrolled && !!previous ? "reply" : "none";
const body = lines.slice(Math.max(0, start)), rawBody = raw.slice(Math.max(0, start)), markedBody = marked.slice(Math.max(0, start));
// A "⏺" block whose next line is a "⎿" result is a tool call, collapsed
// ("⏺ Running 1 shell command…") or not; it lands as its own entry.
const toolBlock = (index) => {
let wrapped = false;
for (let next = index + 1; next < body.length; next++) {
if (!body[next].trim())
continue;
// A notice can be drawn under a tool call's marker (" ⎿ Background
// command …"); it is not that call's result.
if (claudeNotice(body[next]))
return false;
// A result ("⎿") or a sub-agent tree ("├─ Plan · 0 tool uses") follows a tool call.
// A narrow pane wraps the call's description ("⏺ Finding retire wording
// around Power" / "Portal reports"); its "⎿", indented under the call as
// Claude draws it, comes after the wrap. A new block, the prompt or a
// blank line after text ends the search.
if ((wrapped ? /^\s+(?:│\s*)?[⎿├└]/ : /^\s*(?:│\s*)?[⎿├└]/).test(rawBody[next]))
return true;
wrapped = true;
if (/^\s*[⏺●❯>]/.test(body[next]))
return false;
if (!body[next + 1]?.trim())
return false;
}
return false;
};
for (const [index, line] of body.entries()) {
if (/^\s*[❯>]/.test(line) || /esc(?:ape)? to interrupt/i.test(line))
break;
if (/^\s*[✻✽✶✢✳✦·⠁-⣿]/u.test(line) || parseClaudeSpinnerLine(line))
continue;
// Claude Code's own notices (a background command's completion, a hook's
// output, a Monitor event, an interruption or a compaction) can share the
// reply's marker. They never clear or join an already collected reply, and
// their wrapped payload stays out until a fresh reply marker starts one.
if (claudeNotice(line)) {
block = "notice";
continue;
}
// Claude Code draws a finished or running tool group as an unbulleted,
// indented summary under the reply (" Ran 1 shell command", " Called
// phren, ran 1 shell command", " Running 1 shell command… grep -rn …").
// It starts a block after a blank line; it and its wrapped command lines
// are tool activity, which lands as its own entry.
if (!body[index - 1]?.trim() && claudeToolSummary(line)) {
block = "tool";
continue;
}
// A running tool group ("⏺ Running 2 agents…") and a tool call
// ("⏺ Bash(ls)", "⏺ phren - search (MCP)(…)") are not reply
// text; it lands as its own entry a moment later.
if (/^\s*[⏺●]\s*[\w.:-]+(?: - [\w.:-]+)?(?: \(MCP\))?\(/.test(line) || (/^\s*[⏺●]/.test(line) && toolBlock(index))
|| /^\s*[⏺●]\s*(?:Running|Calling|Reading|Searching|Writing|Editing|Fetching|Updating|Listing|Creating)\b[^.!?]*(?:…|\.\.\.)/.test(line)) {
block = "tool";
continue;
}
const tidy = (value) => value.replace(/^\s*[⏺●]\s?/, "").replace(/[⠁-⣿✻✽✶✢✳]/gu, "");
const clean = tidy(line);
const skipped = /^\s*(?:↳|⎿|ctrl\+|shift\+|\? for shortcuts)/i.test(clean) || claudeChrome(clean);
if (/^\s*[⏺●]/.test(line)) {
reply.length = 0;
shown.length = 0;
block = "reply";
}
else if (block === "reply") {
// A reply's wrapped rows stay indented under its marker; an unmarked,
// nonindented row (a notice's payload included) ends the acceptance.
if (line.trim() && !/^ {2,}\S/.test(line)) {
block = "none";
continue;
}
}
else
continue;
if (skipped)
continue;
reply.push(clean.replace(/^ {2}/, ""));
// A rule line has no marked twin: it never reaches here.
shown.push(tidy(markedBody[index] ?? line).replace(/^ {2}/, ""));
}
const text = unwrapTerminalLines(reply, shown).trim().slice(0, MAX_TEXT);
if (!scrolled)
return text;
if (text.startsWith(previous))
return text;
const overlap = previous.lastIndexOf(text.split("\n", 1)[0].slice(0, 80));
return overlap >= 0 && text.startsWith(previous.slice(overlap))
? (previous.slice(0, overlap) + text).slice(0, MAX_TEXT) : previous;
}
const TOOL_SUMMARY_CLAUSE = String.raw `(?:(?:[Cc]alled|[Cc]alling) [\w.-]+(?: \d+ times?)?|(?:[Rr]an|[Rr]unning|[Rr]ead|[Rr]eading|[Ss]earched|[Ss]earching|[Ww]rote|[Ww]riting|[Ee]dited|[Ee]diting|[Uu]pdated|[Uu]pdating|[Ff]etched|[Ff]etching|[Ll]isted|[Ll]isting|[Cc]reated|[Cc]reating|[Ll]aunched|[Ll]aunching) \d+ [a-z]+(?: [a-z]+)?)`;
const TOOL_SUMMARY = new RegExp(`^ {1,4}${TOOL_SUMMARY_CLAUSE}(?:, ${TOOL_SUMMARY_CLAUSE})*(?:(?:…|\\.\\.\\.)(?:\\s.*)?)?(?: \\(ctrl\\+o to expand\\))?\\s*$`);
/** An unbulleted tool-group summary line, e.g. " Read 1 file, ran 1 shell command". */
export function claudeToolSummary(line) {
return TOOL_SUMMARY.test(line);
}
/**
* Claude Code's own screen text, never part of a reply: the update and
* restart notices, status lines it marks ✔ / ✗ / ⚠ / ※, tips, and the
* context and auto-accept hints drawn around the input box.
*/
export function claudeChrome(line) {
const text = line.trim();
if (!text)
return false;
return /^[✔✓✗✘⚠※]\s/.test(text)
|| /\b(?:Update installed|Restart to update|Auto-update failed|Update available|Run \/doctor|Claude Code has been updated)\b/i.test(text)
|| /^(?:Tip|Hint):\s/i.test(text)
|| /^(?:⏵⏵|⏸)\s/.test(text)
|| /\b(?:auto-accept edits|plan mode) (?:on|off)\b/i.test(text)
|| /^(?:(?:manual|auto) mode|accept edits|auto-accept edits|plan mode|bypass permissions) (?:on|off)\b/i.test(text)
|| /^Context left until auto-compact\b/i.test(text)
|| /^(?:esc to (?:interrupt|cancel)|press esc)\b/i.test(text);
}
/** A notice line's detection text: terminal borders, indentation and the
* optional ⏺ / ● / ⎿ decoration are presentation, not part of what it says. */
function noticeText(line) {
return line.replace(/^[\s\u2500-\u257f]*/, "").replace(/^[⏺●⎿]\s*/, "").trim();
}
/** Claude Code's own notices, which share the reply's marker. A header starts
* a notice block; its wrapped payload must not be taken for reply text. */
function claudeNotice(line) {
const text = noticeText(line);
if (!text)
return false;
return /^Background command\s+["“]/.test(text)
|| /^Monitor event\b/.test(text)
|| /^<task-notification>/.test(text)
|| /^Agent\b.+\bcompleted\b/.test(text)
|| /^(?:SessionStart|UserPromptSubmit|PreToolUse|PostToolUse|Stop|SubagentStop|Notification|PreCompact|SessionEnd)(?::[\w-]+)? hook\b/.test(text)
|| /^Hook output:/.test(text)
|| /^(?:Interrupted by user\b|\[Request interrupted by user)/.test(text)
|| /^(?:Compacting conversation(?:…|\.\.\.)|Conversation compacted|Context compacted)/.test(text)
|| /^(?:⏵⏵|⏸)\s/.test(text)
|| /^(?:(?:manual|auto) mode|accept edits|auto-accept edits|plan mode|bypass permissions) (?:on|off)\b/i.test(text);
}
/** A block line that starts its own row even inside a paragraph: a list
* item, heading, quote, table row or code fence. */
/** No terminal pane Claude draws in is narrower than this. */
const MIN_WRAP_WIDTH = 40;
const BLOCK_START = /^\s*(?:[-*+•]\s|\d+[.)]\s|#{1,6}\s|>|\||```|~~~)/;
/**
* Undoes the terminal's word wrap. Claude draws a paragraph wrapped to the
* pane's width, so the phone would show each wrap as a hard break. A line is
* joined to the next when the next line's first word would not have fitted
* on it, which is exactly what a soft wrap looks like; the widest line
* stands in for the pane width, and below 40 columns nothing is joined. Blank lines, block starts and fenced code
* keep their breaks. `display` is what is joined, line for line: the text
* with Markdown put back, measured by its plain twin.
*/
export function unwrapTerminalLines(lines, display = lines) {
const width = Math.max(0, ...lines.map(line => line.length));
// Too narrow to be a pane's wrap: short replies keep their own lines.
if (width < MIN_WRAP_WIDTH)
return display.join("\n");
const out = [];
let fenced = false;
lines.forEach((line, index) => {
const fence = /^\s*(?:```|~~~)/.test(line);
const before = index > 0 ? lines[index - 1] : undefined;
const firstWord = line.trimStart().split(/\s/, 1)[0] ?? "";
const wrapped = !fenced && !fence && before !== undefined && out.length > 0
&& before.trim() !== "" && line.trim() !== "" && !BLOCK_START.test(line)
&& before.trimEnd().length + 1 + firstWord.length > width;
if (wrapped)
out[out.length - 1] += " " + display[index].trim();
else
out.push(display[index]);
if (fence)
fenced = !fenced;
});
return out.join("\n");
}
const SPINNER_LINE = /^\s*[✻✽✶✢✳✦·*⠁-⣿]\s+([A-Z][\p{L}'-]{1,30})(?:…|\.\.\.)\s*\(([^)]*)\)/u;
function spinnerSeconds(text) {
const match = /^(?:(\d{1,4})h\s*)?(?:(\d{1,4})m\s*)?(?:(\d{1,5})s)?$/.exec(text.trim());
if (!match || (!match[1] && !match[2] && !match[3]))
return undefined;
return Number(match[1] ?? 0) * 3600 + Number(match[2] ?? 0) * 60 + Number(match[3] ?? 0);
}
/** One spinner line, or undefined for anything else. The parenthesis must
* start with a time or say "esc to interrupt", as Claude's does. */
export function parseClaudeSpinnerLine(line) {
const match = SPINNER_LINE.exec(line);
if (!match)
return undefined;
const parts = match[2].split("·").map(part => part.trim()).filter(Boolean);
if (!/^\d/.test(parts[0] ?? "") && !parts.some(part => /esc to interrupt/i.test(part)))
return undefined;
const spinner = { verb: match[1], thinking: false };
for (const part of parts) {
const seconds = spinnerSeconds(part);
const tokens = /^([↑↓])\s*(\d{1,6}(?:[.,]\d{1,3})?)\s*([kKmM]?)\s+tokens?$/.exec(part);
const thought = /^thought for (.+)$/i.exec(part);
if (seconds !== undefined && spinner.elapsed === undefined)
spinner.elapsed = seconds;
else if (tokens) {
const scale = /k/i.test(tokens[3]) ? 1_000 : /m/i.test(tokens[3]) ? 1_000_000 : 1;
const count = Math.round(Number(tokens[2].replace(",", ".")) * scale);
if (Number.isFinite(count) && count <= 1e9)
spinner.tokens = { count, direction: tokens[1] === "↑" ? "up" : "down" };
}
else if (/^thinking\b/i.test(part))
spinner.thinking = true;
else if (thought) {
const value = spinnerSeconds(thought[1]);
if (value !== undefined)
spinner.thoughtFor = value;
}
}
return spinner;
}
/** The newest spinner line on screen. */
export function claudeSpinner(rendered) {
const lines = stripTerminal(rendered).split("\n");
for (let i = lines.length - 1; i >= 0; i--) {
const spinner = parseClaudeSpinnerLine(lines[i]);
if (spinner)
return spinner;
}
return undefined;
}
/** The word Claude's own spinner shows ("✻ Pondering… (12s · esc to interrupt)"). */
export function claudeSpinnerVerb(rendered) {
return claudeSpinner(rendered)?.verb;
}
/** Copilot's reasoning state for the running turn, from the headers it draws
* above each reasoning block ("⌄ Thought for 16s", "Thinking" while it
* streams), newest below the turn's prompt line. Only the header is read:
* the reasoning under it ("│ …") never leaves the Hook. */
export function copilotThinking(rendered) {
// Copilot draws a scrollbar down the right edge once the chat overflows.
const lines = stripTerminal(rendered).split("\n").map(line => line.replace(/\s*┃\s*$/, ""));
let from = 0;
lines.forEach((line, index) => { if (/^\s*❯\s+(?!\d+[.)]\s)\S/.test(line))
from = index + 1; });
for (let i = lines.length - 1; i >= from; i--) {
const header = /^\s*[⌄⌃▾▸›>]?\s*(?:(Thinking)\b.*|Thought for (\S+))\s*$/.exec(lines[i]);
if (!header)
continue;
if (header[1])
return { verb: "Working", thinking: true };
const seconds = spinnerSeconds(header[2]);
if (seconds !== undefined)
return { verb: "Working", thinking: false, thoughtFor: seconds };
}
return undefined;
}
export function readPreviewPane(target) {
// With its styles: Claude's bold becomes Markdown; everything else strips.
return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 80, stripAnsi: false, format: "ansi", timeoutMs: 2_000, what: "Preview pane read" });
}
// An SGR sequence (captured) or any other control sequence stripTerminal removes.
const PANE_CONTROL = /\x1b\[([0-?]*)[ -/]*([@-~])|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\r/g;
/** Separate a styled sidebar before classifying rows or measuring wraps. Claude's diff
* panel has no enclosing box: bold paths and dim/italic instructions start at a fixed
* column, with padding between them and the reply. Two rows establish that column;
* crop every row there, including unstyled wraps and rows with no intervening space.
* An isolated region cannot establish a safe boundary, so that read stays silent. */
function claudeReplyRegion(screen) {
const columns = new Map();
const rows = screen.map(line => {
const styles = new Map();
const runs = [];
let plain = "", last = 0, inkStyle = "";
const take = (end) => {
const text = line.slice(last, end);
if (!text)
return;
runs.push({ raw: last, plain: plain.length, text });
if (text.trim()) {
const style = [...styles].sort(([a], [b]) => a - b).map(([key, value]) => `${key}:${value}`).join(";");
const before = plain + text.slice(0, text.length - text.trimStart().length);
// A panel is drawn in bold or dim/italic only, beside a reply at least
// MIN_WRAP_WIDTH wide. Coloured or padded tool output (a diff, a table,
// a command's aligned columns) nearer the left edge is the reply
// region's own text, never a panel: cropping there cut every row short.
const panelStyle = [...styles.keys()].every(key => key === 1 || key === 2 || key === 3);
if (before.length >= MIN_WRAP_WIDTH && / {4,}$/.test(before) && style && panelStyle && style !== inkStyle) {
columns.set(before.length, (columns.get(before.length) ?? 0) + 1);
}
inkStyle = style;
}
plain += text;
};
for (const match of line.matchAll(PANE_CONTROL)) {
take(match.index);
last = match.index + match[0].length;
if (match[2] !== "m")
continue;
const params = (match[1] || "0").split(/[;:]/).map(value => Number(value || 0));
for (let i = 0; i < params.length; i++) {
const code = params[i];
if (code === 0)
styles.clear();
else if (code === 22) {
styles.delete(1);
styles.delete(2);
}
else if ([23, 24, 27, 29].includes(code))
styles.delete(code - 20);
else if (code === 39 || code === 49)
styles.delete(code - 1);
else if (code === 38 || code === 48 || code === 58) {
const size = params[i + 1] === 5 ? 2 : params[i + 1] === 2 ? 4 : 0;
styles.set(code, params.slice(i + 1, i + size + 1).join(":"));
i += size;
}
else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97))
styles.set(38, String(code));
else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
styles.set(48, String(code));
else
styles.set(code, "");
}
}
take(line.length);
return { line, runs };
});
// Without usable styles/padding, a known diff-panel notice is still evidence
// that this read cannot safely be interpreted as a single text region.
const panelNotice = screen.some(line => /New file not yet staged\.|Run `?git add :\/.*to see line counts\./.test(stripTerminal(line)));
if (!columns.size)
return panelNotice ? undefined : screen;
const repeated = [...columns].filter(([, count]) => count >= 2).map(([column]) => column);
if (!repeated.length)
return undefined;
const column = Math.min(...repeated);
// Offsets above count UTF-16 units. Wide glyphs and combining marks make that
// an unsafe terminal column; do not guess a crop in those reads.
if (rows.some(({ line }) => /[\t\p{Mark}\u1100-\u11ff\u2e80-\ua4cf\uac00-\ud7a3\ud800-\udfff\uf900-\ufaff\ufe00-\ufe6f\uff00-\uffef]/u.test(stripTerminal(line).slice(0, column))))
return undefined;
return rows.map(({ line, runs }) => {
const run = runs.find(run => run.plain + run.text.length > column);
return run ? line.slice(0, run.raw + Math.max(0, column - run.plain)) + "\x1b[0m" : line;
});
}
/**
* One pane line as Markdown bold. Claude draws a reply's **bold** with SGR 1
* and drops the asterisks, so a plain read loses it and the phone's preview
* would gain it only when the reply lands. Whitespace stays outside the
* markers (Markdown does not close `**a **`); other styles are dropped.
*/
export function claudeBoldMarkdown(line) {
const runs = [];
let bold = false, last = 0;
const take = (text) => {
if (!text)
return;
const previous = runs[runs.length - 1];
if (previous?.bold === bold)
previous.text += text;
else
runs.push({ text, bold });
};
for (const match of line.matchAll(PANE_CONTROL)) {
take(line.slice(last, match.index));
last = match.index + match[0].length;
if (match[2] !== "m")
continue;
const params = (match[1] || "0").split(/[;:]/);
for (let i = 0; i < params.length; i++) {
const code = Number(params[i] || 0);
// Extended colors carry their own numbers: 38;5;1 is not bold.
if (code === 38 || code === 48 || code === 58) {
i += params[i + 1] === "5" ? 2 : params[i + 1] === "2" ? 4 : 0;
continue;
}
if (code === 1)
bold = true;
else if (code === 0 || code === 22)
bold = false;
}
}
take(line.slice(last));
return runs.map(({ text, bold }) => {
const core = text.trim();
if (!bold || !core)
return text;
const lead = text.slice(0, text.length - text.trimStart().length), trail = text.slice(text.trimEnd().length);
return `${lead}**${core}**${trail}`;
}).join("");
}
/** Older Codex rollouts may carry public text deltas between response items.
* Keep a bounded raw cursor, since history intentionally filters these out. */
export class CodexRolloutPreview {
revision;
cursor = 0;
startedAt;
text = "";
async read(file) {
return withTranscriptIndex(file, async (handle, index) => {
if (this.revision !== index.revision) {
this.cursor = Math.max(0, index.lines - 2_000);
this.startedAt = undefined;
this.text = "";
}
const rows = [];
for await (const row of index.rows(handle, index.lines, Math.max(this.cursor, index.lines - 2_000))) {
if (!row.bytes)
continue;
try {
rows.push(object(JSON.parse(row.bytes.toString())));
}
catch { /* Incomplete or malformed event. */ }
}
for (const raw of rows.reverse()) {
const payload = object(raw.payload), params = object(raw.params);
if (raw.type === "event_msg" && payload.type === "task_started") {
const time = payload.started_at;
this.startedAt = typeof raw.timestamp === "string" ? raw.timestamp
: typeof time === "number" ? new Date(time > 1e12 ? time : time * 1000).toISOString() : undefined;
this.text = "";
}
else if (raw.type === "event_msg" && ["task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(payload.type))) {
this.startedAt = undefined;
this.text = "";
}
else if (raw.type === "response_item" && payload.type === "message" && payload.role === "assistant")
this.text = "";
else if (this.startedAt && ((raw.type === "event_msg" && payload.type === "agent_message_delta" && payload.channel !== "analysis")
|| (raw.method === "item/agentMessage/delta" && params.threadId !== undefined))) {
const delta = raw.method ? params.delta : payload.delta;
if (typeof delta === "string")
this.text = (this.text + delta).slice(0, MAX_TEXT);
}
}
this.cursor = index.lines;
this.revision = index.revision;
return this.startedAt && Number.isFinite(Date.parse(this.startedAt)) && this.text ? { turnStartedAt: this.startedAt, text: this.text } : null;
});
}
}
export async function readDeltaPreview(target, file, rollout) {
if (target.source === "codex")
return await codexThreadPreview(target.session)
?? (file && rollout ? await rollout.read(file).catch(() => null) : null);
// OpenCode's plugin and phren's agent write the same sidecar beside their
// event log (packages/agent/src/session/preview.ts).
if ((target.source !== "opencode" && target.source !== "phren") || !file)
return null;
try {
const handle = await open(file + ".preview.json", constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
let bytes;
try {
const stat = await handle.stat();
if (!stat.isFile() || stat.size > MAX_PREVIEW_BYTES)
return null;
// Bound the read too: the file can grow between stat and read.
const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
if (bytesRead > MAX_PREVIEW_BYTES)
return null;
bytes = buffer.subarray(0, bytesRead);
}
finally {
await handle.close();
}
const value = object(JSON.parse(bytes.toString("utf8")));
if (typeof value.turnStartedAt !== "string" || !Number.isFinite(Date.parse(value.turnStartedAt))
|| typeof value.text !== "string" || !value.text || value.text.length > MAX_TEXT)
return null;
return { turnStartedAt: value.turnStartedAt, text: value.text };
}
catch {
return null;
}
}
/** A landed block shorter than this many letters and digits is not a longer pane block that starts with it. */
const LANDED_MATCH_CHARS = 40;
/** A reply's words alone, for comparing what the pane draws with what landed: the Markdown Claude draws
* otherwise (code fences and their language, list markers and numbers, link targets) is left out. */
function previewWords(text) {
return text.split("\n").filter(line => !/^\s*(?:```|~~~)/.test(line))
.map(line => line.replace(/^\s*(?:\d+[.)]|[-*+•])\s+/, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")).join("\n")
.replace(/[^\p{L}\p{N}]+/gu, "").toLowerCase();
}
/** The pane's words may miss a few stretches of a landed block's: a row taken for Claude's chrome ("Tip: …",
* a `ctrl+` key), or a number a wrap put at a row's start, taken for a list marker. */
const LANDED_GAPS = 4, LANDED_GAP_CHARS = 200, LANDED_RESYNC_CHARS = 16;
/** Whether pane words agree with a landed block's as far as both go, but for at most LANDED_GAPS stretches
* of the landed block's missing from the pane: a number, or up to LANDED_GAP_CHARS after which the pane's
* next LANDED_RESYNC_CHARS follow on. Fewer than those left on the pane is a block of its own. */
function drawsLanded(words, landed) {
let at = 0, from = 0, gaps = 0;
while (at < words.length && from < landed.length) {
if (words[at] === landed[from]) {
at++;
from++;
continue;
}
if (++gaps > LANDED_GAPS)
return false;
if (/\d/.test(landed[from])) {
while (/\d/.test(landed[from] ?? ""))
from++;
continue;
}
const next = words.slice(at, at + LANDED_RESYNC_CHARS);
const skip = next.length < LANDED_RESYNC_CHARS ? -1 : landed.indexOf(next, from + 1);
if (skip < 0 || skip - from > LANDED_GAP_CHARS)
return false;
from = skip;
}
return true;
}
/** Socket-local, ephemeral state. It never writes transcript rows or advances
* the history cursor. Final rows bypass the text throttle and clear atomically. */
export class TranscriptPreviewStream {
target;
pane;
delta;
startedAt;
prompt = "";
/** Claude: the turn landed an entry (a reply block, a tool call or result). */
landed = false;
/** Claude: the turn's reply text blocks that landed as entries, compared by their words. The pane keeps
* showing a landed block until a newer one is drawn, so only a block not among these is previewed. */
landedTexts = new Set();
ended = false;
lifecycleEnded = false;
retirementComplete = true;
/** Claude's own spinner word for the running turn, sent beside frames as
* `activityVerb` for older phones. */
verb;
/** The whole spinner line for the running turn, sent as `activity`;
* phones without it ignore the field. */
activity;
sentActivity = "";
lastRead = -Infinity;
lastSent = -Infinity;
current = null;
clearPending = false;
observedLine = -1;
wasWorking = false;
/** Replies that already landed as entries: a sidecar or thread a tick
* behind them must not bring the same text back as a preview. */
completed = new Set();
rollout = new CodexRolloutPreview();
constructor(target, pane = () => readPreviewPane(target), delta = file => readDeltaPreview(target, file, this.rollout)) {
this.target = target;
this.pane = pane;
this.delta = delta;
}
observe(entries, reset = false) {
if (reset) {
this.clearPending ||= !!this.current;
this.observedLine = -1;
this.startedAt = undefined;
this.landed = false;
this.landedTexts.clear();
this.retirementComplete = true;
this.lifecycleEnded = false;
this.ended = false;
this.wasWorking = false;
this.completed.clear();
}
for (const { raw, line } of entries) {
if (line <= this.observedLine)
continue;
this.observedLine = line;
if (this.target.source === "codex") {
// A completed commentary message can land before task_complete while
// Codex keeps working on a tool call.
const payload = object(raw.payload);
if (raw.type === "event_msg" && payload.type === "task_started") {
this.ended = false;
this.completed.clear();
}
else if (raw.type === "response_item" && payload.type === "message" && payload.role === "user" && !raw.phrenQueued) {
this.ended = false;
this.completed.clear();
}
else if (raw.type === "response_item" && payload.type === "message" && payload.role === "assistant") {
const text = (typeof payload.content === "string" ? payload.content
: objects(payload.content).map(block => typeof block.text === "string" ? block.text : "").join("\n")).trim();
if (text) {
this.completed.add(text);
if (this.completed.size > 32)
this.completed.delete(this.completed.values().next().value);
}
}
else if (raw.type === "event_msg" && ["task_complete", "task_completed", "turn_aborted", "task_aborted"].includes(String(payload.type)))
this.ended = true;
continue;
}
if (this.target.source === "phren") {
const data = object(raw.data), message = object(data.message);
if (raw.type === "user/message")
this.completed.clear();
else if (raw.type === "assistant/message") {
const text = (typeof message.content === "string" ? message.content
: objects(message.content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join("\n")).trim();
if (text) {
this.completed.add(text);
if (this.completed.size > 32)
this.completed.delete(this.completed.values().next().value);
}
}
continue;
}
if (this.target.source === "copilot") {
// A prompt starts the turn; idle or abort ends it (Copilot writes a
// turn_start/turn_end pair per model call, not per prompt).
if (raw.type === "user.message" && typeof raw.timestamp === "string") {
this.startedAt = raw.timestamp;
this.ended = false;
this.wasWorking = false;
this.verb = undefined;
this.activity = undefined;
}
else if (["session.idle", "abort"].includes(String(raw.type))) {
this.ended = true;
this.verb = undefined;
this.activity = undefined;
}
continue;
}
if (this.target.source !== "claude" || raw.phrenExecution === "background")
continue;
const message = object(raw.message), blocks = objects(message.content);
const prompt = typeof message.content === "string" ? message.content : blocks.filter(b => b.type === "text").map(b => String(b.text ?? "")).join("\n");
const input = classifyClaudeInput({ text: prompt, hasImage: blocks.some(b => b.type === "image"), origin: raw.origin, commandMode: raw.commandMode,
isMeta: raw.isMeta, isSidechain: raw.isSidechain, isCompactSummary: raw.isCompactSummary,
toolResult: blocks.some(b => b.type === "tool_result") });
if (raw.type === "user" && input.category === "owner" && !raw.phrenQueued) {
if ((prompt.trim() || blocks.some(b => b.type === "image")) && typeof raw.timestamp === "string" && Number.isFinite(Date.parse(raw.timestamp))) {
this.clearPending ||= !!this.current;
this.startedAt = raw.timestamp;
this.prompt = prompt;
this.landed = false;
this.landedTexts.clear();
this.retirementComplete = true;
this.lifecycleEnded = false;
this.ended = false;
this.wasWorking = false;
this.verb = undefined;
this.activity = undefined;
}
}
else if (this.startedAt && raw.type === "user" && blocks.some(b => b.type === "tool_result")) {
// A tool result is the turn's own activity, never a new owner prompt.
this.landed = true;
}
else if (this.startedAt && ((raw.type === "assistant" && message.stop_reason === "end_turn")
|| (raw.type === "system" && raw.subtype === "turn_duration"))) {
// The transcript says the turn is over before the shared snapshot
// (up to 2.5 s old) stops saying "working": stop reading the pane now.
this.landed = true;
this.ended = true;
this.verb = undefined;
this.activity = undefined;
}
else if (this.startedAt && (raw.type === "assistant" || blocks.some(b => b.type === "tool_result"))) {
this.landed = true;
if (raw.type === "assistant") {
const texts = typeof message.content === "string" ? [message.content] : blocks.filter(b => b.type === "text").map(b => String(b.text ?? ""));
for (const text of texts.map(previewWords).filter(Boolean))
this.landedTexts.add(text);
while (this.landedTexts.size > 64) {
this.retirementComplete = false;
this.landedTexts.delete(this.landedTexts.values().next().value);
}
}
}
}
}
/** Whether pane text is a reply block that already landed: its words agree with the block's as far as
* both go (drawsLanded), or a long paragraph is still on screen after the block's opening scrolled away.
* A block still drawing the same opening as a landed one waits until the two part. */
hasLanded(text) {
const words = previewWords(text);
return !words || [...this.landedTexts].some(landed =>
// A short block ("Let me check.") is not a longer one that starts with its words.
(words.length >= LANDED_MATCH_CHARS && landed.includes(words))
|| !(landed.length < LANDED_MATCH_CHARS && words.length > landed.length) && drawsLanded(words, landed));
}
/** Seed a reconnect from a classified owner row in the verified transcript. */
seedTurn(turnStartedAt, prompt) {
if (this.startedAt || !prompt.trim() || !Number.isFinite(Date.parse(turnStartedAt)))
return;
this.startedAt = turnStartedAt;
this.prompt = prompt;
// The anchor came from a classified owner row in the verified transcript.
this.landed = true;
this.ended = false;
}
/**
* Accept a pane candidate monotonically. Within one block, only a growing
* extension (or a verified overlap) is taken; a shorter or unrelated screen
* cannot replace the accepted block. A later block is accepted only once the
* previous one landed (which clears `current` first) or the caller observed a
* structural boundary.
*/
acceptClaudeCandidate(candidate) {
const current = this.current && this.current.turnStartedAt === this.startedAt ? this.current.text : "";
if (!current)
return candidate.slice(0, MAX_TEXT);
if (candidate === current)
return "";
if (candidate.startsWith(current))
return candidate.slice(0, MAX_TEXT);
// A shorter screen is an incomplete redraw, never a replacement.
if (current.startsWith(candidate))
return "";
// Verified overlap: a redraw may drop the opening rows but keep a stretch.
for (let size = Math.min(current.length, 160); size >= 24; size -= 8) {
const overlap = current.slice(-size);
const at = candidate.indexOf(overlap);
if (at === 0)
return (current.slice(0, current.length - size) + candidate.slice(at)).slice(0, MAX_TEXT);
}
return "";
}
async update(status, file, now, lifecycle) {
const readAt = now ?? Date.now();
let next = null;
if (this.target.source === "claude" && lifecycle?.ended !== undefined) {
this.lifecycleEnded = lifecycle.ended;
if (this.lifecycleEnded) {
this.verb = undefined;
this.activity = undefined;
}
}
// Settled rows and genuine ends clear in the same append, even between
// scrape ticks. Only pane reads and growth frames are throttled.
if (this.target.source === "claude" && this.current && (this.ended || this.lifecycleEnded || this.clearPending
|| this.current.turnStartedAt !== this.startedAt || this.hasLanded(this.current.text))) {
this.current = null;
this.clearPending = false;
if (this.ended || this.lifecycleEnded) {
this.verb = undefined;
this.activity = undefined;
this.sentActivity = "";
}
return { preview: null };
}
this.clearPending = false;
if (status === "working") {
this.wasWorking = true;
if (STREAMED_SOURCES.has(this.target.source)) {
// These harnesses own a delta source. Never scrape their pane, even
// when the source is temporarily empty or unavailable.
if (!this.ended)
next = await this.delta(file);
if (this.target.source !== "opencode" && next) {
const text = next.text.trim();
if (text && [...this.completed].some(completed => completed.startsWith(text)))
next = null;
}
}
else if (this.target.source === "claude" && this.startedAt && !this.ended && !this.lifecycleEnded && this.retirementComplete) {
if (readAt - this.lastRead < PREVIEW_INTERVAL_MS)
return undefined;
this.lastRead = readAt;
// A reply block stops once it lands as an entry; the next one written after a tool or thinking
// previews in turn. Claude's spinner verb keeps naming the work until the turn ends.
const pane = await this.pane();
const candidate = claudePanePreview(pane, this.prompt, this.current?.turnStartedAt === this.startedAt ? this.current.text : "", this.landed);
const spinner = claudeSpinner(pane);
if (spinner) {
this.activity = spinner;
this.verb = spinner.verb;
}
if (candidate && !this.hasLanded(candidate)) {
const accepted = this.acceptClaudeCandidate(candidate);
if (accepted)
next = { turnStartedAt: this.startedAt, text: accepted };
else if (this.current?.turnStartedAt === this.startedAt)
next = this.current;
}
else if (this.current?.turnStartedAt === this.startedAt) {
// An inconclusive scrape (empty, notice-only, transiently incomplete)
// never retires an accepted preview while work continues.
next = this.current;
}
}
else if (this.target.source === "copilot" && this.startedAt && !this.ended) {
// No reply text from the pane: only whether Copilot is thinking.
if (readAt - this.lastRead < PREVIEW_INTERVAL_MS)
return undefined;
this.lastRead = readAt;
const thinking = copilotThinking(await this.pane());
if (thinking) {
this.activity = thinking;
this.verb = thinking.verb;
}
}
}
else if (["claude", "copilot"].includes(this.target.source) && this.wasWorking) {
// Only a resolved genuine end terminates. A bare status snapshot can be a
// notification-driven idle or a stale terminal report; server-stream
// passes the resolver's answer as `lifecycle`. A caller without lifecycle evidence
// preserves the accepted Claude preview.
const ended = this.target.source === "copilot" || lifecycle?.ended === true;
if (ended) {
this.landed = true;
if (this.target.source === "copilot")
this.ended = true;
this.verb = undefined;
this.activity = undefined;
}
else if (this.current && this.current.turnStartedAt === this.startedAt)
next = this.current;
}
const sentAt = now ?? Date.now();
// The phone ticks the clock itself: only the verb, tokens and thinking
// state are worth a frame of their own.
const activity = this.activity ? JSON.stringify({ ...this.activity, elapsed: undefined }) : "";
const previewChanged = next?.text !== this.current?.text || next?.turnStartedAt !== this.current?.turnStartedAt;
const activityChanged = activity !== this.sentActivity;
if (!previewChanged && !activityChanged)
return undefined;
if ((next || !previewChanged) && sentAt - this.lastSent < PREVIEW_INTERVAL_MS)
return undefined;
if (next && STREAMED_SOURCES.has(this.target.source)) {
const before = this.current?.turnStartedAt === next.turnStartedAt ? this.current.text : "";
next = { turnStartedAt: next.turnStartedAt, text: next.text,
delta: before && next.text.startsWith(before) ? next.text.slice(before.length) : next.text, streamed: true };
}
this.current = next;
this.sentActivity = activity;
if (next || activityChanged)
this.lastSent = sentAt;
return { preview: next };
}
}