Skip to content

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

feat(cli): runtime thinking-level control and collapsed tool output (#322)

Yaowei Zheng691fa87da3b1
diff --git a/changelog/unreleased/2026-08-18-cli-thinking-and-output-collapse.md b/changelog/unreleased/2026-08-18-cli-thinking-and-output-collapse.md
new file mode 100644
index 00000000..28b6ec13
--- /dev/null
+++ b/changelog/unreleased/2026-08-18-cli-thinking-and-output-collapse.md
@@ -0,0 +1,24 @@
+# CLI: runtime thinking-level control and collapsed tool output
+
+- **Date:** 2026-08-18
+- **Type:** feature
+- **Scope:** `cli`, `docs`
+- **PR:** [#322](https://github.com/Prism-Shadow/penguin-harness/pull/322)
+- **Issue:** [#305](https://github.com/Prism-Shadow/penguin-harness/issues/305)
+
+[中文版](2026-08-18-cli-thinking-and-output-collapse.zh.md)
+
+CLI mode gained two runtime controls that previously needed an Agent config edit or nothing at all: a thinking level settable per invocation and changeable mid-chat, and head/tail collapsing of long tool output in the chat REPL with a `/verbose` escape hatch. The CLI reference documents both.
+
+## Thinking level
+
+- `penguin run --thinking <low|medium|high|xhigh>` and `penguin chat --thinking <level>` pin the Session's thinking level at creation, so spawned subagent sessions inherit it. Omitted, the configured chain applies: the Agent's `model.thinking_level`, else the Project's `default_chat.thinking_level`, else `medium`.
+- In the chat REPL, `/thinking` reports the level the next turn will run at — naming whether it is this Session's default or an active per-turn override, and which default that override replaces — and `/thinking <level>` overrides subsequent turns. The override is a per-turn `RunOptions.thinkingLevel`, mirroring the web active-session picker, and is never written back to the Agent config; only the Session's own level is inherited by spawned subagent sessions (a `run_subagent` call can still name its own `thinking_level`). Under `--resume` the flag becomes that initial override instead, since a resumed Session's construction values are fixed.
+- The selectable tiers reuse core's `DEFAULT_CHAT_THINKING_LEVELS` (no `none`, matching the web picker); a stored legacy `none` still displays as-is.
+
+## Collapsed tool output
+
+- The chat REPL collapses long tool output by default: the first 4 lines stream live, then an elision marker (`… (+N lines, /verbose for full output)`) and the last 4 lines print when the stream ends. Outputs of up to 9 lines render whole, and the marker never hides fewer than 2 lines. Resumed history (`--resume`) is collapsed the same way, down to reporting the same hidden count as the live stream for the same output.
+- Collapsing is display-only: the model, the Trace, and the Web App receive the complete text either way.
+- `/verbose` toggles full output mid-chat, and `penguin chat --verbose` starts a session with collapsing already off. `penguin run` never collapses — its output feeds pipes and nested CLIs.
+- A tool-output stream cut off by an interrupt still settles its held-back tail at task end, so nothing silently vanishes from the screen.
diff --git a/changelog/unreleased/2026-08-18-cli-thinking-and-output-collapse.zh.md b/changelog/unreleased/2026-08-18-cli-thinking-and-output-collapse.zh.md
new file mode 100644
index 00000000..daa5a212
--- /dev/null
+++ b/changelog/unreleased/2026-08-18-cli-thinking-and-output-collapse.zh.md
@@ -0,0 +1,24 @@
+# CLI:运行期调整思考等级与折叠工具输出
+
+- **Date:** 2026-08-18
+- **Type:** feature
+- **Scope:** `cli`, `docs`
+- **PR:** [#322](https://github.com/Prism-Shadow/penguin-harness/pull/322)
+- **Issue:** [#305](https://github.com/Prism-Shadow/penguin-harness/issues/305)
+
+[English](2026-08-18-cli-thinking-and-output-collapse.md)
+
+CLI 模式新增两项运行期控制,此前它们要么得去改 Agent 配置、要么根本没有:思考等级可在每次调用时指定,也可在对话中途改动;chat REPL 对过长的工具输出做首尾折叠,并留下 `/verbose` 这个出口。CLI 参考文档同步收录了两者。
+
+## 思考等级
+
+- `penguin run --thinking <low|medium|high|xhigh>` 与 `penguin chat --thinking <level>` 在 Session 创建时钉定其思考等级,派生的子会话随之继承。省略时沿用原有的配置链:Agent 的 `model.thinking_level`,其次 Project 的 `default_chat.thinking_level`,最后 `medium`。
+- 在 chat REPL 中,`/thinking` 报出下一轮将使用的等级——并指明它是本 Session 的缺省值还是生效中的逐轮覆盖值,后者同时给出被覆盖的那个缺省值——`/thinking <level>` 则覆盖后续轮次。该覆盖是逐轮的 `RunOptions.thinkingLevel`,与 Web 端活动会话选择器保持一致,永不写回 Agent 配置;只有 Session 自身的等级才会被派生的子会话继承(`run_subagent` 调用仍可自行指定 `thinking_level`)。`--resume` 之下这个 flag 转而作为初始覆盖值生效,因为已恢复 Session 的构造参数是固定的。
+- 可选等级复用 core 的 `DEFAULT_CHAT_THINKING_LEVELS`(不含 `none`,与 Web 选择器一致);历史遗留的 `none` 仍按原样显示。
+
+## 工具输出折叠
+
+- chat REPL 缺省折叠过长的工具输出:前 4 行照常流式打印,流结束时打印省略标记(`……(另有 N 行,/verbose 显示完整输出)`)与最后 4 行。不超过 9 行的输出完整呈现,标记也绝不会为了藏起不足 2 行而出现。`--resume` 恢复的历史按同一规则折叠,同一份输出报出的隐藏行数与实时流完全相同。
+- 折叠只作用于显示层:无论折不折叠,模型、Trace 与 Web App 拿到的都是完整文本。
+- `/verbose` 可在对话中途切换到完整输出,`penguin chat --verbose` 则在启动时就把折叠关掉。`penguin run` 从不折叠——它的输出要供管道和嵌套 CLI 消费。
+- 被中断切断的工具输出流,仍会在任务结束时把扣住的尾部补齐落屏,不会有内容悄无声息地从屏幕上消失。
diff --git a/packages/cli/src/commands/chat.ts b/packages/cli/src/commands/chat.ts
index d0b48b62..93b5a08f 100644
--- a/packages/cli/src/commands/chat.ts
+++ b/packages/cli/src/commands/chat.ts
@@ -3,11 +3,16 @@
*
* penguin chat [--model-id <id> --provider <group>] [--project-id <id>] [--agent-id <id>]
* [--workspace <path>] [--approve <allow-all|deny-all|read-only|always-ask>]
+ * [--thinking <low|medium|high|xhigh>] [--verbose]
*
* 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); `/clear` starts a fresh
- * blank Session in place (the old Session's Trace stays on disk, resumable); `/exit` or
+ * blank Session in place (the old Session's Trace stays on disk, resumable);
+ * `/thinking [<level>]` shows or overrides the thinking level for subsequent turns
+ * (see thinking-command.ts for the flag/command semantics); `/verbose` toggles
+ * tool-output collapsing (long outputs render head/tail + an elision marker by default —
+ * display only, the Trace keeps the full text; see output-collapse.ts); `/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
@@ -32,6 +37,7 @@ import type { Command } from "commander";
import { createAgent, userText, VERSION } from "@prismshadow/penguin-core";
import type {
ApprovalDecision,
+ DefaultChatThinkingLevel,
OmniMessage,
Session,
ToolCallPayload,
@@ -39,6 +45,11 @@ import type {
import { StreamRenderer, dim, renderHistory } from "../render.js";
import { runTask } from "../task-loop.js";
import { parseGoalCommand } from "../goal-command.js";
+import {
+ configuredThinkingLevel,
+ parseThinkingCommand,
+ resolveThinkingLevel,
+} from "../thinking-command.js";
import { parseApprovalAnswer, resolveApprovalMode } from "../approval.js";
import { LineComposer, PasteFilter } from "../input.js";
import type { Messages } from "../i18n.js";
@@ -74,6 +85,8 @@ export function registerChatCommand(program: Command, t: Messages): void {
.option("--agent-id <id>", t.common.agentId)
.option("--workspace <path>", t.common.workspace)
.option("--approve <mode>", t.common.approve)
+ .option("--thinking <level>", t.common.thinking)
+ .option("--verbose", t.chat.verbose)
.option("--resume [sessionId]", t.chat.resume)
.action(async (opts) => {
// The model reference is a pair: commander can only require each option on its own,
@@ -88,6 +101,10 @@ export function registerChatCommand(program: Command, t: Messages): void {
return;
}
const mode = resolveApprovalMode(opts.approve, t);
+ const flagThinking = resolveThinkingLevel(opts.thinking, t);
+ // Tool-output collapsing (display only; the Trace keeps everything): on by default,
+ // `--verbose` starts with full output, `/verbose` toggles it mid-chat.
+ let verbose = opts.verbose === true;
const out = process.stdout;
const agent = await createAgent({
@@ -119,10 +136,23 @@ export function registerChatCommand(program: Command, t: Messages): void {
workspaceDir: opts.workspace ?? process.cwd(),
...(opts.modelId ? { modelId: opts.modelId } : {}),
...(opts.provider ? { provider: opts.provider } : {}),
+ ...(flagThinking ? { thinkingLevel: flagThinking } : {}),
});
}
- let renderer = new StreamRenderer(out, t);
+ // Thinking level shown/changed by `/thinking` (a per-turn run parameter, so it CAN
+ // change mid-session — unlike workspace/model):
+ // - `--thinking` on a new chat pins the Session default at creation (above), so
+ // subagent sessions follow it; under `--resume` the Session already exists and the
+ // flag becomes the initial per-turn override instead.
+ // - `/thinking <level>` sets the override; unset turns omit the parameter so core's
+ // construction-time default applies (`sessionThinkingDefault` mirrors it for display).
+ let thinkingOverride: DefaultChatThinkingLevel | undefined =
+ opts.resume !== undefined ? flagThinking : undefined;
+ const sessionThinkingDefault = (): string =>
+ opts.resume === undefined && flagThinking ? flagThinking : configuredThinkingLevel(agent);
+
+ let renderer = new StreamRenderer(out, t, { collapseToolOutput: !verbose });
// 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.
@@ -136,7 +166,7 @@ export function registerChatCommand(program: Command, t: Messages): void {
// regular input.
if (session.resumedHistory) {
out.write(`${t.resumedBanner(session.sessionId, session.resumedHistory.length)}\n`);
- renderHistory(session.resumedHistory, out, t);
+ renderHistory(session.resumedHistory, out, t, { collapseToolOutput: !verbose });
}
// TTY: raw mode + bracketed paste + PasteFilter; non-TTY (pipe/test): read stdin directly.
@@ -369,6 +399,37 @@ export function registerChatCommand(program: Command, t: Messages): void {
if (text === "/exit" || text === "/quit") break;
if (text.length === 0) continue;
+ // Instant local commands (no Task runs, state stays idle). Like every slash
+ // command they are recognized at the prompt only — typed mid-run they are
+ // steering text.
+ if (text === "/thinking" || text.startsWith("/thinking ")) {
+ const parsed = parseThinkingCommand(text);
+ if (!parsed.ok) {
+ out.write(`${t.error(t.thinkingInvalid(parsed.value))}\n`);
+ } else if (parsed.level === null) {
+ // Name the source, not just the level: an override applies to this chat's turns
+ // only, while the Session default is also what spawned subagents inherit.
+ const sessionDefault = sessionThinkingDefault();
+ out.write(
+ `${
+ thinkingOverride
+ ? t.thinkingCurrentOverride(thinkingOverride, sessionDefault)
+ : t.thinkingCurrentDefault(sessionDefault)
+ }\n`,
+ );
+ } else {
+ thinkingOverride = parsed.level;
+ out.write(`${t.thinkingSet(parsed.level)}\n`);
+ }
+ continue;
+ }
+ if (text === "/verbose") {
+ verbose = !verbose;
+ renderer.setCollapseToolOutput(!verbose);
+ out.write(`${verbose ? t.verboseOn() : t.verboseOff()}\n`);
+ continue;
+ }
+
state = "running";
taskAbort = new AbortController();
try {
@@ -407,11 +468,12 @@ export function registerChatCommand(program: Command, t: Messages): void {
workspaceDir: session.workspaceDir,
modelId: session.modelId,
provider: session.provider,
+ ...(flagThinking ? { thinkingLevel: flagThinking } : {}),
});
if (resumable) out.write(`${dim(t.resumeHint(resumeCommand(session.sessionId)))}\n`);
session.dispose();
session = next;
- renderer = new StreamRenderer(out, t);
+ renderer = new StreamRenderer(out, t, { collapseToolOutput: !verbose });
resumable = false;
out.write(`${t.clearDone()}\n`);
} else if (text === "/goal" || text.startsWith("/goal:") || text.startsWith("/goal ")) {
@@ -427,6 +489,7 @@ export function registerChatCommand(program: Command, t: Messages): void {
await runTask(session, [userText(parsed.objective)], {
mode,
signal: taskAbort.signal,
+ ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),
renderer,
interactivePrompt,
t,
@@ -438,6 +501,7 @@ export function registerChatCommand(program: Command, t: Messages): void {
await runTask(session, [userText(text)], {
mode,
signal: taskAbort.signal,
+ ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),
renderer,
interactivePrompt,
t,
diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts
index 476fd040..4722796c 100644
--- a/packages/cli/src/commands/run.ts
+++ b/packages/cli/src/commands/run.ts
@@ -4,7 +4,7 @@
* penguin run -m <msg> [--model-id <id> --provider <group>] [--workspace <path>]
* [--project-id <id>] [--agent-id <id>]
* [--approve <allow-all|deny-all|read-only|always-ask>]
- * [--goal [budget]]
+ * [--thinking <low|medium|high|xhigh>] [--goal [budget]]
*
* Uses the current directory when Workspace is unspecified; uses the Project's default model
* when model is unspecified. A model reference is always an explicit `(provider, model_id)`
@@ -14,6 +14,10 @@
* `--goal` switches to goal mode: `-m` becomes the objective and the run loops until the
* goal reaches a terminal state (optional value = token budget, e.g. `--goal 500k`); only a
* completed goal exits 0.
+ * `--thinking` pins the Session's thinking level at creation (subagent sessions follow it);
+ * omitted, the Agent's configured level applies. Tool output is never collapsed here —
+ * `penguin run` output feeds pipes and nested CLIs, so every line must survive (the
+ * collapsed display is a chat-REPL affair).
* Docs: /docs/cli § "penguin run".
*/
import type { Command } from "commander";
@@ -21,6 +25,7 @@ import { UNLIMITED_BUDGET, createAgent, userText, VERSION } from "@prismshadow/p
import { StreamRenderer } from "../render.js";
import { runTask } from "../task-loop.js";
import { parseTokenBudget } from "../goal-command.js";
+import { resolveThinkingLevel } from "../thinking-command.js";
import { denyActivePrompt, resolveApprovalMode } from "../approval.js";
import type { Messages } from "../i18n.js";
@@ -35,6 +40,7 @@ export function registerRunCommand(program: Command, t: Messages): void {
.option("--agent-id <id>", t.common.agentId)
.option("--workspace <path>", t.common.workspace)
.option("--approve <mode>", t.common.approve)
+ .option("--thinking <level>", t.common.thinking)
.option("--goal [budget]", t.run.goal)
.action(async (opts) => {
// The model reference is a pair: commander can only require each option on its own,
@@ -64,6 +70,7 @@ export function registerRunCommand(program: Command, t: Messages): void {
}
}
const mode = resolveApprovalMode(opts.approve, t);
+ const thinking = resolveThinkingLevel(opts.thinking, t);
const agent = await createAgent({
...(opts.agentId ? { agentId: opts.agentId } : {}),
@@ -74,6 +81,7 @@ export function registerRunCommand(program: Command, t: Messages): void {
workspaceDir: opts.workspace ?? process.cwd(),
...(opts.modelId ? { modelId: opts.modelId } : {}),
...(opts.provider ? { provider: opts.provider } : {}),
+ ...(thinking ? { thinkingLevel: thinking } : {}),
});
const out = process.stdout;
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index 9fc6ff57..95390fd1 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -36,6 +36,8 @@ export interface Messages {
root: string;
workspace: string;
approve: string;
+ /** run/chat's --thinking: the session's thinking level (selectable tiers only, mirrors the web picker). */
+ thinking: string;
};
config: {
desc: string;
@@ -77,7 +79,12 @@ export interface Messages {
/** run's --goal: goal mode, with an optional token budget value (`--goal 500k`). */
goal: string;
};
- chat: { desc: string; resume: string };
+ chat: {
+ desc: string;
+ resume: string;
+ /** chat's --verbose: start with full tool output (collapsing off). */
+ verbose: string;
+ };
serve: {
serverDesc: string;
webDesc: string;
@@ -224,6 +231,27 @@ export interface Messages {
goalBudgetInvalid(value: string): string;
/** run's --goal given an empty/whitespace -m (the objective must be non-empty text). */
goalObjectiveEmpty(): string;
+ /**
+ * `/thinking` with no argument and no override in effect: the level the next turn will run
+ * at is the Session's own default (pinned by `--thinking` at creation, else the config chain).
+ */
+ thinkingCurrentDefault(level: string): string;
+ /**
+ * `/thinking` with no argument while a per-turn override is in effect: the level the next
+ * turn will run at, plus the Session default it overrides — the two are a real distinction
+ * (only the Session default reaches spawned subagent sessions).
+ */
+ thinkingCurrentOverride(level: string, sessionDefault: string): string;
+ /** `/thinking <level>` accepted: subsequent turns carry the override (never written to the config). */
+ thinkingSet(level: string): string;
+ /** Invalid `--thinking` / `/thinking` value (lists the selectable levels). */
+ thinkingInvalid(value: string): string;
+ /** `/verbose` toggled on: tool output renders in full from here on. */
+ verboseOn(): string;
+ /** `/verbose` toggled off: long tool output is collapsed again from here on. */
+ verboseOff(): string;
+ /** Dim elision-marker line inside a collapsed tool output; `hidden` = lines not shown (>= 2). */
+ toolOutputElided(hidden: number): string;
/** Prompt for an invalid --approve mode. */
approveModeInvalid(value: string): string;
/** Render label for an approval decision (frontend renders the approval_decision event; one label each for allow/deny). */
@@ -315,6 +343,8 @@ const en: Messages = {
workspace: "Workspace directory; must already exist (defaults to the current directory)",
approve:
"Approval mode: allow-all (auto-approve, default), deny-all (auto-reject), read-only (auto-approve read-only tools, prompt for the rest), always-ask (prompt per tool)",
+ thinking:
+ "Thinking level for this session: low, medium, high, or xhigh (defaults to the Agent's configured level)",
},
config: {
desc: "Manage Project configuration",
@@ -361,6 +391,8 @@ const en: Messages = {
desc: "Open the interactive REPL",
resume:
"Resume an existing Session (defaults to the agent's most recent one); workspace and model follow the original Session",
+ verbose:
+ "Show full tool output (by default long tool outputs are collapsed to their first and last lines; /verbose toggles it mid-chat)",
},
serve: {
serverDesc:
@@ -455,7 +487,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; /clear to start a fresh session; /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; /thinking changes the thinking level; /verbose toggles full tool output; /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}`,
@@ -507,6 +539,17 @@ const en: Messages = {
goalBudgetInvalid: (value) =>
`Invalid token budget "${value}". Use a positive number with an optional k/m suffix (500k, 2m).`,
goalObjectiveEmpty: () => "Goal mode requires a non-empty objective: pass it via -m.",
+ thinkingCurrentDefault: (level) =>
+ `[thinking] level: ${level} (this Session's default) — change with /thinking <low|medium|high|xhigh>`,
+ thinkingCurrentOverride: (level, sessionDefault) =>
+ `[thinking] level: ${level} (override for this chat's turns; this Session's default is ${sessionDefault}) — change with /thinking <low|medium|high|xhigh>`,
+ thinkingSet: (level) =>
+ `[thinking] level set to ${level} for this chat's subsequent turns (the Agent config is unchanged)`,
+ thinkingInvalid: (value) => `Invalid thinking level "${value}". Use low, medium, high, or xhigh.`,
+ verboseOn: () => "[verbose] on — tool output from here on shows in full",
+ verboseOff: () =>
+ "[verbose] off — long tool output from here on is collapsed (/verbose to toggle)",
+ toolOutputElided: (hidden) => `… (+${hidden} lines, /verbose for full output)`,
approveModeInvalid: (value) =>
`Invalid approval mode "${value}". Use allow-all, deny-all, read-only, or always-ask.`,
approvalDecision: (decision) => (decision === "allow" ? "✓ [approved]" : "× [denied]"),
@@ -576,6 +619,7 @@ const zh: Messages = {
workspace: "Workspace 目录,须为已存在目录(默认当前目录)",
approve:
"审批模式:allow-all(全部放行,缺省)、deny-all(全部拒绝)、read-only(自动放行只读工具,其余仍逐个询问)、always-ask(逐个询问)",
+ thinking: "本会话的思考等级:low、medium、high 或 xhigh(缺省用 Agent 配置的等级)",
},
config: {
desc: "管理 Project 配置",
@@ -619,6 +663,7 @@ const zh: Messages = {
desc: "打开交互式 REPL",
resume:
"恢复既有 Session 继续对话(缺省恢复当前 Agent 最近一次);Workspace 与模型沿用原 Session",
+ verbose: "显示完整工具输出(缺省折叠过长的工具输出、只保留首尾数行;/verbose 可随时切换)",
},
serve: {
serverDesc:
@@ -706,7 +751,7 @@ const zh: Messages = {
header: headerZh,
chatHints: () =>
- "输入消息发起对话;行尾 \\ 续行;运行中输入可插话引导;/goal 以目标模式运行至完成;/compact 压缩上下文;/clear 开启全新会话;/exit 退出;Ctrl-C 中断对话。",
+ "输入消息发起对话;行尾 \\ 续行;运行中输入可插话引导;/goal 以目标模式运行至完成;/compact 压缩上下文;/clear 开启全新会话;/thinking 调整思考等级;/verbose 切换完整工具输出;/exit 退出;Ctrl-C 中断对话。",
confirmExit: () => "确认退出 penguin?[y/N] ",
taskInterrupted: () => "[已中断当前对话]",
steerQueued: (text) => `» 插话已排队(随下一轮送达):${text}`,
@@ -758,6 +803,15 @@ const zh: Messages = {
goalBudgetInvalid: (value) =>
`无效的 token 预算 "${value}":应为正数,可带 k/m 后缀(500k、2m)。`,
goalObjectiveEmpty: () => "目标模式需要非空的目标文本:请通过 -m 传入。",
+ thinkingCurrentDefault: (level) =>
+ `[思考] 当前等级:${level}(本 Session 的缺省值)——用 /thinking <low|medium|high|xhigh> 修改`,
+ thinkingCurrentOverride: (level, sessionDefault) =>
+ `[思考] 当前等级:${level}(本次对话后续轮次的覆盖值;本 Session 缺省为 ${sessionDefault})——用 /thinking <low|medium|high|xhigh> 修改`,
+ thinkingSet: (level) => `[思考] 等级已设为 ${level},本次对话后续轮次生效(不改动 Agent 配置)`,
+ thinkingInvalid: (value) => `无效的思考等级 "${value}"。请使用 low、medium、high 或 xhigh。`,
+ verboseOn: () => "[详细输出] 已开启——后续工具输出完整显示(/verbose 切换)",
+ verboseOff: () => "[详细输出] 已关闭——后续过长的工具输出将折叠(/verbose 切换)",
+ toolOutputElided: (hidden) => `……(另有 ${hidden} 行,/verbose 显示完整输出)`,
approveModeInvalid: (value) =>
`无效的审批模式 "${value}"。请使用 allow-all、deny-all、read-only 或 always-ask。`,
approvalDecision: (decision) => (decision === "allow" ? "✓ [已批准]" : "× [已拒绝]"),
diff --git a/packages/cli/src/output-collapse.ts b/packages/cli/src/output-collapse.ts
new file mode 100644
index 00000000..ede08233
--- /dev/null
+++ b/packages/cli/src/output-collapse.ts
@@ -0,0 +1,147 @@
+/**
+ * Display-only head/tail collapsing of long tool outputs (pure logic, unit-tested).
+ *
+ * The chat REPL floods the screen when a tool returns hundreds of lines (a long
+ * `exec_command` result, a whole file from `read_file`). Collapsed rendering keeps the
+ * first TOOL_OUTPUT_HEAD_LINES streaming live (so a long-running command still shows
+ * immediate progress), holds the rest back, and settles at stream end: everything still
+ * fits -> print it all (short outputs stay untouched); otherwise print one dim elision
+ * marker (`… (+N lines …)`) followed by the last TOOL_OUTPUT_TAIL_LINES — the tail is
+ * where an exec result carries its verdict. The marker never hides fewer than 2 lines
+ * (hiding a single line would replace it with a marker line and save nothing).
+ *
+ * This is presentation only: the full output still reaches the model, the Trace, and the
+ * Web App unchanged. The chat REPL turns it off with `--verbose` / the `/verbose` toggle;
+ * `penguin run` keeps full output (piped runs — e.g. a nested CLI driven through
+ * `exec_command` — must not lose lines).
+ */
+
+/** Completed head lines that keep streaming live before the hold-back starts. */
+export const TOOL_OUTPUT_HEAD_LINES = 4;
+/** Trailing lines shown after the elision marker when the stream ends. */
+export const TOOL_OUTPUT_TAIL_LINES = 4;
+
+/** Settled tail of one collapsed stream: the lines to print now and how many stay hidden (0 = nothing was elided). */
+export interface CollapsedFlush {
+ hidden: number;
+ lines: string[];
+}
+
+/**
+ * Collapse state machine for one streaming tool-output segment. `push` is fed each raw
+ * chunk (chunks split lines arbitrarily) and returns the prefix to write through live;
+ * `flush` settles the held-back remainder at stream end.
+ */
+export class ToolOutputCollapser {
+ /** Completed lines still allowed to stream live (a line mid-stream stays live until its newline spends one). */
+ private headRemaining: number;
+ private readonly tail: number;
+ /**
+ * Held-back completed lines, bounded to tail+1: one more than the tail so `flush` can
+ * tell "fits entirely" (<= tail+1 with nothing dropped -> print all) from "must elide"
+ * (anything dropped -> hidden >= 2 by construction). Keeps memory bounded however long
+ * the output runs.
+ */
+ private buffered: string[] = [];
+ /** Lines pushed out of the bounded buffer (always hidden). */
+ private dropped = 0;
+ /** The held-back line still awaiting its newline (chunks split lines arbitrarily). */
+ private partial = "";
+ /** Head allowance spent: everything from here on is held back until flush. */
+ private holding = false;
+
+ constructor(head = TOOL_OUTPUT_HEAD_LINES, tail = TOOL_OUTPUT_TAIL_LINES) {
+ this.headRemaining = head;
+ this.tail = tail;
+ }
+
+ /** Feeds one streamed chunk; returns the prefix to write live (empty once the head allowance is spent). */
+ push(chunk: string): string {
+ let live = "";
+ if (!this.holding) {
+ let idx = 0;
+ while (idx < chunk.length && this.headRemaining > 0) {
+ const nl = chunk.indexOf("\n", idx);
+ if (nl === -1) {
+ // The current head line continues past this chunk: it stays live; its eventual
+ // newline is what spends the allowance.
+ idx = chunk.length;
+ break;
+ }
+ idx = nl + 1;
+ this.headRemaining -= 1;
+ }
+ live = chunk.slice(0, idx);
+ chunk = chunk.slice(idx);
+ if (chunk.length === 0) return live;
+ this.holding = true;
+ }
+ const parts = (this.partial + chunk).split("\n");
+ this.partial = parts.pop()!;
+ for (const line of parts) this.bufferLine(line);
+ return live;
+ }
+
+ private bufferLine(line: string): void {
+ this.buffered.push(line);
+ if (this.buffered.length > this.tail + 1) {
+ this.buffered.shift();
+ this.dropped += 1;
+ }
+ }
+
+ /** Whether `flush` would print anything (any line was held back). */
+ hasBuffered(): boolean {
+ return this.buffered.length > 0 || this.partial.length > 0;
+ }
+
+ /**
+ * Settles the held-back remainder at stream end. An unterminated final line counts as a
+ * line. Nothing dropped -> everything held back still fits (at most tail+1 lines): print
+ * it all, hidden 0 — a short output renders exactly as it would have uncollapsed. Anything
+ * dropped -> print the last `tail` lines and report the rest hidden (always >= 2).
+ */
+ flush(): CollapsedFlush {
+ if (this.partial.length > 0) {
+ this.bufferLine(this.partial);
+ this.partial = "";
+ }
+ let result: CollapsedFlush;
+ if (this.dropped === 0) {
+ result = { hidden: 0, lines: this.buffered };
+ } else {
+ result = {
+ hidden: this.dropped + (this.buffered.length - this.tail),
+ lines: this.buffered.slice(-this.tail),
+ };
+ }
+ this.buffered = [];
+ this.dropped = 0;
+ return result;
+ }
+}
+
+/** Head/tail split of one collapsed (non-streaming) output; `hidden` 0 = short enough, shown whole. */
+export interface CollapsedLines {
+ head: readonly string[];
+ hidden: number;
+ tail: readonly string[];
+}
+
+/**
+ * Collapses an already-complete output (resumed-history rendering): same shape as the
+ * streaming collapse — up to head + tail + 1 lines render whole (the marker must hide at
+ * least 2 lines to earn its row), longer outputs keep the first `head` and last `tail`.
+ */
+export function collapseLines(
+ lines: readonly string[],
+ head = TOOL_OUTPUT_HEAD_LINES,
+ tail = TOOL_OUTPUT_TAIL_LINES,
+): CollapsedLines {
+ if (lines.length <= head + tail + 1) return { head: lines, hidden: 0, tail: [] };
+ return {
+ head: lines.slice(0, head),
+ hidden: lines.length - head - tail,
+ tail: lines.slice(-tail),
+ };
+}
diff --git a/packages/cli/src/render.ts b/packages/cli/src/render.ts
index 6d3aa88c..d79c16de 100644
--- a/packages/cli/src/render.ts
+++ b/packages/cli/src/render.ts
@@ -65,6 +65,7 @@ import type {
ToolDefinition,
} from "@prismshadow/penguin-core";
import { renderFileToolApprovalPayload, renderPartialToolCall } from "./tool-render.js";
+import { ToolOutputCollapser, collapseLines } from "./output-collapse.js";
import { defaultMessages } from "./i18n.js";
import type { Messages } from "./i18n.js";
@@ -188,6 +189,17 @@ export function formatAbort(p: AbortPayload, t: Messages, c: Palette = STDOUT_PA
return dim(t.abortLabel(p.reason ?? undefined), c);
}
+/** Options shared by history and streaming rendering. */
+export interface RenderOptions {
+ /**
+ * Collapse long tool outputs to head/tail lines plus a dim elision marker (see
+ * output-collapse.ts). Display only — the Trace keeps the full text. Default off, so
+ * `penguin run` (whose output feeds pipes and nested CLIs) stays complete; the chat
+ * REPL turns it on unless `--verbose`.
+ */
+ collapseToolOutput?: boolean;
+}
+
/**
* Statically renders resumed history messages (`--resume`: full-message semantics, no
* partial_*, including interrupted messages and their markers). Uses the
@@ -199,6 +211,7 @@ export function renderHistory(
messages: OmniMessage[],
out: NodeJS.WritableStream,
t: Messages = defaultMessages(),
+ opts: RenderOptions = {},
): void {
const c = paletteFor(out);
// tool_call_id -> tool name (keyed with the origin chain: parent/child ids may collide),
@@ -262,14 +275,30 @@ export function renderHistory(
const name = toolNames.get(nameKey(msg, p.tool_call_id ?? ""));
const label = name ? `${tag} ${name}` : tag;
const colorDiff = name !== undefined && DIFF_OUTPUT_TOOLS.has(name);
- for (const line of (p.output ?? "").split("\n")) {
+ const writeLine = (line: string): void => {
const color = colorDiff ? diffLineColor(line[0], c) : null;
out.write(
color
? `${c.dim}${label} -> ${c.reset}${color}${line}${c.reset}\n`
: `${c.dim}${label} -> ${c.reset}${line}\n`,
);
+ };
+ // Collapsed history rendering keeps the same head/tail shape as the streaming
+ // collapse, so a resumed transcript doesn't re-flood the screen. An output ending
+ // in a newline splits into a trailing "" that the streaming collapser never counts
+ // (flush only buffers its partial line when non-empty) — drop it here too, so the
+ // same output reports the same hidden count live and on resume instead of spending
+ // one of the four tail rows on a blank gutter line. The uncollapsed path keeps it
+ // and renders exactly as before.
+ const lines = (p.output ?? "").split("\n");
+ const collapsed = opts.collapseToolOutput
+ ? collapseLines(lines.length > 1 && lines.at(-1) === "" ? lines.slice(0, -1) : lines)
+ : { head: lines, hidden: 0, tail: [] };
+ for (const line of collapsed.head) writeLine(line);
+ if (collapsed.hidden > 0) {
+ out.write(`${c.dim}${label} -> ${t.toolOutputElided(collapsed.hidden)}${c.reset}\n`);
}
+ for (const line of collapsed.tail) writeLine(line);
// Attached images aren't rendered by the terminal; print one placeholder line per image.
for (const _ of p.images ?? []) {
out.write(`${c.dim}${label} -> [image]${c.reset}\n`);
@@ -304,6 +333,10 @@ export class StreamRenderer {
private readonly t: Messages;
/** This renderer's palette, decided once at construction from the output stream and NO_COLOR/FORCE_COLOR/TERM (see supportsColor). */
private readonly c: Palette;
+ /** Collapse long tool outputs to head/tail + a dim elision marker (see RenderOptions); toggled live by the chat REPL's `/verbose`. */
+ private collapseToolOutput: boolean;
+ /** Per-stream collapse state (keyed by tool_call_id), created lazily on the first output delta; settled and dropped at the stream's stop (endTask settles leftovers of aborted streams). */
+ private readonly toolOutCollapsers = new Map<string, ToolOutputCollapser>();
/** Pending render queue: while the screen is held (a streaming segment is in progress / awaiting user input), messages queue up here. */
private pending: OmniMessage[] = [];
@@ -429,10 +462,24 @@ export class StreamRenderer {
/** The pending failure's attempt ordinal (request_end.attempt — the core's authoritative count, printed on the retry line). */
private pendingRetryAttempt: number | undefined;
- constructor(out: NodeJS.WritableStream = process.stdout, t: Messages = defaultMessages()) {
+ constructor(
+ out: NodeJS.WritableStream = process.stdout,
+ t: Messages = defaultMessages(),
+ opts: RenderOptions = {},
+ ) {
this.out = out;
this.t = t;
this.c = paletteFor(out);
+ this.collapseToolOutput = opts.collapseToolOutput === true;
+ }
+
+ /**
+ * Turns tool-output collapsing on/off (the chat REPL's `/verbose` toggle). Commands are
+ * accepted only while the REPL is idle, so no stream is mid-collapse when this flips —
+ * it simply decides how subsequent outputs render.
+ */
+ setCollapseToolOutput(collapse: boolean): void {
+ this.collapseToolOutput = collapse;
}
handle(msg: OmniMessage): void {
@@ -1008,19 +1055,38 @@ export class StreamRenderer {
}
private handlePartialToolOutput(p: PartialToolCallOutputPayload): void {
+ const label = this.outputLabel(p.tool_call_id);
+ const name = this.toolNames.get(p.tool_call_id);
+ const colorDiff = name !== undefined && DIFF_OUTPUT_TOOLS.has(name);
if (p.event_type === "stop") {
+ this.settleCollapser(p.tool_call_id, label, colorDiff);
this.finishLine();
return;
}
if (this.inDim) this.finishLine();
- const label = this.outputLabel(p.tool_call_id);
- const name = this.toolNames.get(p.tool_call_id);
- const colorDiff = name !== undefined && DIFF_OUTPUT_TOOLS.has(name);
- if (p.output) this.writeToolOutput(p.output, label, colorDiff);
+ if (p.output) {
+ if (this.collapseToolOutput) {
+ // Collapsed mode: the head lines stream through live; the rest is held back and
+ // settled at the stream's stop (elision marker + tail, see output-collapse.ts).
+ let collapser = this.toolOutCollapsers.get(p.tool_call_id);
+ if (!collapser) {
+ collapser = new ToolOutputCollapser();
+ this.toolOutCollapsers.set(p.tool_call_id, collapser);
+ }
+ const live = collapser.push(p.output);
+ if (live) this.writeToolOutput(live, label, colorDiff);
+ } else {
+ this.writeToolOutput(p.output, label, colorDiff);
+ }
+ }
// Image delta (carried whole in a single delta): the terminal doesn't render the
// image itself, so print one placeholder line per image, using the same gutter label
// as the text output.
if (p.images && p.images.length > 0) {
+ // Keep display order under collapsing: settle any held-back text before the image
+ // placeholders (text arriving after starts a fresh collapser — a new head allowance
+ // for this rare mixed text/image output).
+ this.settleCollapser(p.tool_call_id, label, colorDiff);
this.finishLine();
for (const _ of p.images) {
this.out.write(`${this.c.dim}${label} -> [image]${this.c.reset}\n`);
@@ -1029,6 +1095,39 @@ export class StreamRenderer {
}
}
+ /**
+ * Writes a collapsed stream's held-back remainder — the dim elision marker (when lines
+ * stay hidden) followed by the tail lines — and retires its collapse state. No-op for
+ * streams that never held anything back (short outputs, verbose mode).
+ */
+ private settleCollapser(toolCallId: string, label: string, colorDiff: boolean): void {
+ const collapser = this.toolOutCollapsers.get(toolCallId);
+ if (!collapser) return;
+ this.toolOutCollapsers.delete(toolCallId);
+ if (!collapser.hasBuffered()) return;
+ const { hidden, lines } = collapser.flush();
+ this.finishLine();
+ if (hidden > 0) {
+ this.out.write(
+ `${this.c.dim}${label} -> ${this.t.toolOutputElided(hidden)}${this.c.reset}\n`,
+ );
+ }
+ if (lines.length > 0) this.writeToolOutput(`${lines.join("\n")}\n`, label, colorDiff);
+ this.lastLineKey = null;
+ }
+
+ /** Settles every outstanding collapser (a stream aborted before its stop must not swallow its held-back tail); called by endTask. */
+ private settleAllCollapsers(): void {
+ for (const id of [...this.toolOutCollapsers.keys()]) {
+ const name = this.toolNames.get(id);
+ this.settleCollapser(
+ id,
+ this.outputLabel(id),
+ name !== undefined && DIFF_OUTPUT_TOOLS.has(name),
+ );
+ }
+ }
+
/** Output-gutter label: the `[tool-xxx]` pairing tag plus the tool name of the preceding call (the bare tag when no call was seen). */
private outputLabel(toolCallId: string): string {
const tag = `[${callTag(toolCallId)}]`;
@@ -1092,6 +1191,9 @@ export class StreamRenderer {
this.flushDeferredDecisions();
this.holder = null;
this.drain();
+ // A tool-output stream cut off before its stop (aborted turn) still has held-back
+ // collapsed lines: settle them here so nothing silently vanishes from the screen.
+ this.settleAllCollapsers();
this.finishLine();
// This task's elapsed time = first message -> last non-compaction request_end
// (mid-turn compaction falls within the span and is counted; compaction after the
diff --git a/packages/cli/src/task-loop.ts b/packages/cli/src/task-loop.ts
index f2716e12..2ceb197d 100644
--- a/packages/cli/src/task-loop.ts
+++ b/packages/cli/src/task-loop.ts
@@ -13,7 +13,13 @@
* outcome summary read from the stream's terminal `goal_finished` event.
*/
import { goalFinishedOf, isEventMessage, isGoalRoundInput } from "@prismshadow/penguin-core";
-import type { ApproveFn, GoalOutcome, OmniMessage, Session } from "@prismshadow/penguin-core";
+import type {
+ ApproveFn,
+ GoalOutcome,
+ OmniMessage,
+ Session,
+ ThinkingLevelName,
+} from "@prismshadow/penguin-core";
import { dim, humanizeTokens } from "./render.js";
import type { StreamRenderer } from "./render.js";
import { makeApprove, promptApproval, type ApprovalMode } from "./approval.js";
@@ -24,6 +30,11 @@ export interface RunTaskOptions {
mode?: ApprovalMode;
/** Interrupt signal (Ctrl-C, etc.). */
signal?: AbortSignal;
+ /**
+ * Per-run thinking-level override (`RunOptions.thinkingLevel`); omitted = the Session's
+ * construction-time default. In goal mode core reuses it for every round.
+ */
+ thinkingLevel?: ThinkingLevelName;
renderer: StreamRenderer;
/** The actual Q&A for interactive approval; defaults to the one-off `promptApproval`. */
interactivePrompt?: ApproveFn;
@@ -115,6 +126,7 @@ export async function runTask(
for await (const msg of session.run(prompt, {
approve,
...(opts.signal ? { signal: opts.signal } : {}),
+ ...(opts.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),
...(goal ? { goal: { budget: goal.budget } } : {}),
})) {
if (isEventMessage(msg) && msg.payload.type === "abort" && (msg.origin?.length ?? 0) === 0) {
diff --git a/packages/cli/src/thinking-command.ts b/packages/cli/src/thinking-command.ts
new file mode 100644
index 00000000..d201eccf
--- /dev/null
+++ b/packages/cli/src/thinking-command.ts
@@ -0,0 +1,82 @@
+/**
+ * Thinking-level control (pure logic, shared by chat's `/thinking`, the `--thinking`
+ * startup flag on run/chat, and unit tests).
+ *
+ * The selectable levels are core's DEFAULT_CHAT_THINKING_LEVELS (low/medium/high/xhigh),
+ * mirroring the web pickers: "none" stays a valid stored config value but is never offered
+ * for selection (many models cannot disable thinking).
+ *
+ * Semantics (aligned with the web active-session picker and core's tri-state option):
+ * - `--thinking <level>` pins the Session's default level at creation
+ * (`createSession.thinkingLevel`, so spawned subagent sessions follow it too). Under
+ * chat `--resume` the Session already exists — the flag becomes the initial per-turn
+ * override instead (the thinking level is a per-turn run parameter, so this is allowed
+ * where `--workspace` / `--model-id` are not).
+ * - `/thinking <level>` sets a per-turn override carried on every subsequent run
+ * (`RunOptions.thinkingLevel`); it never writes back to the Agent config.
+ * - `/thinking` bare shows the level the next turn will run at, and names its source: the
+ * Session's own default, or the per-turn override (plus the default it replaces). The two
+ * differ in reach — only the Session's level is inherited by spawned subagent sessions.
+ */
+import { DEFAULT_CHAT_THINKING_LEVELS } from "@prismshadow/penguin-core";
+import type { DefaultChatThinkingLevel, ThinkingLevelName } from "@prismshadow/penguin-core";
+import type { Messages } from "./i18n.js";
+
+/** Parses one level token (trimmed, case-insensitive); null when it is not a selectable level. */
+export function parseThinkingLevel(text: string): DefaultChatThinkingLevel | null {
+ const v = text.trim().toLowerCase();
+ return (DEFAULT_CHAT_THINKING_LEVELS as readonly string[]).includes(v)
+ ? (v as DefaultChatThinkingLevel)
+ : null;
+}
+
+export type ThinkingCommandResult =
+ /** `level` null = bare `/thinking`: show the current level. */
+ { ok: true; level: DefaultChatThinkingLevel | null } | { ok: false; value: string };
+
+/** Parses a full `/thinking…` chat line (the caller has already matched the `/thinking` prefix). */
+export function parseThinkingCommand(line: string): ThinkingCommandResult {
+ const rest = line.trim().slice("/thinking".length).trim();
+ if (rest === "") return { ok: true, level: null };
+ const level = parseThinkingLevel(rest);
+ if (level === null) return { ok: false, value: rest };
+ return { ok: true, level };
+}
+
+/**
+ * Resolve the `--thinking` startup flag: absent -> undefined (follow the config chain);
+ * print a message and exit if the value is invalid (same contract as resolveApprovalMode).
+ */
+export function resolveThinkingLevel(
+ thinking: string | undefined,
+ t: Messages,
+): DefaultChatThinkingLevel | undefined {
+ if (thinking === undefined) return undefined;
+ const level = parseThinkingLevel(thinking);
+ if (level !== null) return level;
+ process.stderr.write(`${t.thinkingInvalid(thinking)}\n`);
+ process.exit(1);
+}
+
+/** The slices of Agent the fallback chain reads (structurally satisfied by core's Agent; keeps test doubles small). */
+export interface ThinkingConfigSource {
+ state: { systemConfig: { model?: { thinking_level?: ThinkingLevelName } } };
+ projectConfig: { default_chat?: { thinking_level?: DefaultChatThinkingLevel } };
+}
+
+/**
+ * The level a Session created without an explicit `thinkingLevel` runs at — the SAME chain
+ * core resolves at Session creation (core/src/agent.ts `configuredThinkingLevel`, the single
+ * rule; the web draft picker mirrors it too in features/chat/thinking-level.ts — keep the
+ * sites in sync): the Agent's explicit `model.thinking_level` > the Project's
+ * `default_chat.thinking_level` > the built-in "medium". Used only for DISPLAY (`/thinking`
+ * with no argument); runs without an override simply omit the parameter so core's own
+ * fallback stays authoritative.
+ */
+export function configuredThinkingLevel(agent: ThinkingConfigSource): ThinkingLevelName {
+ return (
+ agent.state.systemConfig.model?.thinking_level ??
+ agent.projectConfig.default_chat?.thinking_level ??
+ "medium"
+ );
+}
diff --git a/packages/cli/test/chat-thinking.test.ts b/packages/cli/test/chat-thinking.test.ts
new file mode 100644
index 00000000..efd66c1b
--- /dev/null
+++ b/packages/cli/test/chat-thinking.test.ts
@@ -0,0 +1,261 @@
+/**
+ * chat `/thinking` + `--thinking` (per-turn thinking level) and `/verbose` (tool-output
+ * collapsing): drives the real REPL over a fake stdin with `createAgent` mocked, the same
+ * harness as chat-clear.test.ts. Sessions record the options of every `run` call, proving
+ * what the engine would receive (`RunOptions.thinkingLevel`); the verbose test streams a
+ * long fake tool output through the real renderer to prove the collapsed/full switch.
+ */
+import { PassThrough } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import {
+ createAgent,
+ partialToolCall,
+ partialToolCallOutput,
+ type OmniMessage,
+} 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() };
+});
+
+const t = getMessages("en");
+
+interface RunCall {
+ text: string;
+ opts: Record<string, unknown>;
+}
+
+interface FakeSession {
+ sessionId: string;
+ provider: string;
+ modelId: string;
+ workspaceDir: string;
+ runs: RunCall[];
+ run(prompt: unknown[], opts: Record<string, unknown>): AsyncGenerator<OmniMessage>;
+ compact(opts: unknown): AsyncGenerator<never>;
+ steer(): boolean;
+ toolPermission(): undefined;
+ dispose(): void;
+}
+
+/** A Session double recording each run's options; `messages` (if given) stream out of every run. */
+function makeFakeSession(sessionId: string, messages: () => OmniMessage[]): FakeSession {
+ const session: FakeSession = {
+ sessionId,
+ provider: "prov",
+ modelId: "model",
+ workspaceDir: "/ws",
+ runs: [],
+ async *run(prompt, opts) {
+ const text = (prompt[0] as { payload?: { text?: string } }).payload?.text ?? "";
+ session.runs.push({ text, opts });
+ yield* messages();
+ },
+ async *compact() {},
+ steer: () => false,
+ toolPermission: () => undefined,
+ dispose() {},
+ };
+ return session;
+}
+
+/**
+ * An Agent double with the config slices `/thinking`'s display fallback reads
+ * (agent explicit level > project default > "medium").
+ */
+function makeFakeAgent(opts?: {
+ agentLevel?: string;
+ projectLevel?: string;
+ messages?: () => OmniMessage[];
+}) {
+ const sessions: FakeSession[] = [];
+ const track = (session: FakeSession): FakeSession => {
+ sessions.push(session);
+ return session;
+ };
+ const createSession = vi.fn(async (_createOpts: Record<string, unknown> = {}) =>
+ track(makeFakeSession(`sess-${sessions.length + 1}`, opts?.messages ?? (() => []))),
+ );
+ const agent = {
+ state: {
+ agentId: "test-agent",
+ systemConfig: {
+ model: opts?.agentLevel ? { thinking_level: opts.agentLevel } : {},
+ },
+ },
+ projectConfig: opts?.projectLevel
+ ? { default_chat: { thinking_level: opts.projectLevel } }
+ : {},
+ createSession,
+ // A resumed Session is a fully built Session like any other — it just isn't created by
+ // this run, which is exactly why --thinking cannot pin its construction-time level.
+ resumeSession: vi.fn(async (_resumeOpts: { sessionId: string }) =>
+ track(makeFakeSession("sess-old", opts?.messages ?? (() => []))),
+ ),
+ latestSessionId: vi.fn(async () => "sess-old"),
+ };
+ vi.mocked(createAgent).mockResolvedValue(
+ agent as unknown as Awaited<ReturnType<typeof createAgent>>,
+ );
+ return { agent, sessions };
+}
+
+/** Runs `penguin chat <argv>` end to end over a PassThrough stdin, feeding each line at the prompt (same driver as chat-clear.test.ts). */
+async function driveChat(lines: string[], argv: 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, t);
+ const done = program.parseAsync(["node", "penguin", "chat", ...argv]);
+ for (let i = 0; i < lines.length; i++) {
+ 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 /thinking (per-turn thinking level)", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("bare /thinking shows the configured chain (agent explicit > project default > medium)", async () => {
+ makeFakeAgent({ projectLevel: "high" });
+ const out = await driveChat(["/thinking", "/exit"]);
+ expect(out).toContain(t.thinkingCurrentDefault("high"));
+ });
+
+ it("/thinking <level> overrides subsequent turns; invalid values change nothing", async () => {
+ const { sessions } = makeFakeAgent();
+ const out = await driveChat([
+ "/thinking",
+ "first",
+ "/thinking high",
+ "second",
+ "/thinking none",
+ "third",
+ "/thinking",
+ "/exit",
+ ]);
+ // Display before any override: the built-in medium (no agent/project level configured).
+ expect(out).toContain(t.thinkingCurrentDefault("medium"));
+ expect(out).toContain(t.thinkingSet("high"));
+ // Once overridden, the display says so and still names the Session default it overrides.
+ expect(out).toContain(t.thinkingCurrentOverride("high", "medium"));
+ // "none" is not selectable (mirrors the web picker): error + the override stays "high".
+ expect(out).toContain(t.error(t.thinkingInvalid("none")));
+ const runs = sessions[0]!.runs;
+ expect(runs.map((r) => r.text)).toEqual(["first", "second", "third"]);
+ expect(runs[0]!.opts["thinkingLevel"]).toBeUndefined(); // untouched -> core's default applies
+ expect(runs[1]!.opts["thinkingLevel"]).toBe("high");
+ expect(runs[2]!.opts["thinkingLevel"]).toBe("high");
+ });
+
+ it("--thinking pins the Session default at creation (runs carry no per-turn override) and /thinking shows it", async () => {
+ const { agent, sessions } = makeFakeAgent({ agentLevel: "low" });
+ const out = await driveChat(["/thinking", "go", "/exit"], ["--thinking", "xhigh"]);
+ expect(agent.createSession.mock.calls[0]![0]).toMatchObject({ thinkingLevel: "xhigh" });
+ expect(out).toContain(t.thinkingCurrentDefault("xhigh"));
+ expect(sessions[0]!.runs[0]!.opts["thinkingLevel"]).toBeUndefined();
+ });
+
+ it("--resume turns --thinking into the initial per-turn override (the Session already exists)", async () => {
+ // A resumed Session's construction values are fixed, so the flag can only ride along as
+ // RunOptions.thinkingLevel — and the display must show it as an override of the resumed
+ // Session's own default (the config chain: agent explicit "low" here).
+ const { agent, sessions } = makeFakeAgent({ agentLevel: "low" });
+ const out = await driveChat(["/thinking", "go", "/exit"], ["--resume", "--thinking", "high"]);
+ expect(agent.createSession).not.toHaveBeenCalled();
+ expect(agent.resumeSession).toHaveBeenCalledWith({ sessionId: "sess-old" });
+ expect(out).toContain(t.thinkingCurrentOverride("high", "low"));
+ expect(sessions[0]!.runs[0]!.opts["thinkingLevel"]).toBe("high");
+ });
+
+ it("--resume without --thinking runs on the resumed Session's own default (no override)", async () => {
+ const { sessions } = makeFakeAgent({ projectLevel: "xhigh" });
+ const out = await driveChat(["/thinking", "go", "/exit"], ["--resume"]);
+ expect(out).toContain(t.thinkingCurrentDefault("xhigh"));
+ expect(sessions[0]!.runs[0]!.opts["thinkingLevel"]).toBeUndefined();
+ });
+
+ it("/clear keeps the --thinking session default and the /thinking override", async () => {
+ const { agent, sessions } = makeFakeAgent();
+ await driveChat(["/thinking high", "/clear", "after", "/exit"], ["--thinking", "low"]);
+ expect(agent.createSession.mock.calls[1]![0]).toMatchObject({ thinkingLevel: "low" });
+ expect(sessions[1]!.runs[0]!.opts["thinkingLevel"]).toBe("high");
+ });
+});
+
+describe("chat /verbose (tool-output collapsing)", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ /** One exec_command call whose output streams 12 lines (l1..l12). */
+ function longToolOutput(): OmniMessage[] {
+ const id = "call_c9";
+ return [
+ partialToolCall({ eventType: "start", name: "exec_command", toolCallId: id }),
+ partialToolCall({ eventType: "delta", name: "", arguments: '{"cmd":"x"}', toolCallId: id }),
+ partialToolCall({ eventType: "stop", name: "", toolCallId: id }),
+ partialToolCallOutput({ eventType: "start", toolCallId: id }),
+ ...Array.from({ length: 12 }, (_, i) =>
+ partialToolCallOutput({ eventType: "delta", output: `l${i + 1}\n`, toolCallId: id }),
+ ),
+ partialToolCallOutput({ eventType: "stop", toolCallId: id }),
+ ];
+ }
+
+ it("collapses long tool output by default; /verbose switches to full output", async () => {
+ makeFakeAgent({ messages: longToolOutput });
+ const out = await driveChat(["go", "/verbose", "again", "/exit"]);
+ const [collapsed, full] = out.split(t.verboseOn()) as [string, string];
+ // Before the toggle: head + marker + tail, the middle hidden.
+ expect(collapsed).toContain("exec_command -> l4\n");
+ expect(collapsed).toContain(t.toolOutputElided(4));
+ expect(collapsed).toContain("exec_command -> l12\n");
+ expect(collapsed).not.toContain("-> l5\n");
+ // After /verbose: every line renders.
+ expect(full).toContain("-> l5\n");
+ expect(full).not.toContain(t.toolOutputElided(4));
+ });
+
+ it("--verbose starts with full output; /verbose collapses from the next output on", async () => {
+ makeFakeAgent({ messages: longToolOutput });
+ const out = await driveChat(["go", "/verbose", "again", "/exit"], ["--verbose"]);
+ const [full, collapsed] = out.split(t.verboseOff()) as [string, string];
+ expect(full).toContain("-> l5\n");
+ expect(collapsed).toContain(t.toolOutputElided(4));
+ expect(collapsed).not.toContain("-> l5\n");
+ });
+});
diff --git a/packages/cli/test/i18n.test.ts b/packages/cli/test/i18n.test.ts
index 30618400..7ff1fd89 100644
--- a/packages/cli/test/i18n.test.ts
+++ b/packages/cli/test/i18n.test.ts
@@ -46,6 +46,27 @@ describe("getMessages", () => {
expect(getMessages("en").config.langDesc).toContain("language");
expect(getMessages("en").langSet("zh", "/x/.zshrc")).toContain("/x/.zshrc");
expect(getMessages("zh").langInvalid("fr")).toContain("fr");
+ // Thinking-level control and tool-output collapsing (issue #305).
+ expect(getMessages("en").thinkingCurrentDefault("medium")).toContain("medium");
+ expect(getMessages("zh").thinkingCurrentDefault("medium")).toContain("medium");
+ // The override form names both levels, so the distinction is readable in either locale.
+ for (const lang of ["en", "zh"] as const) {
+ const shown = getMessages(lang).thinkingCurrentOverride("high", "low");
+ expect(shown).toContain("high");
+ expect(shown).toContain("low");
+ expect(shown).not.toBe(getMessages(lang).thinkingCurrentDefault("high"));
+ }
+ expect(getMessages("en").thinkingSet("high")).toContain("high");
+ expect(getMessages("zh").thinkingSet("high")).toContain("high");
+ expect(getMessages("en").thinkingInvalid("none")).toContain('"none"');
+ expect(getMessages("zh").thinkingInvalid("none")).toContain('"none"');
+ expect(getMessages("en").toolOutputElided(42)).toContain("42");
+ expect(getMessages("zh").toolOutputElided(42)).toContain("42");
+ // The hints line teaches the two new commands in both languages.
+ expect(getMessages("en").chatHints()).toContain("/thinking");
+ expect(getMessages("en").chatHints()).toContain("/verbose");
+ expect(getMessages("zh").chatHints()).toContain("/thinking");
+ expect(getMessages("zh").chatHints()).toContain("/verbose");
});
it("header shows the version and Agent / Workspace / Model on their own lines", () => {
diff --git a/packages/cli/test/output-collapse.test.ts b/packages/cli/test/output-collapse.test.ts
new file mode 100644
index 00000000..f720276d
--- /dev/null
+++ b/packages/cli/test/output-collapse.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+import {
+ TOOL_OUTPUT_HEAD_LINES,
+ TOOL_OUTPUT_TAIL_LINES,
+ ToolOutputCollapser,
+ collapseLines,
+} from "../src/output-collapse.js";
+
+/** Numbered test lines l1..ln. */
+function lines(n: number, from = 1): string[] {
+ return Array.from({ length: n }, (_, i) => `l${from + i}`);
+}
+
+describe("ToolOutputCollapser (streaming head/tail collapse)", () => {
+ it("streams a short output through live, byte for byte (untouched)", () => {
+ const c = new ToolOutputCollapser();
+ expect(c.push("l1\nl2\n")).toBe("l1\nl2\n");
+ expect(c.push("l3")).toBe("l3");
+ expect(c.hasBuffered()).toBe(false);
+ expect(c.flush()).toEqual({ hidden: 0, lines: [] });
+ });
+
+ it("a head line split across chunks stays live until its newline spends the allowance", () => {
+ const c = new ToolOutputCollapser(2, 2);
+ expect(c.push("l1\nl2 sta")).toBe("l1\nl2 sta");
+ expect(c.push("rts here\n")).toBe("rts here\n"); // completes head line 2
+ expect(c.push("l3\n")).toBe(""); // allowance spent: held back
+ expect(c.hasBuffered()).toBe(true);
+ });
+
+ it("holds everything after the head allowance and prints it all when nothing was dropped", () => {
+ const c = new ToolOutputCollapser(2, 2);
+ expect(c.push("l1\nl2\nl3\nl4\n")).toBe("l1\nl2\n");
+ // 2 held lines <= tail+1: everything still fits, nothing hidden.
+ expect(c.flush()).toEqual({ hidden: 0, lines: ["l3", "l4"] });
+ });
+
+ it("head + tail + 1 lines print whole (the marker must hide at least 2 lines)", () => {
+ const c = new ToolOutputCollapser(2, 2);
+ expect(c.push("l1\nl2\nl3\nl4\nl5\n")).toBe("l1\nl2\n");
+ expect(c.flush()).toEqual({ hidden: 0, lines: ["l3", "l4", "l5"] });
+ });
+
+ it("elides the middle beyond head+tail+1 and reports the hidden count", () => {
+ const c = new ToolOutputCollapser(2, 2);
+ expect(c.push(`${lines(8).join("\n")}\n`)).toBe("l1\nl2\n");
+ // 8 lines: head l1-l2 live, l3-l6 hidden (4), tail l7-l8.
+ expect(c.flush()).toEqual({ hidden: 4, lines: ["l7", "l8"] });
+ });
+
+ it("an unterminated final line counts as a line", () => {
+ const c = new ToolOutputCollapser(2, 2);
+ expect(c.push("l1\nl2\nl3\nl4\nl5\nl6")).toBe("l1\nl2\n");
+ // Held: l3..l6 (l6 unterminated) -> l3 and l4 hidden, tail l5 l6.
+ expect(c.flush()).toEqual({ hidden: 2, lines: ["l5", "l6"] });
+ });
+
+ it("buffers with bounded memory across many chunks (drop counting stays exact)", () => {
+ const c = new ToolOutputCollapser(1, 3);
+ let live = "";
+ for (let i = 1; i <= 100; i++) live += c.push(`l${i}\n`);
+ expect(live).toBe("l1\n");
+ // 99 held lines, tail keeps the last 3, the other 96 are hidden.
+ expect(c.flush()).toEqual({ hidden: 96, lines: ["l98", "l99", "l100"] });
+ });
+
+ it("flush resets the held state (a settled collapser prints nothing more)", () => {
+ const c = new ToolOutputCollapser(1, 1);
+ c.push("l1\nl2\nl3\nl4\n");
+ c.flush();
+ expect(c.hasBuffered()).toBe(false);
+ expect(c.flush()).toEqual({ hidden: 0, lines: [] });
+ });
+});
+
+describe("collapseLines (complete outputs, resumed-history rendering)", () => {
+ it("keeps short outputs whole up to head+tail+1 lines", () => {
+ const nine = lines(TOOL_OUTPUT_HEAD_LINES + TOOL_OUTPUT_TAIL_LINES + 1);
+ expect(collapseLines(nine)).toEqual({ head: nine, hidden: 0, tail: [] });
+ });
+
+ it("splits longer outputs into head, hidden count, tail (hidden always >= 2)", () => {
+ const ten = lines(TOOL_OUTPUT_HEAD_LINES + TOOL_OUTPUT_TAIL_LINES + 2);
+ expect(collapseLines(ten)).toEqual({
+ head: lines(TOOL_OUTPUT_HEAD_LINES),
+ hidden: 2,
+ tail: lines(TOOL_OUTPUT_TAIL_LINES, 7),
+ });
+ });
+
+ it("honors custom head/tail sizes", () => {
+ expect(collapseLines(lines(6), 1, 1)).toEqual({ head: ["l1"], hidden: 4, tail: ["l6"] });
+ });
+});
diff --git a/packages/cli/test/render.test.ts b/packages/cli/test/render.test.ts
index 98d441e9..61e8924f 100644
--- a/packages/cli/test/render.test.ts
+++ b/packages/cli/test/render.test.ts
@@ -964,6 +964,171 @@ describe("renderHistory (resume)", () => {
});
});
+describe("tool-output collapsing (chat display; the Trace keeps the full text)", () => {
+ /** Streams one exec_command call and a `total`-line output through a renderer. */
+ function streamExec(r: StreamRenderer, total: number, id = "c9"): void {
+ r.handle(partialToolCall({ eventType: "start", name: "exec_command", toolCallId: id }));
+ r.handle(
+ partialToolCall({ eventType: "delta", name: "", arguments: '{"cmd":"x"}', toolCallId: id }),
+ );
+ r.handle(partialToolCall({ eventType: "stop", name: "", toolCallId: id }));
+ r.handle(partialToolCallOutput({ eventType: "start", toolCallId: id }));
+ for (let i = 1; i <= total; i++) {
+ r.handle(partialToolCallOutput({ eventType: "delta", output: `l${i}\n`, toolCallId: id }));
+ }
+ r.handle(partialToolCallOutput({ eventType: "stop", toolCallId: id }));
+ }
+
+ it("streams the head live, then settles marker + tail at stop; the hint names /verbose", () => {
+ const { stream, text } = collector();
+ const r = new StreamRenderer(stream, t, { collapseToolOutput: true });
+ streamExec(r, 12);
+ const s = stripAnsi(text());
+ // Head (first 4 lines) streamed live; l5..l8 hidden behind the marker; tail l9..l12.
+ expect(s).toBe(
+ "[tool-c9] exec_command <- $ x\n" +
+ "[tool-c9] exec_command -> l1\n" +
+ "[tool-c9] exec_command -> l2\n" +
+ "[tool-c9] exec_command -> l3\n" +
+ "[tool-c9] exec_command -> l4\n" +
+ `[tool-c9] exec_command -> ${t.toolOutputElided(4)}\n` +
+ "[tool-c9] exec_command -> l9\n" +
+ "[tool-c9] exec_command -> l10\n" +
+ "[tool-c9] exec_command -> l11\n" +
+ "[tool-c9] exec_command -> l12\n",
+ );
+ });
+
+ it("keeps short outputs untouched (up to head+tail+1 lines, no marker)", () => {
+ const { stream, text } = collector();
+ const r = new StreamRenderer(stream, t, { collapseToolOutput: true });
+ streamExec(r, 9);
+ const s = stripAnsi(text());
+ for (let i = 1; i <= 9; i++) expect(s).toContain(`exec_command -> l${i}\n`);
+ expect(s).not.toContain("/verbose");
+ });
+
+ it("default renderer (penguin run) never collapses", () => {
+ const { stream, text } = collector();
+ const r = new StreamRenderer(stream, t);
+ streamExec(r, 40);
+ const s = stripAnsi(text());
+ for (let i = 1; i <= 40; i++) expect(s).toContain(`exec_command -> l${i}\n`);
+ expect(s).not.toContain("/verbose");
+ });
+
+ it("setCollapseToolOutput(false) restores full output (the /verbose toggle)", () => {
+ const { stream, text } = collector();
+ const r = new StreamRenderer(stream, t, { collapseToolOutput: true });
+ r.setCollapseToolOutput(false);
+ streamExec(r, 12);
+ expect(stripAnsi(text())).toContain("exec_command -> l6\n");
+ });
+
+ it("a stream aborted before its stop still settles at endTask (held lines never vanish)", () => {
+ const { stream, text } = collector();
+ const r = new StreamRenderer(stream, t, { collapseToolOutput: true });
+ r.handle(partialToolCall({ eventType: "start", name: "exec_command", toolCallId: "c9" }));
+ r.handle(
+ partialToolCall({ eventType: "delta", name: "", arguments: '{"cmd":"x"}', toolCallId: "c9" }),
+ );
+ r.handle(partialToolCall({ eventType: "stop", name: "", toolCallId: "c9" }));
+ r.handle(partialToolCallOutput({ eventType: "start", toolCallId: "c9" }));
+ for (let i = 1; i <= 12; i++) {
+ r.handle(partialToolCallOutput({ eventType: "delta", output: `l${i}\n`, toolCallId: "c9" }));
+ }
+ // No stop delta: the turn aborted mid-stream; endTask must flush the held tail.
+ r.endTask(10);
+ const s = stripAnsi(text());
+ expect(s).toContain(t.toolOutputElided(4));
+ expect(s).toContain("exec_command -> l12\n");
+ expect(s).not.toContain("-> l5\n");
+ });
+
+ it("diff coloring survives collapsing for tail lines", () => {
+ vi.stubEnv("FORCE_COLOR", "1");
+ const { stream, text } = collector();
+ const r = new StreamRenderer(stream, t, { collapseToolOutput: true });
+ const id = "d9";
+ r.handle(partialToolCall({ eventType: "start", name: "edit_file", toolCallId: id }));
+ r.handle(
+ partialToolCall({
+ eventType: "delta",
+ name: "",
+ arguments: '{"file_path":"x.ts","old_string":"a","new_string":"b"}',
+ toolCallId: id,
+ }),
+ );
+ r.handle(partialToolCall({ eventType: "stop", name: "", toolCallId: id }));
+ r.handle(partialToolCallOutput({ eventType: "start", toolCallId: id }));
+ const body = Array.from({ length: 10 }, (_, i) => `ctx${i + 1}`);
+ r.handle(
+ partialToolCallOutput({
+ eventType: "delta",
+ output: `${body.join("\n")}\n-old\n+new\n`,
+ toolCallId: id,
+ }),
+ );
+ r.handle(partialToolCallOutput({ eventType: "stop", toolCallId: id }));
+ const raw = text();
+ expect(raw).toContain("\x1b[31m-old\x1b[0m");
+ expect(raw).toContain("\x1b[32m+new\x1b[0m");
+ expect(stripAnsi(raw)).toContain(t.toolOutputElided(4));
+ });
+
+ it("renderHistory collapses long tool outputs when asked (resume in chat)", () => {
+ const { stream, text } = collector();
+ const lines = Array.from({ length: 20 }, (_, i) => `l${i + 1}`).join("\n");
+ renderHistory(
+ [
+ toolCall({ name: "exec_command", arguments: '{"cmd":"ls"}', toolCallId: "call_653" }),
+ toolCallOutput({ output: lines, toolCallId: "call_653" }),
+ ],
+ stream,
+ t,
+ { collapseToolOutput: true },
+ );
+ const s = stripAnsi(text());
+ expect(s).toContain("[tool-653] exec_command -> l4\n");
+ expect(s).toContain(`[tool-653] exec_command -> ${t.toolOutputElided(12)}\n`);
+ expect(s).toContain("[tool-653] exec_command -> l17\n");
+ expect(s).toContain("[tool-653] exec_command -> l20\n");
+ expect(s).not.toContain("-> l5\n");
+ });
+
+ it("renderHistory reports the same hidden count as the live stream for a newline-terminated output", () => {
+ // Real tool output (exec_command streams the process bytes verbatim) ends in a newline;
+ // the trailing "" of the split must not be counted as a hidden line, nor eat a tail row.
+ const body = Array.from({ length: 12 }, (_, i) => `l${i + 1}`);
+ const live = collector();
+ const r = new StreamRenderer(live.stream, t, { collapseToolOutput: true });
+ streamExec(r, 12);
+ const history = collector();
+ renderHistory(
+ [
+ toolCall({ name: "exec_command", arguments: '{"cmd":"x"}', toolCallId: "call_0c9" }),
+ toolCallOutput({ output: `${body.join("\n")}\n`, toolCallId: "call_0c9" }),
+ ],
+ history.stream,
+ t,
+ { collapseToolOutput: true },
+ );
+ const historyText = stripAnsi(history.text());
+ expect(historyText).toContain(`exec_command -> ${t.toolOutputElided(4)}\n`);
+ expect(historyText).toContain("exec_command -> l12\n");
+ // No blank gutter row wasted on the trailing newline, and the live render agrees.
+ expect(historyText).not.toContain("exec_command -> \n");
+ expect(stripAnsi(live.text())).toContain(`exec_command -> ${t.toolOutputElided(4)}\n`);
+ });
+
+ it("renderHistory leaves outputs whole by default", () => {
+ const { stream, text } = collector();
+ const lines = Array.from({ length: 20 }, (_, i) => `l${i + 1}`).join("\n");
+ renderHistory([toolCallOutput({ output: lines, toolCallId: "call_653" })], stream, t);
+ expect(stripAnsi(text())).toContain("-> l10\n");
+ });
+});
+
describe("mid-run steering rendering ([user_steering] user messages)", () => {
it("streaming: a complete [user_steering] user text renders as prefixed steering lines (other complete texts stay unrendered)", () => {
const { stream, text } = collector();
diff --git a/packages/cli/test/task-loop.test.ts b/packages/cli/test/task-loop.test.ts
index 61751d1b..6e22bc1d 100644
--- a/packages/cli/test/task-loop.test.ts
+++ b/packages/cli/test/task-loop.test.ts
@@ -49,3 +49,19 @@ describe("runTask abort reporting", () => {
expect(result.aborted).toBe(false);
});
});
+
+describe("runTask option forwarding", () => {
+ it("forwards the per-turn thinking level to session.run (omitted when unset)", async () => {
+ const seen: Array<Record<string, unknown>> = [];
+ const session = {
+ async *run(_prompt: OmniMessage[], opts: Record<string, unknown>) {
+ seen.push(opts);
+ },
+ toolPermission: () => "rw",
+ } as unknown as Session;
+ await runTask(session, [], { renderer: silentRenderer(), t, thinkingLevel: "high" });
+ await runTask(session, [], { renderer: silentRenderer(), t });
+ expect(seen[0]!["thinkingLevel"]).toBe("high");
+ expect("thinkingLevel" in seen[1]!).toBe(false);
+ });
+});
diff --git a/packages/cli/test/thinking-command.test.ts b/packages/cli/test/thinking-command.test.ts
new file mode 100644
index 00000000..51ba01b8
--- /dev/null
+++ b/packages/cli/test/thinking-command.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import {
+ configuredThinkingLevel,
+ parseThinkingCommand,
+ parseThinkingLevel,
+} from "../src/thinking-command.js";
+import type { ThinkingConfigSource } from "../src/thinking-command.js";
+
+describe("parseThinkingLevel", () => {
+ it("accepts the four selectable tiers (trimmed, case-insensitive)", () => {
+ expect(parseThinkingLevel("low")).toBe("low");
+ expect(parseThinkingLevel("medium")).toBe("medium");
+ expect(parseThinkingLevel(" HIGH ")).toBe("high");
+ expect(parseThinkingLevel("xhigh")).toBe("xhigh");
+ });
+
+ it('rejects "none" (a valid stored value but never selectable, mirroring the web picker) and garbage', () => {
+ expect(parseThinkingLevel("none")).toBeNull();
+ expect(parseThinkingLevel("")).toBeNull();
+ expect(parseThinkingLevel("max")).toBeNull();
+ expect(parseThinkingLevel("x-high")).toBeNull();
+ });
+});
+
+describe("parseThinkingCommand", () => {
+ it("bare /thinking asks to show the current level", () => {
+ expect(parseThinkingCommand("/thinking")).toEqual({ ok: true, level: null });
+ expect(parseThinkingCommand(" /thinking ")).toEqual({ ok: true, level: null });
+ });
+
+ it("/thinking <level> selects a tier", () => {
+ expect(parseThinkingCommand("/thinking high")).toEqual({ ok: true, level: "high" });
+ expect(parseThinkingCommand("/thinking XHIGH ")).toEqual({ ok: true, level: "xhigh" });
+ });
+
+ it("reports the offending value for anything else", () => {
+ expect(parseThinkingCommand("/thinking none")).toEqual({ ok: false, value: "none" });
+ expect(parseThinkingCommand("/thinking turbo")).toEqual({ ok: false, value: "turbo" });
+ // Trailing extra tokens are part of the offending value, not silently dropped.
+ expect(parseThinkingCommand("/thinking high now")).toEqual({ ok: false, value: "high now" });
+ });
+});
+
+describe("configuredThinkingLevel (display mirror of core's resolution chain)", () => {
+ const source = (
+ agentLevel: "none" | "low" | "medium" | "high" | "xhigh" | undefined,
+ projectDefault: "low" | "medium" | "high" | "xhigh" | undefined,
+ ): ThinkingConfigSource => ({
+ state: { systemConfig: agentLevel ? { model: { thinking_level: agentLevel } } : {} },
+ projectConfig: projectDefault ? { default_chat: { thinking_level: projectDefault } } : {},
+ });
+
+ it("the Agent's explicit level wins over the Project default", () => {
+ expect(configuredThinkingLevel(source("high", "low"))).toBe("high");
+ });
+
+ it("falls back to the Project default, then the built-in medium", () => {
+ expect(configuredThinkingLevel(source(undefined, "xhigh"))).toBe("xhigh");
+ expect(configuredThinkingLevel(source(undefined, undefined))).toBe("medium");
+ });
+
+ it('a stored legacy "none" still displays as-is (never rewritten)', () => {
+ expect(configuredThinkingLevel(source("none", "high"))).toBe("none");
+ });
+});
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 434a2b2b..151bab32 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -27,6 +27,7 @@ penguin run -m "Summarize the code structure of this directory"
| `--agent-id <id>` | Agent to use |
| `--workspace <path>` | Workspace directory; defaults to the current directory and must exist |
| `--approve <mode>` | Approval mode, see below |
+| `--thinking <level>` | Thinking level for the Session: `low` / `medium` / `high` / `xhigh`. Omitted, the configured chain applies (the Agent's `model.thinking_level`, else the Project's `default_chat.thinking_level`, else `medium`). Pinned at Session creation, so spawned subagent sessions follow it |
## penguin chat
@@ -35,8 +36,9 @@ Interactive REPL; each input line starts a Task. Takes the same options as `run`
| Option | Description |
| --- | --- |
| `--resume [sessionId]` | Resume a Session; without an id, resumes the Agent's latest Session |
+| `--verbose` | Show full tool output; by default long tool outputs are collapsed (see below) |
-With `--resume`, the Workspace and model are locked by the original Session and cannot be overridden via `--workspace` / `--model-id` / `--provider`. On exit, a copy-pastable `penguin chat --resume <sessionId>` command is printed.
+With `--resume`, the Workspace and model are locked by the original Session and cannot be overridden via `--workspace` / `--model-id` / `--provider`. The thinking level is a per-turn parameter, so `--thinking` is still accepted: it becomes the initial `/thinking` override instead of a creation-time default. On exit, a copy-pastable `penguin chat --resume <sessionId>` command is printed.
In-REPL commands:
@@ -45,8 +47,13 @@ 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` |
+| `/thinking` | Show the thinking level the next turn will run at, and whether it is this Session's default or an active per-turn override (which also names the default it overrides) |
+| `/thinking <level>` | Override the thinking level (`low` / `medium` / `high` / `xhigh`) for subsequent turns of this chat; never written back to the Agent config. The override applies to this Session's own turns only — subagent sessions are spawned with the level the Session was created with |
+| `/verbose` | Toggle between collapsed and full tool output |
| `/exit`, `/quit` | Quit |
+Long tool outputs (an `exec_command` result, a whole file from `read_file`) are collapsed by default so they don't flood the screen: the first 4 lines stream live, and when the output finishes an elision marker (`… (+N lines, /verbose for full output)`) plus the last 4 lines are printed; outputs of up to 9 lines are shown in full. This is display-only — the model, the Trace, and the Web App always receive the complete output. `/verbose` (or starting with `--verbose`) turns collapsing off for subsequent outputs; resumed history (`--resume`) is collapsed the same way. `penguin run` never collapses: its output feeds pipes and nested CLIs.
+
Ctrl-C is state-dependent:
| State | Behavior |
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 1bdb479d..cde8ca2c 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -27,6 +27,7 @@ penguin run -m "总结当前目录的代码结构"
| `--agent-id <id>` | 指定 Agent |
| `--workspace <path>` | Workspace 目录,默认当前目录,必须已存在 |
| `--approve <mode>` | 审批模式,见下文 |
+| `--thinking <level>` | 本 Session 的思考等级:`low` / `medium` / `high` / `xhigh`。省略时按配置链取值(Agent 的 `model.thinking_level`,其次 Project 的 `default_chat.thinking_level`,最后 `medium`)。在 Session 创建时钉定,派生的子会话随之生效 |
## penguin chat
@@ -35,8 +36,9 @@ penguin run -m "总结当前目录的代码结构"
| 选项 | 说明 |
| --- | --- |
| `--resume [sessionId]` | 恢复指定 Session;省略 id 时恢复该 Agent 最近的 Session |
+| `--verbose` | 显示完整工具输出;缺省折叠过长的工具输出(见下文) |
-使用 `--resume` 时,Workspace 与模型由原 Session 锁定,不可再用 `--workspace` / `--model-id` / `--provider` 覆盖。退出时会打印可直接复制的 `penguin chat --resume <sessionId>` 命令。
+使用 `--resume` 时,Workspace 与模型由原 Session 锁定,不可再用 `--workspace` / `--model-id` / `--provider` 覆盖。思考等级是逐轮参数,`--resume` 下仍接受 `--thinking`:它作为初始的 `/thinking` 覆盖生效,而不是创建时的缺省值。退出时会打印可直接复制的 `penguin chat --resume <sessionId>` 命令。
REPL 内命令:
@@ -45,8 +47,13 @@ REPL 内命令:
| 运行中输入任意文字 | 运行中插话:排队后以 `[user_steering]` 用户消息随下一轮送达模型(`»` 确认行会回显文字);输入期间渲染暂挂,流式输出不会打断正在输入的行。若 Task 恰好已结束,该行作为下一条普通消息发送 |
| `/compact` | 主动压缩当前上下文 |
| `/clear` | 原地开启全新空白 Session;原会话保留在磁盘上,仍可用 `--resume` 恢复 |
+| `/thinking` | 显示下一轮将使用的思考等级,并区分它是本 Session 的缺省值还是生效中的逐轮覆盖值(后者同时给出被覆盖的缺省值) |
+| `/thinking <level>` | 覆盖本次对话后续轮次的思考等级(`low` / `medium` / `high` / `xhigh`);不会写回 Agent 配置。该覆盖只作用于本 Session 自己的轮次——派生的子会话仍按 Session 创建时的等级启动 |
+| `/verbose` | 在折叠与完整工具输出之间切换 |
| `/exit`、`/quit` | 退出 |
+过长的工具输出(`exec_command` 的结果、`read_file` 读回的整个文件)缺省折叠显示,避免刷屏:前 4 行照常流式打印,输出结束时打印省略标记(`……(另有 N 行,/verbose 显示完整输出)`)与最后 4 行;不超过 9 行的输出完整显示。这只是显示层截断——模型、Trace 与 Web App 收到的始终是完整输出。`/verbose`(或启动时加 `--verbose`)可关闭折叠、对后续输出生效;`--resume` 恢复的历史按同一规则折叠。`penguin run` 从不折叠:它的输出供管道与嵌套 CLI 消费。
+
Ctrl-C 的行为依状态而定:
| 状态 | 行为 |