Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(cli): penguin chat marks its prompts with OSC 133 on a terminal

lmliheng3713a9aa8519
diff --git a/changelog/unreleased/2026-10-11-chat-prompt-marks.md b/changelog/unreleased/2026-10-11-chat-prompt-marks.md
new file mode 100644
index 00000000..e1e79664
--- /dev/null
+++ b/changelog/unreleased/2026-10-11-chat-prompt-marks.md
@@ -0,0 +1,27 @@
+# `penguin chat` marks its prompts for terminals
+
+- **Date:** 2026-10-11
+- **Type:** feature
+- **Scope:** `cli`, `docs`
+
+[中文版](2026-10-11-chat-prompt-marks.zh.md)
+
+Ported from upstream PenguinHarness (#1003, commit `c95ef950`).
+
+On a terminal, `penguin chat` now writes the OSC 133 semantic prompt sequences (the ones shells
+write for shell integration). A terminal that supports them can jump between the chat's prompts
+and select one turn's output, and a program hosting the chat in a terminal of its own can tell
+when the chat is back at its prompt and takes input, without matching the prompt text.
+
+## Details
+
+- `A` is written where the `> ` prompt starts and `B` where input starts after it. The
+ continuation prompt, the approval question and the exit confirmation are not marked.
+- `C` is written when a submitted prompt's turn starts, including `/compact`, `/clear`,
+ `/switch-model` and `/goal`, and `D;0` when it ends, or `D;1` when it ended in an error.
+ Commands answered locally, such as `/thinking` and `/verbose`, run no turn and are not
+ enclosed.
+- Nothing is written unless both stdin and stdout are a terminal and `TERM` is not `dumb`, so a
+ redirected or piped output never carries them. The sequences are zero-width and terminals that
+ do not know them ignore them.
+- The CLI page describes the marks and notes that they are advisory, in both languages.
diff --git a/changelog/unreleased/2026-10-11-chat-prompt-marks.zh.md b/changelog/unreleased/2026-10-11-chat-prompt-marks.zh.md
new file mode 100644
index 00000000..1a1a7975
--- /dev/null
+++ b/changelog/unreleased/2026-10-11-chat-prompt-marks.zh.md
@@ -0,0 +1,18 @@
+# `penguin chat` 为终端标记提示符
+
+- **Date:** 2026-10-11
+- **Type:** feature
+- **Scope:** `cli`, `docs`
+
+[English](2026-10-11-chat-prompt-marks.md)
+
+移植自上游 PenguinHarness(#1003,提交 `c95ef950`)。
+
+在终端里,`penguin chat` 现在会输出 OSC 133 语义提示符序列,也就是 shell 为终端集成输出的那组序列。支持这些序列的终端可以在对话的提示符之间跳转、选中某一轮的输出;在自己的终端里承载对话的程序也能判断对话何时回到提示符、可以接收输入,而无需匹配提示符文本。
+
+## 细节
+
+- `> ` 提示符开始处输出 `A`,其后输入开始处输出 `B`。续行提示符、审批询问与退出确认不做标记。
+- 提交的 Prompt 开始一轮时输出 `C`(`/compact`、`/clear`、`/switch-model` 与 `/goal` 也一样),该轮结束时输出 `D;0`,出错结束时输出 `D;1`。`/thinking`、`/verbose` 等在本地应答的命令不运行一轮,不做包围标记。
+- 只有 stdin 与 stdout 都是终端且 `TERM` 不是 `dumb` 时才输出,输出被重定向或接管道时一个标记也没有。这些序列宽度为零,不认识它们的终端会忽略。
+- CLI 页面中英两版都说明了这些标记,并注明它们仅供参考。
diff --git a/packages/cli/src/commands/chat.ts b/packages/cli/src/commands/chat.ts
index a929907d..4753ece5 100644
--- a/packages/cli/src/commands/chat.ts
+++ b/packages/cli/src/commands/chat.ts
@@ -80,6 +80,19 @@ interface RlInternals {
const MAIN_PROMPT = "> ";
const CONT_PROMPT = "… ";
+/**
+ * Semantic prompt marks (OSC 133, the FinalTerm sequences shells emit for shell integration):
+ * `A` where the main prompt starts, `B` where input starts after it, `C` when a submitted
+ * prompt's turn starts, `D;<0|1>` when it ends (1 = it ended in an error). Terminals that know
+ * them can jump between prompts and select a turn's output; a host embedding the chat can tell
+ * that it is back at its prompt and takes input. Zero-width and ignored by terminals that do
+ * not know them; written only when stdin and stdout are both a terminal and `TERM` is not
+ * `dumb`. Advisory: model output reaches the terminal unfiltered and can carry them too.
+ */
+function promptMark(kind: "A" | "B" | "C" | "D", exitCode?: number): string {
+ return `\x1b]133;${kind}${exitCode === undefined ? "" : `;${exitCode}`}\x07`;
+}
+
export function registerChatCommand(program: Command, t: Messages): void {
program
.command("chat")
@@ -236,6 +249,12 @@ export function registerChatCommand(program: Command, t: Messages): void {
let state: ChatState = "idle";
let closed = false;
+ // The marks are output: a TTY stdin is not enough when stdout is redirected to a file or
+ // a pipe, or the terminal is a dumb one.
+ const marksOn = isTTY && out.isTTY === true && process.env.TERM !== "dumb";
+ const mark = (kind: "A" | "B" | "C" | "D", exitCode?: number): void => {
+ if (marksOn) out.write(promptMark(kind, exitCode));
+ };
/** Set while a turn runs; SIGINT posts /abort through it exactly once per turn. */
let abortTurn: (() => void) | null = null;
let pendingLine: ((line: string | null) => void) | null = null;
@@ -428,8 +447,10 @@ export function registerChatCommand(program: Command, t: Messages): void {
rli.line = "";
rli.cursor = 0;
out.write("\n");
+ mark("A");
rl.setPrompt(MAIN_PROMPT);
rl.prompt();
+ mark("B");
});
// Interactive approval prompt: reuses the persistent readline; the tool call is
@@ -596,6 +617,8 @@ export function registerChatCommand(program: Command, t: Messages): void {
}
state = "running";
+ mark("C");
+ let failed = false;
try {
if (text === "/compact") {
// Proactive context compaction: POST /compact and render its paired events
@@ -668,9 +691,11 @@ export function registerChatCommand(program: Command, t: Messages): void {
);
}
} catch (err) {
+ failed = true;
out.write(`\n${t.error(err instanceof Error ? err.message : String(err))}\n`);
} finally {
state = "idle";
+ mark("D", failed ? 1 : 0);
}
}
} finally {
diff --git a/packages/cli/test/chat-prompt-marks.test.ts b/packages/cli/test/chat-prompt-marks.test.ts
new file mode 100644
index 00000000..dd53731a
--- /dev/null
+++ b/packages/cli/test/chat-prompt-marks.test.ts
@@ -0,0 +1,126 @@
+/**
+ * chat: semantic prompt marks (OSC 133) on a terminal. Drives the real REPL over a fake
+ * terminal (stdin in raw mode, stdout claiming a TTY) against the in-process fake server and
+ * reads the marks out of what it printed.
+ *
+ * - Given a chat on a terminal, when it is ready for input, its main prompt is enclosed by
+ * `A` (prompt start) and `B` (input start).
+ * - Given a submitted prompt, its turn is enclosed by `C` and `D;0`, and the next prompt is
+ * marked again.
+ * - Given a turn that ends in an error, it ends with `D;1`.
+ * - Given stdin that is a pipe, stdout redirected to a file or a pipe, or `TERM=dumb`, nothing
+ * is marked and the chat still runs the prompt.
+ */
+import { PassThrough } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import { registerChatCommand } from "../src/commands/chat.js";
+import { getMessages } from "../src/i18n.js";
+import { FakeServer } from "./fake-server.js";
+
+const ENTER = "\r";
+const OSC_133 = /\x1b\]133;([A-D](?:;\d+)?)\x07/g;
+
+let server: FakeServer;
+let uninstall: () => void;
+
+beforeEach(() => {
+ server = new FakeServer();
+ uninstall = server.install();
+ vi.stubEnv("TERM", "xterm-256color");
+});
+afterEach(() => {
+ uninstall();
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+});
+
+/** Which ends of the chat are a terminal; the other is a pipe (stdin) or a redirect (stdout). */
+interface Ends {
+ stdin: boolean;
+ stdout: boolean;
+}
+const TERMINAL: Ends = { stdin: true, stdout: true };
+
+/**
+ * Runs `penguin chat` with the given input lines and returns what it printed. A terminal
+ * stdin runs in raw mode and gets keys; a piped one gets lines. Each line goes in once the
+ * REPL has printed its next `> ` prompt.
+ */
+async function runChat(lines: string[], ends: Ends): Promise<string> {
+ const stdin = new PassThrough() as PassThrough & {
+ isTTY?: boolean;
+ setRawMode?: (mode: boolean) => unknown;
+ };
+ if (ends.stdin) {
+ stdin.isTTY = true;
+ stdin.setRawMode = () => stdin;
+ }
+ const realStdin = process.stdin;
+ const stdoutTty = Object.getOwnPropertyDescriptor(process.stdout, "isTTY");
+ Object.defineProperty(process, "stdin", { value: stdin, configurable: true });
+ Object.defineProperty(process.stdout, "isTTY", { value: ends.stdout, configurable: true });
+ let printed = "";
+ let ready = 0;
+ const waiters: Array<() => void> = [];
+ vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ const text = String(chunk);
+ printed += text;
+ if (text === "> ") ready++;
+ for (const wake of waiters.splice(0)) wake();
+ return true;
+ });
+ const readyFor = (n: number): Promise<void> =>
+ new Promise((resolve) => {
+ const check = (): void => (ready >= n ? resolve() : void waiters.push(check));
+ check();
+ });
+ try {
+ const program = new Command();
+ program.exitOverride();
+ registerChatCommand(program, getMessages("en"));
+ const done = program.parseAsync(["node", "penguin", "chat"]);
+ for (let i = 0; i < lines.length; i++) {
+ await Promise.race([readyFor(i + 1), done]);
+ stdin.write(`${lines[i]}${ends.stdin ? ENTER : "\n"}`);
+ }
+ await done;
+ return printed;
+ } finally {
+ Object.defineProperty(process, "stdin", { value: realStdin, configurable: true });
+ if (stdoutTty) Object.defineProperty(process.stdout, "isTTY", stdoutTty);
+ else delete (process.stdout as { isTTY?: boolean }).isTTY;
+ }
+}
+
+const marks = (printed: string): string[] => [...printed.matchAll(OSC_133)].map((m) => m[1]!);
+
+describe("chat: semantic prompt marks on a terminal", () => {
+ it("encloses the main prompt in A and B, and each turn in C and D;0", async () => {
+ const printed = await runChat(["hello", "/exit"], TERMINAL);
+ expect(marks(printed)).toEqual(["A", "B", "C", "D;0", "A", "B"]);
+ // A precedes the prompt itself; B follows it.
+ expect(printed).toMatch(/\x1b\]133;A\x07[^\x07]*> [^\x07]*\x1b\]133;B\x07/);
+ expect([...server.sessions.values()][0]!.tasks).toHaveLength(1);
+ });
+
+ it("ends a turn that failed with D;1", async () => {
+ server.switchModel = { refuse: "something_new" };
+ const printed = await runChat(
+ ["/switch-model openrouter anthropic/claude-opus-5", "/exit"],
+ TERMINAL,
+ );
+ expect(marks(printed)).toEqual(["A", "B", "C", "D;1", "A", "B"]);
+ });
+
+ it.each([
+ { when: "stdin is a pipe", ends: { stdin: false, stdout: true }, term: "xterm-256color" },
+ { when: "stdout is redirected", ends: { stdin: true, stdout: false }, term: "xterm-256color" },
+ { when: "the terminal is dumb", ends: TERMINAL, term: "dumb" },
+ ])("marks nothing when $when", async ({ ends, term }) => {
+ vi.stubEnv("TERM", term);
+ const printed = await runChat(["hello", "/exit"], ends);
+ expect(marks(printed)).toEqual([]);
+ expect([...server.sessions.values()][0]!.tasks).toHaveLength(1);
+ });
+});
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index fcb5f8ab..e58cc6b4 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -91,6 +91,8 @@ penguin chat [options]
With `--resume`, the original Session fixes the Workspace and model, so `--workspace`, `--model-id` and `--provider` cannot override them; to change the model, use `/switch-model` inside the resumed chat. `--thinking` is still accepted: it re-pins the existing Session from its next LLM request. Changing the level mid-context costs the provider's cached context, so compact first. On exit, if the Session has any history, the REPL prints a copy-pastable `penguin chat --resume <sessionId>` command.
+On a terminal, the REPL marks its prompts with OSC 133 semantic prompt sequences, the ones shells emit for shell integration: `A` and `B` around the `> ` prompt, `C` when a submitted prompt's turn starts, and `D;0` when it ends (`D;1` after an error). A terminal that supports them can jump between prompts and select one turn's output, and a program that runs the chat in a terminal of its own can tell when it is back at its prompt. Other terminals ignore them, and none are written unless both stdin and stdout are a terminal and `TERM` is not `dumb`. The marks are advisory: model output reaches the terminal unfiltered and can contain the same sequences.
+
### In-REPL commands
| Input | Behavior |
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index d75b28b1..2557c082 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -91,6 +91,8 @@ penguin chat [options]
使用 `--resume` 时,原 Session 已固定 Workspace 和模型,`--workspace`、`--model-id` 和 `--provider` 无法覆盖它们;要换模型,在恢复后的对话里使用 `/switch-model`。`--thinking` 仍然有效:它重新固定现有 Session,从下一次 LLM 请求起生效。在上下文中途更改等级会使供应商的上下文缓存失效,所以请先压缩。退出时,如果 Session 已有历史,REPL 会打印一条可直接复制运行的 `penguin chat --resume <sessionId>` 命令。
+在终端里,REPL 会用 OSC 133 语义提示符序列标记它的提示符,也就是 shell 为终端集成输出的那组序列:`> ` 提示符前后分别是 `A` 和 `B`,提交的 Prompt 开始一轮时是 `C`,该轮结束时是 `D;0`(出错结束时是 `D;1`)。支持这些序列的终端可以在提示符之间跳转、选中某一轮的输出;在自己的终端里运行对话的程序也能据此判断对话已回到提示符。其他终端会忽略它们;只有 stdin 与 stdout 都是终端且 `TERM` 不是 `dumb` 时才会输出。这些标记仅供参考:模型输出未经过滤就写到终端,同样可能含有这些序列。
+
### REPL 内命令
| 输入 | 行为 |