A local-first multi-agent app development platform, built on PenguinHarness
feat(cli): add /clear to start a fresh session in chat (#269)
Yaowei Zheng4c1180c48312
diff --git a/README.md b/README.mdindex 9657a372..78abe648 100644--- a/README.md+++ b/README.md@@ -229,7 +229,7 @@ The same engine, scriptable — made to be driven by agents (and agents building```bashpenguin config model add --provider deepseek --model-id deepseek-v4-flash --api-key sk-... --set-defaultpenguin run -m "Create hello.txt containing Hello, Penguin" # one-shot task-penguin chat # interactive REPL (/compact, /exit, Ctrl-C to interrupt)+penguin chat # interactive REPL (/compact, /clear, /exit, Ctrl-C to interrupt)penguin server # headless service (same API the Web App uses)```diff --git a/README.zh.md b/README.zh.mdindex db344611..c6622951 100644--- a/README.zh.md+++ b/README.zh.md@@ -229,7 +229,7 @@ cd penguin-install```bashpenguin config model add --provider deepseek --model-id deepseek-v4-flash --api-key sk-... --set-defaultpenguin run -m "Create hello.txt containing Hello, Penguin" # 单次任务-penguin chat # 交互式 REPL(/compact、/exit、Ctrl-C 中断)+penguin chat # 交互式 REPL(/compact、/clear、/exit、Ctrl-C 中断)penguin server # 无界面服务(与 Web 应用同一套 API)```diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 3a63bb85..ad0eb670 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -13,7 +13,7 @@ penguin server # same service, headlesspenguin config model add --model-id deepseek-v4-pro --api-key sk-... --set-defaultpenguin run -m "Create hello.txt containing Hello, Penguin" # one Task, then exit-penguin chat # REPL: /compact, /exit, Ctrl-C interrupts+penguin chat # REPL: /compact, /clear, /exit, Ctrl-C interruptspenguin chat --resume # resume the latest session```diff --git a/packages/cli/src/commands/chat.ts b/packages/cli/src/commands/chat.tsindex 54048ea0..d0b48b62 100644--- a/packages/cli/src/commands/chat.ts+++ b/packages/cli/src/commands/chat.ts@@ -6,7 +6,9 @@** Each line of input starts one conversation turn; `/goal[:<budget>] <objective>` runs* goal mode (looping until the goal reaches a terminal state);- * `/compact` proactively compacts the context (reason=manual); `/exit` or `/quit` exits.+ * `/compact` proactively compacts the context (reason=manual); `/clear` starts a fresh+ * blank Session in place (the old Session's Trace stays on disk, resumable); `/exit` or+ * `/quit` exits.* Uses the current directory when no Workspace is specified. A model reference is always an* explicit `(provider, model_id)` pair, so `--model-id` and `--provider` must be given* together; giving neither uses the Project's default model.@@ -28,7 +30,12 @@import { createInterface, type Interface } from "node:readline";import type { Command } from "commander";import { createAgent, userText, VERSION } from "@prismshadow/penguin-core";-import type { ApprovalDecision, OmniMessage, ToolCallPayload } from "@prismshadow/penguin-core";+import type {+ ApprovalDecision,+ OmniMessage,+ Session,+ ToolCallPayload,+} from "@prismshadow/penguin-core";import { StreamRenderer, dim, renderHistory } from "../render.js";import { runTask } from "../task-loop.js";import { parseGoalCommand } from "../goal-command.js";@@ -90,8 +97,9 @@ export function registerChatCommand(program: Command, t: Messages): void {// --resume: resumes an existing Session. Workspace and// Model follow the original Session and cannot be overridden; when omitted, resumes- // the current Agent's most recent Session.- let session;+ // the current Agent's most recent Session. Annotated (not inferred) because /clear+ // reassigns it mid-REPL, after the closures below have captured it.+ let session: Session;if (opts.resume !== undefined) {if (opts.workspace || opts.modelId || opts.provider) {out.write(`${t.error(t.resumeNoOverride())}\n`);@@ -114,7 +122,7 @@ export function registerChatCommand(program: Command, t: Messages): void {});}- const renderer = new StreamRenderer(out, t);+ let renderer = new StreamRenderer(out, t);// Tool schemas (each tool's call-line preview path) arrive on the stream as the// first run's tool_list_ready event — the toolset isn't known before then (MCP// servers connect lazily); the renderer registers them as they flow by.@@ -345,6 +353,14 @@ export function registerChatCommand(program: Command, t: Messages): void {// command example on exit.let resumable = opts.resume !== undefined;+ // The copy-pastable resume command for one Session: includes this run's Project /+ // Agent options so it works as-is. Printed on exit, and by /clear for the Session+ // it retires.+ const resumeCommand = (sessionId: string): string =>+ `penguin chat --resume ${sessionId}` ++ (opts.projectId ? ` --project-id ${opts.projectId}` : "") ++ (opts.agentId ? ` --agent-id ${opts.agentId}` : "");+try {for (;;) {const line = await askLine();@@ -378,6 +394,26 @@ export function registerChatCommand(program: Command, t: Messages): void {renderer.endCompact(Date.now() - startedAt);}if (!sawMessage) out.write(`${t.compactNothing()}\n`);+ } else if (text === "/clear") {+ // Start over with a brand-new blank Session on the same Workspace and model+ // (pinned from the current Session, so a --resume'd chat clears to the same+ // settings). The old Session is only disposed — its persisted Trace stays on+ // disk and resumable — so its resume command is printed first (same shape as+ // the exit hint). The new Session is created before the old one is dropped:+ // a failure keeps the current conversation intact. A fresh renderer starts+ // the Session-cumulative stats from zero; the new Session has no Trace+ // record yet, so `resumable` resets until its first Task / compact.+ const next = await agent.createSession({+ workspaceDir: session.workspaceDir,+ modelId: session.modelId,+ provider: session.provider,+ });+ if (resumable) out.write(`${dim(t.resumeHint(resumeCommand(session.sessionId)))}\n`);+ session.dispose();+ session = next;+ renderer = new StreamRenderer(out, t);+ resumable = false;+ out.write(`${t.clearDone()}\n`);} else if (text === "/goal" || text.startsWith("/goal:") || text.startsWith("/goal ")) {// Goal mode: one command drives the whole loop; Ctrl-C aborts the entire// goal (a single signal spans every round), never just the current round.@@ -419,15 +455,10 @@ export function registerChatCommand(program: Command, t: Messages): void {cleanup();session.dispose(); // tear down managed long-running command sessions to avoid leaking background processesprocess.removeListener("exit", cleanup);- // On exit, print a dimmed resume command example: includes this- // session's Project / Agent options so the command can be copy-pasted directly;- // skipped when the Session has no Trace record yet (nothing to resume).+ // On exit, print a dimmed resume command example; skipped when the Session has+ // no Trace record yet (nothing to resume).if (resumable) {- const command =- `penguin chat --resume ${session.sessionId}` +- (opts.projectId ? ` --project-id ${opts.projectId}` : "") +- (opts.agentId ? ` --agent-id ${opts.agentId}` : "");- out.write(`${dim(t.resumeHint(command))}\n`);+ out.write(`${dim(t.resumeHint(resumeCommand(session.sessionId)))}\n`);}}});diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex 15a160c0..e2177b93 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -193,6 +193,8 @@ export interface Messages {): string;/** Prompt shown when `/compact` has nothing to compact (session just started / two consecutive compactions). */compactNothing(): string;+ /** Feedback after `/clear`: a fresh blank Session is now active; the old Session stays on disk (its resume command is printed right above when it has a Trace record). */+ clearDone(): string;/** Dim line announcing one goal round (printed before the round runs). */goalRound(round: number): string;/** Dim summary line after a goal ends: how it ended, rounds run, tokens consumed. */@@ -415,7 +417,7 @@ const en: Messages = {header: headerEn,chatHints: () =>- "Type a message to start a conversation; end a line with \\; typing while a task runs steers the agent; /goal runs a goal to completion; /compact to compact the context; /exit to quit; and Ctrl-C interrupts the current conversation.",+ "Type a message to start a conversation; end a line with \\; typing while a task runs steers the agent; /goal runs a goal to completion; /compact to compact the context; /clear to start a fresh session; /exit to quit; and Ctrl-C interrupts the current conversation.",confirmExit: () => "Exit penguin? [y/N] ",taskInterrupted: () => "[current conversation interrupted]",steerQueued: (text) => `» steering queued (delivered with the next turn): ${text}`,@@ -452,6 +454,7 @@ const en: Messages = {: `[compaction] ${status}${errorMessage !== undefined ? ` (${errorMessage})` : ""}; keeping the current context`) +(tokens ? ` · tokens ${tokens.total} (${tokens.delta})` : ""),compactNothing: () => "[compaction] nothing to compact yet",+ clearDone: () => "[clear] started a fresh session (the previous one is kept and resumable)",goalRound: (round) => `[goal] round ${round}`,goalFinished: (outcome, rounds, tokens) => {const label = {@@ -648,7 +651,7 @@ const zh: Messages = {header: headerZh,chatHints: () =>- "输入消息发起对话;行尾 \\ 续行;运行中输入可插话引导;/goal 以目标模式运行至完成;/compact 压缩上下文;/exit 退出;Ctrl-C 中断对话。",+ "输入消息发起对话;行尾 \\ 续行;运行中输入可插话引导;/goal 以目标模式运行至完成;/compact 压缩上下文;/clear 开启全新会话;/exit 退出;Ctrl-C 中断对话。",confirmExit: () => "确认退出 penguin?[y/N] ",taskInterrupted: () => "[已中断当前对话]",steerQueued: (text) => `» 插话已排队(随下一轮送达):${text}`,@@ -685,6 +688,7 @@ const zh: Messages = {: `[压缩] ${status === "aborted" ? "已中断" : `失败${errorMessage !== undefined ? `(${errorMessage})` : ""}`},保留当前上下文`) +(tokens ? ` · tokens ${tokens.total} (${tokens.delta})` : ""),compactNothing: () => "[压缩] 当前上下文为空,无需压缩",+ clearDone: () => "[清空] 已开启全新 Session(原会话仍保留,可恢复)",goalRound: (round) => `[目标] 第 ${round} 轮`,goalFinished: (outcome, rounds, tokens) => {const label = {diff --git a/packages/cli/test/chat-clear.test.ts b/packages/cli/test/chat-clear.test.tsnew file mode 100644index 00000000..0f30fb68--- /dev/null+++ b/packages/cli/test/chat-clear.test.ts@@ -0,0 +1,167 @@+/**+ * chat `/clear`: starts a brand-new blank Session in place. The old Session is only+ * disposed (runtime teardown — Session/Agent expose no deletion API, and /clear must not+ * grow one), its resume command is printed so it stays reachable via `--resume`, the+ * replacement is created with the same Workspace and model, and subsequent input runs on+ * the new Session. Drives the real REPL over a fake stdin with `createAgent` mocked; each+ * line is fed only after the REPL prints its input prompt, so no line lands mid-run.+ */+import { PassThrough } from "node:stream";+import { afterEach, describe, expect, it, vi } from "vitest";+import { Command } from "commander";+import { createAgent } from "@prismshadow/penguin-core";+import { registerChatCommand } from "../src/commands/chat.js";+import { getMessages } from "../src/i18n.js";++vi.mock("@prismshadow/penguin-core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@prismshadow/penguin-core")>();+ return { ...actual, createAgent: vi.fn() };+});++interface FakeSession {+ sessionId: string;+ provider: string;+ modelId: string;+ workspaceDir: string;+ /** User text of each run() prompt: proves which Session an input line was routed to. */+ runs: string[];+ disposeCalls: number;+ run(prompt: unknown[], opts: unknown): AsyncGenerator<never>;+ compact(opts: unknown): AsyncGenerator<never>;+ steer(): boolean;+ toolPermission(): undefined;+ dispose(): void;+}++/** A Session double covering exactly what the chat REPL touches; run() yields nothing (a task with no output or usage). */+function makeFakeSession(+ sessionId: string,+ opts: { workspaceDir?: string; modelId?: string; provider?: string },+): FakeSession {+ const session: FakeSession = {+ sessionId,+ provider: opts.provider ?? "prov-default",+ modelId: opts.modelId ?? "model-default",+ workspaceDir: opts.workspaceDir ?? "/ws",+ runs: [],+ disposeCalls: 0,+ async *run(prompt) {+ const text = (prompt[0] as { payload?: { text?: string } }).payload?.text ?? "";+ session.runs.push(text);+ },+ async *compact() {},+ steer: () => false,+ toolPermission: () => undefined,+ dispose() {+ session.disposeCalls++;+ },+ };+ return session;+}++/** An Agent double whose createSession records every Session it hands out. */+function makeFakeAgent() {+ const sessions: FakeSession[] = [];+ const createSession = vi.fn(+ async (opts: { workspaceDir?: string; modelId?: string; provider?: string } = {}) => {+ const session = makeFakeSession(`sess-${sessions.length + 1}`, opts);+ sessions.push(session);+ return session;+ },+ );+ const agent = {+ state: { agentId: "test-agent" },+ createSession,+ resumeSession: vi.fn(),+ latestSessionId: vi.fn(async () => null),+ };+ vi.mocked(createAgent).mockResolvedValue(+ agent as unknown as Awaited<ReturnType<typeof createAgent>>,+ );+ return { agent, sessions };+}++/**+ * Runs `penguin chat` end to end over a PassThrough stdin, capturing stdout. Each input+ * line is written only once the REPL has printed the matching `> ` prompt (the non-TTY+ * REPL writes the prompt when — and only when — it is ready for the next line).+ */+async function driveChat(lines: string[]): Promise<string> {+ const stdin = new PassThrough();+ const realStdin = process.stdin;+ Object.defineProperty(process, "stdin", { value: stdin, configurable: true });+ const chunks: string[] = [];+ let promptCount = 0;+ const waiters: Array<() => void> = [];+ const outSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {+ const text = String(chunk);+ chunks.push(text);+ if (text === "> ") promptCount++;+ for (const wake of waiters.splice(0)) wake();+ return true;+ });+ const waitForPrompt = (n: number): Promise<void> =>+ new Promise((resolve) => {+ const check = (): void => {+ if (promptCount >= n) resolve();+ else 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++) {+ // Racing against `done` keeps a REPL that errors out early from hanging the test.+ await Promise.race([waitForPrompt(i + 1), done]);+ stdin.write(`${lines[i]}\n`);+ }+ await done;+ return chunks.join("");+ } finally {+ outSpy.mockRestore();+ Object.defineProperty(process, "stdin", { value: realStdin, configurable: true });+ }+}++describe("chat /clear (fresh Session in place)", () => {+ afterEach(() => {+ vi.clearAllMocks();+ });++ it("swaps in a new Session with the same Workspace/model; the old one is disposed (not deleted) and stays resumable; later input runs on the new Session", async () => {+ const { agent, sessions } = makeFakeAgent();+ const out = await driveChat(["hello", "/clear", "second", "/exit"]);++ // A second Session was created, pinning the first one's Workspace and model reference.+ expect(agent.createSession).toHaveBeenCalledTimes(2);+ expect(agent.createSession.mock.calls[1]![0]).toEqual({+ workspaceDir: sessions[0]!.workspaceDir,+ modelId: sessions[0]!.modelId,+ provider: sessions[0]!.provider,+ });+ // Input routing: "hello" ran on the old Session, "second" on the new one.+ expect(sessions[0]!.runs).toEqual(["hello"]);+ expect(sessions[1]!.runs).toEqual(["second"]);+ // The old Session got runtime teardown only (dispose once, never resumed/recreated+ // here), and /clear advertised its resume command before switching over.+ expect(sessions[0]!.disposeCalls).toBe(1);+ expect(agent.resumeSession).not.toHaveBeenCalled();+ expect(out).toContain("penguin chat --resume sess-1");+ expect(out).toContain(getMessages("en").clearDone());+ // The exit hint names the new Session (it ran "second", so it is resumable).+ expect(out).toContain("penguin chat --resume sess-2");+ expect(sessions[1]!.disposeCalls).toBe(1); // disposed by the exit path+ });++ it("/clear before any Task prints no resume hint (neither Session has a Trace record yet)", async () => {+ const { agent } = makeFakeAgent();+ const out = await driveChat(["/clear", "/exit"]);++ expect(agent.createSession).toHaveBeenCalledTimes(2);+ expect(out).toContain(getMessages("en").clearDone());+ expect(out).not.toContain("--resume");+ });+});diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.mdindex 8b1c045f..51149904 100644--- a/packages/docs/content/cli.en.md+++ b/packages/docs/content/cli.en.md@@ -44,6 +44,7 @@ In-REPL commands:| --- | --- || any text while a Task runs | Mid-run steering: queued and delivered to the model between turns as a `[user_steering]` user message (a `»` acknowledgment echoes the text); rendering is held while you type so streamed output doesn't scribble over the line. If the Task finishes first, the line is sent as the next normal prompt || `/compact` | Proactively compact the current context |+| `/clear` | Start a fresh blank Session in place; the old Session stays on disk and can be resumed with `--resume` || `/exit`, `/quit` | Quit |Ctrl-C is state-dependent:diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.mdindex 0d3ac32f..243ace06 100644--- a/packages/docs/content/cli.zh.md+++ b/packages/docs/content/cli.zh.md@@ -44,6 +44,7 @@ REPL 内命令:| --- | --- || 运行中输入任意文字 | 运行中插话:排队后以 `[user_steering]` 用户消息随下一轮送达模型(`»` 确认行会回显文字);输入期间渲染暂挂,流式输出不会打断正在输入的行。若 Task 恰好已结束,该行作为下一条普通消息发送 || `/compact` | 主动压缩当前上下文 |+| `/clear` | 原地开启全新空白 Session;原会话保留在磁盘上,仍可用 `--resume` 恢复 || `/exit`、`/quit` | 退出 |Ctrl-C 的行为依状态而定:diff --git a/packages/docs/content/quickstart.en.md b/packages/docs/content/quickstart.en.mdindex 76045e49..f2bfe7c5 100644--- a/packages/docs/content/quickstart.en.md+++ b/packages/docs/content/quickstart.en.md@@ -47,7 +47,7 @@ penguin chat```- Each input line starts a Task.-- `/compact` compacts the context; `/exit` or `/quit` quits; Ctrl-C interrupts the running Task.+- `/compact` compacts the context; `/clear` starts a fresh Session (the old one stays resumable); `/exit` or `/quit` quits; Ctrl-C interrupts the running Task.- On exit it prints a `penguin chat --resume <sessionId>` hint for resuming this Session; `--resume` without an id resumes the Agent's latest Session.## SDK hellodiff --git a/packages/docs/content/quickstart.zh.md b/packages/docs/content/quickstart.zh.mdindex 83c08e64..f14fbbca 100644--- a/packages/docs/content/quickstart.zh.md+++ b/packages/docs/content/quickstart.zh.md@@ -47,7 +47,7 @@ penguin chat```- 每输入一行即发起一个 Task。-- `/compact` 压缩上下文;`/exit` 或 `/quit` 退出;Ctrl-C 中断正在运行的 Task。+- `/compact` 压缩上下文;`/clear` 开启全新 Session(原会话仍可恢复);`/exit` 或 `/quit` 退出;Ctrl-C 中断正在运行的 Task。- 退出时会打印 `penguin chat --resume <sessionId>` 提示,用于恢复本次 Session;`--resume` 不带 id 时恢复该 Agent 最近的 Session。## SDK 示例