Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

feat(mcp): add pane prompt delivery for typed, command and file turns

Jack Rudenkoccc8f34f5a66
diff --git a/packages/cli/src/pane/prompt-delivery.test.ts b/packages/cli/src/pane/prompt-delivery.test.ts
new file mode 100644
index 00000000..d2b24d72
--- /dev/null
+++ b/packages/cli/src/pane/prompt-delivery.test.ts
@@ -0,0 +1,226 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ ALT_SPLIT_MARKER,
+ MAX_TYPED_LINE,
+ READ_LINE_LIMIT,
+ SPLIT_MARKER,
+ fileTemplate,
+ isPlainLine,
+ joinSplitLines,
+ planDelivery,
+ renderTurnFile,
+ writeTurnFile,
+} from "./prompt-delivery.js";
+import { transcriptRecords } from "./test-helpers/transcript-fixtures.js";
+
+const TURN_DIR = "/tmp/claudish-mux-501/launch-Ab3dE9";
+const dirs: string[] = [];
+afterEach(() => {
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
+});
+
+describe("plain lines are typed", () => {
+ test("conversational replies", () => {
+ for (const t of [
+ "yes",
+ "continue with option 2",
+ "Reply with exactly PEAR and nothing else.",
+ ]) {
+ expect(planDelivery(t, TURN_DIR, 1, true)).toEqual({
+ mode: "typed",
+ line: t,
+ witness: { kind: "text", text: t },
+ });
+ }
+ });
+
+ test("not plain: leading ! # ? @ & \\, trailing @x or /x, control chars, tab, CR, newline, > 512 chars", () => {
+ for (const t of [
+ "!ls",
+ "#memo",
+ "?help",
+ "@file look",
+ "&bg",
+ "\\x",
+ "look at @src",
+ "open /tmp/x",
+ "a\tb",
+ "a\rb",
+ "a\nb",
+ "a\u001bb",
+ "a\u007fb",
+ "x".repeat(MAX_TYPED_LINE + 1),
+ ])
+ expect(isPlainLine(t)).toBe(false);
+ expect(isPlainLine("x".repeat(MAX_TYPED_LINE))).toBe(true);
+ expect(isPlainLine(" ")).toBe(false);
+ });
+});
+
+describe("slash commands", () => {
+ test("a short single-line command is typed and witnessed by its command name", () => {
+ expect(planDelivery("/pear", TURN_DIR, 1, true)).toEqual({
+ mode: "command",
+ line: "/pear",
+ witness: { kind: "command", name: "pear" },
+ });
+ expect(planDelivery("/review\tthe diff", TURN_DIR, 1, true)).toMatchObject({
+ mode: "command",
+ line: "/review the diff",
+ });
+ expect(planDelivery("/plugin:cmd arg", TURN_DIR, 1, true)).toMatchObject({
+ witness: { kind: "command", name: "plugin:cmd" },
+ });
+ });
+
+ test("the witness name matches the record the real /pear wrote", () => {
+ const rec = transcriptRecords("slash-and-reads").find(
+ (r) => r.type === "user" && JSON.stringify(r.message.content).includes("command-name")
+ );
+ const d = planDelivery("/pear", TURN_DIR, 1, true);
+ expect(d.mode).toBe("command");
+ if (d.mode === "command" && d.witness.kind === "command")
+ expect(rec!.message.content).toContain(`<command-name>/${d.witness.name}</command-name>`);
+ });
+
+ test("a multi-line command goes to the file with a pointer line", () => {
+ const d = planDelivery("/review\nplease look at\nall of it", TURN_DIR, 3, true);
+ expect(d).toMatchObject({
+ mode: "command",
+ line: `/review — the full arguments are in the file \`${TURN_DIR}/turn-3.md\`; read all of it first.`,
+ file: `${TURN_DIR}/turn-3.md`,
+ fileContent: "/review\nplease look at\nall of it",
+ witness: { kind: "command", name: "review" },
+ });
+ });
+
+ test("a first line over 512 chars also goes to the file", () => {
+ const d = planDelivery(`/review ${"x".repeat(600)}`, TURN_DIR, 1, true);
+ expect(d.mode).toBe("command");
+ if (d.mode === "command") expect(d.file).toBe(`${TURN_DIR}/turn-1.md`);
+ });
+
+ test("/exit and /quit are control deliveries", () => {
+ expect(planDelivery("/exit", TURN_DIR, 1, true)).toEqual({ mode: "control", line: "/exit" });
+ expect(planDelivery(" /quit ", TURN_DIR, 1, true)).toEqual({ mode: "control", line: "/quit" });
+ });
+});
+
+describe("everything else is a turn file", () => {
+ test("the typed line is exactly the template, and it is the witness", () => {
+ const text = "line one\nline two";
+ const d = planDelivery(text, TURN_DIR, 2, true);
+ expect(d.mode).toBe("file");
+ if (d.mode !== "file") return;
+ expect(d.file).toBe(`${TURN_DIR}/turn-2.md`);
+ expect(d.line).toBe(
+ `Your task is in the file \`${TURN_DIR}/turn-2.md\`. Read all of it with the Read tool (in parts if it is long), then do exactly what it says, treating its content as the user's message.`
+ );
+ expect(d.witness).toEqual({ kind: "text", text: d.line });
+ expect(d.fileContent).toBe(text);
+ expect(d.lines).toBe(2);
+ });
+
+ test("the template the capture typed was witnessed verbatim (s03 t11)", () => {
+ const rec = transcriptRecords("tools-session").find(
+ (r) =>
+ typeof r.message?.content === "string" &&
+ r.message.content.startsWith("Your task is in the file")
+ );
+ const file = (rec!.message.content as string).match(/`([^`]+)`/)![1]!;
+ expect(rec!.message.content).toBe(fileTemplate(file, null));
+ });
+
+ test("the template is a plain line: ≤ 300 chars, no @, ends with '.', opens no menu", () => {
+ const line = fileTemplate(`${TURN_DIR}/turn-99.md`, SPLIT_MARKER);
+ expect(line.length).toBeLessThanOrEqual(400);
+ expect(fileTemplate(`${TURN_DIR}/turn-99.md`, null).length).toBeLessThanOrEqual(300);
+ expect(line.includes("@")).toBe(false);
+ expect(line.endsWith(".")).toBe(true);
+ expect(isPlainLine(fileTemplate(`${TURN_DIR}/turn-1.md`, null))).toBe(true);
+ });
+
+ test("CRLF, tabs, leading ! and a 200 KB prompt keep their bytes in the file", () => {
+ for (const text of [
+ "a\r\nb\r\n",
+ "\tindented\n",
+ "!rm -rf /",
+ "x".repeat(200_000).replace(/(.{100})/g, "$1\n"),
+ ]) {
+ const d = planDelivery(text, TURN_DIR, 1, true);
+ expect(d.mode).toBe("file");
+ if (d.mode === "file") expect(d.fileContent).toBe(text);
+ }
+ });
+
+ test("without the Read tool, a non-plain prompt is refused with a reason", () => {
+ const d = planDelivery("line one\nline two", TURN_DIR, 1, false);
+ expect(d.mode).toBe("refused");
+ expect(planDelivery("yes", TURN_DIR, 1, false).mode).toBe("typed");
+ expect(planDelivery("/review\nmore", TURN_DIR, 1, false).mode).toBe("refused");
+ });
+
+ test("an empty prompt is refused", () => {
+ expect(planDelivery(" \n ", TURN_DIR, 1, true).mode).toBe("refused");
+ });
+});
+
+describe("line splitting (Read page budget)", () => {
+ test("READ_LINE_LIMIT is 20,000: Read itself returned a 90,005-char line whole (phase-2 s11)", () => {
+ expect(READ_LINE_LIMIT).toBe(20_000);
+ });
+
+ test("an over-long line is split at whitespace below the bound, marked, and reversible", () => {
+ const words = Array.from({ length: 3000 }, (_, i) => `word${i}`).join(" ");
+ const tf = renderTurnFile(`head\n${words}\ntail`);
+ expect(tf.marker).toBe(SPLIT_MARKER);
+ const lines = tf.content.split("\n");
+ for (const l of lines) expect(l.length).toBeLessThanOrEqual(READ_LINE_LIMIT - 16 + 1);
+ expect(
+ lines
+ .slice(1, -1)
+ .every((l, i, a) =>
+ i < a.length - 1 ? l.endsWith(SPLIT_MARKER) : !l.endsWith(SPLIT_MARKER)
+ )
+ ).toBe(true);
+ expect(lines[1]!.endsWith(` ${SPLIT_MARKER}`)).toBe(true); // split after the whitespace, kept on the left
+ expect(joinSplitLines(tf.content, SPLIT_MARKER)).toBe(`head\n${words}\ntail`);
+ expect(tf.lines).toBe(lines.length);
+ });
+
+ test("a line with no whitespace is hard-split", () => {
+ const tf = renderTurnFile("y".repeat(50_000));
+ expect(tf.content.split("\n")[0]!.length).toBe(READ_LINE_LIMIT - 16 + 1);
+ expect(joinSplitLines(tf.content, tf.marker!)).toBe("y".repeat(50_000));
+ });
+
+ test("an original line already ending in ↩ switches the marker to ⤶, named in the template", () => {
+ const text = `ends with arrow ${SPLIT_MARKER}\n${"z ".repeat(15_000)}`;
+ const d = planDelivery(text, TURN_DIR, 1, true);
+ expect(d.mode).toBe("file");
+ if (d.mode !== "file") return;
+ expect(d.line).toContain(`Lines ending in ${ALT_SPLIT_MARKER} were split for reading`);
+ expect(joinSplitLines(d.fileContent, ALT_SPLIT_MARKER)).toBe(text);
+ });
+
+ test("no split, no extra sentence", () => {
+ const d = planDelivery("short\nfile", TURN_DIR, 1, true);
+ if (d.mode === "file") expect(d.line).not.toContain("were split");
+ });
+});
+
+describe("writeTurnFile", () => {
+ test("writes 0600 with exclusive create", () => {
+ const dir = mkdtempSync(join(tmpdir(), "pane-turn-"));
+ dirs.push(dir);
+ const d = planDelivery("line one\nline two", dir, 1, true);
+ writeTurnFile(d);
+ if (d.mode !== "file") throw new Error("expected file");
+ expect(readFileSync(d.file, "utf8")).toBe("line one\nline two");
+ expect(statSync(d.file).mode & 0o777).toBe(0o600);
+ expect(() => writeTurnFile(d)).toThrow();
+ });
+});
diff --git a/packages/cli/src/pane/prompt-delivery.ts b/packages/cli/src/pane/prompt-delivery.ts
new file mode 100644
index 00000000..42fc7680
--- /dev/null
+++ b/packages/cli/src/pane/prompt-delivery.ts
@@ -0,0 +1,221 @@
+/**
+ * How a prompt's text reaches the REPL (architecture §2.13, D13).
+ *
+ * - a PLAIN single line (≤ 512 printable chars, no leading `! # ? @ & \ /`, no trailing
+ * `@x`/`/x` token) is typed as is;
+ * - a SLASH command is typed as its first line; when that line is too long or more
+ * follows, the whole text goes to the turn file and the typed line points at it;
+ * - EVERYTHING ELSE is written to `<turnDir>/turn-<n>.md` (0600) and the child is told,
+ * in one typed fixed-template line, to Read it. No paste path exists.
+ *
+ * Read's limits, measured on Claude Code 2.1.290 (phase2-captures.md §4.4): no per-line
+ * truncation (a 90,005-char line came back whole), no line-count cap (2,601 lines in one
+ * call), a 25,000-token cap per call. A line longer than a page can never be read, at any
+ * offset, so lines longer than `READ_LINE_LIMIT − 16` are split at whitespace with a
+ * marker the template explains; the split is reversible.
+ */
+
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+import type { Witness } from "./transcript-follower.js";
+
+/** Longest line written to a turn file, in characters (a page budget, not a Read limit). */
+export const READ_LINE_LIMIT = 20_000;
+/** Longest line ever typed into the REPL. */
+export const MAX_TYPED_LINE = 512;
+
+export const SPLIT_MARKER = "↩"; // U+21A9
+export const ALT_SPLIT_MARKER = "⤶"; // U+2936, used when an original line already ends in ↩
+
+export type Delivery =
+ | { mode: "typed"; line: string; witness: Witness }
+ | {
+ mode: "command";
+ line: string;
+ witness: Witness;
+ file?: string;
+ fileContent?: string;
+ lines?: number;
+ }
+ | {
+ mode: "file";
+ line: string;
+ file: string;
+ fileContent: string;
+ lines: number;
+ witness: Witness;
+ }
+ | { mode: "control"; line: "/exit" | "/quit" }
+ | { mode: "refused"; reason: string };
+
+const SLASH = /^\/([A-Za-z0-9][A-Za-z0-9:_-]*)(\s|$)/;
+
+/** Remove C0 controls and DEL. */
+function stripControl(s: string): string {
+ let out = "";
+ for (const ch of s) {
+ const c = ch.codePointAt(0) ?? 0;
+ if (c >= 0x20 && c !== 0x7f) out += ch;
+ }
+ return out;
+}
+
+function printable(s: string): boolean {
+ for (const ch of s) {
+ const c = ch.codePointAt(0) ?? 0;
+ if (c < 0x20 || c === 0x7f) return false;
+ }
+ return true;
+}
+
+/** A plain line: typed exactly as given. */
+export function isPlainLine(text: string): boolean {
+ if (!text.trim()) return false;
+ if (text.length > MAX_TYPED_LINE) return false;
+ if (!printable(text)) return false;
+ const first = text.trimStart()[0] ?? "";
+ if ("!#?@&\\/".includes(first)) return false;
+ const tokens = text.trim().split(/\s+/);
+ const last = tokens[tokens.length - 1] ?? "";
+ if (last.startsWith("@") || last.startsWith("/")) return false;
+ return true;
+}
+
+export interface TurnFile {
+ content: string;
+ /** line count exactly as Read numbers it (the empty line after a final newline counts) */
+ lines: number;
+ /** the marker used, or null when no line was split */
+ marker: string | null;
+}
+
+/** Split one over-long line at the last whitespace before `bound` (hard split if none). */
+function splitLine(line: string, bound: number, marker: string): string[] {
+ const out: string[] = [];
+ let rest = line;
+ while (rest.length > bound) {
+ let cut = rest.lastIndexOf(" ", bound);
+ const tab = rest.lastIndexOf("\t", bound);
+ if (tab > cut) cut = tab;
+ if (cut <= 0) cut = bound;
+ else cut += 1; // keep the whitespace on the left segment, so joining is exact
+ out.push(rest.slice(0, cut) + marker);
+ rest = rest.slice(cut);
+ }
+ out.push(rest);
+ return out;
+}
+
+/** The turn file for `text`: the caller's bytes unchanged except marked splits of over-long lines. */
+export function renderTurnFile(text: string, limit: number = READ_LINE_LIMIT): TurnFile {
+ const bound = limit - 16;
+ const original = text.split("\n");
+ const needsSplit = original.some((l) => l.length > bound);
+ if (!needsSplit) return { content: text, lines: original.length, marker: null };
+ const marker = original.some((l) => l.replace(/\r$/, "").endsWith(SPLIT_MARKER))
+ ? ALT_SPLIT_MARKER
+ : SPLIT_MARKER;
+ const out: string[] = [];
+ for (const l of original) out.push(...(l.length > bound ? splitLine(l, bound, marker) : [l]));
+ return { content: out.join("\n"), lines: out.length, marker };
+}
+
+/** Reverse `renderTurnFile`: join every line ending in `marker` with the next, dropping it. */
+export function joinSplitLines(content: string, marker: string): string {
+ const lines = content.split("\n");
+ const out: string[] = [];
+ let acc = "";
+ for (const l of lines) {
+ if (l.endsWith(marker)) acc += l.slice(0, -marker.length);
+ else {
+ out.push(acc + l);
+ acc = "";
+ }
+ }
+ if (acc) out.push(acc);
+ return out.join("\n");
+}
+
+export function turnFilePath(turnDir: string, turnIndex: number): string {
+ return join(turnDir, `turn-${turnIndex}.md`);
+}
+
+/** The fixed instruction typed for a file-delivered turn. */
+export function fileTemplate(file: string, marker: string | null): string {
+ const base = `Your task is in the file \`${file}\`. Read all of it with the Read tool (in parts if it is long), then do exactly what it says, treating its content as the user's message.`;
+ return marker
+ ? `${base} Lines ending in ${marker} were split for reading: join each with the next line, dropping the ${marker}.`
+ : base;
+}
+
+function commandPointer(name: string, file: string): string {
+ return `/${name} — the full arguments are in the file \`${file}\`; read all of it first.`;
+}
+
+/**
+ * Decide how `text` is delivered for turn `turnIndex`. Pure: the caller writes the file
+ * (`writeTurnFile`) before typing the line.
+ */
+export function planDelivery(
+ text: string,
+ turnDir: string,
+ turnIndex: number,
+ readAvailable: boolean
+): Delivery {
+ const trimmed = text.trim();
+ if (trimmed === "/exit" || trimmed === "/quit") return { mode: "control", line: trimmed };
+ if (!trimmed) return { mode: "refused", reason: "the prompt is empty" };
+
+ const firstLine = text.split("\n")[0] ?? "";
+ const slash = firstLine.trimStart().match(SLASH);
+ if (slash) {
+ const name = slash[1] ?? "";
+ const normalised = stripControl(firstLine.trimStart().replace(/\t/g, " ")).trimEnd();
+ const more = text.slice(firstLine.length).trim().length > 0;
+ if (!more && normalised.length <= MAX_TYPED_LINE) {
+ return { mode: "command", line: normalised, witness: { kind: "command", name } };
+ }
+ if (!readAvailable)
+ return {
+ mode: "refused",
+ reason: `/${name} carries more than one ${MAX_TYPED_LINE}-character line and the Read tool is unavailable`,
+ };
+ const file = turnFilePath(turnDir, turnIndex);
+ const tf = renderTurnFile(text);
+ return {
+ mode: "command",
+ line: commandPointer(name, file),
+ witness: { kind: "command", name },
+ file,
+ fileContent: tf.content,
+ lines: tf.lines,
+ };
+ }
+
+ if (isPlainLine(text)) return { mode: "typed", line: text, witness: { kind: "text", text } };
+
+ if (!readAvailable)
+ return {
+ mode: "refused",
+ reason:
+ "the prompt is not a plain single line and the Read tool is unavailable, so it cannot be delivered as a file",
+ };
+ const file = turnFilePath(turnDir, turnIndex);
+ const tf = renderTurnFile(text);
+ const line = fileTemplate(file, tf.marker);
+ return {
+ mode: "file",
+ line,
+ file,
+ fileContent: tf.content,
+ lines: tf.lines,
+ witness: { kind: "text", text: line },
+ };
+}
+
+/** Write a delivery's turn file: exclusive create, mode 0600. No-op for typed/control deliveries. */
+export function writeTurnFile(d: Delivery): void {
+ if ((d.mode === "file" || d.mode === "command") && d.file && d.fileContent !== undefined) {
+ writeFileSync(d.file, d.fileContent, { mode: 0o600, flag: "wx" });
+ }
+}