Skip to content

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

The CLI becomes a thin client of the server, and agents get a local control plane (#466)

Yaowei Zheng460a960d8989
diff --git a/changelog/unreleased/2026-08-25-backward-compatibility.md b/changelog/unreleased/2026-08-25-backward-compatibility.md
new file mode 100644
index 00000000..23bebe9a
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-backward-compatibility.md
@@ -0,0 +1,43 @@
+# Backward compatibility
+
+- **Date:** 2026-08-25
+- **Type:** process
+- **Scope:** `cli`, `server`, `web`
+- **PR:** [#466](https://github.com/Prism-Shadow/penguin-harness/pull/466)
+- **Breaking:** yes — old CLI binaries ran tasks core-direct and offline; the rebuilt commands require a server (auto-started locally) and the per-user "show CLI sessions" preference is gone
+
+[中文版](2026-08-25-backward-compatibility.zh.md)
+
+The CLI-on-server batch touches three kinds of existing state. What breaks without
+handling, and what was chosen:
+
+## Legacy CLI-direct traces on disk
+
+Sessions run by the old core-direct CLI exist only as Trace files, with no row in the
+server's session index. Without handling they would silently vanish from every list now
+that lists are pure-SQLite. Chosen: a **startup adoption sweep** — once per server boot the
+trace tree is walked (through the existing mtime-gated TraceIndexService discovery path)
+and every unmanaged session is adopted as a `client:'cli'` index row; afterwards lists
+never scan the filesystem. The sweep is idempotent and stays for as long as pre-server
+CLI traces can exist on disk, i.e. indefinitely at negligible cost (one gated reconcile
+per boot); removing it would orphan any root restored from an old backup.
+
+## The retired `showCliSessions` preference
+
+The per-user pref and its `cli=1` query parameter are gone; every session is always
+listed. A stored `showCliSessions` key in `ui_prefs` is simply ignored by the shallow
+merge — stale JSON keys are tolerated forever by design, so no migration runs and nothing
+needs cleaning up. Users who kept the toggle off will now see their old CLI sessions in
+the sidebar and the trace tree; that is the intended new behavior, not a bug. External
+API callers still sending `cli=1` get the parameter ignored (the listing is already the
+superset they asked for).
+
+## Old CLI binaries and the new transport
+
+The old `penguin run` / `penguin chat` executed tasks in-process against core, worked with
+no server, and left server-invisible traces. The rebuilt commands are server-backed: with
+no server running they auto-start one locally (exit with a clear error only when the
+entry is not re-runnable, e.g. a tsx dev run). Accepted break, stated here: fully offline
+core-direct execution is no longer a CLI mode — the SDK keeps that capability for
+embedders. Old binaries keep working against their own cores until updated; nothing on
+disk stops them.
diff --git a/changelog/unreleased/2026-08-25-backward-compatibility.zh.md b/changelog/unreleased/2026-08-25-backward-compatibility.zh.md
new file mode 100644
index 00000000..5655d8f9
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-backward-compatibility.zh.md
@@ -0,0 +1,36 @@
+# 向后兼容
+
+- **Date:** 2026-08-25
+- **Type:** process
+- **Scope:** `cli`, `server`, `web`
+- **PR:** [#466](https://github.com/Prism-Shadow/penguin-harness/pull/466)
+- **Breaking:** yes — 旧 CLI 二进制直连 core、可离线运行;重建后的命令依赖服务端(本机自动拉起),按用户的「显示 CLI 会话」偏好随之移除
+
+[English](2026-08-25-backward-compatibility.md)
+
+CLI 直连服务端这一批改动触及三类存量状态。不处理会发生什么、以及选定的方案:
+
+## 磁盘上的存量 CLI 直连 Trace
+
+旧的 core 直连 CLI 跑出的会话只存在于 Trace 文件里,服务端会话索引中没有对应行。若不处
+理,在列表改为纯 SQLite 渲染后它们会从所有列表里悄然消失。选定方案:**启动收编对账**——
+服务端每次启动遍历一次 Trace 树(复用既有的 mtime 门控 TraceIndexService 发现路径),把
+每个无索引会话收编为 `client:'cli'` 索引行;此后列表永不扫描文件系统。对账幂等,保留期
+与「磁盘上可能存在旧 CLI Trace」等长,即无限期保留(代价可忽略:每次启动一轮门控对账);
+移除它会让从旧备份还原的数据根丢失这些会话。
+
+## 退役的 `showCliSessions` 偏好
+
+按用户的偏好键与 `cli=1` 查询参数一并移除;所有会话恒被列出。`ui_prefs` 中已存的
+`showCliSessions` 键由浅合并直接忽略——陈旧 JSON 键本就被设计为永久容忍,因此不跑迁移、
+也无需清理。此前保持开关关闭的用户现在会在侧栏与轨迹树里看到自己的旧 CLI 会话;这是有意
+的新行为,不是缺陷。仍发送 `cli=1` 的外部 API 调用方会看到参数被忽略(列表本就是他们所要
+的超集)。
+
+## 旧 CLI 二进制与新传输
+
+旧的 `penguin run` / `penguin chat` 在进程内直连 core 执行任务,无需服务端,留下的 Trace
+服务端不可见。重建后的命令走服务端:本机没有服务器时自动拉起一个(仅在入口无法重跑时报
+明确错误,如 tsx 开发态运行)。接受并在此声明的不兼容:完全离线的 core 直连执行不再是
+CLI 的一种模式——SDK 为嵌入方保留该能力。旧二进制在升级前仍按自己的 core 正常工作,磁盘
+上没有任何东西会阻止它们。
diff --git a/changelog/unreleased/2026-08-25-cli-on-server.md b/changelog/unreleased/2026-08-25-cli-on-server.md
new file mode 100644
index 00000000..556e76b3
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-cli-on-server.md
@@ -0,0 +1,131 @@
+# The CLI becomes a thin client of the server, and agents get a local control plane
+
+- **Date:** 2026-08-25
+- **Type:** feature
+- **Scope:** `cli`, `server`, `core`, `web`, `docs`
+- **PR:** [#466](https://github.com/Prism-Shadow/penguin-harness/pull/466)
+
+[中文版](2026-08-25-cli-on-server.zh.md)
+
+`penguin run` and `penguin chat` were rebuilt on the server API — the CLI now parses
+arguments, sends HTTP/SSE requests, and renders the streamed OmniMessages, while the task
+itself executes on the server. Everything the CLI creates shows up in the Web App and vice
+versa, and a new command family lets agents inside PenguinHarness drive the harness through
+the CLI: list sessions, send messages into them, follow logs, create agents, and query
+costs and schedules. A CLI talking to the local machine's server needs no login.
+
+## The command surface
+
+```
+penguin run -m <msg> [--project-id] [--agent-id] [--workspace] [--model-id --provider]
+ [--approve] [--thinking] [--session <id>] [--background] [--timeout <dur>]
+ [--goal [budget]] [--json] [--server <url>]
+penguin chat [--project-id] [--agent-id] [--workspace] [--model-id --provider] [--approve]
+ [--thinking] [--resume [id]] [--verbose] [--server]
+penguin ls [--project-id] [--agent-id] [-a|--all] [--days <n>] [--json] [--server]
+penguin input [session_id] [-m <text>] [--timeout <dur>] [--project-id] [--agent-id]
+ [--json] [--server]
+penguin logs [session_id] [--tail <n>] [-f|--follow] [--timeout <dur>] [--project-id]
+ [--agent-id] [--json] [--server]
+penguin agent ls|create ...
+penguin project ls
+penguin cost [--days <n>] [--from --to] [--by date|agent|model|session] ...
+penguin schedule ls|add|update|rm ...
+```
+
+- `run` creates a session (or reuses `--session` — a full id or any unique fragment, such
+ as the 8-hex tail `penguin ls` prints), posts the task, renders the stream to the stats
+ line, and exits 0 on completed (goal runs exit 0 only on `complete`). `--background`
+ returns the session id immediately; `--json` prints a final `{sessionId, status, text}`.
+- `input` steers a running session and starts a task on an idle one; `logs -f` follows the
+ live stream read-only.
+- `--project-id` / `--agent-id` default to `PENGUIN_PROJECT_ID` / `PENGUIN_AGENT_ID`, then
+ `default_project` / `default_agent`.
+
+## Connection and authentication
+
+- Resolution order: `--server` > `PENGUIN_API_URL` > a live `server.lock` at the data root
+ > auto-start (a detached `node <cli> server` with `PORT=0`, logging to
+ `<root>/logs/server-auto-<date>.log`; the loser of a concurrent spawn race exits and
+ both CLIs attach to the winner's lock).
+- The server mints a local API token every boot and writes it to `<root>/api-token`
+ (0600). `authMiddleware` accepts it as `Authorization: Bearer` (constant-time compare)
+ and authenticates the caller as the built-in admin — on SSE endpoints too. The CLI reads
+ `PENGUIN_API_TOKEN`, else the file (loopback targets only; a 401 re-reads it once); a
+ remote `--server` without `PENGUIN_API_TOKEN` is refused with instructions.
+- The authorization model is deliberate: local filesystem access to the data root already
+ is admin authority — the `penguin server reset-admin-password` rule. An earlier on-disk
+ token was removed over exactly this property; that objection is reversed on purpose,
+ because agents driving their own server through the CLI is the feature.
+
+## Control env injection
+
+Server-driven sessions inject into every tool subprocess: `PENGUIN_API_URL` (the server's
+own canonical base URL), `PENGUIN_API_TOKEN` (the current boot token),
+`PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID`, `PENGUIN_SESSION_ID`. The seam is
+`CreateAgentOptions.controlEnv`, a policy getter mirroring `proxyEnv`: core binds it to
+each Session's own coordinates and re-evaluates it at every spawn; injected entries
+override vault entries of the same name; subagent sessions evaluate it with their own ids;
+SDK/CLI-direct embedding without the option injects nothing.
+
+## Agent-side ergonomics
+
+- **Caller-context defaults**: inside a harness agent (`PENGUIN_SESSION_ID` present), a
+ session created by `run` / `chat` defaults each unspecified field to the calling
+ session's live values (`GET /api/sessions/$PENGUIN_SESSION_ID`) — Workspace, the model
+ pair, approval mode and thinking level — the same inheritance `run_subagent` applies to
+ spawned children. Per field: explicit flag > caller value > plain fallback; a failed
+ lookup warns (dim) and falls back; outside an agent nothing changes.
+- **`--timeout <duration>` soft yield** on `run` (non-background), `input` and `logs -f`:
+ wait up to the budget (`30s` / `5m` / `2h`, or bare seconds), then detach cleanly —
+ exit 0, a dim still-running line with the session id (`status: "running"` under
+ `--json`) — while the task keeps running server-side, mirroring the command tools'
+ yield-window semantics. No flag = wait indefinitely.
+- **Bare `penguin input <session>` (no `-m`) polls**: prints the session's most recent
+ complete assistant text (an idempotent last-answer snapshot; thinking and tool output
+ skipped), mirroring `input_subagent`'s empty-prompt semantics — nothing queued, nothing
+ steered. A running session is waited on silently (bounded by `--timeout` when given);
+ still running at expiry prints the current latest text plus the still-running note.
+- **`--timeout 0` replaces `input --no-wait`** (the surface was unreleased): the one
+ timeout knob covers "don't wait" — deliver, then return immediately with the
+ still-running note (`{sessionId, status: "running"}` under `--json`); `run --timeout 0`
+ behaves the same for symmetry, while `run --background` stays the idiomatic
+ fire-and-forget for new tasks (bare session id for scripts).
+- **`penguin ls --days <n>`**: only sessions last active within the trailing n calendar
+ days (today counts as day 1 — `cost --days` semantics); combines with `-a` and
+ `--json`.
+- **`penguin schedule add|update|rm <name>`**: a validated writer over the schedules
+ API — the API writes the TOML file, which remains the single source of truth (the
+ model-config/vault pattern), and API errors surface verbatim for synchronous
+ validation. Target is `--session-id` XOR the new-session form; `--start-at now` means
+ the current instant. One deliberate divergence: `add` defaults to enabled (`--disabled`
+ opts out; the raw file's enabled=false default stays for hand edits); `update` is
+ read-modify-write; `rm` deletes without prompting.
+- **The session id is optional on `input` and `logs`**: omitted, it means the agent's
+ most recent session — the default `chat --resume` already carried, off the same
+ newest-first listing — announced as a dim `[latest]` line on stderr, so the target is
+ never ambiguous and `--json` on stdout stays parseable. Bare `penguin logs` is
+ therefore "what just happened" and bare `penguin input` is "what did my agent last
+ say"; `--agent-id` picks whose. An agent with no session at all gets one line pointing
+ at `penguin run` / `penguin chat`, and a non-zero exit.
+- **The `penguin-orchestration` skill tracks the surface**: the shipped skill's command
+ block and its session-targeting notes now carry the optional session id on `input` /
+ `logs` and the `--agent-id` that picks whose (skill version 2).
+
+## Argument errors speak the interface language
+
+A command typed wrong prints one localized line — missing argument, missing required
+option, unknown option, mistyped command — followed by that command's own usage and a
+pointer at its `--help`, in place of commander's raw English. Exit codes stay commander's.
+The `ExperimentalWarning: SQLite is an experimental feature` that Node raises while the
+CLI's module graph loads is filtered at the entry point, on the packaged binary and the
+development run alike; every other warning still prints.
+
+## The CLI-session toggle is retired
+
+Sessions created through the API now carry a `client` hint (`"cli"` from the CLI, default
+`"web"`), stored on the existing column as provenance only — list endpoints stopped
+filtering by client, and the `cli=1` query parameter, the `showCliSessions` preference and
+its settings toggle were removed. Legacy CLI-direct traces are adopted once per server
+boot by a startup sweep; see
+[backward compatibility](2026-08-25-backward-compatibility.md).
diff --git a/changelog/unreleased/2026-08-25-cli-on-server.zh.md b/changelog/unreleased/2026-08-25-cli-on-server.zh.md
new file mode 100644
index 00000000..8dbd230e
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-cli-on-server.zh.md
@@ -0,0 +1,112 @@
+# CLI 重建为服务端瘦客户端,Agent 获得本机控制面
+
+- **Date:** 2026-08-25
+- **Type:** feature
+- **Scope:** `cli`, `server`, `core`, `web`, `docs`
+- **PR:** [#466](https://github.com/Prism-Shadow/penguin-harness/pull/466)
+
+[English](2026-08-25-cli-on-server.md)
+
+`penguin run` 与 `penguin chat` 重建在服务端 API 之上——CLI 只负责解析参数、发 HTTP/SSE
+请求并渲染流式 OmniMessage,Task 本身在服务端执行。CLI 创建的一切都出现在 Web App 里
+(反之亦然);新增的一组命令让 PenguinHarness 内部的 Agent 也能经 CLI 驱动 harness:列出
+会话、向会话发消息、跟随日志、创建 Agent、查询成本与定时任务。连接本机服务器的 CLI 无需
+登录。
+
+## 命令面
+
+```
+penguin run -m <msg> [--project-id] [--agent-id] [--workspace] [--model-id --provider]
+ [--approve] [--thinking] [--session <id>] [--background] [--timeout <dur>]
+ [--goal [budget]] [--json] [--server <url>]
+penguin chat [--project-id] [--agent-id] [--workspace] [--model-id --provider] [--approve]
+ [--thinking] [--resume [id]] [--verbose] [--server]
+penguin ls [--project-id] [--agent-id] [-a|--all] [--days <n>] [--json] [--server]
+penguin input [session_id] [-m <text>] [--timeout <dur>] [--project-id] [--agent-id]
+ [--json] [--server]
+penguin logs [session_id] [--tail <n>] [-f|--follow] [--timeout <dur>] [--project-id]
+ [--agent-id] [--json] [--server]
+penguin agent ls|create ...
+penguin project ls
+penguin cost [--days <n>] [--from --to] [--by date|agent|model|session] ...
+penguin schedule ls|add|update|rm ...
+```
+
+- `run` 创建 Session(或以 `--session` 复用——接受完整 id 或任意唯一片段,如 `penguin ls`
+ 打印的末尾 8 位十六进制),提交任务并渲染流式输出直至统计行,完成退出 0(goal 运行仅
+ `complete` 退出 0)。`--background` 立即返回 session id;`--json` 输出最终的
+ `{sessionId, status, text}`。
+- `input` 对运行中的会话是插话,对空闲会话发起新任务;`logs -f` 只读跟随实时流。
+- `--project-id` / `--agent-id` 缺省依次取 `PENGUIN_PROJECT_ID` / `PENGUIN_AGENT_ID`,再退到
+ `default_project` / `default_agent`。
+
+## 连接与鉴权
+
+- 解析顺序:`--server` > `PENGUIN_API_URL` > 数据根目录下存活的 `server.lock` > 自动拉起
+ (分离子进程 `node <cli> server`、`PORT=0`,日志写 `<root>/logs/server-auto-<date>.log`;
+ 并发拉起竞争的输家自行退出,双方都附着到赢家的锁)。
+- 服务端每次启动铸造本机 API token 并写入 `<root>/api-token`(0600)。`authMiddleware`
+ 接受 `Authorization: Bearer`(恒定时比较),认证为内置 admin——SSE 端点亦然。CLI 依次取
+ `PENGUIN_API_TOKEN`、token 文件(仅回环目标;401 时重读一次);远端 `--server` 无
+ `PENGUIN_API_TOKEN` 时明确拒绝并给出设置指引。
+- 授权模型是有意为之:对数据根目录的本机文件系统访问本就等于管理员权限——与
+ `penguin server reset-admin-password` 同一条规则。早先的磁盘 token 正是因这一性质被移除;
+ 该反对被有意反转,因为 Agent 经 CLI 驱动自己的服务器正是要交付的功能。
+
+## 控制环境注入
+
+服务端驱动的会话向每个工具子进程注入:`PENGUIN_API_URL`(服务端自身规范地址)、
+`PENGUIN_API_TOKEN`(本次启动的 token)、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID`、
+`PENGUIN_SESSION_ID`。接缝是 `CreateAgentOptions.controlEnv`——与 `proxyEnv` 同构的策略
+getter:core 按各 Session 自身坐标绑定、逐次 spawn 重新求值;注入条目覆盖 vault 同名条目;
+子会话以自己的 id 求值;SDK / CLI 直连嵌入不提供该选项时不注入任何内容。
+
+## Agent 侧易用性
+
+- **调用方上下文缺省值**:在 harness Agent 内部(存在 `PENGUIN_SESSION_ID`)时,`run` /
+ `chat` 新建会话的每个未指定字段都缺省取调用方会话的实时值(`GET
+ /api/sessions/$PENGUIN_SESSION_ID`)——Workspace、模型对、审批模式与思考等级——与
+ `run_subagent` 派生子会话的继承同一条约定。逐字段优先级:显式选项 > 调用方值 > 普通缺省;
+ 查询失败打印暗色警告并回落;不在 Agent 内时一切不变。
+- **`--timeout <duration>` 软让出**(`run` 非 background、`input`、`logs -f`):最多等待该
+ 预算(`30s` / `5m` / `2h` 或纯数字秒数),到期干净脱开——退出 0,打印一行暗色「仍在运行」
+ (含 session id;`--json` 下 `status: "running"`)——任务继续在服务端运行,与命令工具的
+ yield 窗口语义互为镜像。不带该选项即无限等待。
+- **不带 `-m` 的 `penguin input <session>` 即轮询**:打印该会话最近一条完整助手文本(幂等的
+ 「最新答案」快照;跳过思考与工具输出),与 `input_subagent` 的空 prompt 语义互为镜像——不
+ 排队、不插话。运行中的会话先静默等待(给出 `--timeout` 时以其为限);到期仍在运行则打印当
+ 前最新文本并附仍在运行提示。
+- **`--timeout 0` 取代 `input --no-wait`**(该表面尚未发布):一个 timeout 旋钮同时覆盖「不
+ 等待」——送达后立即返回并附仍在运行提示(`--json` 下为 `{sessionId, status: "running"}`);
+ `run --timeout 0` 对称同义,而 `run --background` 保留为新建任务的惯用「发完即走」(为脚本
+ 打印裸 session id)。
+- **`penguin ls --days <n>`**:只列最近 n 个自然日内活跃过的会话(今天算第 1 天,与
+ `cost --days` 同口径);可与 `-a`、`--json` 组合。
+- **`penguin schedule add|update|rm <name>`**:映射既有 schedules API 的带校验写入器——由 API
+ 写 TOML 文件,文件仍为唯一真相源(与模型配置 / vault 同一模式),API 错误原样透出、校验同
+ 步呈现。目标为 `--session-id` 与新建会话形式二选一(XOR);`--start-at now` 即当前时刻。一
+ 处有意分歧:`add` 缺省启用(`--disabled` 关闭;原始文件的 enabled=false 缺省留给手编);
+ `update` 为读改写;`rm` 直接删除、不做确认。
+- **`input` 与 `logs` 的 session id 可省**:省略即指当前 Agent 最近一次会话——`chat --resume`
+ 本就有的缺省,取自同一份最新在前的列表——并在 stderr 打印一行暗色 `[latest]` 说明选中了
+ 哪个,目标因此从不含糊,stdout 上的 `--json` 也仍可解析。于是裸 `penguin logs` 就是「刚才
+ 发生了什么」,裸 `penguin input` 就是「我的 Agent 最后说了什么」;`--agent-id` 决定是哪个
+ Agent。该 Agent 一个会话都没有时,打印一行指向 `penguin run` / `penguin chat` 的提示,并以
+ 非零码退出。
+- **`penguin-orchestration` Skill 跟上命令面**:随包发布的该 Skill,其命令块与会话定位说明
+ 现已包含 `input` / `logs` 可省的 session id,以及决定是哪个 Agent 的 `--agent-id`(Skill
+ 版本 2)。
+
+## 参数错误按界面语言呈现
+
+命令写错时打印一行本地化说明——缺少参数、缺少必填选项、未知选项、命令拼错——随后是该命令自身
+的用法与 `--help` 指引,取代 commander 的原始英文。退出码仍是 commander 的那一套。CLI 模块图
+加载时 Node 抛出的 `ExperimentalWarning: SQLite is an experimental feature` 在入口处被滤掉,
+发布二进制与开发态运行一视同仁;其余警告照常打印。
+
+## 「显示 CLI 会话」开关退役
+
+经 API 创建的 Session 现在携带 `client` 标记(CLI 传 `"cli"`,缺省 `"web"`),存入既有列、
+仅作来源信息——列表端点不再按客户端过滤,`cli=1` 查询参数、`showCliSessions` 偏好及其设置
+开关一并移除。存量 CLI 直连留下的 Trace 由服务端每次启动的收编对账一次性并入;见
+[向后兼容](2026-08-25-backward-compatibility.zh.md)。
diff --git a/packages/cli/src/client.ts b/packages/cli/src/client.ts
new file mode 100644
index 00000000..1a254145
--- /dev/null
+++ b/packages/cli/src/client.ts
@@ -0,0 +1,424 @@
+/**
+ * The CLI's server client: connection resolution, Bearer-token auth, JSON requests, and
+ * a dependency-free fetch-based SSE consumer (the HMR deploy path bundles this file with
+ * esbuild, so everything here rides on globals — fetch above all).
+ *
+ * Connection resolution order (first hit wins):
+ * 1. `--server <url>` — an explicit target. A non-loopback URL requires
+ * PENGUIN_API_TOKEN: the on-disk token file belongs to the LOCAL data root and must
+ * never be sent to a remote host.
+ * 2. `PENGUIN_API_URL` — the same, from the environment. Server-driven sessions inject
+ * it (with PENGUIN_API_TOKEN) into tool subprocesses, which is how an agent's own
+ * `penguin` calls find the server that runs them.
+ * 3. A live `server.lock` at the data root (PENGUIN_HOME or ~/.penguin/data): attach to
+ * the running local server on `http://localhost:<port>`.
+ * 4. Auto-start: spawn a detached `node <cli entry> server` with PORT=0, wait for its
+ * lock, attach. The loser of a two-CLI spawn race exits with code 3 ("already
+ * running"), which the lock poll absorbs — it finds the winner's lock either way.
+ *
+ * Token resolution: PENGUIN_API_TOKEN, else `<root>/api-token` (written by the server
+ * each boot). A 401 with a file-sourced token re-reads the file once and retries — the
+ * server may have restarted (and rotated the token) since the first read.
+ */
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { resolveRoot } from "@prismshadow/penguin-core";
+import { liveServerLock } from "@prismshadow/penguin-server/lock";
+import type { Messages } from "./i18n.js";
+
+/** Session-id shape (core's convention); a full id needs no directory search. */
+const SESSION_ID_RE = /^session-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}-[0-9a-f]{8}$/;
+
+/** Hosts that count as this machine for token-file purposes. */
+const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
+
+/** How the auth token was obtained; decides whether a 401 retries after re-reading the file. */
+export type TokenSource = "env" | "file" | "none";
+
+export interface Connection {
+ /** Normalized base URL, no trailing slash. */
+ baseUrl: string;
+ /** Data root used for the token file and the lock (resolution-time value). */
+ root: string;
+ /** Whether this call auto-started the server (surfaced to the user on stderr). */
+ autoStarted: boolean;
+ /** Whether the target host is loopback (gates the file-token fallback). */
+ loopback: boolean;
+}
+
+/** One parsed SSE frame; `data` is the raw payload (possibly multi-line joined). */
+export interface SseFrame {
+ id?: string;
+ event?: string;
+ data: string;
+}
+
+export function isLoopbackUrl(url: URL): boolean {
+ return LOOPBACK_HOSTS.has(url.hostname.toLowerCase());
+}
+
+/** Strips trailing slashes and validates the scheme; throws a localized error on junk. */
+export function normalizeServerUrl(raw: string, t: Messages): URL {
+ let url: URL;
+ try {
+ url = new URL(raw.trim());
+ } catch {
+ throw new Error(t.client.invalidServerUrl(raw));
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ throw new Error(t.client.invalidServerUrl(raw));
+ }
+ return url;
+}
+
+/** The token file the server writes each boot (kept in sync with the server's auth/api-token.ts). */
+export function apiTokenPath(root: string): string {
+ return path.join(root, "api-token");
+}
+
+function readTokenFile(root: string): string | null {
+ try {
+ const value = fs.readFileSync(apiTokenPath(root), "utf8").trim();
+ return value === "" ? null : value;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The CLI entry script for auto-start, or null when this process cannot re-run itself
+ * with plain node (a tsx dev run has a .ts entry) — same rule as serve.ts's cliEntryFor.
+ */
+export function autoStartEntry(argv1: string | undefined): string | null {
+ if (!argv1) return null;
+ return /\.(js|mjs|cjs)$/i.test(argv1) ? path.resolve(argv1) : null;
+}
+
+/** yyyy-mm-dd of the local clock (log file naming). */
+function localDate(d = new Date()): string {
+ const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+}
+
+/**
+ * Spawns a detached local server (PORT=0 → ephemeral port), logs to
+ * `<root>/logs/server-auto-<date>.log`, and waits for a live lock on the root. The lock
+ * poll accepts ANY live server on the root: if a concurrent CLI won the spawn race, our
+ * child exits 3 and the winner's lock satisfies the wait just the same.
+ */
+export async function autoStartServer(
+ root: string,
+ t: Messages,
+ opts: { timeoutMs?: number } = {},
+): Promise<{ port: number; logPath: string }> {
+ const entry = autoStartEntry(process.argv[1]);
+ if (entry === null) throw new Error(t.client.autoStartUnavailable());
+ fs.mkdirSync(path.join(root, "logs"), { recursive: true });
+ const logPath = path.join(root, "logs", `server-auto-${localDate()}.log`);
+ const fd = fs.openSync(logPath, "a");
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(process.execPath, [entry, "server"], {
+ detached: true,
+ stdio: ["ignore", fd, fd],
+ env: { ...process.env, PORT: "0" },
+ });
+ } finally {
+ fs.closeSync(fd);
+ }
+ let exitCode: number | null = null;
+ child.on("error", () => {
+ exitCode = -1;
+ });
+ child.on("exit", (code) => {
+ exitCode = code ?? -1;
+ });
+ child.unref();
+
+ const deadline = Date.now() + (opts.timeoutMs ?? 20_000);
+ for (;;) {
+ const lock = await liveServerLock(root);
+ if (lock !== null) return { port: lock.port, logPath };
+ // Exit 3 = "another server owns this root" — the race's loser; keep polling for the
+ // winner's lock. Any other exit is a startup failure: point at the log.
+ if (exitCode !== null && exitCode !== 3) {
+ throw new Error(t.client.autoStartFailed(logPath));
+ }
+ if (Date.now() >= deadline) throw new Error(t.client.autoStartFailed(logPath));
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+}
+
+/** Resolves where to connect (see the module doc for the order); may auto-start a server. */
+export async function resolveConnection(
+ opts: { server?: string; autoStart?: boolean },
+ t: Messages,
+): Promise<Connection> {
+ const root = resolveRoot();
+ const explicit = opts.server?.trim() || process.env.PENGUIN_API_URL?.trim() || "";
+ if (explicit !== "") {
+ const url = normalizeServerUrl(explicit, t);
+ const loopback = isLoopbackUrl(url);
+ if (!loopback && !process.env.PENGUIN_API_TOKEN?.trim()) {
+ throw new Error(t.client.remoteNeedsToken(url.origin));
+ }
+ return { baseUrl: url.origin, root, autoStarted: false, loopback };
+ }
+ const lock = await liveServerLock(root);
+ if (lock !== null) {
+ return { baseUrl: `http://localhost:${lock.port}`, root, autoStarted: false, loopback: true };
+ }
+ if (opts.autoStart === false) throw new Error(t.client.noServer());
+ const { port, logPath } = await autoStartServer(root, t);
+ const conn: Connection = {
+ baseUrl: `http://localhost:${port}`,
+ root,
+ autoStarted: true,
+ loopback: true,
+ };
+ process.stderr.write(`${t.client.autoStarted(conn.baseUrl, logPath)}\n`);
+ return conn;
+}
+
+/** Error the client raises for non-2xx responses; `code` is the server's error code when the body carried one. */
+export class ApiError extends Error {
+ constructor(
+ readonly status: number,
+ readonly code: string,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+export class ServerClient {
+ private token: string | null;
+ private tokenSource: TokenSource;
+
+ constructor(
+ readonly conn: Connection,
+ private readonly t: Messages,
+ ) {
+ const envToken = process.env.PENGUIN_API_TOKEN?.trim();
+ if (envToken) {
+ this.token = envToken;
+ this.tokenSource = "env";
+ } else if (conn.loopback) {
+ this.token = readTokenFile(conn.root);
+ this.tokenSource = this.token !== null ? "file" : "none";
+ } else {
+ this.token = null;
+ this.tokenSource = "none";
+ }
+ }
+
+ private headers(extra: Record<string, string> = {}): Record<string, string> {
+ return {
+ ...(this.token !== null ? { authorization: `Bearer ${this.token}` } : {}),
+ ...extra,
+ };
+ }
+
+ /**
+ * One JSON request. 401 with a file-sourced token re-reads the file once (the server
+ * may have restarted and rotated it) and retries; every other non-2xx becomes an
+ * ApiError carrying the server's code and message.
+ */
+ async request<T>(method: string, apiPath: string, body?: unknown): Promise<T> {
+ const res = await this.fetchAuthed(apiPath, {
+ method,
+ headers: this.headers(body !== undefined ? { "content-type": "application/json" } : {}),
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
+ });
+ if (!res.ok) throw await this.toError(res);
+ if (res.status === 204 || res.headers.get("content-length") === "0") {
+ void res.body?.cancel();
+ return undefined as T;
+ }
+ const text = await res.text();
+ return (text === "" ? undefined : JSON.parse(text)) as T;
+ }
+
+ /** The authenticated fetch with the one-shot 401 file-token refresh. */
+ private async fetchAuthed(apiPath: string, init: RequestInit): Promise<Response> {
+ const res = await fetch(`${this.conn.baseUrl}${apiPath}`, init);
+ if (res.status !== 401) return res;
+ if (this.tokenSource === "env" || !this.conn.loopback) return res;
+ const fresh = readTokenFile(this.conn.root);
+ if (fresh === null || fresh === this.token) return res;
+ void res.body?.cancel();
+ this.token = fresh;
+ this.tokenSource = "file";
+ const headers = { ...(init.headers as Record<string, string>), ...this.headers() };
+ return fetch(`${this.conn.baseUrl}${apiPath}`, { ...init, headers });
+ }
+
+ private async toError(res: Response): Promise<ApiError> {
+ let code = "http_error";
+ let message = "";
+ try {
+ const body = (await res.json()) as { error?: { code?: string; message?: string } };
+ if (body.error?.code) code = body.error.code;
+ if (body.error?.message) message = body.error.message;
+ } catch {
+ // Non-JSON error body: keep the fallback wording.
+ }
+ if (res.status === 401) {
+ return new ApiError(
+ 401,
+ "unauthorized",
+ this.token === null
+ ? this.t.client.noToken(this.conn.baseUrl, apiTokenPath(this.conn.root))
+ : this.t.client.authFailed(this.conn.baseUrl),
+ );
+ }
+ return new ApiError(res.status, code, this.t.client.httpError(res.status, code, message));
+ }
+
+ /**
+ * Opens one SSE subscription (fetch with headers — EventSource cannot carry the
+ * Bearer token) and yields parsed frames. The caller handles reconnects; aborting
+ * `signal` ends the generator quietly.
+ */
+ async *sse(apiPath: string, opts: { lastEventId?: string; signal?: AbortSignal } = {}) {
+ const res = await this.fetchAuthed(apiPath, {
+ headers: this.headers({
+ accept: "text/event-stream",
+ ...(opts.lastEventId !== undefined ? { "last-event-id": opts.lastEventId } : {}),
+ }),
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ if (!res.ok || res.body === null) throw await this.toError(res);
+ yield* parseSseBody(res.body, opts.signal);
+ }
+}
+
+/**
+ * Minimal SSE parser over a fetch body: `id:` / `event:` / `data:` fields, multi-line
+ * data joined with \n, blank line dispatches, `:` comment lines (heartbeats) ignored.
+ * Tolerates \r\n line endings.
+ */
+export async function* parseSseBody(
+ body: ReadableStream<Uint8Array>,
+ signal?: AbortSignal,
+): AsyncGenerator<SseFrame> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ let id: string | undefined;
+ let event: string | undefined;
+ let data: string[] = [];
+ const flush = (): SseFrame | null => {
+ if (data.length === 0 && event === undefined) {
+ id = undefined;
+ event = undefined;
+ return null;
+ }
+ const frame: SseFrame = {
+ ...(id !== undefined ? { id } : {}),
+ ...(event !== undefined ? { event } : {}),
+ data: data.join("\n"),
+ };
+ event = undefined;
+ data = [];
+ return frame;
+ };
+ try {
+ for (;;) {
+ if (signal?.aborted) return;
+ const { done, value } = await reader.read();
+ if (done) return;
+ buffer += decoder.decode(value, { stream: true });
+ for (;;) {
+ const nl = buffer.indexOf("\n");
+ if (nl === -1) break;
+ let line = buffer.slice(0, nl);
+ buffer = buffer.slice(nl + 1);
+ if (line.endsWith("\r")) line = line.slice(0, -1);
+ if (line === "") {
+ const frame = flush();
+ if (frame) yield frame;
+ continue;
+ }
+ if (line.startsWith(":")) continue; // heartbeat comment
+ const colon = line.indexOf(":");
+ const field = colon === -1 ? line : line.slice(0, colon);
+ let value2 = colon === -1 ? "" : line.slice(colon + 1);
+ if (value2.startsWith(" ")) value2 = value2.slice(1);
+ if (field === "data") data.push(value2);
+ else if (field === "event") event = value2;
+ else if (field === "id") id = value2;
+ // Other fields (retry) are ignored.
+ }
+ }
+ } finally {
+ try {
+ await reader.cancel();
+ } catch {
+ // The stream is already closed/errored; nothing to release.
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Session references
+// ---------------------------------------------------------------------------
+
+/** The 8-hex tail of a session id — the short form `penguin ls` prints. */
+export function shortSessionId(sessionId: string): string {
+ const m = /-([0-9a-f]{8})$/.exec(sessionId);
+ return m === null ? sessionId : m[1]!;
+}
+
+/** Minimal shape of a session row for reference resolution (matches the server's SessionInfo). */
+export interface SessionRef {
+ sessionId: string;
+ agentId: string;
+}
+
+/**
+ * Resolves a session argument: a full session id is used as-is; anything else is a
+ * fragment matched as a substring over the project's sessions (all agents). Exactly one
+ * match resolves; zero or several are errors — the ambiguous error lists the candidates.
+ */
+export async function resolveSessionRef(
+ client: ServerClient,
+ projectId: string,
+ ref: string,
+ t: Messages,
+): Promise<string> {
+ const trimmed = ref.trim();
+ if (SESSION_ID_RE.test(trimmed)) return trimmed;
+ const { agents } = await client.request<{ agents: Array<{ agentId: string }> }>(
+ "GET",
+ `/api/projects/${encodeURIComponent(projectId)}/agents`,
+ );
+ const candidates: string[] = [];
+ for (const agent of agents) {
+ const { sessions } = await client.request<{ sessions: SessionRef[] }>(
+ "GET",
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agent.agentId)}/sessions`,
+ );
+ for (const s of sessions) {
+ if (s.sessionId.includes(trimmed)) candidates.push(s.sessionId);
+ }
+ }
+ if (candidates.length === 1) return candidates[0]!;
+ if (candidates.length === 0) throw new Error(t.client.sessionNotFound(trimmed, projectId));
+ throw new Error(t.client.sessionAmbiguous(trimmed, candidates));
+}
+
+// ---------------------------------------------------------------------------
+// Shared option defaults
+// ---------------------------------------------------------------------------
+
+/** `--project-id` default chain: flag > PENGUIN_PROJECT_ID > default_project. */
+export function resolveProjectId(flag: string | undefined): string {
+ return flag?.trim() || process.env.PENGUIN_PROJECT_ID?.trim() || "default_project";
+}
+
+/** `--agent-id` default chain: flag > PENGUIN_AGENT_ID > default_agent. */
+export function resolveAgentId(flag: string | undefined): string {
+ return flag?.trim() || process.env.PENGUIN_AGENT_ID?.trim() || "default_agent";
+}
diff --git a/packages/cli/src/commands/agent.ts b/packages/cli/src/commands/agent.ts
new file mode 100644
index 00000000..6f08b4fe
--- /dev/null
+++ b/packages/cli/src/commands/agent.ts
@@ -0,0 +1,86 @@
+/**
+ * `penguin agent` — list and create agents through the server.
+ *
+ * penguin agent ls [--project-id <id>] [--json] [--server <url>]
+ * penguin agent create --agent-id <id> [--name <s>] [--description <s>]
+ * [--skills <a,b>] [--project-id <id>] [--json] [--server <url>]
+ *
+ * `create` mirrors the Web dialog's fields: id (required), display name, description,
+ * and library skills to seed (comma-separated names; unknown names are rejected by the
+ * server before anything is created).
+ * Docs: /docs/cli § "penguin agent".
+ */
+import type { Command } from "commander";
+import type { AgentCreateResponse, AgentSummary } from "@prismshadow/penguin-server/api";
+import { resolveConnection, resolveProjectId, ServerClient } from "../client.js";
+import { listAgents } from "../server-session.js";
+import { renderTable } from "../table.js";
+import type { Messages } from "../i18n.js";
+
+export function registerAgentCommand(program: Command, t: Messages): void {
+ const agent = program.command("agent").description(t.agent.desc);
+
+ agent
+ .command("ls")
+ .description(t.agent.lsDesc)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agents = await listAgents(client, projectId);
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify(agents)}\n`);
+ return;
+ }
+ process.stdout.write(
+ renderTable(
+ [t.agent.colId(), t.agent.colName(), t.agent.colSessions(), t.agent.colDescription()],
+ agents.map((a: AgentSummary) => [
+ a.agentId,
+ a.name ?? "",
+ String(a.sessionCount),
+ (a.description ?? "").slice(0, 60),
+ ]),
+ ),
+ );
+ });
+
+ agent
+ .command("create")
+ .description(t.agent.createDesc)
+ .requiredOption("--agent-id <id>", t.agent.createId)
+ .option("--name <name>", t.agent.createName)
+ .option("--description <text>", t.agent.createDescription)
+ .option("--skills <names>", t.agent.createSkills)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const skills =
+ typeof opts.skills === "string"
+ ? opts.skills
+ .split(",")
+ .map((s: string) => s.trim())
+ .filter((s: string) => s.length > 0)
+ : undefined;
+ const res = await client.request<AgentCreateResponse>(
+ "POST",
+ `/api/projects/${encodeURIComponent(projectId)}/agents`,
+ {
+ agentId: String(opts.agentId),
+ ...(opts.name !== undefined ? { name: String(opts.name) } : {}),
+ ...(opts.description !== undefined ? { description: String(opts.description) } : {}),
+ ...(skills !== undefined && skills.length > 0 ? { skills } : {}),
+ },
+ );
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify(res.agent)}\n`);
+ return;
+ }
+ process.stdout.write(`${t.agent.created(res.agent.agentId, projectId)}\n`);
+ });
+}
diff --git a/packages/cli/src/commands/chat.ts b/packages/cli/src/commands/chat.ts
index a89bcac7..e9eac0ab 100644
--- a/packages/cli/src/commands/chat.ts
+++ b/packages/cli/src/commands/chat.ts
@@ -1,57 +1,52 @@
/**
- * `penguin chat` — interactive REPL.
+ * `penguin chat` — interactive REPL over the server.
*
- * 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|max>] [--verbose]
+ * penguin chat [--project-id <id>] [--agent-id <id>] [--workspace <path>]
+ * [--model-id <id> --provider <group>] [--approve <mode>]
+ * [--thinking <level>] [--resume [sessionId]] [--verbose] [--server <url>]
*
- * 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);
- * `/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
- * together; giving neither uses the Project's default model.
+ * The REPL machinery (persistent readline, bracketed paste, the Ctrl-C state machine)
+ * is unchanged; the transport is the server: each turn POSTs a task and consumes the
+ * Session's SSE stream (subscribe first, POST second) through the shared watcher.
+ * `/goal[:<budget>] <objective>` runs goal mode; `/compact` POSTs a compaction and
+ * renders its progress; `/clear` creates a fresh server Session in place; `/thinking`
+ * shows or overrides the per-turn thinking level; `/verbose` toggles tool-output
+ * collapsing (display only); `/exit` or `/quit` exits. Typing while a turn runs POSTs
+ * a steering message (delivered between turns); Ctrl-C during a run POSTs /abort.
*
- * Multi-line input: trailing `\` continues the line; when the terminal supports bracketed
- * paste, a multi-line paste is treated as a single message (sent on Enter).
- *
- * Ctrl-C behavior (state-dependent): buffer has content -> clear it;
- * awaiting approval -> deny; running -> abort the current turn and return to input;
- * empty buffer -> show a y/N exit confirmation.
- *
- * Implementation notes: on a TTY, stdin is put into raw mode with bracketed paste enabled;
- * stdin is piped through PasteFilter into a readline created with `terminal: true` — Ctrl-C
- * is captured in-process by readline as 'SIGINT' (it never escapes as an OS signal killing
- * the process group), and pasted content is held whole by PasteFilter (not split into
- * multiple submits by embedded newlines).
+ * `--resume` reuses an existing Session (full id or unique fragment; omitted = the
+ * agent's most recent Session) and first renders its history from GET /messages.
+ * Ctrl-C behavior (state-dependent): buffer has content -> clear it; awaiting approval
+ * -> deny; running -> abort the current turn; empty buffer -> y/N exit confirmation.
* Docs: /docs/cli § "penguin chat".
*/
import { createInterface, type Interface } from "node:readline";
import type { Command } from "commander";
-import { createAgent, userText, VERSION } from "@prismshadow/penguin-core";
-import type {
- ApprovalDecision,
- DefaultChatThinkingLevel,
- OmniMessage,
- Session,
- ToolCallPayload,
-} from "@prismshadow/penguin-core";
+import { VERSION } from "@prismshadow/penguin-core";
+import type { ApprovalDecision, OmniMessage, ToolCallPayload } from "@prismshadow/penguin-core";
+import type { SessionInfo } from "@prismshadow/penguin-server/api";
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 { parseThinkingCommand, resolveThinkingLevel } from "../thinking-command.js";
import { parseApprovalAnswer, resolveApprovalMode } from "../approval.js";
import { LineComposer, PasteFilter } from "../input.js";
+import {
+ ApiError,
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ resolveSessionRef,
+ ServerClient,
+} from "../client.js";
+import {
+ callerSessionContext,
+ createServerSession,
+ getSessionInfo,
+ getSessionMessages,
+ listAgentSessions,
+ resolveWorkspace,
+} from "../server-session.js";
+import { SessionStream, watchTask } from "../server-task.js";
import type { Messages } from "../i18n.js";
export type ChatState = "idle" | "running" | "approving" | "confirming-exit";
@@ -79,27 +74,31 @@ export function registerChatCommand(program: Command, t: Messages): void {
program
.command("chat")
.description(t.chat.desc)
- .option("--model-id <id>", t.common.modelId)
- .option("--provider <group>", t.common.provider)
.option("--project-id <id>", t.common.projectId)
.option("--agent-id <id>", t.common.agentId)
.option("--workspace <path>", t.common.workspace)
+ .option("--model-id <id>", t.common.modelId)
+ .option("--provider <group>", t.common.provider)
.option("--approve <mode>", t.common.approve)
.option("--thinking <level>", t.common.thinking)
- .option("--verbose", t.chat.verbose)
.option("--resume [sessionId]", t.chat.resume)
+ .option("--verbose", t.chat.verbose)
+ .option("--server <url>", t.common.server)
.action(async (opts) => {
- // The model reference is a pair: commander can only require each option on its own,
- // so the "both or neither" rule is enforced here. Giving neither is the normal case
- // and falls back to the Project's default model. Skipped under --resume, which
- // rejects both options outright further down with a more specific message.
- // Usage errors go to stderr (as in `run` and `config model add`), unlike this file's
- // informational messages, which the REPL writes to stdout.
+ // The model reference is a pair; both-or-neither (skipped under --resume, which
+ // rejects both outright below). Usage errors go to stderr, REPL info to stdout.
if (opts.resume === undefined && Boolean(opts.modelId) !== Boolean(opts.provider)) {
process.stderr.write(`${t.error(t.modelRefIncomplete())}\n`);
process.exitCode = 1;
return;
}
+ // --resume excludes --workspace and the model pair (neither can change once the
+ // Session exists); checked before any connection is made.
+ if (opts.resume !== undefined && (opts.workspace || opts.modelId || opts.provider)) {
+ process.stdout.write(`${t.error(t.resumeNoOverride())}\n`);
+ process.exitCode = 1;
+ 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,
@@ -107,66 +106,87 @@ export function registerChatCommand(program: Command, t: Messages): void {
let verbose = opts.verbose === true;
const out = process.stdout;
- const agent = await createAgent({
- ...(opts.agentId ? { agentId: opts.agentId } : {}),
- ...(opts.projectId ? { projectId: opts.projectId } : {}),
- });
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agentId = resolveAgentId(opts.agentId);
- // --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. Annotated (not inferred) because /clear
- // reassigns it mid-REPL, after the closures below have captured it.
- let session: Session;
+ // --resume reuses an existing Session (workspace/model fixed at creation); a new
+ // chat creates one on this cwd. `session` is reassigned by /clear after the
+ // closures below capture it, so it stays a let.
+ let session: SessionInfo;
+ let resumedMessages: OmniMessage[] | null = null;
if (opts.resume !== undefined) {
- if (opts.workspace || opts.modelId || opts.provider) {
- out.write(`${t.error(t.resumeNoOverride())}\n`);
- process.exitCode = 1;
- return;
+ let sessionId: string | undefined;
+ if (typeof opts.resume === "string") {
+ sessionId = await resolveSessionRef(client, projectId, opts.resume, t);
+ } else {
+ // Most recent Session of the agent (the list is newest-first).
+ sessionId = (await listAgentSessions(client, projectId, agentId))[0]?.sessionId;
}
- const sessionId =
- typeof opts.resume === "string" ? opts.resume : await agent.latestSessionId();
if (!sessionId) {
out.write(`${t.error(t.resumeNoSession())}\n`);
process.exitCode = 1;
return;
}
- session = await agent.resumeSession({ sessionId });
+ session = await getSessionInfo(client, sessionId);
+ resumedMessages = await getSessionMessages(client, sessionId);
+ if (opts.approve !== undefined) {
+ await client.request("PATCH", `/api/sessions/${session.sessionId}`, {
+ approvalMode: mode,
+ });
+ }
} else {
- session = await agent.createSession({
- workspaceDir: opts.workspace ?? process.cwd(),
- ...(opts.modelId ? { modelId: opts.modelId } : {}),
- ...(opts.provider ? { provider: opts.provider } : {}),
- ...(flagThinking ? { thinkingLevel: flagThinking } : {}),
+ // Inside a harness agent, unspecified fields default to the CALLING session's
+ // values — the run_subagent inheritance, applied to the CLI surface. Per field:
+ // explicit flag > caller value > the plain fallback.
+ const caller = await callerSessionContext(client, t);
+ session = await createServerSession(client, {
+ projectId,
+ agentId,
+ workspace: resolveWorkspace(opts.workspace, caller?.workspace),
+ ...(opts.modelId
+ ? { modelId: opts.modelId, provider: opts.provider }
+ : caller
+ ? { modelId: caller.modelId, provider: caller.provider }
+ : {}),
+ ...(opts.approve !== undefined
+ ? { approvalMode: mode }
+ : caller
+ ? { approvalMode: caller.approvalMode }
+ : {}),
});
+ // `--thinking` on a new chat pins the Session default (sticky server-side, so
+ // spawned subagent sessions follow it — the same effect creation-time pinning
+ // had); with no flag, the caller's level pins the same way.
+ const pin = flagThinking ?? caller?.thinkingLevel;
+ if (pin) {
+ await client.request("PATCH", `/api/sessions/${session.sessionId}`, {
+ thinkingLevel: pin,
+ });
+ session = { ...session, thinkingLevel: pin };
+ }
}
- // 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;
+ // Thinking level shown/changed by `/thinking` (a per-turn run parameter):
+ // - a new chat's `--thinking` pinned the Session default above; under `--resume`
+ // the Session already exists and the flag becomes the initial per-turn override.
+ // - `/thinking <level>` sets the override; unset turns omit the parameter so the
+ // Session's pinned level (else the Agent config) applies.
+ let thinkingOverride = opts.resume !== undefined ? flagThinking : undefined;
const sessionThinkingDefault = (): string =>
- opts.resume === undefined && flagThinking ? flagThinking : configuredThinkingLevel(agent);
+ session.thinkingLevel ?? t.chatThinkingConfigured();
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.
out.write(
- `${t.header("chat", VERSION, agent.state.agentId, session.workspaceDir, session.modelId)}\n` +
+ `${t.header("chat", VERSION, session.agentId, session.workspace, session.modelId)}\n` +
`${t.chatHints()}\n`,
);
- // On resume, first render the history messages of the current context per Trace
- // (full messages, including interrupted turns and their markers), then proceed to
- // regular input.
- if (session.resumedHistory) {
- out.write(`${t.resumedBanner(session.sessionId, session.resumedHistory.length)}\n`);
- renderHistory(session.resumedHistory, out, t, { collapseToolOutput: !verbose });
+ // On resume, first render the history messages of the current context (full
+ // messages, same endpoint the Web history uses), then proceed to regular input.
+ if (resumedMessages !== null) {
+ out.write(`${t.resumedBanner(session.sessionId, resumedMessages.length)}\n`);
+ renderHistory(resumedMessages, out, t, { collapseToolOutput: !verbose });
}
// TTY: raw mode + bracketed paste + PasteFilter; non-TTY (pipe/test): read stdin directly.
@@ -189,12 +209,9 @@ export function registerChatCommand(program: Command, t: Messages): void {
const rli = rl as unknown as RlInternals;
const composer = new LineComposer();
- // Typing lock (owner directive): while the user is composing a line mid-run, streamed
- // output must not scribble over it — the renderer holds (queues) output while the input
- // buffer is non-empty and flushes once the line is submitted or cleared. Synced after
- // readline has processed each chunk (setImmediate: listener order is not guaranteed);
- // TTY only — non-TTY input (pipe/tests) has no echoed line to protect. The approval
- // prompt has its own lock (beginUserPrompt), so the hold applies to "running" only.
+ // Typing lock: while the user is composing a line mid-run, streamed output must not
+ // scribble over it — the renderer holds output while the input buffer is non-empty
+ // and flushes once the line is submitted or cleared. TTY only.
const syncInputHold = (): void => {
renderer.setInputHold(state === "running" && rli.line.length > 0);
};
@@ -204,7 +221,8 @@ export function registerChatCommand(program: Command, t: Messages): void {
let state: ChatState = "idle";
let closed = false;
- let taskAbort: AbortController | null = null;
+ /** Set while a turn runs; SIGINT posts /abort through it exactly once per turn. */
+ let abortTurn: (() => void) | null = null;
let pendingLine: ((line: string | null) => void) | null = null;
let pendingApproval: ((decision: ApprovalDecision) => void) | null = null;
/** A line typed in the running->idle race window (steer refused): becomes the next prompt instead of being dropped. */
@@ -246,6 +264,26 @@ export function registerChatCommand(program: Command, t: Messages): void {
});
}
+ // Mid-run steering over the API: POST /steer; a 409 (the task just finished — the
+ // running->idle race) must not drop the line, so it becomes the next prompt — fed
+ // straight to a waiting askLine, else stashed for the next one.
+ const steer = (text: string): void => {
+ void client
+ .request("POST", `/api/sessions/${session.sessionId}/steer`, { text })
+ .then(() => {
+ renderer.printLine(dim(t.steerQueued(text)));
+ })
+ .catch(() => {
+ if (pendingLine) {
+ const resolve = pendingLine;
+ pendingLine = null;
+ resolve(text);
+ } else {
+ queuedPrompt = text;
+ }
+ });
+ };
+
rl.on("line", (line) => {
if (state === "confirming-exit") {
if (parseApprovalAnswer(line) === "allow") {
@@ -279,21 +317,11 @@ export function registerChatCommand(program: Command, t: Messages): void {
resolve(parseApprovalAnswer(line, "allow"));
return;
}
- // running: a non-empty line becomes a steering message for the running Task — core
- // delivers it between turns as a standalone [user_steering] user message, so the
- // model sees it without the loop being interrupted. Empty lines are still ignored.
- // steer() returning false (race: the task just finished) must not drop the line:
- // it is stashed and becomes the next normal prompt as soon as the loop asks again.
+ // running: a non-empty line becomes a steering message for the running Task.
if (state === "running") {
const text = line.trim();
if (text.length === 0) return;
- if (session.steer([userText(text)])) {
- // Printed via the renderer while the typing hold is still engaged, so the ack
- // lands before the held stream output flushes underneath it.
- renderer.printLine(dim(t.steerQueued(text)));
- } else {
- queuedPrompt = text;
- }
+ steer(text);
}
});
@@ -308,9 +336,10 @@ export function registerChatCommand(program: Command, t: Messages): void {
resolve("deny");
}
} else if (action === "abort") {
- if (taskAbort && !taskAbort.signal.aborted) {
+ if (abortTurn) {
out.write(`\n${t.taskInterrupted()}\n`);
- taskAbort.abort();
+ abortTurn();
+ abortTurn = null;
}
} else if (action === "clear") {
composer.reset();
@@ -363,9 +392,8 @@ export function registerChatCommand(program: Command, t: Messages): void {
rl.prompt();
});
- // Interactive approval prompt: reuses the persistent readline, prompt text is
- // localized; the tool call is already rendered above via streaming, so it is not
- // re-rendered here.
+ // Interactive approval prompt: reuses the persistent readline; the tool call is
+ // already rendered above via streaming, so it is not re-rendered here.
const interactivePrompt = (_tc: OmniMessage<ToolCallPayload>): Promise<ApprovalDecision> =>
new Promise((resolve) => {
state = "approving";
@@ -377,15 +405,46 @@ export function registerChatCommand(program: Command, t: Messages): void {
rl.prompt();
});
- // Whether this Session already has a resumable Trace record: a resumed Session
- // naturally has one; a new Session gets one starting from its first Task / compact
- // (session_meta is written along with it). This decides whether to print the resume
- // command example on exit.
+ /**
+ * One server-driven turn: subscribe, POST via `post`, watch to idle. Returns once
+ * the turn (or compaction/goal) has fully settled. Wires this turn's Ctrl-C to
+ * POST /abort exactly once.
+ */
+ const runTurn = async (
+ post: () => Promise<unknown>,
+ watch: { goal?: boolean } = {},
+ ): Promise<void> => {
+ const stream = new SessionStream(client, session.sessionId, t);
+ let aborted = false;
+ abortTurn = () => {
+ if (aborted) return;
+ aborted = true;
+ void client
+ .request("POST", `/api/sessions/${session.sessionId}/abort`)
+ .catch(() => undefined);
+ };
+ try {
+ await stream.waitReady();
+ await post();
+ await watchTask(stream, {
+ client,
+ sessionId: session.sessionId,
+ t,
+ renderer,
+ approvalPrompt: interactivePrompt,
+ ...(watch.goal ? { goal: { out } } : {}),
+ });
+ } finally {
+ abortTurn = null;
+ stream.close();
+ }
+ };
+
+ // Whether this Session already has (or gained) history worth a resume hint.
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.
+ // Agent options so it works as-is.
const resumeCommand = (sessionId: string): string =>
`penguin chat --resume ${sessionId}` +
(opts.projectId ? ` --project-id ${opts.projectId}` : "") +
@@ -399,16 +458,13 @@ 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.
+ // Instant local commands (no Task runs, state stays idle). 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(
`${
@@ -431,54 +487,55 @@ export function registerChatCommand(program: Command, t: Messages): void {
}
state = "running";
- taskAbort = new AbortController();
try {
if (text === "/compact") {
- // Proactive context compaction (Task boundary, reason=manual): the renderer
- // prints compaction progress; Ctrl-C aborts the compaction via signal
- // (preserving the original context). When there's nothing to compact (session
- // just started / two consecutive /compact calls), the engine silently returns
- // and we add one line of feedback here. Afterwards, settle the renderer's
- // counters (endCompact) — compaction usage is already shown on the completion
- // line and must not be counted again toward the next task's stats delta.
+ // Proactive context compaction: POST /compact and render its paired events
+ // from the stream; a 409 (nothing to compact / just compacted) prints one
+ // line of feedback. endCompact settles the renderer's counters afterwards.
const startedAt = Date.now();
- let sawMessage = false;
try {
- for await (const msg of session.compact({
- signal: taskAbort.signal,
- })) {
- sawMessage = true;
- resumable = true;
- renderer.handle(msg);
+ await runTurn(() =>
+ client.request("POST", `/api/sessions/${session.sessionId}/compact`),
+ );
+ resumable = true;
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 409) {
+ out.write(`${t.compactNothing()}\n`);
+ } else {
+ throw err;
}
} finally {
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,
+ // Start over with a brand-new blank Session on the same Workspace and model.
+ // The old Session stays on the server (resumable), so its resume command is
+ // printed first. The new Session is created before the old one is dropped: a
+ // failure keeps the current conversation intact.
+ const next = await createServerSession(client, {
+ projectId,
+ agentId,
+ workspace: session.workspace,
modelId: session.modelId,
provider: session.provider,
- ...(flagThinking ? { thinkingLevel: flagThinking } : {}),
+ approvalMode: session.approvalMode,
});
+ // Carry the current session's pinned thinking level over (whether it came
+ // from --thinking or from the calling session's context).
+ const pin = session.thinkingLevel;
+ if (pin) {
+ await client.request("PATCH", `/api/sessions/${next.sessionId}`, {
+ thinkingLevel: pin,
+ });
+ }
if (resumable) out.write(`${dim(t.resumeHint(resumeCommand(session.sessionId)))}\n`);
- session.dispose();
- session = next;
+ session = pin ? { ...next, thinkingLevel: pin } : next;
renderer = new StreamRenderer(out, t, { collapseToolOutput: !verbose });
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.
+ // Goal mode: one POST drives the whole loop server-side; Ctrl-C aborts the
+ // entire goal.
const parsed = parseGoalCommand(text);
if (!parsed.ok) {
const message =
@@ -486,41 +543,37 @@ export function registerChatCommand(program: Command, t: Messages): void {
out.write(`${t.error(message)}\n`);
} else {
resumable = true;
- await runTask(session, [userText(parsed.objective)], {
- mode,
- signal: taskAbort.signal,
- ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),
- renderer,
- interactivePrompt,
- t,
- goal: { budget: parsed.budget, out },
- });
+ await runTurn(
+ () =>
+ client.request("POST", `/api/sessions/${session.sessionId}/tasks`, {
+ input: [{ type: "text", text: parsed.objective }],
+ ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),
+ goal: { budget: parsed.budget },
+ }),
+ { goal: true },
+ );
}
} else {
resumable = true;
- await runTask(session, [userText(text)], {
- mode,
- signal: taskAbort.signal,
- ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),
- renderer,
- interactivePrompt,
- t,
- });
+ await runTurn(() =>
+ client.request("POST", `/api/sessions/${session.sessionId}/tasks`, {
+ input: [{ type: "text", text }],
+ ...(thinkingOverride ? { thinkingLevel: thinkingOverride } : {}),
+ }),
+ );
}
} catch (err) {
out.write(`\n${t.error(err instanceof Error ? err.message : String(err))}\n`);
} finally {
- taskAbort = null;
state = "idle";
}
}
} finally {
rl.close();
cleanup();
- session.dispose(); // tear down managed long-running command sessions to avoid leaking background processes
process.removeListener("exit", cleanup);
// On exit, print a dimmed resume command example; skipped when the Session has
- // no Trace record yet (nothing to resume).
+ // no history yet (nothing to resume). The Session itself lives on the server.
if (resumable) {
out.write(`${dim(t.resumeHint(resumeCommand(session.sessionId)))}\n`);
}
diff --git a/packages/cli/src/commands/cost.ts b/packages/cli/src/commands/cost.ts
new file mode 100644
index 00000000..cb89b5dd
--- /dev/null
+++ b/packages/cli/src/commands/cost.ts
@@ -0,0 +1,132 @@
+/**
+ * `penguin cost` — token/cost aggregates from GET /api/projects/:p/usage.
+ *
+ * penguin cost [--days <n>] [--from <d> --to <d>] [--by date|agent|model|session]
+ * [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+ *
+ * Default prints the summary card (today / last 7 days / total — the endpoint computes
+ * them unconditionally). `--days n` sets from/to to the trailing n days; `--from/--to`
+ * (a pair) pin an explicit range. `--by` maps to the endpoint's groupBy and prints the
+ * grouped table instead of the card. `--agent-id` filters; there is no default agent
+ * here — costs are a project view unless narrowed explicitly.
+ * Docs: /docs/cli § "penguin cost".
+ */
+import type { Command } from "commander";
+import type { UsageResponse } from "@prismshadow/penguin-server/api";
+import { humanizeTokens } from "../render.js";
+import { resolveConnection, resolveProjectId, ServerClient } from "../client.js";
+import { renderTable } from "../table.js";
+import type { Messages } from "../i18n.js";
+
+const GROUP_BYS = ["date", "agent", "model", "session"] as const;
+type GroupBy = (typeof GROUP_BYS)[number];
+
+/** yyyy-mm-dd of a local date. */
+function localDate(d: Date): string {
+ const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+}
+
+function formatCost(cost: number | null, hasUncosted: boolean, t: Messages): string {
+ if (cost === null) return t.cost.noPricing();
+ const value = `$${cost.toFixed(4)}`;
+ return hasUncosted ? `${value}+` : value;
+}
+
+export function registerCostCommand(program: Command, t: Messages): void {
+ program
+ .command("cost")
+ .description(t.cost.desc)
+ .option("--days <n>", t.cost.days)
+ .option("--from <date>", t.cost.from)
+ .option("--to <date>", t.cost.to)
+ .option("--by <dimension>", t.cost.by)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.agentId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ if ((opts.from === undefined) !== (opts.to === undefined)) {
+ process.stderr.write(`${t.error(t.cost.rangeIncomplete())}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ let from = opts.from as string | undefined;
+ let to = opts.to as string | undefined;
+ if (opts.days !== undefined) {
+ const days = Number(opts.days);
+ if (!Number.isInteger(days) || days <= 0) {
+ process.stderr.write(`${t.error(t.cost.daysInvalid(String(opts.days)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ const now = new Date();
+ to = localDate(now);
+ from = localDate(new Date(now.getFullYear(), now.getMonth(), now.getDate() - (days - 1)));
+ }
+ let groupBy: GroupBy | undefined;
+ if (opts.by !== undefined) {
+ if (!(GROUP_BYS as readonly string[]).includes(String(opts.by))) {
+ process.stderr.write(`${t.error(t.cost.byInvalid(String(opts.by)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ groupBy = opts.by as GroupBy;
+ }
+
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const params = new URLSearchParams();
+ if (groupBy !== undefined) params.set("groupBy", groupBy);
+ if (from !== undefined) params.set("from", from);
+ if (to !== undefined) params.set("to", to);
+ if (opts.agentId !== undefined) params.set("agentId", String(opts.agentId));
+ const qs = params.size > 0 ? `?${params.toString()}` : "";
+ const usage = await client.request<UsageResponse>(
+ "GET",
+ `/api/projects/${encodeURIComponent(projectId)}/usage${qs}`,
+ );
+
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify(usage)}\n`);
+ return;
+ }
+ const out = process.stdout;
+ if (groupBy === undefined) {
+ // The summary card: today / last7d / total (the endpoint computes all three
+ // regardless of from/to).
+ const line = (label: string, b: UsageResponse["summary"]["today"]): string[] => [
+ label,
+ humanizeTokens(b.total),
+ String(b.requests),
+ formatCost(b.cost, b.hasUncosted, t),
+ ];
+ out.write(
+ renderTable(
+ ["", t.cost.colTokens(), t.cost.colRequests(), t.cost.colCost()],
+ [
+ line(t.cost.today(), usage.summary.today),
+ line(t.cost.last7d(), usage.summary.last7d),
+ line(t.cost.total(), usage.summary.total),
+ ],
+ ),
+ );
+ return;
+ }
+ if (usage.groups.length === 0) {
+ out.write(`${t.cost.empty()}\n`);
+ return;
+ }
+ out.write(
+ renderTable(
+ [t.cost.colGroup(groupBy), t.cost.colTokens(), t.cost.colRequests(), t.cost.colCost()],
+ usage.groups.map((g) => [
+ g.provider !== undefined ? `${g.key} (${g.provider})` : g.key,
+ humanizeTokens(g.total),
+ String(g.requests),
+ formatCost(g.cost, g.hasUncosted, t),
+ ]),
+ ),
+ );
+ });
+}
diff --git a/packages/cli/src/commands/input.ts b/packages/cli/src/commands/input.ts
new file mode 100644
index 00000000..d572b289
--- /dev/null
+++ b/packages/cli/src/commands/input.ts
@@ -0,0 +1,207 @@
+/**
+ * `penguin input` — send a message into an existing session, or poll its last answer.
+ *
+ * penguin input [session_id] [-m <text>] [--timeout <duration>]
+ * [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+ *
+ * `[session_id]` accepts a full id or a unique fragment (e.g. the 8-hex tail `penguin
+ * ls` prints); omitted, it is the agent's most recent session (announced as a dim
+ * `[latest]` line on stderr — see resolveSessionTarget), which makes bare `penguin
+ * input` the answer to "what did my agent last say".
+ *
+ * With `-m`: a running session gets the text as steering (POST /steer, delivered between
+ * turns); an idle one gets a new task (POST /tasks). The default waits and renders the
+ * stream until the turn completes; `--timeout` bounds the wait with soft-yield
+ * semantics — on expiry the command detaches (exit 0, the task keeps running
+ * server-side) instead of erroring. `--timeout 0` is the degenerate window: return
+ * immediately after delivery — the one timeout knob covers "don't wait" too.
+ *
+ * Without `-m`: **poll** — print the session's most recent complete assistant text
+ * (an idempotent last-answer snapshot from the messages tail; thinking and tool output
+ * are skipped), mirroring `input_subagent`'s empty-prompt semantics. Nothing is queued
+ * or steered. A running session is waited on (silently, no rendering) up to the window
+ * before the snapshot is taken; still running at expiry prints the current latest text
+ * plus the still-running note, exit 0 (`--timeout 0` snapshots immediately).
+ *
+ * The fragment search scopes to the project (PENGUIN_PROJECT_ID / default_project);
+ * a full session id needs no scope.
+ * Docs: /docs/cli § "penguin input".
+ */
+import type { Command } from "commander";
+import { isModelMessage, type OmniMessage } from "@prismshadow/penguin-core";
+import { StreamRenderer, dim } from "../render.js";
+import { parseDurationMs } from "../duration.js";
+import { promptApproval } from "../approval.js";
+import {
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ ServerClient,
+ shortSessionId,
+} from "../client.js";
+import { getSessionInfo, getSessionMessages, resolveSessionTarget } from "../server-session.js";
+import { SessionStream, watchTask } from "../server-task.js";
+import type { Messages } from "../i18n.js";
+
+/** The most recent complete assistant text of the main session (poll's snapshot); null when none exists yet. */
+export function latestAssistantText(messages: OmniMessage[]): string | null {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i]!;
+ if ((msg.origin?.length ?? 0) > 0 || !isModelMessage(msg)) continue;
+ const p = msg.payload as { type?: string; role?: string; text?: string };
+ if (p.type === "text" && p.role !== "user" && typeof p.text === "string") return p.text;
+ }
+ return null;
+}
+
+export function registerInputCommand(program: Command, t: Messages): void {
+ program
+ .command("input [sessionId]")
+ .description(t.input.desc)
+ .option("-m, --message <text>", t.input.message)
+ .option("--timeout <duration>", t.common.timeout)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.latestAgentId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (sessionRef: string | undefined, opts) => {
+ const json = opts.json === true;
+ let timeoutMs: number | undefined;
+ if (opts.timeout !== undefined) {
+ const parsed = parseDurationMs(String(opts.timeout));
+ if (parsed === null) {
+ process.stderr.write(`${t.error(t.client.timeoutInvalid(String(opts.timeout)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ timeoutMs = parsed;
+ }
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const sessionId = await resolveSessionTarget(
+ client,
+ { ref: sessionRef, projectId, agentId: resolveAgentId(opts.agentId) },
+ t,
+ );
+ if (sessionId === null) return; // no session to act on; the hint is already printed
+ const out = process.stdout;
+
+ // —— Poll form (no -m): print the last answer, waiting out a running turn first ——
+ if (opts.message === undefined) {
+ const info = await getSessionInfo(client, sessionId);
+ let status: "idle" | "running" = info.status === "idle" ? "idle" : "running";
+ if (status === "running" && timeoutMs !== 0) {
+ // Wait (silently — the snapshot is the output, not the stream) for the turn to
+ // end, bounded by --timeout when given; unbounded like every waiting command
+ // otherwise. A zero window skips the wait entirely: snapshot right away.
+ const stream = new SessionStream(client, sessionId, t);
+ try {
+ const state = await stream.waitReady();
+ if (state !== "idle") {
+ const result = await watchTask(stream, {
+ client,
+ sessionId,
+ t,
+ ...(timeoutMs !== undefined ? { deadlineMs: Date.now() + timeoutMs } : {}),
+ });
+ status = result.timedOut ? "running" : "idle";
+ } else {
+ status = "idle";
+ }
+ } finally {
+ stream.close();
+ }
+ }
+ const text = latestAssistantText(await getSessionMessages(client, sessionId));
+ if (json) {
+ out.write(`${JSON.stringify({ sessionId, status, text: text ?? "" })}\n`);
+ } else {
+ if (text !== null) out.write(`${text}\n`);
+ else out.write(`${dim(t.input.noReplyYet())}\n`);
+ if (status === "running") {
+ out.write(`${dim(t.client.stillRunning(shortSessionId(sessionId)))}\n`);
+ }
+ }
+ return;
+ }
+
+ const text = String(opts.message);
+ // Running -> steer; idle -> task. The status read races the run ending, so the
+ // steer path falls back to a task on 409 (the same fallback the Web applies).
+ const post = async (running: boolean): Promise<void> => {
+ if (running) {
+ try {
+ await client.request("POST", `/api/sessions/${sessionId}/steer`, { text });
+ return;
+ } catch {
+ // 409 not_running (the task just ended): fall through to a normal task.
+ }
+ }
+ await client.request("POST", `/api/sessions/${sessionId}/tasks`, {
+ input: [{ type: "text", text }],
+ });
+ };
+
+ if (timeoutMs === 0) {
+ // The zero window: deliver and return — no subscription, no rendering. The
+ // still-running note carries the id for the later poll/follow.
+ const info = await getSessionInfo(client, sessionId);
+ await post(info.status !== "idle");
+ if (json) out.write(`${JSON.stringify({ sessionId, status: "running" })}\n`);
+ else out.write(`${dim(t.client.stillRunning(shortSessionId(sessionId)))}\n`);
+ return;
+ }
+
+ const stream = new SessionStream(client, sessionId, t);
+ const renderer = json ? undefined : new StreamRenderer(out, t);
+ const texts: string[] = [];
+ let interrupted = false;
+ const onSigint = () => {
+ if (interrupted) return;
+ interrupted = true;
+ if (!json) out.write(`\n${t.taskInterrupted()}\n`);
+ void client.request("POST", `/api/sessions/${sessionId}/abort`).catch(() => undefined);
+ };
+ process.on("SIGINT", onSigint);
+ try {
+ const state = await stream.waitReady();
+ await post(state !== "idle");
+ // The soft-yield clock starts once the message is delivered.
+ const result = await watchTask(stream, {
+ client,
+ sessionId,
+ t,
+ ...(renderer ? { renderer } : {}),
+ approvalPrompt: () => promptApproval({ t }),
+ onAssistantText: (chunk) => {
+ texts.push(chunk);
+ },
+ ...(timeoutMs !== undefined ? { deadlineMs: Date.now() + timeoutMs } : {}),
+ });
+ if (result.timedOut) {
+ // Soft yield: detach, task keeps running server-side, exit 0.
+ if (json) {
+ out.write(
+ `${JSON.stringify({ sessionId, status: "running", text: texts.join("\n") })}\n`,
+ );
+ } else {
+ out.write(`${dim(t.client.stillRunning(shortSessionId(sessionId)))}\n`);
+ }
+ return;
+ }
+ if (json) {
+ out.write(
+ `${JSON.stringify({
+ sessionId,
+ status: result.aborted ? "aborted" : "completed",
+ text: texts.join("\n"),
+ })}\n`,
+ );
+ }
+ if (result.aborted) process.exitCode = 1;
+ } finally {
+ process.off("SIGINT", onSigint);
+ stream.close();
+ }
+ });
+}
diff --git a/packages/cli/src/commands/logs.ts b/packages/cli/src/commands/logs.ts
new file mode 100644
index 00000000..b111562e
--- /dev/null
+++ b/packages/cli/src/commands/logs.ts
@@ -0,0 +1,122 @@
+/**
+ * `penguin logs` — render a session's history (and optionally follow it live).
+ *
+ * penguin logs [session_id] [--tail <n>] [-f|--follow] [--json] [--server <url>]
+ *
+ * `[session_id]` is a full id or a unique fragment; omitted, it is the agent's most
+ * recent session (announced as a dim `[latest]` line on stderr — see
+ * resolveSessionTarget), so a bare `penguin logs` shows what just happened.
+ *
+ * History comes from GET /messages and renders through the same history renderer the
+ * REPL's `--resume` uses; `--tail n` keeps the last n entries. `-f` keeps the command
+ * attached: after the history it subscribes to the session's SSE stream and renders new
+ * messages as they arrive (read-only — Ctrl-C detaches without touching the session).
+ * Docs: /docs/cli § "penguin logs".
+ */
+import type { Command } from "commander";
+import { StreamRenderer, dim, renderHistory } from "../render.js";
+import { parseDurationMs } from "../duration.js";
+import {
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ ServerClient,
+ shortSessionId,
+} from "../client.js";
+import { getSessionMessages, resolveSessionTarget } from "../server-session.js";
+import { SessionStream, nextFrameOrDeadline } from "../server-task.js";
+import type { OmniMessage } from "@prismshadow/penguin-core";
+import type { Messages } from "../i18n.js";
+
+export function registerLogsCommand(program: Command, t: Messages): void {
+ program
+ .command("logs [sessionId]")
+ .description(t.logs.desc)
+ .option("--tail <n>", t.logs.tail)
+ .option("-f, --follow", t.logs.follow)
+ .option("--timeout <duration>", t.common.timeout)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.latestAgentId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (sessionRef: string | undefined, opts) => {
+ let tail: number | undefined;
+ if (opts.tail !== undefined) {
+ tail = Number(opts.tail);
+ if (!Number.isInteger(tail) || tail <= 0) {
+ process.stderr.write(`${t.error(t.logs.tailInvalid(String(opts.tail)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ }
+ // --timeout bounds the follow (soft yield): only meaningful with -f.
+ let timeoutMs: number | undefined;
+ if (opts.timeout !== undefined) {
+ if (opts.follow !== true) {
+ process.stderr.write(`${t.error(t.logs.timeoutNeedsFollow())}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ const parsed = parseDurationMs(String(opts.timeout));
+ if (parsed === null) {
+ process.stderr.write(`${t.error(t.client.timeoutInvalid(String(opts.timeout)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ timeoutMs = parsed;
+ }
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const sessionId = await resolveSessionTarget(
+ client,
+ { ref: sessionRef, projectId, agentId: resolveAgentId(opts.agentId) },
+ t,
+ );
+ if (sessionId === null) return; // no session to show; the hint is already printed
+
+ let messages = await getSessionMessages(client, sessionId);
+ if (tail !== undefined) messages = messages.slice(-tail);
+
+ const out = process.stdout;
+ if (opts.json === true) {
+ out.write(`${JSON.stringify(messages)}\n`);
+ if (opts.follow !== true) return;
+ } else {
+ renderHistory(messages, out, t);
+ }
+
+ if (opts.follow !== true) return;
+ // Live continuation: a fresh subscription carries only new events (no buffer
+ // replay without Last-Event-ID); an in-flight message's early chunks may be
+ // missing, and the complete message that follows converges the transcript —
+ // the same orphan-delta rule every stream client applies.
+ const stream = new SessionStream(client, sessionId, t);
+ const renderer = new StreamRenderer(out, t);
+ const deadlineMs = timeoutMs !== undefined ? Date.now() + timeoutMs : undefined;
+ const onSigint = () => {
+ stream.close();
+ };
+ process.on("SIGINT", onSigint);
+ try {
+ for (;;) {
+ const frame = await nextFrameOrDeadline(stream, deadlineMs);
+ if (frame === "timeout") {
+ // Soft yield: stop following, exit 0 — the session is untouched.
+ if (opts.json !== true) {
+ out.write(`${dim(t.client.stillRunning(shortSessionId(sessionId)))}\n`);
+ }
+ break;
+ }
+ if (frame === null) break;
+ if (frame.event !== undefined) continue; // server events: not transcript content
+ const msg = JSON.parse(frame.data) as OmniMessage;
+ if (opts.json === true) out.write(`${JSON.stringify(msg)}\n`);
+ else renderer.handle(msg);
+ }
+ } finally {
+ process.off("SIGINT", onSigint);
+ stream.close();
+ out.write("\n");
+ }
+ });
+}
diff --git a/packages/cli/src/commands/ls.ts b/packages/cli/src/commands/ls.ts
new file mode 100644
index 00000000..9938d1fa
--- /dev/null
+++ b/packages/cli/src/commands/ls.ts
@@ -0,0 +1,105 @@
+/**
+ * `penguin ls` — list the project's sessions.
+ *
+ * penguin ls [--project-id <id>] [--agent-id <id>] [-a|--all] [--days <n>] [--json] [--server <url>]
+ *
+ * All agents of the project unless `--agent-id` narrows it (the API lists per agent, so
+ * the command iterates GET /agents then per-agent sessions). Columns: short id (the
+ * 8-hex tail `penguin input` / `penguin logs` accept as a fragment), agent, title,
+ * running/idle, last active, workspace tail. Archived sessions appear only with `-a`.
+ * `--days <n>` keeps sessions whose lastActiveAt falls within the last n calendar days
+ * (today is day 1, so `--days 2` covers yesterday and today — the `cost --days`
+ * calendar semantics); it combines with `-a` and `--json`.
+ * Docs: /docs/cli § "penguin ls".
+ */
+import type { Command } from "commander";
+import type { SessionInfo } from "@prismshadow/penguin-server/api";
+import {
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ ServerClient,
+ shortSessionId,
+} from "../client.js";
+import { listAgents, listAgentSessions } from "../server-session.js";
+import { relativeTime, renderTable } from "../table.js";
+import type { Messages } from "../i18n.js";
+
+export function registerLsCommand(program: Command, t: Messages): void {
+ program
+ .command("ls")
+ .description(t.ls.desc)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.agentId)
+ .option("-a, --all", t.ls.all)
+ .option("--days <n>", t.ls.days)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ let sinceMs: number | undefined;
+ if (opts.days !== undefined) {
+ const days = Number(opts.days);
+ if (!Number.isInteger(days) || days <= 0) {
+ process.stderr.write(`${t.error(t.ls.daysInvalid(String(opts.days)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ // Calendar semantics (same as cost --days): today counts as day 1, so the window
+ // starts at local midnight (days - 1) days ago.
+ const now = new Date();
+ sinceMs = new Date(now.getFullYear(), now.getMonth(), now.getDate() - (days - 1)).getTime();
+ }
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agentIds =
+ opts.agentId !== undefined
+ ? [resolveAgentId(opts.agentId)]
+ : (await listAgents(client, projectId)).map((a) => a.agentId);
+
+ const all: SessionInfo[] = [];
+ for (const agentId of agentIds) {
+ all.push(...(await listAgentSessions(client, projectId, agentId)));
+ }
+ const rows = all
+ .filter((s) => opts.all === true || !s.archived)
+ .filter((s) => sinceMs === undefined || Date.parse(s.lastActiveAt) >= sinceMs)
+ .sort((a, b) => b.lastActiveAt.localeCompare(a.lastActiveAt));
+
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify(rows)}\n`);
+ return;
+ }
+ if (rows.length === 0) {
+ process.stdout.write(`${t.ls.empty(projectId)}\n`);
+ return;
+ }
+ const stateText = (s: SessionInfo): string =>
+ s.status === "idle" ? t.ls.stateIdle() : t.ls.stateRunning();
+ process.stdout.write(
+ renderTable(
+ [
+ t.ls.colId(),
+ t.ls.colAgent(),
+ t.ls.colTitle(),
+ t.ls.colState(),
+ t.ls.colLast(),
+ t.ls.colWorkspace(),
+ ],
+ rows.map((s) => [
+ shortSessionId(s.sessionId),
+ s.agentId,
+ (s.title ?? "").slice(0, 40),
+ stateText(s),
+ relativeTime(s.lastActiveAt),
+ workspaceTail(s.workspace),
+ ]),
+ ),
+ );
+ });
+}
+
+/** Last path segment of the workspace (enough to tell rows apart at a glance). */
+function workspaceTail(workspace: string): string {
+ const parts = workspace.replace(/[\\/]+$/, "").split(/[\\/]/);
+ return parts[parts.length - 1] || workspace;
+}
diff --git a/packages/cli/src/commands/project.ts b/packages/cli/src/commands/project.ts
new file mode 100644
index 00000000..8d867a9a
--- /dev/null
+++ b/packages/cli/src/commands/project.ts
@@ -0,0 +1,35 @@
+/**
+ * `penguin project ls` — the projects this token/user can reach (own and shared).
+ *
+ * penguin project ls [--json] [--server <url>]
+ * Docs: /docs/cli § "penguin project".
+ */
+import type { Command } from "commander";
+import type { ProjectsResponse } from "@prismshadow/penguin-server/api";
+import { resolveConnection, ServerClient } from "../client.js";
+import { renderTable } from "../table.js";
+import type { Messages } from "../i18n.js";
+
+export function registerProjectCommand(program: Command, t: Messages): void {
+ const project = program.command("project").description(t.project.desc);
+
+ project
+ .command("ls")
+ .description(t.project.lsDesc)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const res = await client.request<ProjectsResponse>("GET", "/api/projects");
+ if (opts.json === true) {
+ process.stdout.write(`${JSON.stringify(res.projects)}\n`);
+ return;
+ }
+ process.stdout.write(
+ renderTable(
+ [t.project.colId(), t.project.colName(), t.project.colRole()],
+ res.projects.map((p) => [p.projectId, p.name ?? "", p.role]),
+ ),
+ );
+ });
+}
diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts
index 8bb05284..283e84f3 100644
--- a/packages/cli/src/commands/run.ts
+++ b/packages/cli/src/commands/run.ts
@@ -1,32 +1,52 @@
/**
- * `penguin run` — send a single Task in one shot.
+ * `penguin run` — send a single Task through the server and render its stream.
*
- * 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>]
- * [--thinking <low|medium|high|xhigh|max>] [--goal [budget]]
+ * penguin run -m <msg> [--project-id <id>] [--agent-id <id>] [--workspace <path>]
+ * [--model-id <id> --provider <group>] [--approve <mode>]
+ * [--thinking <level>] [--session <session_id>] [--background]
+ * [--goal [budget]] [--json] [--server <url>]
*
- * 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)`
- * pair, so `--model-id` and `--provider` must be given together — giving only one of them is
- * an error, never a lookup. Defaults to interactive per-call approval; `--approve`
- * selects the permission mode.
- * `--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).
+ * The CLI is a thin client: it creates a Session over the API (or reuses `--session`),
+ * POSTs the task, subscribes to the SSE stream and renders OmniMessages until the task
+ * ends, then prints the stats line. Exit 0 on completed; a goal run exits 0 only when
+ * the goal outcome is `complete`.
+ *
+ * - Defaults: project/agent from PENGUIN_PROJECT_ID / PENGUIN_AGENT_ID (else
+ * default_project / default_agent); Workspace = the CLI's cwd (resolved locally —
+ * server and CLI share the machine in the default flow); model = the Project default;
+ * approval mode allow-all (the historical run default).
+ * - `--session` accepts a full id or a unique fragment; it excludes `--workspace` and
+ * the model pair (neither can change after creation); `--approve` PATCHes the mode.
+ * - `--background`: POST the task and exit immediately, printing the session id
+ * (`{"sessionId"}` under `--json`) — the task keeps running on the server.
+ * - `--json` (non-background): suppress rendering; print `{sessionId, status, text}`
+ * where `text` joins the main session's assistant text messages of this task.
+ * - Ctrl-C: during an approval prompt → deny that call; otherwise POST /abort and let
+ * the stream wind down (the abort event maps to exit code 1).
* Docs: /docs/cli § "penguin run".
*/
import type { Command } from "commander";
-import { UNLIMITED_BUDGET, createAgent, userText, VERSION } from "@prismshadow/penguin-core";
-import { StreamRenderer } from "../render.js";
-import { runTask } from "../task-loop.js";
+import { UNLIMITED_BUDGET, VERSION } from "@prismshadow/penguin-core";
+import { StreamRenderer, dim } from "../render.js";
+import { parseDurationMs } from "../duration.js";
import { parseTokenBudget } from "../goal-command.js";
import { resolveThinkingLevel } from "../thinking-command.js";
-import { denyActivePrompt, resolveApprovalMode } from "../approval.js";
+import { denyActivePrompt, promptApproval, resolveApprovalMode } from "../approval.js";
+import {
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ resolveSessionRef,
+ ServerClient,
+ shortSessionId,
+} from "../client.js";
+import {
+ callerSessionContext,
+ createServerSession,
+ getSessionInfo,
+ resolveWorkspace,
+} from "../server-session.js";
+import { SessionStream, watchTask } from "../server-task.js";
import type { Messages } from "../i18n.js";
export function registerRunCommand(program: Command, t: Messages): void {
@@ -34,14 +54,19 @@ export function registerRunCommand(program: Command, t: Messages): void {
.command("run")
.description(t.run.desc)
.requiredOption("-m, --message <message>", t.run.message)
- .option("--model-id <id>", t.common.modelId)
- .option("--provider <group>", t.common.provider)
.option("--project-id <id>", t.common.projectId)
.option("--agent-id <id>", t.common.agentId)
.option("--workspace <path>", t.common.workspace)
+ .option("--model-id <id>", t.common.modelId)
+ .option("--provider <group>", t.common.provider)
.option("--approve <mode>", t.common.approve)
.option("--thinking <level>", t.common.thinking)
+ .option("--session <sessionId>", t.run.session)
+ .option("--background", t.run.background)
+ .option("--timeout <duration>", t.common.timeout)
.option("--goal [budget]", t.run.goal)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
.action(async (opts) => {
// The model reference is a pair: commander can only require each option on its own,
// so the "both or neither" rule is enforced here. Giving neither is the normal case
@@ -52,7 +77,7 @@ export function registerRunCommand(program: Command, t: Messages): void {
return;
}
// --goal's optional value is the token budget (`--goal 500k`); a bare --goal means no
- // budget. Validated before any Session is created, like the model-pair check above.
+ // budget. Validated before anything touches the server.
let goalBudget: number | null = null;
if (opts.goal !== undefined) {
goalBudget = opts.goal === true ? UNLIMITED_BUDGET : parseTokenBudget(String(opts.goal));
@@ -61,76 +86,198 @@ export function registerRunCommand(program: Command, t: Messages): void {
process.exitCode = 1;
return;
}
- // The objective must be non-empty text (core throws on an empty one — turn the
- // programming-level error into a friendly refusal before any Session exists).
if (String(opts.message).trim() === "") {
process.stderr.write(`${t.error(t.goalObjectiveEmpty())}\n`);
process.exitCode = 1;
return;
}
}
+ if (opts.session !== undefined && (opts.workspace || opts.modelId || opts.provider)) {
+ // Workspace and model are fixed at creation; a reused Session keeps its own.
+ process.stderr.write(`${t.error(t.run.sessionNoOverride())}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ // --timeout is a soft-yield budget on the WAIT: meaningless when the command does
+ // not wait at all.
+ let timeoutMs: number | undefined;
+ if (opts.timeout !== undefined) {
+ if (opts.background === true) {
+ process.stderr.write(`${t.error(t.run.timeoutWithBackground())}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ const parsed = parseDurationMs(String(opts.timeout));
+ if (parsed === null) {
+ process.stderr.write(`${t.error(t.client.timeoutInvalid(String(opts.timeout)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ timeoutMs = parsed;
+ }
const mode = resolveApprovalMode(opts.approve, t);
const thinking = resolveThinkingLevel(opts.thinking, t);
+ const json = opts.json === true;
+
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agentId = resolveAgentId(opts.agentId);
+
+ let session;
+ let callerThinking: string | undefined;
+ if (opts.session !== undefined) {
+ const sessionId = await resolveSessionRef(client, projectId, String(opts.session), t);
+ session = await getSessionInfo(client, sessionId);
+ if (opts.approve !== undefined) {
+ await client.request("PATCH", `/api/sessions/${session.sessionId}`, {
+ approvalMode: mode,
+ });
+ }
+ } else {
+ // Inside a harness agent, unspecified fields default to the CALLING session's
+ // values — the run_subagent inheritance, applied to the CLI surface. Per field:
+ // explicit flag > caller value > the plain fallback (cwd / Project default /
+ // allow-all / no level).
+ const caller = await callerSessionContext(client, t);
+ session = await createServerSession(client, {
+ projectId,
+ agentId,
+ workspace: resolveWorkspace(opts.workspace, caller?.workspace),
+ ...(opts.modelId
+ ? { modelId: opts.modelId, provider: opts.provider }
+ : caller
+ ? { modelId: caller.modelId, provider: caller.provider }
+ : {}),
+ // The historical run default is allow-all — also the server default; sent
+ // explicitly only when the user picked a mode (or the caller carries one).
+ ...(opts.approve !== undefined
+ ? { approvalMode: mode }
+ : caller
+ ? { approvalMode: caller.approvalMode }
+ : {}),
+ });
+ if (thinking === undefined && caller?.thinkingLevel !== undefined) {
+ callerThinking = caller.thinkingLevel;
+ }
+ }
+
+ const effectiveThinking = thinking ?? callerThinking;
+ const taskBody = {
+ input: [{ type: "text", text: String(opts.message) }],
+ ...(effectiveThinking ? { thinkingLevel: effectiveThinking } : {}),
+ ...(goalBudget !== null ? { goal: { budget: goalBudget } } : {}),
+ };
- const agent = await createAgent({
- ...(opts.agentId ? { agentId: opts.agentId } : {}),
- ...(opts.projectId ? { projectId: opts.projectId } : {}),
- });
+ if (opts.background === true) {
+ // POST and leave: the task runs on the server; the id is what `penguin input` /
+ // `penguin logs` address later.
+ await client.request("POST", `/api/sessions/${session.sessionId}/tasks`, taskBody);
+ process.stdout.write(
+ json ? `${JSON.stringify({ sessionId: session.sessionId })}\n` : `${session.sessionId}\n`,
+ );
+ return;
+ }
- const session = await agent.createSession({
- workspaceDir: opts.workspace ?? process.cwd(),
- ...(opts.modelId ? { modelId: opts.modelId } : {}),
- ...(opts.provider ? { provider: opts.provider } : {}),
- ...(thinking ? { thinkingLevel: thinking } : {}),
- });
+ if (timeoutMs === 0) {
+ // The zero window (`--timeout 0`): deliver and return, no subscription — the
+ // same return-after-POST shape `input --timeout 0` has. `--background` remains
+ // the idiomatic fire-and-forget for NEW tasks (it prints the bare session id for
+ // scripts); the zero timeout exists for symmetry with the wait budget.
+ await client.request("POST", `/api/sessions/${session.sessionId}/tasks`, taskBody);
+ if (json) {
+ process.stdout.write(
+ `${JSON.stringify({ sessionId: session.sessionId, status: "running" })}\n`,
+ );
+ } else {
+ process.stdout.write(
+ `${dim(t.client.stillRunning(shortSessionId(session.sessionId)))}\n`,
+ );
+ }
+ return;
+ }
const out = process.stdout;
- out.write(
- `${t.header("run", VERSION, agent.state.agentId, session.workspaceDir, session.modelId)}\n`,
- );
+ if (!json) {
+ out.write(
+ `${t.header("run", VERSION, session.agentId, session.workspace, session.modelId)}\n`,
+ );
+ }
- const controller = new AbortController();
+ // Subscribe BEFORE posting so no early frame is missed; the first task_state is
+ // the authoritative snapshot.
+ const stream = new SessionStream(client, session.sessionId, t);
+ const renderer = json ? undefined : new StreamRenderer(out, t);
+ const texts: string[] = [];
+ let interrupted = false;
const onSigint = () => {
- // Single SIGINT handler: Ctrl-C during approval collapses to "deny this tool" (see
- // approval.ts); at all other times it interrupts the whole turn.
+ // Ctrl-C during approval collapses to "deny this tool" (see approval.ts); at all
+ // other times it aborts the server-side task — the stream then winds down on its
+ // own (abort event + idle flip).
if (denyActivePrompt()) return;
- controller.abort();
+ if (interrupted) return;
+ interrupted = true;
+ if (!json) out.write(`\n${t.taskInterrupted()}\n`);
+ void client
+ .request("POST", `/api/sessions/${session.sessionId}/abort`)
+ .catch(() => undefined);
};
process.on("SIGINT", onSigint);
-
- const 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.
try {
+ await stream.waitReady();
+ await client.request("POST", `/api/sessions/${session.sessionId}/tasks`, taskBody);
+ // The soft-yield clock starts once the task is actually posted: the budget bounds
+ // the wait for THIS turn, never the connection setup.
+ const result = await watchTask(stream, {
+ client,
+ sessionId: session.sessionId,
+ t,
+ ...(renderer ? { renderer } : {}),
+ approvalPrompt: () => promptApproval({ t }),
+ ...(goalBudget !== null && !json ? { goal: { out } } : {}),
+ ...(goalBudget !== null && json ? { goal: { out: new NullSink() } } : {}),
+ onAssistantText: (text) => {
+ texts.push(text);
+ },
+ ...(timeoutMs !== undefined ? { deadlineMs: Date.now() + timeoutMs } : {}),
+ });
+ if (result.timedOut) {
+ // Soft yield, not an error: detach and leave the task running server-side.
+ if (json) {
+ out.write(
+ `${JSON.stringify({ sessionId: session.sessionId, status: "running", text: texts.join("\n") })}\n`,
+ );
+ } else {
+ out.write(`${dim(t.client.stillRunning(shortSessionId(session.sessionId)))}\n`);
+ }
+ return;
+ }
+ const status =
+ goalBudget !== null
+ ? (result.goal?.outcome ?? "aborted")
+ : result.aborted
+ ? "aborted"
+ : "completed";
+ if (json) {
+ out.write(
+ `${JSON.stringify({ sessionId: session.sessionId, status, text: texts.join("\n") })}\n`,
+ );
+ }
if (goalBudget !== null) {
- // Goal mode: -m is the objective; the one run loops to a terminal state. Exit
- // code follows the outcome — only a completed goal exits 0 (blocked /
- // budget_limited / aborted are all "the goal did not finish", for scripts/CI to
- // check).
- const result = await runTask(session, [userText(opts.message)], {
- mode,
- signal: controller.signal,
- renderer,
- t,
- goal: { budget: goalBudget, out },
- });
if (result.goal?.outcome !== "complete") process.exitCode = 1;
- } else {
- const result = await runTask(session, [userText(opts.message)], {
- mode,
- signal: controller.signal,
- renderer,
- t,
- });
- // Task ended with an abort (LLM failure/reconnect exhausted/user interrupt): non-zero
- // exit code, for scripts/CI to check.
- if (result.aborted) process.exitCode = 1;
+ } else if (result.aborted) {
+ process.exitCode = 1;
}
} finally {
process.off("SIGINT", onSigint);
- session.dispose(); // Tear down managed long-running command sessions to avoid leaking background processes
+ stream.close();
}
- out.write("\n");
+ if (!json) out.write("\n");
});
}
+
+/** Swallows goal round lines under --json (the outcome still reaches the JSON object). */
+class NullSink {
+ write(_chunk: string): boolean {
+ return true;
+ }
+}
diff --git a/packages/cli/src/commands/schedule.ts b/packages/cli/src/commands/schedule.ts
new file mode 100644
index 00000000..8fbf7b91
--- /dev/null
+++ b/packages/cli/src/commands/schedule.ts
@@ -0,0 +1,306 @@
+/**
+ * `penguin schedule` — list and manage the project's scheduled tasks.
+ *
+ * penguin schedule ls [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+ * penguin schedule add <name> --prompt <s> --start-at <ISO|now> [--period <dur>]
+ * [--end-at <ISO>] [--session-id <id> | --workspace <path>
+ * [--model-id <id> --provider <p>]] [--disabled]
+ * [--project-id] [--agent-id] [--json] [--server]
+ * penguin schedule update <name> [--prompt] [--start-at] [--period] [--end-at]
+ * [--session-id | --workspace [--model-id --provider]]
+ * [--enable|--disable] [--project-id] [--agent-id] [--json] [--server]
+ * penguin schedule rm <name> [--project-id] [--agent-id] [--json] [--server]
+ *
+ * `ls`: schedules live per agent (GET .../agents/:a/schedules); without `--agent-id`
+ * the command iterates every agent of the project. Columns: agent, name, enabled,
+ * startAt, period, target (bound sessionId or "new session"), lastFiredAt, and a status
+ * marker for the non-active states (expired / done / missed / invalid — unparsable
+ * files are listed too, marked invalid).
+ *
+ * `add` / `update` / `rm` map onto the schedules API (POST / PUT / DELETE), which
+ * writes the TOML file — the file remains the single source of truth, and the CLI is a
+ * validated writer (the same pattern model config and vault follow: updates go through
+ * the system interface, validation converges at the interface layer, hand edits stay
+ * possible). API errors surface verbatim, so an agent gets synchronous validation
+ * instead of the reconcile lag hand-editing hits. The target is `--session-id` XOR the
+ * new-session form (`--workspace`, optional `--model-id`+`--provider` pair). One
+ * deliberate divergence from the raw file: `add` defaults to ENABLED (adding a task
+ * means you want it to run; the raw-file default of enabled=false stays for hand
+ * edits) — `--disabled` opts out. `update` is read-modify-write against the stored
+ * item: unspecified fields keep their values, `--enable`/`--disable` flip the flag,
+ * and switching target kinds clears the other kind's fields. `rm` deletes without
+ * prompting (agents drive this; the server's owner authorization still applies).
+ * `--start-at now` means the current instant.
+ * Docs: /docs/cli § "penguin schedule".
+ */
+import type { Command } from "commander";
+import type { ScheduleItem, SchedulesResponse } from "@prismshadow/penguin-server/api";
+import {
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ ServerClient,
+ shortSessionId,
+} from "../client.js";
+import { listAgents } from "../server-session.js";
+import { renderTable } from "../table.js";
+import type { Messages } from "../i18n.js";
+
+const enc = encodeURIComponent;
+
+/** `--start-at` value: the literal `now` becomes the current instant; anything else passes through for the server to validate. */
+function resolveStartAt(raw: string): string {
+ return raw.trim().toLowerCase() === "now" ? new Date().toISOString() : raw;
+}
+
+/** One line confirming a written schedule (name, enabled state, next fire when known). */
+function writtenLine(t: Messages, item: ScheduleItem): string {
+ return t.schedule.written(
+ item.name,
+ item.enabled ? t.schedule.enabled() : t.schedule.disabled(),
+ item.nextFireAt,
+ );
+}
+
+export function registerScheduleCommand(program: Command, t: Messages): void {
+ const schedule = program.command("schedule").description(t.schedule.desc);
+
+ schedule
+ .command("ls")
+ .description(t.schedule.lsDesc)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.agentId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agentIds =
+ opts.agentId !== undefined
+ ? [resolveAgentId(opts.agentId)]
+ : (await listAgents(client, projectId)).map((a) => a.agentId);
+
+ const perAgent = await Promise.all(
+ agentIds.map(async (agentId) => ({
+ agentId,
+ res: await client.request<SchedulesResponse>(
+ "GET",
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/schedules`,
+ ),
+ })),
+ );
+
+ if (opts.json === true) {
+ process.stdout.write(
+ `${JSON.stringify(
+ perAgent.map(({ agentId, res }) => ({
+ agentId,
+ schedules: res.schedules,
+ invalidFiles: res.invalidFiles,
+ })),
+ )}\n`,
+ );
+ return;
+ }
+
+ const rows: string[][] = [];
+ for (const { agentId, res } of perAgent) {
+ for (const s of res.schedules) {
+ // `enabled` is the file's intent; the derived status carries the rest —
+ // active is the quiet norm, everything else gets named.
+ rows.push([
+ agentId,
+ s.name,
+ s.enabled ? t.schedule.enabled() : t.schedule.disabled(),
+ s.startAt,
+ s.period ?? t.schedule.oneShot(),
+ s.sessionId !== undefined ? shortSessionId(s.sessionId) : t.schedule.newSession(),
+ s.lastFiredAt ?? "-",
+ s.status === "active" ? "" : s.status,
+ ]);
+ }
+ for (const f of res.invalidFiles) {
+ rows.push([agentId, f.name, "-", "-", "-", "-", "-", "invalid"]);
+ }
+ }
+ if (rows.length === 0) {
+ process.stdout.write(`${t.schedule.empty(projectId)}\n`);
+ return;
+ }
+ process.stdout.write(
+ renderTable(
+ [
+ t.agent.colId(),
+ t.schedule.colName(),
+ t.schedule.colEnabled(),
+ t.schedule.colStartAt(),
+ t.schedule.colPeriod(),
+ t.schedule.colTarget(),
+ t.schedule.colLastFired(),
+ t.schedule.colStatus(),
+ ],
+ rows,
+ ),
+ );
+ });
+
+ schedule
+ .command("add <name>")
+ .description(t.schedule.addDesc)
+ .requiredOption("--prompt <text>", t.schedule.prompt)
+ .requiredOption("--start-at <when>", t.schedule.startAt)
+ .option("--period <duration>", t.schedule.period)
+ .option("--end-at <iso>", t.schedule.endAt)
+ .option("--session-id <id>", t.schedule.sessionId)
+ .option("--workspace <path>", t.schedule.workspace)
+ .option("--model-id <id>", t.common.modelId)
+ .option("--provider <group>", t.common.provider)
+ .option("--disabled", t.schedule.disabledOpt)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.agentId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (name: string, opts) => {
+ if (!validateTarget(opts, t)) return;
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agentId = resolveAgentId(opts.agentId);
+ const item = await client.request<ScheduleItem>(
+ "POST",
+ `/api/projects/${enc(projectId)}/agents/${enc(agentId)}/schedules`,
+ {
+ name,
+ // The deliberate divergence from the raw file's enabled=false default: a task
+ // added through the CLI is meant to run; --disabled opts out.
+ enabled: opts.disabled !== true,
+ prompt: String(opts.prompt),
+ startAt: resolveStartAt(String(opts.startAt)),
+ ...(opts.period !== undefined ? { period: String(opts.period) } : {}),
+ ...(opts.endAt !== undefined ? { endAt: String(opts.endAt) } : {}),
+ ...(opts.sessionId !== undefined ? { sessionId: String(opts.sessionId) } : {}),
+ ...(opts.workspace !== undefined ? { workspace: String(opts.workspace) } : {}),
+ ...(opts.modelId !== undefined
+ ? { modelId: String(opts.modelId), provider: String(opts.provider) }
+ : {}),
+ },
+ );
+ if (opts.json === true) process.stdout.write(`${JSON.stringify(item)}\n`);
+ else process.stdout.write(`${writtenLine(t, item)}\n`);
+ });
+
+ schedule
+ .command("update <name>")
+ .description(t.schedule.updateDesc)
+ .option("--prompt <text>", t.schedule.prompt)
+ .option("--start-at <when>", t.schedule.startAt)
+ .option("--period <duration>", t.schedule.period)
+ .option("--end-at <iso>", t.schedule.endAt)
+ .option("--session-id <id>", t.schedule.sessionId)
+ .option("--workspace <path>", t.schedule.workspace)
+ .option("--model-id <id>", t.common.modelId)
+ .option("--provider <group>", t.common.provider)
+ .option("--enable", t.schedule.enableOpt)
+ .option("--disable", t.schedule.disableOpt)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.agentId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (name: string, opts) => {
+ if (!validateTarget(opts, t)) return;
+ if (opts.enable === true && opts.disable === true) {
+ process.stderr.write(`${t.error(t.schedule.enableDisableConflict())}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agentId = resolveAgentId(opts.agentId);
+ const base = `/api/projects/${enc(projectId)}/agents/${enc(agentId)}/schedules`;
+ // Read-modify-write: unspecified fields keep the stored values; a target flag of
+ // one kind clears the other kind's stored fields (the file holds one target).
+ const stored = await client.request<ScheduleItem>("GET", `${base}/${enc(name)}`);
+ const switchToSession = opts.sessionId !== undefined;
+ const switchToNew =
+ opts.workspace !== undefined || opts.modelId !== undefined || opts.provider !== undefined;
+ const body: Record<string, unknown> = {
+ enabled: opts.enable === true ? true : opts.disable === true ? false : stored.enabled,
+ prompt: opts.prompt !== undefined ? String(opts.prompt) : stored.prompt,
+ startAt: opts.startAt !== undefined ? resolveStartAt(String(opts.startAt)) : stored.startAt,
+ };
+ const period = opts.period !== undefined ? String(opts.period) : stored.period;
+ if (period !== undefined) body.period = period;
+ const endAt = opts.endAt !== undefined ? String(opts.endAt) : stored.endAt;
+ if (endAt !== undefined) body.endAt = endAt;
+ if (switchToSession) {
+ body.sessionId = String(opts.sessionId);
+ } else if (switchToNew) {
+ const workspace = opts.workspace !== undefined ? String(opts.workspace) : stored.workspace;
+ if (workspace !== undefined) body.workspace = workspace;
+ const modelId = opts.modelId !== undefined ? String(opts.modelId) : stored.modelId;
+ const provider = opts.provider !== undefined ? String(opts.provider) : stored.provider;
+ if (modelId !== undefined) {
+ body.modelId = modelId;
+ body.provider = provider;
+ }
+ } else {
+ if (stored.sessionId !== undefined) body.sessionId = stored.sessionId;
+ if (stored.workspace !== undefined) body.workspace = stored.workspace;
+ if (stored.modelId !== undefined) {
+ body.modelId = stored.modelId;
+ body.provider = stored.provider;
+ }
+ }
+ const item = await client.request<ScheduleItem>("PUT", `${base}/${enc(name)}`, body);
+ if (opts.json === true) process.stdout.write(`${JSON.stringify(item)}\n`);
+ else process.stdout.write(`${writtenLine(t, item)}\n`);
+ });
+
+ schedule
+ .command("rm <name>")
+ .description(t.schedule.rmDesc)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--agent-id <id>", t.common.agentId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (name: string, opts) => {
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const agentId = resolveAgentId(opts.agentId);
+ await client.request(
+ "DELETE",
+ `/api/projects/${enc(projectId)}/agents/${enc(agentId)}/schedules/${enc(name)}`,
+ );
+ if (opts.json === true) process.stdout.write(`${JSON.stringify({ name })}\n`);
+ else process.stdout.write(`${t.schedule.removed(name)}\n`);
+ });
+}
+
+/**
+ * Target validation shared by add/update: `--session-id` XOR the new-session form, and
+ * the model pair both-or-neither (never inferred, as everywhere). Returns false after
+ * printing the error.
+ */
+function validateTarget(
+ opts: {
+ sessionId?: string;
+ workspace?: string;
+ modelId?: string;
+ provider?: string;
+ },
+ t: Messages,
+): boolean {
+ if (Boolean(opts.modelId) !== Boolean(opts.provider)) {
+ process.stderr.write(`${t.error(t.modelRefIncomplete())}\n`);
+ process.exitCode = 1;
+ return false;
+ }
+ if (
+ opts.sessionId !== undefined &&
+ (opts.workspace !== undefined || opts.modelId !== undefined)
+ ) {
+ process.stderr.write(`${t.error(t.schedule.targetConflict())}\n`);
+ process.exitCode = 1;
+ return false;
+ }
+ return true;
+}
diff --git a/packages/cli/src/duration.ts b/packages/cli/src/duration.ts
new file mode 100644
index 00000000..34b536bb
--- /dev/null
+++ b/packages/cli/src/duration.ts
@@ -0,0 +1,14 @@
+/**
+ * `--timeout` duration parsing for the waiting commands (`run`, `input`, `logs -f`).
+ * Accepted shapes: `30s`, `5m`, `2h`, or a bare non-negative integer meaning seconds.
+ * `0` (any unit) is legal and means "do not wait at all" — return right after delivery.
+ * Anything else is rejected by returning null (the caller prints the localized error).
+ */
+export function parseDurationMs(raw: string): number | null {
+ const m = /^(\d+)([smh])?$/.exec(raw.trim());
+ if (m === null) return null;
+ const n = Number(m[1]);
+ if (!Number.isSafeInteger(n) || n < 0) return null;
+ const unit = m[2] ?? "s";
+ return n * (unit === "s" ? 1000 : unit === "m" ? 60_000 : 3_600_000);
+}
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index fbb798ea..2caaa650 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -38,6 +38,29 @@ export interface Messages {
approve: string;
/** run/chat's --thinking: the session's thinking level (selectable tiers only, mirrors the web picker). */
thinking: string;
+ /** Machine-readable output (raw JSON instead of the rendered/tabular form). */
+ json: string;
+ /** --server: explicit server URL (overrides PENGUIN_API_URL, the local lock and auto-start). */
+ server: string;
+ /** --timeout: soft-yield wait budget on run/input/logs -f (30s / 5m / 2h / bare seconds). */
+ timeout: string;
+ /** input/logs' --agent-id: whose most recent session the omitted session argument means. */
+ latestAgentId: string;
+ };
+ /** Commander's own parse failures, rebuilt in the user's language (see usage-error.ts). */
+ usage: {
+ /** A required positional argument was not given. */
+ missingArgument(name: string): string;
+ /** A required option (commander's requiredOption) was not given. */
+ missingOption(flags: string): string;
+ /** An option that takes a value was given none. */
+ optionMissingArgument(flags: string): string;
+ unknownOption(flag: string): string;
+ unknownCommand(name: string): string;
+ /** Everything else commander rejects: its own detail rides verbatim, so nothing is swallowed. */
+ other(detail: string): string;
+ /** Second line of a usage error: how the command is spelled, and where its full option list is. */
+ hint(command: string, usage: string): string;
};
config: {
desc: string;
@@ -81,6 +104,14 @@ export interface Messages {
message: string;
/** run's --goal: goal mode, with an optional token budget value (`--goal 500k`). */
goal: string;
+ /** run's --session: reuse an existing Session (full id or unique fragment). */
+ session: string;
+ /** run's --background: POST the task and exit immediately, printing the session id. */
+ background: string;
+ /** --session combined with --workspace / the model pair: neither can change after creation. */
+ sessionNoOverride(): string;
+ /** --background never waits, so a wait budget cannot apply to it. */
+ timeoutWithBackground(): string;
};
chat: {
desc: string;
@@ -88,6 +119,166 @@ export interface Messages {
/** chat's --verbose: start with full tool output (collapsing off). */
verbose: string;
};
+ /** `penguin ls`: session listing. */
+ ls: {
+ desc: string;
+ /** -a/--all: include archived sessions. */
+ all: string;
+ /** --days: keep sessions last active within the trailing n calendar days (today = day 1). */
+ days: string;
+ daysInvalid(value: string): string;
+ empty(projectId: string): string;
+ colId(): string;
+ colAgent(): string;
+ colTitle(): string;
+ colState(): string;
+ colLast(): string;
+ colWorkspace(): string;
+ stateIdle(): string;
+ stateRunning(): string;
+ };
+ /** `penguin input`: send a message into an existing session (steer when running, task when idle). */
+ input: {
+ desc: string;
+ message: string;
+ /** Poll form on a session that has produced no assistant text yet. */
+ noReplyYet(): string;
+ };
+ /** `penguin logs`: render a session's history, optionally following the live stream. */
+ logs: {
+ desc: string;
+ tail: string;
+ follow: string;
+ tailInvalid(value: string): string;
+ /** --timeout without -f: there is no wait to bound. */
+ timeoutNeedsFollow(): string;
+ };
+ /** `penguin agent`: agent listing and creation. */
+ agent: {
+ desc: string;
+ lsDesc: string;
+ createDesc: string;
+ createId: string;
+ createName: string;
+ createDescription: string;
+ /** --skills: comma-separated library skill names to seed the new agent with. */
+ createSkills: string;
+ created(agentId: string, projectId: string): string;
+ colId(): string;
+ colName(): string;
+ colSessions(): string;
+ colDescription(): string;
+ };
+ /** `penguin project`: project listing. */
+ project: {
+ desc: string;
+ lsDesc: string;
+ colId(): string;
+ colName(): string;
+ colRole(): string;
+ };
+ /** `penguin cost`: token/cost aggregates. */
+ cost: {
+ desc: string;
+ days: string;
+ from: string;
+ to: string;
+ by: string;
+ rangeIncomplete(): string;
+ daysInvalid(value: string): string;
+ byInvalid(value: string): string;
+ today(): string;
+ last7d(): string;
+ total(): string;
+ empty(): string;
+ /** Cost cell when no model in the bucket has pricing configured. */
+ noPricing(): string;
+ colTokens(): string;
+ colRequests(): string;
+ colCost(): string;
+ colGroup(dimension: string): string;
+ };
+ /** `penguin schedule`: scheduled-task listing and management (a validated writer over the schedules API; the TOML file stays the single source of truth). */
+ schedule: {
+ desc: string;
+ lsDesc: string;
+ addDesc: string;
+ updateDesc: string;
+ rmDesc: string;
+ /** --prompt: the text the firing sends. */
+ prompt: string;
+ /** --start-at: first fire time, ISO 8601 — or the literal `now` for the current instant. */
+ startAt: string;
+ /** --period: fixed interval (30m / 12h / 1d / 7d, minimum 5m); omitted = one-shot. */
+ period: string;
+ /** --end-at: stop firing after this instant (ISO 8601). */
+ endAt: string;
+ /** --session-id: bind firings to one session (excludes the new-session form). */
+ sessionId: string;
+ /** --workspace: new-session mode's workspace (omitted = a temp workspace per firing). */
+ workspace: string;
+ /** add's --disabled: opt out of the CLI's enabled-by-default divergence. */
+ disabledOpt: string;
+ /** update's --enable / --disable pair. */
+ enableOpt: string;
+ disableOpt: string;
+ enableDisableConflict(): string;
+ /** --session-id given together with the new-session form: the target is one or the other. */
+ targetConflict(): string;
+ /** Confirmation after add/update; nextFireAt is absent for done/disabled/invalid tasks. */
+ written(name: string, enabledText: string, nextFireAt: string | undefined): string;
+ removed(name: string): string;
+ enabled(): string;
+ disabled(): string;
+ /** Period column for a one-off task (no period configured). */
+ oneShot(): string;
+ /** Target column when the schedule creates a new session each firing. */
+ newSession(): string;
+ empty(projectId: string): string;
+ colName(): string;
+ colEnabled(): string;
+ colStartAt(): string;
+ colPeriod(): string;
+ colTarget(): string;
+ colLastFired(): string;
+ colStatus(): string;
+ };
+ /** Server-connection layer: resolution, auto-start, tokens, streams. */
+ client: {
+ invalidServerUrl(value: string): string;
+ /** --server names a non-loopback URL and no PENGUIN_API_TOKEN is set (the local token file must not travel). */
+ remoteNeedsToken(url: string): string;
+ /** No server reachable and auto-start was disabled by the caller. */
+ noServer(): string;
+ /** Auto-start impossible: the CLI entry is not plain-node runnable (tsx dev run). */
+ autoStartUnavailable(): string;
+ autoStartFailed(logPath: string): string;
+ /** Printed to stderr when a server was auto-started for this invocation. */
+ autoStarted(url: string, logPath: string): string;
+ /** 401 with no token found anywhere (env or file). */
+ noToken(url: string, tokenPath: string): string;
+ /** 401 despite presenting a token. */
+ authFailed(url: string): string;
+ httpError(status: number, code: string, message: string): string;
+ sessionNotFound(ref: string, projectId: string): string;
+ sessionAmbiguous(ref: string, candidates: string[]): string;
+ /** The SSE stream dropped and reconnecting gave up. */
+ streamLost(detail: string): string;
+ /** resync_required: the reconnect fell off the server's replay buffer (a display gap, not data loss). */
+ streamResynced(): string;
+ /** Invalid --timeout value (names the accepted shapes). */
+ timeoutInvalid(value: string): string;
+ /** Soft-yield detach: the wait budget expired, the task keeps running server-side. */
+ stillRunning(shortId: string): string;
+ /** Caller-context lookup failed (PENGUIN_SESSION_ID names a session this server cannot answer for): plain defaults apply. */
+ callerDefaultsFailed(sessionId: string): string;
+ /** Dim stderr note naming the session a bare `logs` / `input` resolved to (the agent's most recent). */
+ latestSession(sessionId: string): string;
+ /** Bare `logs` / `input` when the agent has no session at all: what to run to get one. */
+ noSessionsYet(agentId: string, projectId: string): string;
+ };
+ /** `/thinking` display when the Session pins no level: the Agent's configured default applies. */
+ chatThinkingConfigured(): string;
serve: {
serverDesc: string;
webDesc: string;
@@ -363,6 +554,22 @@ const en: Messages = {
"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, xhigh, or max (defaults to the Agent's configured level)",
+ json: "Print raw JSON instead of the rendered output",
+ server:
+ "Server URL to connect to (defaults to PENGUIN_API_URL, then the local running server, then auto-start)",
+ timeout:
+ "Wait at most this long (30s / 5m / 2h, or bare seconds), then detach and leave the task running (exit 0)",
+ latestAgentId: "Agent whose most recent session is used when no session id is given",
+ },
+ usage: {
+ missingArgument: (name) => `missing required argument <${name}>`,
+ missingOption: (flags) => `missing required option ${flags}`,
+ optionMissingArgument: (flags) => `option ${flags} needs a value`,
+ unknownOption: (flag) => `unknown option ${flag}`,
+ unknownCommand: (name) => `unknown command ${name}`,
+ other: (detail) => detail,
+ hint: (command, usage) =>
+ `Usage: ${command} ${usage} (run \`${command} --help\` for every option)`,
},
config: {
desc: "Manage Project configuration",
@@ -409,6 +616,12 @@ const en: Messages = {
desc: "Run a single Task",
message: "Prompt for this Task",
goal: "Goal mode: loop until the goal completes; optional token budget (e.g. 500k, 2m)",
+ session: "Reuse an existing Session (full id or a unique fragment, e.g. the 8-hex tail)",
+ background: "Post the task and exit immediately, printing the session id",
+ sessionNoOverride: () =>
+ "--session reuses an existing Session: --workspace, --model-id and --provider cannot be combined with it (neither can change after creation).",
+ timeoutWithBackground: () =>
+ "--timeout bounds the wait, and --background does not wait: drop one of them.",
},
chat: {
desc: "Open the interactive REPL",
@@ -417,6 +630,144 @@ const en: Messages = {
verbose:
"Show full tool output (by default long tool outputs are collapsed to their first and last lines; /verbose toggles it mid-chat)",
},
+ ls: {
+ desc: "List the project's sessions (all agents unless --agent-id is given)",
+ all: "Include archived sessions",
+ days: "Only sessions last active within the trailing <n> calendar days (today counts as day 1)",
+ daysInvalid: (value) => `Invalid --days value "${value}": expected a positive integer.`,
+ empty: (projectId) => `No sessions in project ${projectId} yet.`,
+ colId: () => "ID",
+ colAgent: () => "AGENT",
+ colTitle: () => "TITLE",
+ colState: () => "STATE",
+ colLast: () => "LAST",
+ colWorkspace: () => "WORKSPACE",
+ stateIdle: () => "idle",
+ stateRunning: () => "running",
+ },
+ input: {
+ desc: "Send a message into a session (steering while it runs, a new task when idle); without -m, print its most recent assistant reply. The session defaults to the agent's most recent one",
+ message: "Message text (omit to poll the session's last assistant reply instead)",
+ noReplyYet: () => "(no assistant reply yet)",
+ },
+ logs: {
+ desc: "Render a session's history (defaults to the agent's most recent session)",
+ tail: "Show only the last <n> entries",
+ follow: "Keep following the live stream after the history",
+ tailInvalid: (value) => `Invalid --tail value "${value}": expected a positive integer.`,
+ timeoutNeedsFollow: () =>
+ "--timeout only applies to -f/--follow: without it, logs never waits.",
+ },
+ agent: {
+ desc: "Manage the project's agents",
+ lsDesc: "List the project's agents",
+ createDesc: "Create an agent",
+ createId: "Agent id (directory name; letters, digits, underscores)",
+ createName: "Display name (defaults to the id)",
+ createDescription: "Description",
+ createSkills: "Library skills to preinstall, comma-separated (e.g. web-search,pdf)",
+ created: (agentId, projectId) => `Agent ${agentId} created in project ${projectId}.`,
+ colId: () => "ID",
+ colName: () => "NAME",
+ colSessions: () => "SESSIONS",
+ colDescription: () => "DESCRIPTION",
+ },
+ project: {
+ desc: "Manage projects",
+ lsDesc: "List the projects this account can reach",
+ colId: () => "ID",
+ colName: () => "NAME",
+ colRole: () => "ROLE",
+ },
+ cost: {
+ desc: "Show token usage and cost (summary card by default; --by prints a grouped table)",
+ days: "Trailing window in days (sets --from/--to)",
+ from: "Range start (yyyy-mm-dd); requires --to",
+ to: "Range end (yyyy-mm-dd); requires --from",
+ by: "Group the table by: date, agent, model or session",
+ rangeIncomplete: () => "--from and --to must be given together.",
+ daysInvalid: (value) => `Invalid --days value "${value}": expected a positive integer.`,
+ byInvalid: (value) => `Invalid --by value "${value}": expected date, agent, model or session.`,
+ today: () => "today",
+ last7d: () => "last 7 days",
+ total: () => "total",
+ empty: () => "No usage recorded for this range.",
+ noPricing: () => "-",
+ colTokens: () => "TOKENS",
+ colRequests: () => "REQUESTS",
+ colCost: () => "COST",
+ colGroup: (dimension) => dimension.toUpperCase(),
+ },
+ schedule: {
+ desc: "Manage scheduled tasks",
+ lsDesc: "List the project's scheduled tasks (all agents unless --agent-id is given)",
+ addDesc:
+ "Create a scheduled task (writes the schedule file through the API; enabled by default — use --disabled to opt out)",
+ updateDesc:
+ "Update a scheduled task (read-modify-write: unspecified fields keep their stored values)",
+ rmDesc: "Delete a scheduled task (no prompt; the server's owner authorization applies)",
+ prompt: "The text each firing sends",
+ startAt: "First fire time (ISO 8601), or the literal `now` for the current instant",
+ period: "Fixed interval, minimum 5m (e.g. 30m, 12h, 1d, 7d); omitted = one-shot",
+ endAt: "Stop firing after this instant (ISO 8601)",
+ sessionId: "Bind firings to one session (excludes --workspace / the model pair)",
+ workspace: "New-session mode: workspace for each firing (omitted = a temp workspace)",
+ disabledOpt: "Create the task disabled (the CLI default is enabled)",
+ enableOpt: "Enable the task",
+ disableOpt: "Disable the task",
+ enableDisableConflict: () => "--enable and --disable are mutually exclusive.",
+ targetConflict: () =>
+ "--session-id and the new-session form (--workspace / --model-id / --provider) are mutually exclusive: the target is one or the other.",
+ written: (name, enabledText, nextFireAt) =>
+ `Schedule ${name} written (${enabledText}${nextFireAt !== undefined ? `, next fire ${nextFireAt}` : ""}).`,
+ removed: (name) => `Schedule ${name} removed.`,
+ enabled: () => "on",
+ disabled: () => "off",
+ oneShot: () => "once",
+ newSession: () => "new session",
+ empty: (projectId) => `No scheduled tasks in project ${projectId}.`,
+ colName: () => "NAME",
+ colEnabled: () => "ENABLED",
+ colStartAt: () => "START",
+ colPeriod: () => "PERIOD",
+ colTarget: () => "TARGET",
+ colLastFired: () => "LAST FIRED",
+ colStatus: () => "STATUS",
+ },
+ client: {
+ invalidServerUrl: (value) => `Invalid server URL "${value}": expected http(s)://host[:port].`,
+ remoteNeedsToken: (url) =>
+ `${url} is not this machine: set PENGUIN_API_TOKEN to authenticate against a remote server (the local api-token file never leaves its own data root).`,
+ noServer: () => "No running server found for this data root.",
+ autoStartUnavailable: () =>
+ "No running server found, and this CLI entry cannot auto-start one (development run). Start it yourself with `penguin server`.",
+ autoStartFailed: (logPath) =>
+ `The auto-started server did not come up. Its output is in ${logPath}.`,
+ autoStarted: (url, logPath) => `Started a local server at ${url} (log: ${logPath}).`,
+ noToken: (url, tokenPath) =>
+ `${url} rejected the request (401) and no API token is available: set PENGUIN_API_TOKEN, or make sure the server's token file is readable at ${tokenPath}.`,
+ authFailed: (url) =>
+ `${url} rejected the API token (401). If the server restarted, its token rotated — check PENGUIN_API_TOKEN, or let the CLI read the current api-token file.`,
+ httpError: (status, code, message) =>
+ `Server error ${status} (${code})${message ? `: ${message}` : ""}`,
+ sessionNotFound: (ref, projectId) =>
+ `No session matching "${ref}" in project ${projectId} (try \`penguin ls\`).`,
+ sessionAmbiguous: (ref, candidates) =>
+ `"${ref}" matches ${candidates.length} sessions:\n ${candidates.join("\n ")}\nUse a longer fragment or the full id.`,
+ streamLost: (detail) => `Lost the server stream and reconnecting failed: ${detail}`,
+ streamResynced: () =>
+ "[stream] reconnected past the server's replay buffer; some output may be missing here (penguin logs shows the full history)",
+ timeoutInvalid: (value) =>
+ `Invalid --timeout value "${value}": expected 30s, 5m, 2h, or a bare number of seconds.`,
+ stillRunning: (shortId) =>
+ `[still running] session ${shortId} continues on the server — follow with \`penguin logs -f ${shortId}\` or poll with \`penguin input ${shortId}\``,
+ callerDefaultsFailed: (sessionId) =>
+ `[caller context] could not read calling session ${sessionId}; using the plain defaults`,
+ latestSession: (sessionId) => `[latest] session ${sessionId}`,
+ noSessionsYet: (agentId, projectId) =>
+ `Agent ${agentId} has no sessions in project ${projectId} yet: start one with \`penguin run -m "..."\` or \`penguin chat\`.`,
+ },
+ chatThinkingConfigured: () => "agent default",
serve: {
serverDesc:
"Start the Web service (HTTP API and the built-in frontend, same process); subcommand reset-admin-password resets a forgotten admin password",
@@ -684,6 +1035,21 @@ const zh: Messages = {
approve:
"审批模式:allow-all(全部放行,缺省)、deny-all(全部拒绝)、read-only(自动放行只读工具,其余仍逐个询问)、always-ask(逐个询问)",
thinking: "本会话的思考等级:low、medium、high、xhigh 或 max(缺省用 Agent 配置的等级)",
+ json: "输出原始 JSON,不做渲染",
+ server: "要连接的服务器地址(缺省依次取 PENGUIN_API_URL、本机运行中的服务器、自动拉起)",
+ timeout:
+ "最长等待时长(30s / 5m / 2h,或纯数字秒数);到时脱开、任务继续在服务端运行(退出码 0)",
+ latestAgentId: "省略 session id 时,取哪个 Agent 的最近一次会话",
+ },
+ usage: {
+ missingArgument: (name) => `缺少必填参数 <${name}>`,
+ missingOption: (flags) => `缺少必填选项 ${flags}`,
+ optionMissingArgument: (flags) => `选项 ${flags} 缺少取值`,
+ unknownOption: (flag) => `未知选项 ${flag}`,
+ unknownCommand: (name) => `未知命令 ${name}`,
+ other: (detail) => detail,
+ hint: (command, usage) =>
+ `用法:${command} ${usage}(运行 \`${command} --help\` 查看全部选项)`,
},
config: {
desc: "管理 Project 配置",
@@ -726,6 +1092,11 @@ const zh: Messages = {
desc: "单次运行一个 Task",
message: "本次 Task 的 Prompt",
goal: "目标模式:循环运行直至目标完成;可选 token 预算(如 500k、2m)",
+ session: "复用既有 Session(完整 id 或唯一片段,如末尾 8 位十六进制)",
+ background: "提交任务后立即退出,打印 session id",
+ sessionNoOverride: () =>
+ "--session 复用既有 Session:不能与 --workspace、--model-id、--provider 同时使用(二者创建后不可更换)。",
+ timeoutWithBackground: () => "--timeout 限定等待,而 --background 不等待:二者去其一。",
},
chat: {
desc: "打开交互式 REPL",
@@ -733,6 +1104,139 @@ const zh: Messages = {
"恢复既有 Session 继续对话(缺省恢复当前 Agent 最近一次);Workspace 与模型沿用原 Session",
verbose: "显示完整工具输出(缺省折叠过长的工具输出、只保留首尾数行;/verbose 可随时切换)",
},
+ ls: {
+ desc: "列出 Project 的会话(未指定 --agent-id 时覆盖全部 Agent)",
+ all: "包含已归档会话",
+ days: "只列最近 <n> 个自然日内活跃过的会话(今天算第 1 天)",
+ daysInvalid: (value) => `--days 值「${value}」无效:应为正整数。`,
+ empty: (projectId) => `Project ${projectId} 还没有会话。`,
+ colId: () => "ID",
+ colAgent: () => "AGENT",
+ colTitle: () => "标题",
+ colState: () => "状态",
+ colLast: () => "最近活动",
+ colWorkspace: () => "WORKSPACE",
+ stateIdle: () => "空闲",
+ stateRunning: () => "运行中",
+ },
+ input: {
+ desc: "向会话发送消息(运行中即插话,空闲时发起新 Task);不带 -m 时输出其最近一条助手回复。省略 session id 即取当前 Agent 最近一次会话",
+ message: "消息文本(省略时改为轮询该会话的最近助手回复)",
+ noReplyYet: () => "(还没有助手回复)",
+ },
+ logs: {
+ desc: "渲染会话的历史消息(省略 session id 即取当前 Agent 最近一次会话)",
+ tail: "只显示最后 <n> 条",
+ follow: "渲染历史后继续跟随实时输出流",
+ tailInvalid: (value) => `--tail 值「${value}」无效:应为正整数。`,
+ timeoutNeedsFollow: () => "--timeout 只与 -f/--follow 搭配:不跟随时 logs 不等待。",
+ },
+ agent: {
+ desc: "管理 Project 的 Agent",
+ lsDesc: "列出 Project 的 Agent",
+ createDesc: "创建 Agent",
+ createId: "Agent id(即目录名;字母、数字、下划线)",
+ createName: "显示名(缺省同 id)",
+ createDescription: "描述",
+ createSkills: "预装的技能库 Skill,逗号分隔(如 web-search,pdf)",
+ created: (agentId, projectId) => `已在 Project ${projectId} 创建 Agent ${agentId}。`,
+ colId: () => "ID",
+ colName: () => "名称",
+ colSessions: () => "会话数",
+ colDescription: () => "描述",
+ },
+ project: {
+ desc: "管理 Project",
+ lsDesc: "列出当前账号可用的 Project",
+ colId: () => "ID",
+ colName: () => "名称",
+ colRole: () => "角色",
+ },
+ cost: {
+ desc: "查看 Token 用量与成本(缺省打印汇总卡片;--by 打印分组表格)",
+ days: "最近 n 天(自动换算为 --from/--to)",
+ from: "起始日期(yyyy-mm-dd);须与 --to 成对",
+ to: "结束日期(yyyy-mm-dd);须与 --from 成对",
+ by: "分组维度:date、agent、model 或 session",
+ rangeIncomplete: () => "--from 与 --to 必须成对给出。",
+ daysInvalid: (value) => `--days 值「${value}」无效:应为正整数。`,
+ byInvalid: (value) => `--by 值「${value}」无效:应为 date、agent、model 或 session。`,
+ today: () => "今日",
+ last7d: () => "近 7 天",
+ total: () => "累计",
+ empty: () => "该范围内没有用量记录。",
+ noPricing: () => "-",
+ colTokens: () => "TOKEN",
+ colRequests: () => "请求数",
+ colCost: () => "成本",
+ colGroup: (dimension) => dimension.toUpperCase(),
+ },
+ schedule: {
+ desc: "管理定时任务",
+ lsDesc: "列出 Project 的定时任务(未指定 --agent-id 时覆盖全部 Agent)",
+ addDesc: "创建定时任务(经 API 写入任务文件;缺省即启用——用 --disabled 关闭)",
+ updateDesc: "更新定时任务(读改写:未指定的字段保留存储值)",
+ rmDesc: "删除定时任务(不做确认;服务端的 owner 授权照旧生效)",
+ prompt: "每次触发要发送的内容",
+ startAt: "首次触发时刻(ISO 8601),或字面量 `now` 表示当前时刻",
+ period: "固定间隔,下限 5m(如 30m、12h、1d、7d);省略即一次性任务",
+ endAt: "此时刻之后不再触发(ISO 8601)",
+ sessionId: "绑定到某个会话触发(与 --workspace / 模型对互斥)",
+ workspace: "新建会话模式:每次触发所用 Workspace(省略即自动创建临时工作区)",
+ disabledOpt: "以停用状态创建(CLI 缺省为启用)",
+ enableOpt: "启用该任务",
+ disableOpt: "停用该任务",
+ enableDisableConflict: () => "--enable 与 --disable 互斥。",
+ targetConflict: () =>
+ "--session-id 与新建会话形式(--workspace / --model-id / --provider)互斥:目标二选一。",
+ written: (name, enabledText, nextFireAt) =>
+ `定时任务 ${name} 已写入(${enabledText}${nextFireAt !== undefined ? `,下次触发 ${nextFireAt}` : ""})。`,
+ removed: (name) => `定时任务 ${name} 已删除。`,
+ enabled: () => "开",
+ disabled: () => "关",
+ oneShot: () => "一次性",
+ newSession: () => "新建会话",
+ empty: (projectId) => `Project ${projectId} 没有定时任务。`,
+ colName: () => "名称",
+ colEnabled: () => "启用",
+ colStartAt: () => "开始时刻",
+ colPeriod: () => "周期",
+ colTarget: () => "目标",
+ colLastFired: () => "最近触发",
+ colStatus: () => "状态",
+ },
+ client: {
+ invalidServerUrl: (value) => `服务器地址「${value}」无效:应为 http(s)://host[:port]。`,
+ remoteNeedsToken: (url) =>
+ `${url} 不是本机:连接远端服务器须设置 PENGUIN_API_TOKEN(本机的 api-token 文件不会发往其它主机)。`,
+ noServer: () => "该数据根目录没有正在运行的服务器。",
+ autoStartUnavailable: () =>
+ "没有正在运行的服务器,且当前 CLI 入口无法自动拉起(开发态运行)。请自行执行 `penguin server`。",
+ autoStartFailed: (logPath) => `自动启动的服务器未能就绪,输出见 ${logPath}。`,
+ autoStarted: (url, logPath) => `已在本机启动服务器 ${url}(日志:${logPath})。`,
+ noToken: (url, tokenPath) =>
+ `${url} 拒绝了请求(401),且没有可用的 API token:请设置 PENGUIN_API_TOKEN,或确认服务器的 token 文件可读(${tokenPath})。`,
+ authFailed: (url) =>
+ `${url} 拒绝了 API token(401)。服务器重启会轮换 token——检查 PENGUIN_API_TOKEN,或让 CLI 读取最新的 api-token 文件。`,
+ httpError: (status, code, message) =>
+ `服务器错误 ${status}(${code})${message ? `:${message}` : ""}`,
+ sessionNotFound: (ref, projectId) =>
+ `Project ${projectId} 中没有匹配「${ref}」的会话(可用 \`penguin ls\` 查看)。`,
+ sessionAmbiguous: (ref, candidates) =>
+ `「${ref}」匹配到 ${candidates.length} 个会话:\n ${candidates.join("\n ")}\n请使用更长的片段或完整 id。`,
+ streamLost: (detail) => `与服务器的输出流断开且重连失败:${detail}`,
+ streamResynced: () =>
+ "[stream] 重连时已超出服务端回放缓冲,此处可能缺少部分输出(penguin logs 可查看完整历史)",
+ timeoutInvalid: (value) => `--timeout 值「${value}」无效:应为 30s、5m、2h 或纯数字秒数。`,
+ stillRunning: (shortId) =>
+ `[仍在运行] 会话 ${shortId} 继续在服务端执行——可用 \`penguin logs -f ${shortId}\` 跟随,或 \`penguin input ${shortId}\` 轮询`,
+ callerDefaultsFailed: (sessionId) =>
+ `[调用方上下文] 无法读取调用方会话 ${sessionId},改用普通缺省值`,
+ latestSession: (sessionId) => `[latest] 会话 ${sessionId}`,
+ noSessionsYet: (agentId, projectId) =>
+ `Agent ${agentId} 在 Project ${projectId} 下还没有任何会话:先用 \`penguin run -m "..."\` 或 \`penguin chat\` 开始一个。`,
+ },
+ chatThinkingConfigured: () => "Agent 配置值",
serve: {
serverDesc:
"启动 Web 服务(HTTP API 与内置前端,同一进程);子命令 reset-admin-password 重置忘记的管理员密码",
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 914cad4c..f5749754 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -11,9 +11,17 @@ import { buildInfo } from "@prismshadow/penguin-core";
import { registerConfigCommand } from "./commands/config.js";
import { registerRunCommand } from "./commands/run.js";
import { registerChatCommand } from "./commands/chat.js";
+import { registerLsCommand } from "./commands/ls.js";
+import { registerInputCommand } from "./commands/input.js";
+import { registerLogsCommand } from "./commands/logs.js";
+import { registerAgentCommand } from "./commands/agent.js";
+import { registerProjectCommand } from "./commands/project.js";
+import { registerCostCommand } from "./commands/cost.js";
+import { registerScheduleCommand } from "./commands/schedule.js";
import { registerServeCommands } from "./commands/serve.js";
import { registerUpdateCommand } from "./commands/update.js";
import { registerVersionCommand } from "./commands/version.js";
+import { reportCommanderError } from "./usage-error.js";
import { defaultMessages } from "./i18n.js";
/**
@@ -31,11 +39,23 @@ export async function cli(argv: string[]): Promise<number> {
// disagree. Commander stores it eagerly, which costs a source build its two git calls on
// every startup; a release build reads stamped constants and spawns nothing.
.version(buildInfo().describe, "-v, --version", t.versionDesc)
- .exitOverride();
+ .exitOverride()
+ // Commander writes its English `error: ...` line before throwing; drop that channel
+ // and report the failure localized from the catch below (see usage-error.ts). Both
+ // settings must be in place before the subcommands are created — that is when they
+ // are copied down (commander's copyInheritedSettings).
+ .configureOutput({ outputError: () => {} });
registerConfigCommand(program, t);
registerRunCommand(program, t);
registerChatCommand(program, t);
+ registerLsCommand(program, t);
+ registerInputCommand(program, t);
+ registerLogsCommand(program, t);
+ registerAgentCommand(program, t);
+ registerProjectCommand(program, t);
+ registerCostCommand(program, t);
+ registerScheduleCommand(program, t);
registerServeCommands(program, t);
registerUpdateCommand(program, t);
registerVersionCommand(program, t);
@@ -51,7 +71,7 @@ export async function cli(argv: string[]): Promise<number> {
await program.parseAsync(argv, { from: "user" });
return typeof process.exitCode === "number" ? process.exitCode : 0;
} catch (err) {
- if (err instanceof CommanderError) return err.exitCode;
+ if (err instanceof CommanderError) return reportCommanderError(err, program, argv, t);
process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
return 1;
} finally {
diff --git a/packages/cli/src/penguin-hmr.ts b/packages/cli/src/penguin-hmr.ts
index 96eb4426..11046d49 100644
--- a/packages/cli/src/penguin-hmr.ts
+++ b/packages/cli/src/penguin-hmr.ts
@@ -2,6 +2,9 @@
* `penguin-hmr`: the CLI currently pushed to this machine's HMR store, instead of the
* one built into this binary. Use `penguin` when nothing is pushed.
*/
+// First import on purpose, as in penguin.ts: the pushed CLI bundle this entry loads
+// reaches node:sqlite the same way (see warnings.ts).
+import "./warnings.js";
import "dotenv/config";
import { pathToFileURL } from "node:url";
import { resolveRoot } from "@prismshadow/penguin-core";
diff --git a/packages/cli/src/penguin.ts b/packages/cli/src/penguin.ts
index e31b4ac6..a1ad4143 100644
--- a/packages/cli/src/penguin.ts
+++ b/packages/cli/src/penguin.ts
@@ -1,4 +1,7 @@
/** `penguin`: the CLI built into this binary. */
+// First import on purpose: it installs the node:sqlite warning filter, and the graph
+// below reaches that builtin while it loads (see warnings.ts).
+import "./warnings.js";
import "dotenv/config";
import { cli } from "./index.js";
diff --git a/packages/cli/src/server-session.ts b/packages/cli/src/server-session.ts
new file mode 100644
index 00000000..7872c4d3
--- /dev/null
+++ b/packages/cli/src/server-session.ts
@@ -0,0 +1,143 @@
+/**
+ * Session/agent API helpers shared by the server-backed commands (run / chat / ls /
+ * input / logs / schedule). DTO shapes come from `@prismshadow/penguin-server/api`
+ * (type-only — nothing of the server is loaded at runtime).
+ */
+import path from "node:path";
+import type {
+ AgentsResponse,
+ AgentSummary,
+ MessagesResponse,
+ SessionCreateResponse,
+ SessionInfo,
+ SessionResponse,
+ SessionsResponse,
+} from "@prismshadow/penguin-server/api";
+import type { OmniMessage } from "@prismshadow/penguin-core";
+import { resolveSessionRef, ServerClient } from "./client.js";
+import { dim } from "./render.js";
+import type { Messages } from "./i18n.js";
+
+const enc = encodeURIComponent;
+
+/**
+ * `--workspace` resolution: the flag (resolved against the CLI's cwd — the server and
+ * the CLI share the machine in the default flow, so a relative path means "relative to
+ * where I am"), else `fallback` — the CLI's cwd historically, or the calling session's
+ * Workspace when the CLI runs inside a harness agent (see callerSessionContext).
+ */
+export function resolveWorkspace(flag: string | undefined, fallback = process.cwd()): string {
+ return flag === undefined || flag.trim() === "" ? fallback : path.resolve(flag);
+}
+
+/**
+ * The calling session's live values, when this CLI runs inside a harness agent
+ * (server-driven sessions inject PENGUIN_SESSION_ID into tool subprocesses): a session
+ * created here defaults each UNSPECIFIED field to the caller's — workspace, the model
+ * pair, approval mode and thinking level — the same inheritance `run_subagent` applies
+ * to spawned children, so the two surfaces read as one convention. Per field the
+ * precedence is explicit flag > caller value > the plain fallback. Null outside an
+ * agent; a failed lookup warns (dim, stderr) and falls back to the plain defaults.
+ */
+export async function callerSessionContext(
+ client: ServerClient,
+ t: Messages,
+): Promise<SessionInfo | null> {
+ const sessionId = process.env.PENGUIN_SESSION_ID?.trim();
+ if (!sessionId) return null;
+ try {
+ return await getSessionInfo(client, sessionId);
+ } catch {
+ process.stderr.write(`${dim(t.client.callerDefaultsFailed(sessionId))}\n`);
+ return null;
+ }
+}
+
+export interface CreateSessionArgs {
+ projectId: string;
+ agentId: string;
+ workspace?: string;
+ modelId?: string;
+ provider?: string;
+ approvalMode?: string;
+}
+
+/** POST .../sessions with the CLI's client hint. */
+export async function createServerSession(
+ client: ServerClient,
+ args: CreateSessionArgs,
+): Promise<SessionInfo> {
+ const { projectId, agentId, ...body } = args;
+ const res = await client.request<SessionCreateResponse>(
+ "POST",
+ `/api/projects/${enc(projectId)}/agents/${enc(agentId)}/sessions`,
+ { ...body, client: "cli" },
+ );
+ return res.session;
+}
+
+export async function getSessionInfo(
+ client: ServerClient,
+ sessionId: string,
+): Promise<SessionInfo> {
+ const res = await client.request<SessionResponse>("GET", `/api/sessions/${enc(sessionId)}`);
+ return res.session;
+}
+
+export async function listAgents(client: ServerClient, projectId: string): Promise<AgentSummary[]> {
+ const res = await client.request<AgentsResponse>("GET", `/api/projects/${enc(projectId)}/agents`);
+ return res.agents;
+}
+
+export async function listAgentSessions(
+ client: ServerClient,
+ projectId: string,
+ agentId: string,
+): Promise<SessionInfo[]> {
+ const res = await client.request<SessionsResponse>(
+ "GET",
+ `/api/projects/${enc(projectId)}/agents/${enc(agentId)}/sessions`,
+ );
+ return res.sessions;
+}
+
+/**
+ * The session `logs` / `input` act on: an explicit reference (full id or unique
+ * fragment) resolves as everywhere else, and omitting it means the agent's most recent
+ * session — the same default `chat --resume` carries, off the same newest-first listing.
+ * The chosen id is announced on stderr as a dim `[latest]` line so the target is never
+ * ambiguous and `--json` on stdout stays parseable.
+ *
+ * Returns null when the agent has no sessions at all, after printing one line pointing
+ * at `penguin run` / `penguin chat` and setting a non-zero exit code.
+ */
+export async function resolveSessionTarget(
+ client: ServerClient,
+ args: { ref: string | undefined; projectId: string; agentId: string },
+ t: Messages,
+): Promise<string | null> {
+ const { ref, projectId, agentId } = args;
+ if (ref !== undefined) return await resolveSessionRef(client, projectId, ref, t);
+ const latest = (await listAgentSessions(client, projectId, agentId))[0];
+ if (latest === undefined) {
+ process.stderr.write(`${t.error(t.client.noSessionsYet(agentId, projectId))}\n`);
+ process.exitCode = 1;
+ return null;
+ }
+ process.stderr.write(`${dim(t.client.latestSession(latest.sessionId))}\n`);
+ return latest.sessionId;
+}
+
+/** GET /messages — full history messages (rendered through renderHistory). */
+export async function getSessionMessages(
+ client: ServerClient,
+ sessionId: string,
+): Promise<OmniMessage[]> {
+ const res = await client.request<MessagesResponse>(
+ "GET",
+ `/api/sessions/${enc(sessionId)}/messages`,
+ );
+ // MessagesResponse messages are OmniMessages plus an optional tracePosition tag the
+ // renderer ignores.
+ return res.messages as unknown as OmniMessage[];
+}
diff --git a/packages/cli/src/server-task.ts b/packages/cli/src/server-task.ts
new file mode 100644
index 00000000..85fcc5cb
--- /dev/null
+++ b/packages/cli/src/server-task.ts
@@ -0,0 +1,276 @@
+/**
+ * Server-backed task machinery shared by `run`, `chat`, `input` and `logs -f`.
+ *
+ * A task is driven entirely by the server; the CLI subscribes to the Session's SSE
+ * stream FIRST (so nothing is missed), POSTs the task, then consumes frames until the
+ * `task_state` flip back to idle:
+ * - default-event frames are OmniMessages, fed straight into StreamRenderer.handle —
+ * the same protocol core streams, so rendering is unchanged;
+ * - `server_event` frames carry `task_state` (end detection; the first event on a
+ * fresh subscription is an authoritative snapshot), `approval_request` (the [Y/n]
+ * prompt → POST /approvals/:toolCallId) and the goal progress events.
+ *
+ * Reconnects ride Last-Event-ID: the stream keeps the last seen frame id and reopens
+ * with it on a dropped connection; `resync_required` (buffer evicted) prints a dim
+ * notice — the messages endpoint still holds the full history for `penguin logs`.
+ */
+import {
+ goalFinishedOf,
+ isEventMessage,
+ isGoalRoundInput,
+ isModelMessage,
+} from "@prismshadow/penguin-core";
+import type {
+ ApprovalDecision,
+ GoalOutcome,
+ OmniMessage,
+ ToolCallPayload,
+} from "@prismshadow/penguin-core";
+import { ServerClient } from "./client.js";
+import type { SseFrame } from "./client.js";
+import { dim, humanizeTokens } from "./render.js";
+import type { StreamRenderer } from "./render.js";
+import type { Messages } from "./i18n.js";
+
+/** Server events the watcher understands (structural subset of the server's ServerEvent union). */
+interface ServerEventFrame {
+ type: string;
+ state?: "idle" | "running" | "compacting";
+ toolCall?: OmniMessage<ToolCallPayload>;
+ origin?: string[];
+}
+
+/**
+ * A Session's SSE subscription with Last-Event-ID reconnects. `next()` yields frames
+ * across reconnects; `close()` ends it. A subscription that drops MID-TASK reconnects
+ * up to `MAX_RECONNECTS` times with a short backoff (the counter resets whenever a
+ * frame actually arrives); a still-failing stream throws to the consumer.
+ */
+export class SessionStream {
+ private lastEventId: string | undefined;
+ private closed = false;
+ private readonly abort = new AbortController();
+ private iterator: AsyncGenerator<SseFrame> | null = null;
+ private attempts = 0;
+
+ private static readonly MAX_RECONNECTS = 5;
+
+ constructor(
+ private readonly client: ServerClient,
+ private readonly sessionId: string,
+ private readonly t: Messages,
+ ) {}
+
+ close(): void {
+ this.closed = true;
+ this.abort.abort();
+ }
+
+ /** The next frame, reconnecting through connection drops; null once closed. */
+ async next(): Promise<SseFrame | null> {
+ for (;;) {
+ if (this.closed) return null;
+ if (this.iterator === null) {
+ this.iterator = this.client.sse(`/api/sessions/${this.sessionId}/stream`, {
+ ...(this.lastEventId !== undefined ? { lastEventId: this.lastEventId } : {}),
+ signal: this.abort.signal,
+ });
+ }
+ try {
+ const { done, value } = await this.iterator.next();
+ if (done) {
+ // Server closed the stream (restart/shutdown): treat like a drop and retry.
+ this.iterator = null;
+ await this.backoff();
+ continue;
+ }
+ this.attempts = 0;
+ if (value.id !== undefined) this.lastEventId = value.id;
+ return value;
+ } catch (err) {
+ if (this.closed) return null;
+ this.iterator = null;
+ await this.backoff(err);
+ }
+ }
+ }
+
+ private async backoff(err?: unknown): Promise<void> {
+ this.attempts += 1;
+ if (this.attempts > SessionStream.MAX_RECONNECTS) {
+ const detail = err instanceof Error ? err.message : String(err ?? "connection lost");
+ throw new Error(this.t.client.streamLost(detail));
+ }
+ await new Promise((resolve) => setTimeout(resolve, 300 * this.attempts));
+ }
+
+ /**
+ * Consumes frames until the initial `task_state` snapshot arrives (the first event of
+ * every subscription) and returns its state — the authoritative "is it running"
+ * answer callers branch on before POSTing.
+ */
+ async waitReady(): Promise<"idle" | "running" | "compacting"> {
+ for (;;) {
+ const frame = await this.next();
+ if (frame === null) throw new Error(this.t.client.streamLost("closed before ready"));
+ if (frame.event !== "server_event") continue;
+ const ev = JSON.parse(frame.data) as ServerEventFrame;
+ if (ev.type === "task_state" && ev.state !== undefined) return ev.state;
+ }
+ }
+}
+
+export interface WatchTaskOptions {
+ client: ServerClient;
+ sessionId: string;
+ t: Messages;
+ /** Renders the stream; omit for `--json` runs (messages are still parsed for text collection). */
+ renderer?: StreamRenderer;
+ /**
+ * Answers an `approval_request` (the [Y/n] prompt); the decision is POSTed back.
+ * Absent = the request is left pending untouched — a passive watcher (the poll form,
+ * `--json` collectors) must never decide another surface's approvals.
+ */
+ approvalPrompt?: (tc: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
+ /** Goal mode: receives the dim round/summary lines (same rhythm as the core-direct loop had); a minimal sink so --json can swallow them. */
+ goal?: { out: { write(text: string): unknown } };
+ /** Collects main-session assistant text (complete messages) for `--json` output. */
+ onAssistantText?: (text: string) => void;
+ /**
+ * `--timeout` soft-yield deadline (epoch ms): once it passes, the watch detaches
+ * cleanly and reports `timedOut` — the exec_command yield-window semantics, applied to
+ * the wait rather than the task. The task keeps running server-side; nothing is
+ * aborted. Absent = wait indefinitely.
+ */
+ deadlineMs?: number;
+}
+
+/** Result of one watched task. */
+export interface WatchTaskResult {
+ /** The task ended with a main-session abort event (user interrupt / LLM failure). */
+ aborted: boolean;
+ /** The `deadlineMs` budget expired before the task ended: the watch detached, the task runs on. */
+ timedOut: boolean;
+ /** Goal-mode outcome (absent when the stream ended before the terminal event). */
+ goal?: GoalOutcome;
+}
+
+/**
+ * One frame, racing the soft-yield deadline: "timeout" once `deadlineMs` passes. The
+ * losing `stream.next()` stays pending against the stream's internal iterator — the
+ * caller detaches by closing the stream, which settles it. Shared by watchTask and
+ * `logs -f`.
+ */
+export async function nextFrameOrDeadline(
+ stream: SessionStream,
+ deadlineMs: number | undefined,
+): Promise<SseFrame | null | "timeout"> {
+ if (deadlineMs === undefined) return stream.next();
+ const remaining = deadlineMs - Date.now();
+ if (remaining <= 0) return "timeout";
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expiry = new Promise<"timeout">((resolve) => {
+ timer = setTimeout(() => resolve("timeout"), remaining);
+ });
+ try {
+ return await Promise.race([stream.next(), expiry]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * Consumes the stream until the task ends (`task_state` returns to idle). Call it AFTER
+ * `waitReady()` and after POSTing the task/steer — every `task_state` seen here is a
+ * flip, so the first `idle` is the end.
+ */
+export async function watchTask(
+ stream: SessionStream,
+ opts: WatchTaskOptions,
+): Promise<WatchTaskResult> {
+ const { t, renderer } = opts;
+ let aborted = false;
+ let timedOut = false;
+ let outcome: GoalOutcome | undefined;
+ let round = 0;
+ let segmentStartedAt = Date.now();
+ // Approval prompts serialize on a promise chain: concurrent requests (parent +
+ // subagent) must not interleave their Q&A on one stdin.
+ let promptChain: Promise<unknown> = Promise.resolve();
+
+ const answerApproval = (ev: ServerEventFrame): void => {
+ const tc = ev.toolCall;
+ if (tc === undefined || opts.approvalPrompt === undefined) return;
+ const prompt = opts.approvalPrompt;
+ const run = async (): Promise<void> => {
+ let decision: ApprovalDecision = "deny";
+ renderer?.beginUserPrompt(tc);
+ try {
+ decision = await prompt(tc);
+ } finally {
+ // The decision line renders before the screen unlocks, keeping
+ // call → prompt → result adjacent (same contract as the core-direct loop).
+ renderer?.noteApprovalDecision(tc, decision);
+ renderer?.endUserPrompt();
+ }
+ try {
+ await opts.client.request(
+ "POST",
+ `/api/sessions/${opts.sessionId}/approvals/${encodeURIComponent(tc.payload.tool_call_id)}`,
+ { decision },
+ );
+ } catch {
+ // Already decided (abort converged it) or the run ended: nothing to do.
+ }
+ };
+ promptChain = promptChain.then(run, run);
+ };
+
+ for (;;) {
+ const frame = await nextFrameOrDeadline(stream, opts.deadlineMs);
+ if (frame === "timeout") {
+ timedOut = true;
+ break;
+ }
+ if (frame === null) break;
+ if (frame.event === "server_event") {
+ const ev = JSON.parse(frame.data) as ServerEventFrame;
+ if (ev.type === "task_state" && ev.state === "idle") break;
+ if (ev.type === "approval_request") answerApproval(ev);
+ if (ev.type === "resync_required") {
+ renderer?.printLine(dim(t.client.streamResynced()));
+ }
+ continue;
+ }
+ if (frame.event !== undefined) continue; // unknown named events: skip
+ const msg = JSON.parse(frame.data) as OmniMessage;
+ if (isEventMessage(msg) && msg.payload.type === "abort" && (msg.origin?.length ?? 0) === 0) {
+ aborted = true;
+ }
+ if (opts.goal) {
+ if (isGoalRoundInput(msg)) {
+ if (round > 0) renderer?.endTask(Date.now() - segmentStartedAt);
+ round++;
+ segmentStartedAt = Date.now();
+ opts.goal.out.write(`${dim(t.goalRound(round))}\n`);
+ }
+ outcome = goalFinishedOf(msg) ?? outcome;
+ }
+ if (opts.onAssistantText && (msg.origin?.length ?? 0) === 0 && isModelMessage(msg)) {
+ const p = msg.payload as { type?: string; role?: string; text?: string };
+ if (p.type === "text" && p.role !== "user" && typeof p.text === "string") {
+ opts.onAssistantText(p.text);
+ }
+ }
+ renderer?.handle(msg);
+ }
+ // Settle any prompt still in flight (the run ended while a question was open).
+ await promptChain.catch(() => undefined);
+ renderer?.endTask(Date.now() - segmentStartedAt);
+ if (opts.goal && outcome) {
+ opts.goal.out.write(
+ `${dim(t.goalFinished(outcome.outcome, outcome.rounds, humanizeTokens(outcome.tokensUsed)))}\n`,
+ );
+ }
+ return { aborted, timedOut, ...(outcome !== undefined ? { goal: outcome } : {}) };
+}
diff --git a/packages/cli/src/table.ts b/packages/cli/src/table.ts
new file mode 100644
index 00000000..d04af577
--- /dev/null
+++ b/packages/cli/src/table.ts
@@ -0,0 +1,59 @@
+/**
+ * Tiny fixed-width table renderer and relative-time formatter for the listing commands
+ * (`ls`, `agent ls`, `project ls`, `cost --by`, `schedule ls`). Column widths follow the
+ * widest cell; CJK display width is approximated as 2 columns per non-halfwidth code
+ * point so zh titles keep the grid aligned.
+ */
+
+/** Approximate terminal display width (CJK and fullwidth forms count as 2). */
+export function displayWidth(text: string): number {
+ let width = 0;
+ for (const ch of text) {
+ const code = ch.codePointAt(0)!;
+ width +=
+ (code >= 0x1100 && code <= 0x115f) ||
+ (code >= 0x2e80 && code <= 0xa4cf) ||
+ (code >= 0xac00 && code <= 0xd7a3) ||
+ (code >= 0xf900 && code <= 0xfaff) ||
+ (code >= 0xfe30 && code <= 0xfe4f) ||
+ (code >= 0xff00 && code <= 0xff60) ||
+ (code >= 0xffe0 && code <= 0xffe6) ||
+ (code >= 0x20000 && code <= 0x3fffd)
+ ? 2
+ : 1;
+ }
+ return width;
+}
+
+function pad(text: string, width: number): string {
+ return text + " ".repeat(Math.max(0, width - displayWidth(text)));
+}
+
+/** Renders header + rows with two-space gutters; ends with a newline. */
+export function renderTable(header: string[], rows: string[][]): string {
+ const table = [header, ...rows];
+ const widths = header.map((_, col) =>
+ Math.max(...table.map((row) => displayWidth(row[col] ?? ""))),
+ );
+ const line = (row: string[]): string =>
+ row
+ .map((cell, col) => (col === row.length - 1 ? cell : pad(cell, widths[col]!)))
+ .join(" ")
+ .trimEnd();
+ return `${table.map(line).join("\n")}\n`;
+}
+
+/**
+ * Compact relative time for list rows ("now", "5m", "3h", "2d", else yyyy-mm-dd) —
+ * digits + a unit letter, deliberately language-neutral.
+ */
+export function relativeTime(iso: string, now: Date = new Date()): string {
+ const then = Date.parse(iso);
+ if (Number.isNaN(then)) return iso;
+ const seconds = Math.floor((now.getTime() - then) / 1000);
+ if (seconds < 60) return "now";
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
+ if (seconds < 14 * 86400) return `${Math.floor(seconds / 86400)}d`;
+ return new Date(then).toISOString().slice(0, 10);
+}
diff --git a/packages/cli/src/task-loop.ts b/packages/cli/src/task-loop.ts
deleted file mode 100644
index 2ceb197d..00000000
--- a/packages/cli/src/task-loop.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * Consumption loop that drives a Task to completion (CLI side, shared by run and chat).
- *
- * New protocol: `session.run(prompt, { signal, approve })` runs the entire ReAct loop in one
- * call — within a turn, the engine invokes the `approve` callback for each tool_call, executing
- * it on allow, with execution possibly overlapping. The CLI only needs to consume the output
- * stream and supply `approve`. The approval strategy is determined by the permission mode
- * (allow-all / deny-all / read-only / always-ask per-call approval).
- *
- * Goal mode rides the same call (`opts.goal` → `session.run(prompt, { goal })`): core loops
- * the rounds inside the one run, so this loop only adds the per-round rendering rhythm —
- * a dim round line at each `[goal]` round boundary, per-round stats via `endTask`, and the
- * 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,
- 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";
-import type { Messages } from "./i18n.js";
-
-export interface RunTaskOptions {
- /** Approval mode (default allow-all). */
- 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;
- /** Message set. */
- t: Messages;
- /**
- * Present = goal mode: the prompt's text is the objective and the one `session.run` loops
- * until the goal reaches a terminal state (a single AbortSignal spans every round). `out`
- * receives the dim round/summary lines the renderer doesn't own.
- */
- goal?: { budget: number; out: NodeJS.WritableStream };
-}
-
-/** Result of one Task: `aborted` = the Task ended with an abort event (LLM failure/reconnect exhausted/user interrupt); `goal` = the outcome of a goal-mode run (absent when the stream was cut off before the terminal event). */
-export interface RunTaskResult {
- aborted: boolean;
- goal?: GoalOutcome;
-}
-
-export async function runTask(
- session: Session,
- prompt: OmniMessage[],
- opts: RunTaskOptions,
-): Promise<RunTaskResult> {
- const basePrompt: ApproveFn = opts.interactivePrompt ?? (() => promptApproval({ t: opts.t }));
- // Lock the renderer while waiting for the user's approval input: messages from concurrent
- // tools/subsessions are queued and released together once the Q&A finishes, so the prompt
- // isn't scrambled by later output. The pending tool_call is passed in so its call line stays
- // right before the prompt; the approval result is rendered in place **before unlocking** —
- // "tool call → approval prompt → approval result" stays three consecutive lines, for both
- // the main Agent and subagents (messages arriving via the async pipeline may lag behind the
- // approval callback, hence render-in-place plus de-duplication of the copy).
- //
- // Serialization: the parent session and a run_subagent child session share this callback and
- // may request approval concurrently (the parent is waiting on one approval while an
- // already-approved child session starts its own). Concurrent prompts would clobber the same
- // Q&A state and fight over the same stdin (one answer resolving two questions, leaving the
- // other permanently stuck); a promise chain queues them so only one question is asked at a
- // time.
- let promptChain: Promise<unknown> = Promise.resolve();
- const interactivePrompt: ApproveFn = (tc) => {
- const result = promptChain.then(async () => {
- opts.renderer.beginUserPrompt(tc);
- try {
- const decision = await basePrompt(tc);
- opts.renderer.noteApprovalDecision(tc, decision);
- return decision;
- } finally {
- opts.renderer.endUserPrompt();
- }
- });
- promptChain = result.then(
- () => undefined,
- () => undefined,
- );
- return result;
- };
- const approveByMode = makeApprove({
- mode: opts.mode ?? "allow-all",
- toolPermission: (name) => session.toolPermission(name),
- interactivePrompt,
- });
- // The auto-approval path (allow-all / deny-all / read-only approvals) has no prompt: it
- // likewise renders the "call line → approval result" pair in place; the interactive path's
- // already-rendered copy is idempotently de-duplicated inside note.
- const approve: ApproveFn = async (tc) => {
- const decision = await approveByMode(tc);
- opts.renderer.noteApprovalDecision(tc, decision);
- return decision;
- };
-
- // A single run drives the whole ReAct loop (the engine requests approval per call and runs
- // tools concurrently within a turn). Once the task ends (including on error), endTask
- // prints this task's stats (context/Token/elapsed time). The engine collapses failures
- // (auth errors, reconnect exhausted, etc.) into a main-session abort event rather than
- // throwing; the result reported here reflects that, for `penguin run` to map to
- // an exit code.
- //
- // In goal mode the round boundaries are the injected `[goal]` user messages core yields
- // before each round: stats settle per round (the per-Task rhythm of a normal chat), so
- // `segmentStartedAt` tracks the current round rather than the whole run.
- const goal = opts.goal;
- const startedAt = Date.now();
- let segmentStartedAt = startedAt;
- let aborted = false;
- let round = 0;
- let outcome: GoalOutcome | undefined;
- try {
- 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) {
- aborted = true;
- }
- if (goal) {
- if (isGoalRoundInput(msg)) {
- // Settle the previous round's stats before announcing the next (endTask is what
- // prints the per-task `[stats]` line in a normal chat).
- if (round > 0) opts.renderer.endTask(Date.now() - segmentStartedAt);
- round++;
- segmentStartedAt = Date.now();
- goal.out.write(`${dim(opts.t.goalRound(round))}\n`);
- }
- outcome = goalFinishedOf(msg) ?? outcome;
- }
- opts.renderer.handle(msg);
- }
- } finally {
- opts.renderer.endTask(Date.now() - segmentStartedAt);
- }
- if (goal && outcome) {
- goal.out.write(
- `${dim(opts.t.goalFinished(outcome.outcome, outcome.rounds, humanizeTokens(outcome.tokensUsed)))}\n`,
- );
- }
- return { aborted, ...(outcome !== undefined ? { goal: outcome } : {}) };
-}
diff --git a/packages/cli/src/usage-error.ts b/packages/cli/src/usage-error.ts
new file mode 100644
index 00000000..006e5faf
--- /dev/null
+++ b/packages/cli/src/usage-error.ts
@@ -0,0 +1,108 @@
+/**
+ * Commander's own parse failures, said in the user's language.
+ *
+ * With `exitOverride()` commander still WRITES its English line before throwing
+ * (`error: missing required argument 'sessionId'`), so `cli()` silences that output
+ * channel and prints from here instead: one localized sentence naming what is wrong, and
+ * — for every way a command can be typed wrong — that command's own usage plus a pointer
+ * at its `--help`. Exit codes are commander's, unchanged.
+ *
+ * Only the identifier commander quoted survives from its message (the argument name, the
+ * option flags, the command name); the prose around it is rebuilt from the dictionaries.
+ * A failure that quotes nothing keeps commander's detail verbatim, so nothing is ever
+ * swallowed silently.
+ */
+import type { Command, CommanderError } from "commander";
+import type { Messages } from "./i18n.js";
+
+/** Commander codes that mean "the command line was typed wrong" — these earn the usage line. */
+const USAGE_ERROR_CODES = new Set([
+ "commander.missingArgument",
+ "commander.missingMandatoryOptionValue",
+ "commander.optionMissingArgument",
+ "commander.unknownOption",
+ "commander.unknownCommand",
+ "commander.invalidArgument",
+ "commander.excessArguments",
+ "commander.conflictingOption",
+]);
+
+/**
+ * The deepest registered command this argv actually named, so the usage line quotes
+ * `penguin schedule add` rather than `penguin`. Option tokens are skipped and the walk
+ * stops at the first word naming no subcommand — an argument value, or an option's
+ * value, which no grammar-free walk can tell apart from one. Landing on the parent only
+ * costs the usage line some precision.
+ */
+export function commandForArgv(program: Command, argv: string[]): Command {
+ let cmd = program;
+ for (const token of argv) {
+ if (token.startsWith("-")) continue;
+ const next = cmd.commands.find((c) => c.name() === token || c.aliases().includes(token)) as
+ Command | undefined;
+ if (next === undefined) break;
+ cmd = next;
+ }
+ return cmd;
+}
+
+/** Full spelling of a command including its ancestors (`penguin schedule add`). */
+function commandPath(cmd: Command): string {
+ const parts: string[] = [];
+ for (let c: Command | null = cmd; c !== null; c = c.parent) parts.unshift(c.name());
+ return parts.join(" ");
+}
+
+/** The single-quoted identifier in a commander message, when it has one. */
+function quotedIdentifier(message: string): string | null {
+ const m = /'([^']+)'/.exec(message);
+ return m === null ? null : m[1]!;
+}
+
+/** The localized sentence for one commander failure. */
+function usageErrorLine(err: CommanderError, argv: string[], atRoot: boolean, t: Messages): string {
+ // `penguin <typo>`: bare `penguin` prints help, so the root carries an action handler
+ // and commander calls a stray word "too many arguments". For a program that is nothing
+ // but subcommands, the true diagnosis is an unknown command — say that instead.
+ if (err.code === "commander.excessArguments" && atRoot) {
+ const word = argv.find((a) => !a.startsWith("-"));
+ if (word !== undefined) return t.usage.unknownCommand(word);
+ }
+ const detail = err.message.replace(/^error:\s*/, "");
+ const token = quotedIdentifier(err.message);
+ if (token === null) return t.usage.other(detail);
+ switch (err.code) {
+ case "commander.missingArgument":
+ return t.usage.missingArgument(token);
+ case "commander.missingMandatoryOptionValue":
+ return t.usage.missingOption(token);
+ case "commander.optionMissingArgument":
+ return t.usage.optionMissingArgument(token);
+ case "commander.unknownOption":
+ return t.usage.unknownOption(token);
+ case "commander.unknownCommand":
+ return t.usage.unknownCommand(token);
+ default:
+ return t.usage.other(detail);
+ }
+}
+
+/**
+ * Reports one CommanderError and returns the exit code to hand back. `--help` and
+ * `--version` travel this path too (exit code 0): they have already written their own
+ * output, so nothing more is printed.
+ */
+export function reportCommanderError(
+ err: CommanderError,
+ program: Command,
+ argv: string[],
+ t: Messages,
+): number {
+ if (err.exitCode === 0) return err.exitCode;
+ const cmd = commandForArgv(program, argv);
+ process.stderr.write(`${t.error(usageErrorLine(err, argv, cmd === program, t))}\n`);
+ if (USAGE_ERROR_CODES.has(err.code)) {
+ process.stderr.write(`${t.usage.hint(commandPath(cmd), cmd.usage())}\n`);
+ }
+ return err.exitCode;
+}
diff --git a/packages/cli/src/warnings.ts b/packages/cli/src/warnings.ts
new file mode 100644
index 00000000..5edebf0b
--- /dev/null
+++ b/packages/cli/src/warnings.ts
@@ -0,0 +1,64 @@
+/**
+ * Drops one Node warning, and only that one.
+ *
+ * `commands/serve.ts` pulls in `commands/reset-password.ts`, which imports
+ * `@prismshadow/penguin-server/reset-admin-password` — that reaches `node:sqlite` while
+ * the module graph loads, so on a Node that still flags the builtin experimental every
+ * `penguin` invocation prints
+ * `ExperimentalWarning: SQLite is an experimental feature ...`, including the ones whose
+ * whole output is a usage error. Nothing in the CLI's own behavior depends on the
+ * builtin's stability, and the user has no action to take.
+ *
+ * The filter lives in the entry module rather than in a launcher flag because both ways
+ * of starting the CLI reach it: the release tarball's `bin/penguin` execs
+ * `node lib/dist/penguin.js` with no flags, and the dev script runs
+ * `tsx packages/cli/src/penguin.ts`. `--disable-warning=ExperimentalWarning` (what the
+ * server's `start` script uses) would have to be added to both, and would hide every
+ * future experimental warning instead of this one.
+ *
+ * Import this module BEFORE anything else in the entry: ESM evaluates imports in source
+ * order, and the filter has to be in place before the graph reaches `node:sqlite`.
+ */
+
+/** Text of the warning Node emits for the `node:sqlite` builtin. */
+const SQLITE_EXPERIMENTAL = "SQLite is an experimental feature";
+
+/**
+ * The warning category, across `emitWarning`'s overloads: an Error carries its own
+ * `name`, a string warning takes the category from the second argument — a bare type
+ * string, or the `type` of an options object.
+ */
+function warningType(warning: unknown, typeArg: unknown): string {
+ if (warning instanceof Error) return warning.name;
+ if (typeof typeArg === "string") return typeArg;
+ if (typeof typeArg === "object" && typeArg !== null) {
+ const { type } = typeArg as { type?: unknown };
+ if (typeof type === "string") return type;
+ }
+ return "Warning";
+}
+
+/** Whether one `emitWarning` call is the `node:sqlite` experimental notice. */
+export function isSqliteExperimentalWarning(warning: unknown, typeArg?: unknown): boolean {
+ if (warningType(warning, typeArg) !== "ExperimentalWarning") return false;
+ const text = warning instanceof Error ? warning.message : String(warning);
+ return text.startsWith(SQLITE_EXPERIMENTAL);
+}
+
+/**
+ * Wraps `process.emitWarning` so the sqlite notice is discarded and every other warning
+ * reaches the terminal unchanged. Returns the uninstaller (tests restore the original).
+ */
+export function installWarningFilter(): () => void {
+ const original = process.emitWarning;
+ const emit = original.bind(process) as (...args: unknown[]) => void;
+ process.emitWarning = ((warning: string | Error, ...rest: unknown[]) => {
+ if (isSqliteExperimentalWarning(warning, rest[0])) return;
+ emit(warning, ...rest);
+ }) as typeof process.emitWarning;
+ return () => {
+ process.emitWarning = original;
+ };
+}
+
+installWarningFilter();
diff --git a/packages/cli/test/chat-clear.test.ts b/packages/cli/test/chat-clear.test.ts
index 0f30fb68..93ab82ab 100644
--- a/packages/cli/test/chat-clear.test.ts
+++ b/packages/cli/test/chat-clear.test.ts
@@ -1,92 +1,36 @@
/**
- * 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.
+ * chat `/clear`: starts a brand-new blank Session in place, over the server API. The old
+ * Session stays on the server (its resume command is printed so it remains 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
+ * against the in-process fake server; 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 { afterEach, beforeEach, 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";
+import { FakeServer } from "./fake-server.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;
-}
+let server: FakeServer;
+let uninstall: () => 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 };
-}
+beforeEach(() => {
+ server = new FakeServer();
+ uninstall = server.install();
+});
+afterEach(() => {
+ uninstall();
+ vi.restoreAllMocks();
+});
/**
* 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> {
+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 });
@@ -112,7 +56,7 @@ async function driveChat(lines: string[]): Promise<string> {
const program = new Command();
program.exitOverride();
registerChatCommand(program, getMessages("en"));
- const done = program.parseAsync(["node", "penguin", "chat"]);
+ const done = program.parseAsync(["node", "penguin", "chat", ...argv]);
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]);
@@ -126,41 +70,42 @@ async function driveChat(lines: string[]): Promise<string> {
}
}
-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();
+describe("chat /clear (fresh Session in place, server-backed)", () => {
+ it("swaps in a new Session with the same Workspace/model; input routes to the new one; both stay resumable", async () => {
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,
- });
+ const created = [...server.sessions.values()];
+ expect(created).toHaveLength(2);
+ const [first, second] = created;
+ // The replacement pinned the first one's Workspace and model reference.
+ expect(second!.workspace).toBe(first!.workspace);
+ expect(second!.modelId).toBe(first!.modelId);
+ expect(second!.provider).toBe(first!.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(first!.tasks.map((b) => (b.input as Array<{ text: string }>)[0]!.text)).toEqual([
+ "hello",
+ ]);
+ expect(second!.tasks.map((b) => (b.input as Array<{ text: string }>)[0]!.text)).toEqual([
+ "second",
+ ]);
+ // Both were created through the API with the CLI's client hint.
+ const creates = server.requests.filter(
+ (r) => r.method === "POST" && r.path.endsWith("/sessions"),
+ );
+ expect(creates).toHaveLength(2);
+ expect(creates.every((r) => r.body?.client === "cli")).toBe(true);
+ // /clear advertised the old Session's resume command before switching over, and the
+ // exit hint names the new one.
+ expect(out).toContain(`penguin chat --resume ${first!.sessionId}`);
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
+ expect(out).toContain(`penguin chat --resume ${second!.sessionId}`);
+ // No DELETE / dispose call exists for a server Session — nothing was deleted.
+ expect(server.requests.some((r) => r.method === "DELETE")).toBe(false);
});
- it("/clear before any Task prints no resume hint (neither Session has a Trace record yet)", async () => {
- const { agent } = makeFakeAgent();
+ it("/clear before any Task prints no resume hint (neither Session has history yet)", async () => {
const out = await driveChat(["/clear", "/exit"]);
-
- expect(agent.createSession).toHaveBeenCalledTimes(2);
+ expect(server.sessions.size).toBe(2);
expect(out).toContain(getMessages("en").clearDone());
expect(out).not.toContain("--resume");
});
diff --git a/packages/cli/test/chat-thinking.test.ts b/packages/cli/test/chat-thinking.test.ts
index efd66c1b..8cc1acdf 100644
--- a/packages/cli/test/chat-thinking.test.ts
+++ b/packages/cli/test/chat-thinking.test.ts
@@ -1,108 +1,36 @@
/**
* 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.
+ * collapsing), over the server transport: drives the real REPL over a fake stdin against
+ * the in-process fake server (same harness as chat-clear.test.ts). Task bodies record
+ * what the server would receive (`thinkingLevel` on POST /tasks; a sticky pin is a PATCH
+ * on the Session); 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 { afterEach, beforeEach, 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() };
-});
+import { FakeServer } from "./fake-server.js";
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;
-}
+let server: FakeServer;
+let uninstall: () => void;
-/**
- * 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 };
-}
+beforeEach(() => {
+ server = new FakeServer();
+ uninstall = server.install();
+});
+afterEach(() => {
+ uninstall();
+ vi.restoreAllMocks();
+});
/** 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> {
@@ -144,19 +72,19 @@ async function driveChat(lines: string[], argv: string[] = []): Promise<string>
}
}
-describe("chat /thinking (per-turn thinking level)", () => {
- afterEach(() => {
- vi.clearAllMocks();
- });
+/** Task bodies' thinkingLevel in POST order for one session. */
+function taskLevels(sessionOrdinal: number): Array<string | undefined> {
+ const sessions = [...server.sessions.values()];
+ return sessions[sessionOrdinal]!.tasks.map((b) => b.thinkingLevel as string | undefined);
+}
- it("bare /thinking shows the configured chain (agent explicit > project default > medium)", async () => {
- makeFakeAgent({ projectLevel: "high" });
+describe("chat /thinking (per-turn thinking level, server-backed)", () => {
+ it("bare /thinking shows the Session default (unpinned = the Agent's configured level applies server-side)", async () => {
const out = await driveChat(["/thinking", "/exit"]);
- expect(out).toContain(t.thinkingCurrentDefault("high"));
+ expect(out).toContain(t.thinkingCurrentDefault(t.chatThinkingConfigured()));
});
it("/thinking <level> overrides subsequent turns; invalid values change nothing", async () => {
- const { sessions } = makeFakeAgent();
const out = await driveChat([
"/thinking",
"first",
@@ -167,60 +95,60 @@ describe("chat /thinking (per-turn thinking level)", () => {
"/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"));
+ expect(out).toContain(t.thinkingCurrentOverride("high", t.chatThinkingConfigured()));
// "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");
+ const session = [...server.sessions.values()][0]!;
+ expect(session.tasks.map((b) => (b.input as Array<{ text: string }>)[0]!.text)).toEqual([
+ "first",
+ "second",
+ "third",
+ ]);
+ expect(taskLevels(0)).toEqual([undefined, "high", "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" });
+ it("--thinking pins the Session default (a PATCH — sticky, so subagents follow) and runs carry no per-turn override", async () => {
const out = await driveChat(["/thinking", "go", "/exit"], ["--thinking", "xhigh"]);
- expect(agent.createSession.mock.calls[0]![0]).toMatchObject({ thinkingLevel: "xhigh" });
+ const session = [...server.sessions.values()][0]!;
+ expect(session.patches).toContainEqual({ thinkingLevel: "xhigh" });
+ expect(session.thinkingLevel).toBe("xhigh");
expect(out).toContain(t.thinkingCurrentDefault("xhigh"));
- expect(sessions[0]!.runs[0]!.opts["thinkingLevel"]).toBeUndefined();
+ expect(taskLevels(0)).toEqual([undefined]);
});
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" });
+ const existing = server.addSession({ thinkingLevel: "low" });
+ const out = await driveChat(
+ ["/thinking", "go", "/exit"],
+ ["--resume", existing.sessionId, "--thinking", "high"],
+ );
+ // No pin is written on resume; the flag rides each task instead.
+ expect(existing.patches).toEqual([]);
expect(out).toContain(t.thinkingCurrentOverride("high", "low"));
- expect(sessions[0]!.runs[0]!.opts["thinkingLevel"]).toBe("high");
+ expect(existing.tasks.map((b) => b.thinkingLevel)).toEqual(["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"]);
+ it("--resume without --thinking runs on the resumed Session's own pinned level (no override)", async () => {
+ const existing = server.addSession({ thinkingLevel: "xhigh" });
+ const out = await driveChat(["/thinking", "go", "/exit"], ["--resume", existing.sessionId]);
expect(out).toContain(t.thinkingCurrentDefault("xhigh"));
- expect(sessions[0]!.runs[0]!.opts["thinkingLevel"]).toBeUndefined();
+ expect(existing.tasks.map((b) => b.thinkingLevel)).toEqual([undefined]);
});
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");
+ const sessions = [...server.sessions.values()];
+ expect(sessions).toHaveLength(2);
+ // The replacement Session gets the same sticky pin…
+ expect(sessions[1]!.patches).toContainEqual({ thinkingLevel: "low" });
+ // …and the per-turn override still rides the next task.
+ expect(sessions[1]!.tasks.map((b) => b.thinkingLevel)).toEqual(["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";
@@ -237,7 +165,7 @@ describe("chat /verbose (tool-output collapsing)", () => {
}
it("collapses long tool output by default; /verbose switches to full output", async () => {
- makeFakeAgent({ messages: longToolOutput });
+ server.onTask = () => 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.
@@ -251,7 +179,7 @@ describe("chat /verbose (tool-output collapsing)", () => {
});
it("--verbose starts with full output; /verbose collapses from the next output on", async () => {
- makeFakeAgent({ messages: longToolOutput });
+ server.onTask = () => 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");
@@ -259,3 +187,27 @@ describe("chat /verbose (tool-output collapsing)", () => {
expect(collapsed).not.toContain("-> l5\n");
});
});
+
+describe("chat caller-context defaults (PENGUIN_SESSION_ID inheritance)", () => {
+ it("a new chat inside an agent inherits workspace/model/approve and pins the caller's thinking", async () => {
+ const caller = server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-ca11c0de",
+ workspace: "/callers/dir",
+ modelId: "caller-model",
+ provider: "caller-prov",
+ approvalMode: "read-only",
+ thinkingLevel: "xhigh",
+ });
+ process.env.PENGUIN_SESSION_ID = caller.sessionId;
+ const out = await driveChat(["/thinking", "/exit"]);
+ const created = [...server.sessions.values()].find((x) => x.sessionId !== caller.sessionId)!;
+ expect(created.workspace).toBe("/callers/dir");
+ expect(created.modelId).toBe("caller-model");
+ expect(created.provider).toBe("caller-prov");
+ expect(created.approvalMode).toBe("read-only");
+ // The caller's level pins the new Session (sticky, so subagents follow), and the
+ // display names it as the Session default — not an override.
+ expect(created.patches).toContainEqual({ thinkingLevel: "xhigh" });
+ expect(out).toContain(t.thinkingCurrentDefault("xhigh"));
+ });
+});
diff --git a/packages/cli/test/client.test.ts b/packages/cli/test/client.test.ts
new file mode 100644
index 00000000..e531d029
--- /dev/null
+++ b/packages/cli/test/client.test.ts
@@ -0,0 +1,205 @@
+/**
+ * Server-client plumbing: connection resolution order (--server > PENGUIN_API_URL >
+ * live server.lock > auto-start), the remote-token gate, the SSE parser, and session
+ * reference resolution (full id / unique fragment / ambiguity).
+ */
+import fs from "node:fs";
+import net from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ autoStartEntry,
+ normalizeServerUrl,
+ parseSseBody,
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ resolveSessionRef,
+ ServerClient,
+ shortSessionId,
+} from "../src/client.js";
+import { getMessages } from "../src/i18n.js";
+import { FakeServer } from "./fake-server.js";
+
+const t = getMessages("en");
+
+const ENV_KEYS = [
+ "PENGUIN_API_URL",
+ "PENGUIN_API_TOKEN",
+ "PENGUIN_HOME",
+ "PENGUIN_PROJECT_ID",
+ "PENGUIN_AGENT_ID",
+];
+const saved = new Map<string, string | undefined>();
+
+beforeEach(() => {
+ for (const key of ENV_KEYS) {
+ saved.set(key, process.env[key]);
+ delete process.env[key];
+ }
+});
+afterEach(() => {
+ for (const [key, value] of saved) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+describe("connection resolution", () => {
+ it("--server wins over PENGUIN_API_URL; trailing slashes are stripped", async () => {
+ process.env.PENGUIN_API_URL = "http://127.0.0.1:7001";
+ const conn = await resolveConnection({ server: "http://localhost:7002/" }, t);
+ expect(conn.baseUrl).toBe("http://localhost:7002");
+ expect(conn.loopback).toBe(true);
+ expect(conn.autoStarted).toBe(false);
+ });
+
+ it("PENGUIN_API_URL is used when --server is absent", async () => {
+ process.env.PENGUIN_API_URL = "http://127.0.0.1:7001";
+ const conn = await resolveConnection({}, t);
+ expect(conn.baseUrl).toBe("http://127.0.0.1:7001");
+ });
+
+ it("a remote URL without PENGUIN_API_TOKEN is refused with the token hint", async () => {
+ await expect(resolveConnection({ server: "https://box.example.com" }, t)).rejects.toThrow(
+ /PENGUIN_API_TOKEN/,
+ );
+ process.env.PENGUIN_API_TOKEN = "remote-token";
+ const conn = await resolveConnection({ server: "https://box.example.com" }, t);
+ expect(conn.baseUrl).toBe("https://box.example.com");
+ expect(conn.loopback).toBe(false);
+ });
+
+ it("junk URLs are rejected with a localized message", () => {
+ expect(() => normalizeServerUrl("not a url", t)).toThrow(/Invalid server URL/);
+ expect(() => normalizeServerUrl("ftp://x", t)).toThrow(/Invalid server URL/);
+ });
+
+ it("a live server.lock on the data root resolves to http://localhost:<port>", async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-cli-lock-"));
+ process.env.PENGUIN_HOME = root;
+ // Liveness needs a real pid AND an accepting port: use this process and a real listener.
+ const listener = net.createServer();
+ await new Promise<void>((resolve) => listener.listen(0, "127.0.0.1", resolve));
+ const port = (listener.address() as net.AddressInfo).port;
+ fs.writeFileSync(
+ path.join(root, "server.lock"),
+ `${JSON.stringify({ pid: process.pid, port, startedAt: "now" })}\n`,
+ );
+ try {
+ const conn = await resolveConnection({}, t);
+ expect(conn.baseUrl).toBe(`http://localhost:${port}`);
+ expect(conn.autoStarted).toBe(false);
+ } finally {
+ listener.close();
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it("no server + autoStart disabled -> the no-server error; a stale lock does not count", async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-cli-stale-"));
+ process.env.PENGUIN_HOME = root;
+ // A lock whose port nothing accepts is stale and must be ignored.
+ fs.writeFileSync(
+ path.join(root, "server.lock"),
+ `${JSON.stringify({ pid: process.pid, port: 1, startedAt: "now" })}\n`,
+ );
+ try {
+ await expect(resolveConnection({ autoStart: false }, t)).rejects.toThrow(t.client.noServer());
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it("autoStartEntry accepts plain-node entries only (a tsx .ts dev entry cannot re-run)", () => {
+ expect(autoStartEntry("/x/dist/penguin.js")).toBe(path.resolve("/x/dist/penguin.js"));
+ expect(autoStartEntry("/x/dist/penguin.mjs")).not.toBeNull();
+ expect(autoStartEntry("/x/src/penguin.ts")).toBeNull();
+ expect(autoStartEntry(undefined)).toBeNull();
+ });
+});
+
+describe("SSE parsing", () => {
+ async function frames(text: string) {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(text));
+ controller.close();
+ },
+ });
+ const out = [];
+ for await (const frame of parseSseBody(body)) out.push(frame);
+ return out;
+ }
+
+ it("parses id/event/data frames, ignores heartbeat comments, tolerates CRLF", async () => {
+ const out = await frames(
+ ': ping\r\n\r\nid: 7-1\nevent: server_event\ndata: {"type":"hello"}\n\n' +
+ 'id: 7-2\ndata: {"a":1}\r\n\r\n',
+ );
+ expect(out).toEqual([
+ { id: "7-1", event: "server_event", data: '{"type":"hello"}' },
+ { id: "7-2", data: '{"a":1}' },
+ ]);
+ });
+
+ it("joins multi-line data with newlines and handles chunk splits mid-line", async () => {
+ const text = "data: line1\ndata: line2\n\n";
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ const enc = new TextEncoder();
+ controller.enqueue(enc.encode(text.slice(0, 9)));
+ controller.enqueue(enc.encode(text.slice(9)));
+ controller.close();
+ },
+ });
+ const out = [];
+ for await (const frame of parseSseBody(body)) out.push(frame);
+ expect(out).toEqual([{ data: "line1\nline2" }]);
+ });
+});
+
+describe("session references", () => {
+ it("shortSessionId is the 8-hex tail", () => {
+ expect(shortSessionId("session-2026-08-25-10-00-00-00c0ffee")).toBe("00c0ffee");
+ expect(shortSessionId("weird")).toBe("weird");
+ });
+
+ it("full id passes through; a unique fragment resolves; ambiguity lists candidates; misses error", async () => {
+ const server = new FakeServer();
+ const restore = server.install();
+ try {
+ const a = server.addSession({ sessionId: "session-2026-08-25-10-00-00-aaaa1111" });
+ server.addSession({ sessionId: "session-2026-08-25-11-00-00-bbbb1111" });
+ const client = new ServerClient(await resolveConnection({}, t), t);
+ await expect(resolveSessionRef(client, "default_project", a.sessionId, t)).resolves.toBe(
+ a.sessionId,
+ );
+ await expect(resolveSessionRef(client, "default_project", "aaaa1111", t)).resolves.toBe(
+ a.sessionId,
+ );
+ await expect(resolveSessionRef(client, "default_project", "1111", t)).rejects.toThrow(
+ /matches 2 sessions/,
+ );
+ await expect(resolveSessionRef(client, "default_project", "nope", t)).rejects.toThrow(
+ /No session matching/,
+ );
+ } finally {
+ restore();
+ }
+ });
+});
+
+describe("option defaults", () => {
+ it("project/agent ids: flag > env > built-in default", () => {
+ expect(resolveProjectId(undefined)).toBe("default_project");
+ expect(resolveAgentId(undefined)).toBe("default_agent");
+ process.env.PENGUIN_PROJECT_ID = "env-project";
+ process.env.PENGUIN_AGENT_ID = "env-agent";
+ expect(resolveProjectId(undefined)).toBe("env-project");
+ expect(resolveAgentId(undefined)).toBe("env-agent");
+ expect(resolveProjectId("flag-project")).toBe("flag-project");
+ expect(resolveAgentId("flag-agent")).toBe("flag-agent");
+ });
+});
diff --git a/packages/cli/test/duration.test.ts b/packages/cli/test/duration.test.ts
new file mode 100644
index 00000000..6b017dd9
--- /dev/null
+++ b/packages/cli/test/duration.test.ts
@@ -0,0 +1,25 @@
+/**
+ * `--timeout` duration parsing: `30s` / `5m` / `2h` and bare integers (seconds); every
+ * other shape is rejected so the commands can print the localized error.
+ */
+import { describe, expect, it } from "vitest";
+import { parseDurationMs } from "../src/duration.js";
+
+describe("parseDurationMs", () => {
+ it("accepts the documented shapes", () => {
+ expect(parseDurationMs("30s")).toBe(30_000);
+ expect(parseDurationMs("5m")).toBe(300_000);
+ expect(parseDurationMs("2h")).toBe(7_200_000);
+ expect(parseDurationMs("45")).toBe(45_000); // bare integer = seconds
+ expect(parseDurationMs(" 1s ")).toBe(1000); // trimmed
+ // Zero is legal and means "do not wait at all" (return right after delivery).
+ expect(parseDurationMs("0")).toBe(0);
+ expect(parseDurationMs("0s")).toBe(0);
+ });
+
+ it("rejects everything else", () => {
+ for (const bad of ["", "-5s", "1.5m", "5 m", "5d", "m", "5ms", "abc", "1h30m"]) {
+ expect(parseDurationMs(bad)).toBeNull();
+ }
+ });
+});
diff --git a/packages/cli/test/fake-server.ts b/packages/cli/test/fake-server.ts
new file mode 100644
index 00000000..62945cfc
--- /dev/null
+++ b/packages/cli/test/fake-server.ts
@@ -0,0 +1,426 @@
+/**
+ * In-process fake PenguinHarness server for CLI tests: stubs `globalThis.fetch` with a
+ * handler covering exactly the endpoints the server-backed commands touch (session
+ * create/get/patch, tasks/steer/compact/abort, SSE stream, messages, agents, projects,
+ * usage, schedules). Connection resolution is pinned via PENGUIN_API_URL (a loopback
+ * URL, so no token gate) and PENGUIN_HOME points at a scratch directory so nothing of
+ * the developer's real data root is read.
+ *
+ * The SSE stream is real: a ReadableStream whose frames follow the server's wire shape
+ * (default-event OmniMessage frames, `event: server_event` control frames, incrementing
+ * ids). A task POST synchronously emits `task_state running`, the script's messages,
+ * then `task_state idle` — enough for watchTask's full lifecycle.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+type Json = Record<string, unknown>;
+
+export interface FakeSessionState {
+ sessionId: string;
+ projectId: string;
+ agentId: string;
+ provider: string;
+ modelId: string;
+ workspace: string;
+ approvalMode: string;
+ thinkingLevel?: string;
+ title?: string;
+ archived: boolean;
+ status: "idle" | "running" | "compacting";
+ createdAt: string;
+ lastActiveAt: string;
+ /** Bodies of every POST /tasks, in order. */
+ tasks: Json[];
+ /** Bodies of every POST /steer, in order. */
+ steers: Json[];
+ /** PATCH bodies, in order. */
+ patches: Json[];
+ aborts: number;
+}
+
+interface Subscriber {
+ controller: ReadableStreamDefaultController<Uint8Array>;
+ closed: boolean;
+}
+
+const encoder = new TextEncoder();
+
+export class FakeServer {
+ readonly requests: Array<{ method: string; path: string; body?: Json }> = [];
+ readonly sessions = new Map<string, FakeSessionState>();
+ agents: Array<Json> = [
+ {
+ agentId: "default_agent",
+ name: "Default Agent",
+ description: "",
+ sessionCount: 0,
+ activeSessionCount: 0,
+ sessionActivity: [],
+ },
+ ];
+ projects: Array<Json> = [
+ { projectId: "default_project", name: "Default", role: "owner", ownerUserId: "admin" },
+ ];
+ /** Messages a task emits between running and idle (default: one assistant echo). */
+ onTask: (session: FakeSessionState, body: Json) => unknown[] = () => [];
+ /** Messages GET /messages returns. */
+ history: unknown[] = [];
+ /** POST /compact behavior: "reject" -> 409 nothing_to_compact; a function emits its messages like a task. */
+ compact: "reject" | ((session: FakeSessionState) => unknown[]) = "reject";
+ /** POST /steer behavior: accept (202) or reject (409 not_running). */
+ steerMode: "accept" | "reject" = "accept";
+ /** When true, a task POST emits `running` + the script's messages but never `idle` — the turn hangs (soft-yield timeout tests). */
+ hangTasks = false;
+ usage: Json = {
+ summary: {
+ today: { total: 1000, requests: 2, cost: 0.5, hasUncosted: false },
+ last7d: { total: 5000, requests: 9, cost: 2.25, hasUncosted: false },
+ total: { total: 9000, requests: 15, cost: 4.5, hasUncosted: true },
+ },
+ groupBy: "date",
+ groups: [],
+ granularity: "day",
+ series: [],
+ byAgentSeries: [],
+ byModelSeries: [],
+ errors: { total: 0, unexpected: 0, topCode: null, recent: [] },
+ agentIds: [],
+ models: [],
+ };
+ schedules: Json = { schedules: [], invalidFiles: [] };
+ /** Named schedule store behind add/update/rm: name -> the stored item (single-agent tests). */
+ readonly scheduleItems = new Map<string, Json>();
+
+ private nextSessionOrdinal = 1;
+ private nextEventId = 1;
+ private readonly subscribers = new Map<string, Subscriber[]>();
+ private savedFetch: typeof globalThis.fetch | null = null;
+ private savedEnv = new Map<string, string | undefined>();
+ private scratch: string | null = null;
+
+ /** A session id in core's shape whose 8-hex tail is unique per ordinal. */
+ private mintSessionId(): string {
+ const n = this.nextSessionOrdinal++;
+ return `session-2026-08-25-10-00-00-${n.toString(16).padStart(8, "0")}`;
+ }
+
+ addSession(overrides: Partial<FakeSessionState> = {}): FakeSessionState {
+ const sessionId = overrides.sessionId ?? this.mintSessionId();
+ const now = "2026-08-25T10:00:00.000Z";
+ const state: FakeSessionState = {
+ sessionId,
+ projectId: "default_project",
+ agentId: "default_agent",
+ provider: "prov-default",
+ modelId: "model-default",
+ workspace: "/ws",
+ approvalMode: "allow-all",
+ archived: false,
+ status: "idle",
+ createdAt: now,
+ lastActiveAt: now,
+ tasks: [],
+ steers: [],
+ patches: [],
+ aborts: 0,
+ ...overrides,
+ };
+ this.sessions.set(state.sessionId, state);
+ return state;
+ }
+
+ /** Installs the fetch stub and env pinning; returns the uninstaller. */
+ install(): () => void {
+ this.savedFetch = globalThis.fetch;
+ for (const key of [
+ "PENGUIN_API_URL",
+ "PENGUIN_API_TOKEN",
+ "PENGUIN_HOME",
+ "PENGUIN_SESSION_ID",
+ "PENGUIN_PROJECT_ID",
+ "PENGUIN_AGENT_ID",
+ ]) {
+ this.savedEnv.set(key, process.env[key]);
+ }
+ this.scratch = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-cli-test-"));
+ process.env.PENGUIN_HOME = this.scratch;
+ process.env.PENGUIN_API_URL = "http://127.0.0.1:7399";
+ delete process.env.PENGUIN_API_TOKEN;
+ delete process.env.PENGUIN_SESSION_ID;
+ delete process.env.PENGUIN_PROJECT_ID;
+ delete process.env.PENGUIN_AGENT_ID;
+ globalThis.fetch = ((input: string | URL | Request, init?: RequestInit) =>
+ this.handle(input, init)) as typeof globalThis.fetch;
+ return () => this.uninstall();
+ }
+
+ uninstall(): void {
+ if (this.savedFetch) globalThis.fetch = this.savedFetch;
+ for (const [key, value] of this.savedEnv) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ if (this.scratch) fs.rmSync(this.scratch, { recursive: true, force: true });
+ for (const subs of this.subscribers.values()) {
+ for (const sub of subs) {
+ if (!sub.closed) {
+ sub.closed = true;
+ try {
+ sub.controller.close();
+ } catch {
+ /* already closed */
+ }
+ }
+ }
+ }
+ }
+
+ sessionInfo(s: FakeSessionState): Json {
+ return {
+ sessionId: s.sessionId,
+ projectId: s.projectId,
+ agentId: s.agentId,
+ provider: s.provider,
+ modelId: s.modelId,
+ workspace: s.workspace,
+ approvalMode: s.approvalMode,
+ ...(s.thinkingLevel !== undefined ? { thinkingLevel: s.thinkingLevel } : {}),
+ ...(s.title !== undefined ? { title: s.title } : {}),
+ createdAt: s.createdAt,
+ lastActiveAt: s.lastActiveAt,
+ status: s.status,
+ pendingApprovalCount: 0,
+ pendingFollowUpCount: 0,
+ hasTrace: s.tasks.length > 0,
+ archived: s.archived,
+ };
+ }
+
+ /** Emits one SSE frame to every subscriber of the session. */
+ emit(sessionId: string, data: unknown, event?: string): void {
+ const id = this.nextEventId++;
+ const text =
+ `id: ${id}\n` +
+ (event !== undefined ? `event: ${event}\n` : "") +
+ `data: ${JSON.stringify(data)}\n\n`;
+ for (const sub of this.subscribers.get(sessionId) ?? []) {
+ if (!sub.closed) sub.controller.enqueue(encoder.encode(text));
+ }
+ }
+
+ emitServerEvent(sessionId: string, ev: Json): void {
+ this.emit(sessionId, ev, "server_event");
+ }
+
+ /** Runs one scripted turn: running -> messages -> idle. */
+ private runTurn(session: FakeSessionState, messages: unknown[]): void {
+ session.status = "running";
+ this.emitServerEvent(session.sessionId, { type: "task_state", state: "running" });
+ for (const msg of messages) this.emit(session.sessionId, msg);
+ session.status = "idle";
+ this.emitServerEvent(session.sessionId, { type: "task_state", state: "idle" });
+ }
+
+ private json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+ }
+
+ private error(status: number, code: string, message: string): Response {
+ return this.json({ error: { code, message } }, status);
+ }
+
+ private async handle(input: string | URL | Request, init?: RequestInit): Promise<Response> {
+ const url = new URL(
+ typeof input === "string" ? input : input instanceof URL ? input.href : input.url,
+ );
+ const method = (init?.method ?? "GET").toUpperCase();
+ const apiPath = url.pathname;
+ let body: Json | undefined;
+ if (typeof init?.body === "string" && init.body.length > 0) {
+ body = JSON.parse(init.body) as Json;
+ }
+ this.requests.push({ method, path: apiPath, ...(body !== undefined ? { body } : {}) });
+
+ // Session create
+ let m = /^\/api\/projects\/([^/]+)\/agents\/([^/]+)\/sessions$/.exec(apiPath);
+ if (m) {
+ if (method === "POST") {
+ const s = this.addSession({
+ projectId: decodeURIComponent(m[1]!),
+ agentId: decodeURIComponent(m[2]!),
+ ...(typeof body?.workspace === "string" ? { workspace: body.workspace } : {}),
+ ...(typeof body?.modelId === "string" ? { modelId: body.modelId } : {}),
+ ...(typeof body?.provider === "string" ? { provider: body.provider } : {}),
+ ...(typeof body?.approvalMode === "string" ? { approvalMode: body.approvalMode } : {}),
+ });
+ return this.json({ session: this.sessionInfo(s) }, 201);
+ }
+ const agentId = decodeURIComponent(m[2]!);
+ // Newest first, session id breaking ties — the server's own
+ // `ORDER BY created_at DESC, session_id DESC`, which is what makes [0] "the latest".
+ const sessions = [...this.sessions.values()]
+ .filter((s) => s.agentId === agentId)
+ .sort(
+ (a, b) =>
+ b.createdAt.localeCompare(a.createdAt) || b.sessionId.localeCompare(a.sessionId),
+ )
+ .map((s) => this.sessionInfo(s));
+ return this.json({ sessions });
+ }
+
+ m = /^\/api\/projects\/([^/]+)\/agents$/.exec(apiPath);
+ if (m) {
+ if (method === "POST") {
+ const agent = {
+ agentId: String(body?.agentId ?? ""),
+ name: String(body?.name ?? body?.agentId ?? ""),
+ description: String(body?.description ?? ""),
+ sessionCount: 0,
+ activeSessionCount: 0,
+ sessionActivity: [],
+ };
+ this.agents.push(agent);
+ return this.json({ agent }, 201);
+ }
+ return this.json({ agents: this.agents });
+ }
+
+ if (apiPath === "/api/projects" && method === "GET") {
+ return this.json({ projects: this.projects });
+ }
+
+ m = /^\/api\/projects\/([^/]+)\/usage$/.exec(apiPath);
+ if (m) {
+ const groupBy = url.searchParams.get("groupBy") ?? "date";
+ return this.json({ ...this.usage, groupBy });
+ }
+
+ m = /^\/api\/projects\/([^/]+)\/agents\/([^/]+)\/schedules$/.exec(apiPath);
+ if (m) {
+ if (method === "POST") {
+ const name = String(body?.name ?? "");
+ if (this.scheduleItems.has(name)) {
+ return this.error(409, "schedule_exists", `Schedule already exists: ${name}`);
+ }
+ if (typeof body?.enabled !== "boolean") {
+ return this.error(400, "bad_request", "enabled must be a boolean.");
+ }
+ const item = { ...body, status: body.enabled ? "active" : "disabled", queued: false };
+ delete (item as { name?: unknown }).name;
+ const stored = { name, ...item };
+ this.scheduleItems.set(name, stored);
+ return this.json(stored, 201);
+ }
+ return this.json(this.schedules);
+ }
+
+ m = /^\/api\/projects\/([^/]+)\/agents\/([^/]+)\/schedules\/([^/]+)$/.exec(apiPath);
+ if (m) {
+ const name = decodeURIComponent(m[3]!);
+ const stored = this.scheduleItems.get(name);
+ if (!stored) return this.error(404, "schedule_not_found", `Schedule does not exist: ${name}`);
+ if (method === "GET") return this.json(stored);
+ if (method === "PUT") {
+ if (typeof body?.enabled !== "boolean") {
+ return this.error(400, "bad_request", "enabled must be a boolean.");
+ }
+ const next = {
+ name,
+ ...body,
+ status: body.enabled ? "active" : "disabled",
+ queued: false,
+ };
+ this.scheduleItems.set(name, next);
+ return this.json(next);
+ }
+ if (method === "DELETE") {
+ this.scheduleItems.delete(name);
+ return new Response(null, { status: 204 });
+ }
+ }
+
+ // Session-level endpoints
+ m = /^\/api\/sessions\/([^/]+)(\/.*)?$/.exec(apiPath);
+ if (m) {
+ const sessionId = decodeURIComponent(m[1]!);
+ const rest = m[2] ?? "";
+ const session = this.sessions.get(sessionId);
+ if (!session) return this.error(404, "session_not_found", "Session does not exist.");
+ if (rest === "" && method === "GET") return this.json({ session: this.sessionInfo(session) });
+ if (rest === "" && method === "PATCH") {
+ session.patches.push(body ?? {});
+ if (typeof body?.thinkingLevel === "string") session.thinkingLevel = body.thinkingLevel;
+ if (typeof body?.approvalMode === "string") session.approvalMode = body.approvalMode;
+ return this.json({ session: this.sessionInfo(session) });
+ }
+ if (rest === "/messages" && method === "GET") return this.json({ messages: this.history });
+ if (rest === "/stream" && method === "GET") {
+ const subs = this.subscribers.get(sessionId) ?? [];
+ this.subscribers.set(sessionId, subs);
+ const state = session;
+ const server = this;
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ const sub: Subscriber = { controller, closed: false };
+ subs.push(sub);
+ const id = server.nextEventId++;
+ controller.enqueue(
+ encoder.encode(
+ `id: ${id}\nevent: server_event\ndata: ${JSON.stringify({
+ type: "task_state",
+ state: state.status,
+ })}\n\n`,
+ ),
+ );
+ },
+ cancel() {
+ for (const sub of subs) sub.closed = true;
+ },
+ });
+ return new Response(stream, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }
+ if (rest === "/tasks" && method === "POST") {
+ session.tasks.push(body ?? {});
+ if (this.hangTasks) {
+ session.status = "running";
+ this.emitServerEvent(session.sessionId, { type: "task_state", state: "running" });
+ for (const msg of this.onTask(session, body ?? {})) this.emit(session.sessionId, msg);
+ } else {
+ this.runTurn(session, this.onTask(session, body ?? {}));
+ }
+ return this.json({ sessionId: session.sessionId }, 202);
+ }
+ if (rest === "/steer" && method === "POST") {
+ if (this.steerMode === "reject") {
+ return this.error(409, "not_running", "No task in progress.");
+ }
+ session.steers.push(body ?? {});
+ return new Response(null, { status: 202 });
+ }
+ if (rest === "/compact" && method === "POST") {
+ if (this.compact === "reject") {
+ return this.error(409, "nothing_to_compact", "Nothing to compact.");
+ }
+ this.runTurn(session, this.compact(session));
+ return this.json({ sessionId: session.sessionId }, 202);
+ }
+ if (rest === "/abort" && method === "POST") {
+ session.aborts += 1;
+ return new Response(null, { status: 202 });
+ }
+ if (/^\/approvals\//.test(rest) && method === "POST") {
+ return new Response(null, { status: 204 });
+ }
+ }
+
+ return this.error(404, "not_found", `No fake route for ${method} ${apiPath}`);
+ }
+}
diff --git a/packages/cli/test/i18n.test.ts b/packages/cli/test/i18n.test.ts
index 7ff1fd89..e3c605ae 100644
--- a/packages/cli/test/i18n.test.ts
+++ b/packages/cli/test/i18n.test.ts
@@ -69,6 +69,75 @@ describe("getMessages", () => {
expect(getMessages("zh").chatHints()).toContain("/verbose");
});
+ it("server-backed command families exist in both languages (spot checks)", () => {
+ for (const lang of ["en", "zh"] as const) {
+ const m = getMessages(lang);
+ // Every listing command names its subject in its description.
+ expect(m.ls.desc.length).toBeGreaterThan(0);
+ expect(m.input.desc.length).toBeGreaterThan(0);
+ expect(m.logs.desc.length).toBeGreaterThan(0);
+ expect(m.agent.lsDesc.length).toBeGreaterThan(0);
+ expect(m.project.lsDesc.length).toBeGreaterThan(0);
+ expect(m.cost.desc.length).toBeGreaterThan(0);
+ expect(m.schedule.lsDesc.length).toBeGreaterThan(0);
+ // Interpolating messages carry their arguments in both languages.
+ expect(m.ls.empty("proj-x")).toContain("proj-x");
+ expect(m.agent.created("helper", "proj-x")).toContain("helper");
+ expect(m.client.autoStarted("http://localhost:1", "/log")).toContain("http://localhost:1");
+ expect(m.client.remoteNeedsToken("https://r")).toContain("PENGUIN_API_TOKEN");
+ expect(m.client.noToken("http://l", "/root/api-token")).toContain("/root/api-token");
+ expect(m.client.httpError(500, "boom", "detail")).toContain("500");
+ expect(m.client.sessionAmbiguous("ab", ["s1", "s2"])).toContain("s1");
+ expect(m.client.sessionNotFound("zz", "proj-x")).toContain("zz");
+ expect(m.logs.tailInvalid("x")).toContain("x");
+ expect(m.cost.byInvalid("bogus")).toContain("bogus");
+ expect(m.run.sessionNoOverride()).toContain("--session");
+ // The soft-yield / poll / caller-context family.
+ expect(m.common.timeout.length).toBeGreaterThan(0);
+ expect(m.client.timeoutInvalid("5d")).toContain("5d");
+ expect(m.client.stillRunning("abcd1234")).toContain("abcd1234");
+ expect(m.client.callerDefaultsFailed("session-x")).toContain("session-x");
+ expect(m.input.noReplyYet().length).toBeGreaterThan(0);
+ expect(m.logs.timeoutNeedsFollow().length).toBeGreaterThan(0);
+ expect(m.run.timeoutWithBackground()).toContain("--background");
+ // ls --days and the schedule writer family.
+ expect(m.ls.daysInvalid("x")).toContain("x");
+ expect(m.schedule.targetConflict()).toContain("--session-id");
+ expect(m.schedule.enableDisableConflict()).toContain("--enable");
+ expect(
+ m.schedule.written("daily", m.schedule.enabled(), "2026-08-27T09:00:00.000Z"),
+ ).toContain("daily");
+ expect(m.schedule.written("daily", m.schedule.enabled(), undefined)).toContain("daily");
+ expect(m.schedule.removed("daily")).toContain("daily");
+ // The latest-session default and its empty state.
+ expect(m.common.latestAgentId.length).toBeGreaterThan(0);
+ expect(m.client.latestSession("session-x")).toContain("session-x");
+ expect(m.client.noSessionsYet("ag", "proj-x")).toContain("ag");
+ expect(m.client.noSessionsYet("ag", "proj-x")).toContain("proj-x");
+ expect(m.client.noSessionsYet("ag", "proj-x")).toContain("penguin chat");
+ // Argument errors: each shape keeps the identifier commander quoted.
+ expect(m.usage.missingArgument("sessionId")).toContain("sessionId");
+ expect(m.usage.missingOption("--prompt <text>")).toContain("--prompt <text>");
+ expect(m.usage.optionMissingArgument("--tail <n>")).toContain("--tail <n>");
+ expect(m.usage.unknownOption("--nope")).toContain("--nope");
+ expect(m.usage.unknownCommand("nosuch")).toContain("nosuch");
+ expect(m.usage.other("too many arguments.")).toContain("too many arguments.");
+ const hint = m.usage.hint("penguin schedule add", "[options] <name>");
+ expect(hint).toContain("penguin schedule add [options] <name>");
+ expect(hint).toContain("penguin schedule add --help");
+ }
+ // Argument errors really are translated, not the English text twice.
+ expect(getMessages("zh").usage.missingArgument("sessionId")).not.toBe(
+ getMessages("en").usage.missingArgument("sessionId"),
+ );
+ expect(getMessages("zh").client.noSessionsYet("ag", "p")).not.toBe(
+ getMessages("en").client.noSessionsYet("ag", "p"),
+ );
+ // The dictionaries are genuinely two languages, not one copied twice.
+ expect(getMessages("zh").ls.desc).not.toBe(getMessages("en").ls.desc);
+ expect(getMessages("zh").client.noServer()).not.toBe(getMessages("en").client.noServer());
+ });
+
it("header shows the version and Agent / Workspace / Model on their own lines", () => {
for (const lang of ["en", "zh"] as const) {
const lines = getMessages(lang).header("run", "1.2.3", "ag", "/ws", "mod").split("\n");
diff --git a/packages/cli/test/server-commands.test.ts b/packages/cli/test/server-commands.test.ts
new file mode 100644
index 00000000..62b43280
--- /dev/null
+++ b/packages/cli/test/server-commands.test.ts
@@ -0,0 +1,764 @@
+/**
+ * Server-backed command wiring, driven through `cli()` in-process against the fake
+ * server: run (foreground/background/json/goal exit codes), ls, input (steer vs task),
+ * logs, agent ls/create, project ls, cost, schedule ls.
+ */
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { assistantText, partialText, type OmniMessage } from "@prismshadow/penguin-core";
+import { cli } from "../src/index.js";
+import { getMessages } from "../src/i18n.js";
+import { FakeServer } from "./fake-server.js";
+
+/** What the engine really streams for one text reply: the partial stream, then the complete message. */
+function streamedText(text: string): OmniMessage[] {
+ return [
+ partialText("start"),
+ partialText("delta", text),
+ partialText("stop"),
+ assistantText(text),
+ ];
+}
+
+const t = getMessages("en");
+
+let server: FakeServer;
+let uninstall: () => void;
+let stdout: string[];
+let stderr: string[];
+let outSpy: { mockRestore(): void };
+let errSpy: { mockRestore(): void };
+
+beforeEach(() => {
+ server = new FakeServer();
+ uninstall = server.install();
+ stdout = [];
+ stderr = [];
+ outSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ stdout.push(String(chunk));
+ return true;
+ });
+ errSpy = vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ stderr.push(String(chunk));
+ return true;
+ });
+});
+afterEach(() => {
+ outSpy.mockRestore();
+ errSpy.mockRestore();
+ uninstall();
+});
+
+const out = () => stdout.join("");
+
+describe("penguin run", () => {
+ it("creates a Session (client:'cli'), posts the task, renders the reply, exits 0", async () => {
+ server.onTask = () => streamedText("hello from the model");
+ const code = await cli(["run", "-m", "say hi"]);
+ expect(code).toBe(0);
+ const session = [...server.sessions.values()][0]!;
+ expect(session.tasks).toHaveLength(1);
+ expect((session.tasks[0]!.input as Array<{ text: string }>)[0]!.text).toBe("say hi");
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/sessions"));
+ expect(create?.body?.client).toBe("cli");
+ // The default Workspace is the CLI's cwd, resolved locally.
+ expect(create?.body?.workspace).toBe(process.cwd());
+ expect(out()).toContain("hello from the model");
+ });
+
+ it("--background posts and exits with the session id, no stream", async () => {
+ const code = await cli(["run", "-m", "long job", "--background"]);
+ expect(code).toBe(0);
+ const session = [...server.sessions.values()][0]!;
+ expect(out()).toContain(session.sessionId);
+ expect(server.requests.some((r) => r.path.endsWith("/stream"))).toBe(false);
+ expect(session.tasks).toHaveLength(1);
+ });
+
+ it("--json prints {sessionId, status, text} and nothing else on stdout", async () => {
+ server.onTask = () => [assistantText("first"), assistantText("second")];
+ const code = await cli(["run", "-m", "q", "--json"]);
+ expect(code).toBe(0);
+ const parsed = JSON.parse(out()) as { sessionId: string; status: string; text: string };
+ expect(parsed.status).toBe("completed");
+ expect(parsed.text).toBe("first\nsecond");
+ expect(parsed.sessionId).toBe([...server.sessions.keys()][0]);
+ });
+
+ it("--session reuses an existing Session by fragment and refuses workspace/model overrides", async () => {
+ const existing = server.addSession({ sessionId: "session-2026-08-25-10-00-00-feed0001" });
+ const code = await cli(["run", "-m", "again", "--session", "feed0001"]);
+ expect(code).toBe(0);
+ expect(existing.tasks).toHaveLength(1);
+ expect(server.sessions.size).toBe(1); // no new Session was created
+
+ const bad = await cli(["run", "-m", "x", "--session", "feed0001", "--workspace", "/tmp"]);
+ expect(bad).toBe(1);
+ expect(stderr.join("")).toContain("--session");
+ });
+
+ it("a goal run exits non-zero unless the goal completed", async () => {
+ // The fake emits no goal_finished event, which reads as "did not complete".
+ const code = await cli(["run", "-m", "objective", "--goal", "500k"]);
+ expect(code).toBe(1);
+ const session = [...server.sessions.values()][0]!;
+ expect(session.tasks[0]!.goal).toEqual({ budget: 500_000 });
+ });
+
+ it("--thinking rides the task body", async () => {
+ await cli(["run", "-m", "q", "--thinking", "high"]);
+ const session = [...server.sessions.values()][0]!;
+ expect(session.tasks[0]!.thinkingLevel).toBe("high");
+ });
+});
+
+describe("penguin ls", () => {
+ it("lists sessions of every agent with short id / state / workspace tail; -a includes archived", async () => {
+ server.addSession({ sessionId: "session-2026-08-25-10-00-00-11110000", title: "First" });
+ server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-22220000",
+ archived: true,
+ workspace: "/repos/deep/path",
+ });
+ const code = await cli(["ls"]);
+ expect(code).toBe(0);
+ expect(out()).toContain("11110000");
+ expect(out()).toContain("First");
+ expect(out()).not.toContain("22220000");
+
+ stdout.length = 0;
+ await cli(["ls", "-a"]);
+ expect(out()).toContain("22220000");
+ expect(out()).toContain("path"); // workspace tail, not the whole path column value
+ });
+
+ it("--json prints the raw rows", async () => {
+ server.addSession({});
+ await cli(["ls", "--json"]);
+ const rows = JSON.parse(out()) as Array<{ sessionId: string }>;
+ expect(rows).toHaveLength(1);
+ });
+});
+
+describe("penguin input", () => {
+ it("running session -> steer; idle -> task; --timeout 0 returns right after delivery", async () => {
+ const running = server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-abcd0001",
+ status: "running",
+ });
+ let code = await cli(["input", "abcd0001", "-m", "note this", "--timeout", "0"]);
+ expect(code).toBe(0);
+ expect(running.steers).toHaveLength(1);
+ expect(running.tasks).toHaveLength(0);
+ expect(out()).toContain("still running"); // the delivered/still-running note
+ expect(server.requests.some((r) => r.path.endsWith("/stream"))).toBe(false); // no wait at all
+
+ stdout.length = 0;
+ const idle = server.addSession({ sessionId: "session-2026-08-25-10-00-00-abcd0002" });
+ code = await cli(["input", "abcd0002", "-m", "new turn", "--timeout", "0s", "--json"]);
+ expect(code).toBe(0);
+ expect(idle.tasks).toHaveLength(1);
+ expect(JSON.parse(out())).toEqual({ sessionId: idle.sessionId, status: "running" });
+ });
+
+ it("default waits and renders the turn; steer on an idle session falls back to a task", async () => {
+ server.onTask = () => streamedText("turn output");
+ const idle = server.addSession({ sessionId: "session-2026-08-25-10-00-00-abcd0003" });
+ const code = await cli(["input", "abcd0003", "-m", "hello"]);
+ expect(code).toBe(0);
+ expect(idle.tasks).toHaveLength(1);
+ expect(out()).toContain("turn output");
+ });
+});
+
+describe("penguin logs", () => {
+ it("renders history through the history renderer; --tail keeps the last n entries", async () => {
+ server.history = [assistantText("one"), assistantText("two"), assistantText("three")];
+ const s = server.addSession({ sessionId: "session-2026-08-25-10-00-00-10990001" });
+ await cli(["logs", s.sessionId]);
+ expect(out()).toContain("one");
+ expect(out()).toContain("three");
+
+ stdout.length = 0;
+ await cli(["logs", s.sessionId, "--tail", "1"]);
+ expect(out()).not.toContain("one");
+ expect(out()).toContain("three");
+ });
+});
+
+describe("penguin agent / project", () => {
+ it("agent ls prints the table; agent create posts id/name/skills", async () => {
+ await cli(["agent", "ls"]);
+ expect(out()).toContain("default_agent");
+
+ stdout.length = 0;
+ const code = await cli([
+ "agent",
+ "create",
+ "--agent-id",
+ "helper",
+ "--name",
+ "Helper",
+ "--skills",
+ "web-search, pdf",
+ ]);
+ expect(code).toBe(0);
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/agents"));
+ expect(create?.body).toMatchObject({
+ agentId: "helper",
+ name: "Helper",
+ skills: ["web-search", "pdf"],
+ });
+ expect(out()).toContain(t.agent.created("helper", "default_project"));
+ });
+
+ it("project ls lists the reachable projects", async () => {
+ await cli(["project", "ls"]);
+ expect(out()).toContain("default_project");
+ });
+});
+
+describe("penguin cost", () => {
+ it("default prints the summary card (today / last7d / total)", async () => {
+ const code = await cli(["cost"]);
+ expect(code).toBe(0);
+ expect(out()).toContain(t.cost.today());
+ expect(out()).toContain(t.cost.last7d());
+ expect(out()).toContain(t.cost.total());
+ expect(out()).toContain("$2.2500");
+ expect(out()).toContain("$4.5000+"); // hasUncosted marks a partial sum
+ });
+
+ it("--days sets from/to; --by maps to groupBy and prints the grouped table", async () => {
+ server.usage = {
+ ...server.usage,
+ groups: [
+ {
+ key: "default_agent",
+ cacheRead: 1,
+ cacheWrite: 2,
+ output: 3,
+ total: 2048,
+ requests: 4,
+ cost: 1.25,
+ hasUncosted: false,
+ },
+ ],
+ };
+ const code = await cli(["cost", "--days", "7", "--by", "agent"]);
+ expect(code).toBe(0);
+ const req = server.requests.find((r) => r.path.includes("/usage"));
+ expect(req).toBeDefined();
+ expect(out()).toContain("default_agent");
+ expect(out()).toContain("2k");
+ const bad = await cli(["cost", "--by", "bogus"]);
+ expect(bad).toBe(1);
+ });
+});
+
+describe("penguin schedule ls", () => {
+ it("lists schedules with target and status markers; invalid files are marked", async () => {
+ server.schedules = {
+ schedules: [
+ {
+ name: "daily-report",
+ prompt: "p",
+ enabled: true,
+ startAt: "2026-08-25T09:00:00.000Z",
+ period: "1d",
+ sessionId: "session-2026-08-25-10-00-00-dead0001",
+ status: "active",
+ lastFiredAt: "2026-08-25T09:00:00.000Z",
+ queued: false,
+ },
+ {
+ name: "expired-once",
+ prompt: "p",
+ enabled: true,
+ startAt: "2026-01-01T00:00:00.000Z",
+ status: "missed",
+ queued: false,
+ },
+ ],
+ invalidFiles: [{ name: "broken", error: "bad toml" }],
+ };
+ const code = await cli(["schedule", "ls"]);
+ expect(code).toBe(0);
+ expect(out()).toContain("daily-report");
+ expect(out()).toContain("dead0001");
+ expect(out()).toContain(t.schedule.newSession());
+ expect(out()).toContain("missed");
+ expect(out()).toContain("invalid");
+ expect(out()).toContain("broken");
+ });
+});
+
+describe("caller-context defaults (PENGUIN_SESSION_ID inheritance)", () => {
+ it("run inherits workspace/model/approve from the calling session and thinking rides the task", async () => {
+ const caller = server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-ca11e001",
+ workspace: "/callers/workdir",
+ modelId: "caller-model",
+ provider: "caller-prov",
+ approvalMode: "always-ask",
+ thinkingLevel: "high",
+ });
+ process.env.PENGUIN_SESSION_ID = caller.sessionId;
+ const code = await cli(["run", "-m", "child job"]);
+ expect(code).toBe(0);
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/sessions"));
+ expect(create?.body).toMatchObject({
+ workspace: "/callers/workdir",
+ modelId: "caller-model",
+ provider: "caller-prov",
+ approvalMode: "always-ask",
+ client: "cli",
+ });
+ const created = [...server.sessions.values()].find((x) => x.sessionId !== caller.sessionId)!;
+ expect(created.tasks[0]!.thinkingLevel).toBe("high");
+ });
+
+ it("an explicit flag overrides its own field only (the rest still inherit)", async () => {
+ const caller = server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-ca11e002",
+ workspace: "/callers/workdir",
+ modelId: "caller-model",
+ provider: "caller-prov",
+ approvalMode: "always-ask",
+ thinkingLevel: "high",
+ });
+ process.env.PENGUIN_SESSION_ID = caller.sessionId;
+ const code = await cli(["run", "-m", "x", "--workspace", "/elsewhere", "--thinking", "low"]);
+ expect(code).toBe(0);
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/sessions"));
+ expect(create?.body).toMatchObject({
+ // The flag wins over the caller; the value is path.resolve'd against the CLI's cwd
+ // (drive-letter absolute on Windows), so compare the same resolution.
+ workspace: path.resolve("/elsewhere"),
+ modelId: "caller-model", // still inherited
+ provider: "caller-prov",
+ approvalMode: "always-ask",
+ });
+ const created = [...server.sessions.values()].find((x) => x.sessionId !== caller.sessionId)!;
+ expect(created.tasks[0]!.thinkingLevel).toBe("low"); // flag wins
+ });
+
+ it("a failed caller lookup warns (dim, stderr) and falls back to the plain defaults", async () => {
+ process.env.PENGUIN_SESSION_ID = "session-2026-08-25-10-00-00-deadc0de"; // unknown to the server
+ const code = await cli(["run", "-m", "x"]);
+ expect(code).toBe(0);
+ expect(stderr.join("")).toContain("session-2026-08-25-10-00-00-deadc0de");
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/sessions"));
+ expect(create?.body?.workspace).toBe(process.cwd()); // plain default
+ expect(create?.body?.modelId).toBeUndefined(); // project default applies
+ expect(create?.body?.approvalMode).toBeUndefined();
+ });
+
+ it("outside an agent (no PENGUIN_SESSION_ID) nothing changes", async () => {
+ await cli(["run", "-m", "x"]);
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/sessions"));
+ expect(create?.body?.workspace).toBe(process.cwd());
+ expect(create?.body?.modelId).toBeUndefined();
+ expect(create?.body?.approvalMode).toBeUndefined();
+ });
+});
+
+describe("--timeout soft yield", () => {
+ it("run detaches at expiry with the still-running note, exit 0, no abort", async () => {
+ server.hangTasks = true;
+ server.onTask = () => streamedText("partial answer");
+ const code = await cli(["run", "-m", "slow job", "--timeout", "1"]);
+ expect(code).toBe(0);
+ const session = [...server.sessions.values()][0]!;
+ expect(session.aborts).toBe(0); // detach, never abort
+ expect(out()).toContain("partial answer"); // what streamed before expiry rendered
+ expect(out()).toContain("still running");
+ });
+
+ it("run --json reports status running with the collected text", async () => {
+ server.hangTasks = true;
+ server.onTask = () => streamedText("early text");
+ const code = await cli(["run", "-m", "slow job", "--timeout", "1", "--json"]);
+ expect(code).toBe(0);
+ const parsed = JSON.parse(out()) as { sessionId: string; status: string; text: string };
+ expect(parsed.status).toBe("running");
+ expect(parsed.text).toBe("early text");
+ });
+
+ it("run --timeout 0 returns right after the POST with the still-running shape", async () => {
+ server.hangTasks = true;
+ const code = await cli(["run", "-m", "fire and check later", "--timeout", "0", "--json"]);
+ expect(code).toBe(0);
+ const session = [...server.sessions.values()][0]!;
+ expect(session.tasks).toHaveLength(1);
+ expect(JSON.parse(out())).toEqual({ sessionId: session.sessionId, status: "running" });
+ expect(server.requests.some((r) => r.path.endsWith("/stream"))).toBe(false);
+ });
+
+ it("rejects --timeout with --background, and junk durations", async () => {
+ expect(await cli(["run", "-m", "x", "--background", "--timeout", "5s"])).toBe(1);
+ expect(stderr.join("")).toContain("--background");
+ stderr.length = 0;
+ expect(await cli(["run", "-m", "x", "--timeout", "5d"])).toBe(1);
+ expect(stderr.join("")).toContain("5d");
+ expect(server.sessions.size).toBe(0); // validated before anything touches the server
+ });
+
+ it("input -m detaches at expiry the same way", async () => {
+ server.hangTasks = true;
+ const idle = server.addSession({ sessionId: "session-2026-08-25-10-00-00-51ee0001" });
+ const code = await cli(["input", "51ee0001", "-m", "go", "--timeout", "1"]);
+ expect(code).toBe(0);
+ expect(idle.tasks).toHaveLength(1);
+ expect(idle.aborts).toBe(0);
+ expect(out()).toContain("still running");
+ });
+
+ it("logs -f stops following at expiry, exit 0", async () => {
+ server.history = [assistantText("old line")];
+ const s = server.addSession({ sessionId: "session-2026-08-25-10-00-00-10f00001" });
+ const code = await cli(["logs", s.sessionId, "-f", "--timeout", "1"]);
+ expect(code).toBe(0);
+ expect(out()).toContain("old line");
+ const bad = await cli(["logs", s.sessionId, "--timeout", "1"]); // no -f: nothing waits
+ expect(bad).toBe(1);
+ });
+});
+
+describe("penguin input (bare poll form)", () => {
+ it("idle: prints the most recent complete assistant text (skipping user/nested messages)", async () => {
+ server.history = [
+ assistantText("first answer"),
+ { timestamp: "t", type: "model_msg", payload: { type: "text", role: "user", text: "q2" } },
+ assistantText("nested"),
+ assistantText("final answer"),
+ ];
+ // Mark the third entry as a subagent-expanded message: it must be skipped.
+ (server.history[2] as { origin?: string[] }).origin = ["session-child"];
+ const s = server.addSession({ sessionId: "session-2026-08-25-10-00-00-b0110001" });
+ const code = await cli(["input", "b0110001"]);
+ expect(code).toBe(0);
+ expect(out().trim()).toBe("final answer");
+ expect(s.tasks).toHaveLength(0); // nothing queued
+ expect(s.steers).toHaveLength(0); // nothing steered
+ });
+
+ it("running + --timeout: waits out the window, then prints the latest text plus the still-running note", async () => {
+ server.history = [assistantText("latest so far")];
+ server.addSession({ sessionId: "session-2026-08-25-10-00-00-b0110002", status: "running" });
+ const code = await cli(["input", "b0110002", "--timeout", "1"]);
+ expect(code).toBe(0);
+ expect(out()).toContain("latest so far");
+ expect(out()).toContain("still running");
+ });
+
+ it("running + --timeout --json reports status running with the snapshot", async () => {
+ server.history = [assistantText("snapshot")];
+ server.addSession({ sessionId: "session-2026-08-25-10-00-00-b0110003", status: "running" });
+ const code = await cli(["input", "b0110003", "--timeout", "1", "--json"]);
+ expect(code).toBe(0);
+ const parsed = JSON.parse(out()) as { status: string; text: string };
+ expect(parsed.status).toBe("running");
+ expect(parsed.text).toBe("snapshot");
+ });
+
+ it("no reply yet prints the dim placeholder; --json carries an empty text", async () => {
+ server.history = [];
+ server.addSession({ sessionId: "session-2026-08-25-10-00-00-b0110004" });
+ let code = await cli(["input", "b0110004"]);
+ expect(code).toBe(0);
+ expect(out()).toContain(t.input.noReplyYet());
+ stdout.length = 0;
+ code = await cli(["input", "b0110004", "--json"]);
+ expect(code).toBe(0);
+ expect(JSON.parse(out())).toMatchObject({ status: "idle", text: "" });
+ });
+
+ it("poll with --timeout 0 snapshots a running session immediately (no subscription)", async () => {
+ server.history = [assistantText("instant snapshot")];
+ server.addSession({ sessionId: "session-2026-08-25-10-00-00-b0110005", status: "running" });
+ const code = await cli(["input", "b0110005", "--timeout", "0"]);
+ expect(code).toBe(0);
+ expect(out()).toContain("instant snapshot");
+ expect(out()).toContain("still running");
+ expect(server.requests.some((r) => r.path.endsWith("/stream"))).toBe(false);
+ });
+});
+
+describe("logs / input without a session id (the agent's most recent)", () => {
+ /** Two sessions of the same agent, the second one newer. */
+ function twoSessions(): { older: string; newer: string } {
+ const older = "session-2026-08-24-09-00-00-1a7e0001";
+ const newer = "session-2026-08-25-10-00-00-1a7e0002";
+ server.addSession({ sessionId: older, createdAt: "2026-08-24T09:00:00.000Z" });
+ server.addSession({ sessionId: newer, createdAt: "2026-08-25T10:00:00.000Z" });
+ return { older, newer };
+ }
+
+ it("logs renders the newest session and names it in a dim stderr note", async () => {
+ server.history = [assistantText("what happened last")];
+ const { newer } = twoSessions();
+ const code = await cli(["logs"]);
+ expect(code).toBe(0);
+ expect(out()).toContain("what happened last");
+ // The note goes to stderr, so stdout stays exactly what the command renders.
+ expect(stderr.join("")).toContain(t.client.latestSession(newer));
+ expect(out()).not.toContain(newer);
+ });
+
+ it("bare input polls the newest session's last answer, queueing nothing", async () => {
+ server.history = [assistantText("the last thing I said")];
+ const { newer } = twoSessions();
+ const code = await cli(["input"]);
+ expect(code).toBe(0);
+ expect(out().trim()).toBe("the last thing I said");
+ expect(stderr.join("")).toContain(t.client.latestSession(newer));
+ const session = server.sessions.get(newer)!;
+ expect(session.tasks).toHaveLength(0);
+ expect(session.steers).toHaveLength(0);
+ });
+
+ it("--json stays parseable: the note never lands on stdout", async () => {
+ server.history = [assistantText("snapshot")];
+ const { newer } = twoSessions();
+ const code = await cli(["input", "--json"]);
+ expect(code).toBe(0);
+ expect(JSON.parse(out())).toMatchObject({ sessionId: newer, status: "idle" });
+ });
+
+ it("--agent-id picks whose most recent session it is", async () => {
+ twoSessions();
+ server.agents.push({
+ agentId: "helper",
+ name: "Helper",
+ description: "",
+ sessionCount: 0,
+ activeSessionCount: 0,
+ sessionActivity: [],
+ });
+ const helperSession = server.addSession({
+ sessionId: "session-2026-08-20-08-00-00-be1f0001",
+ agentId: "helper",
+ createdAt: "2026-08-20T08:00:00.000Z",
+ });
+ const code = await cli(["logs", "--agent-id", "helper"]);
+ expect(code).toBe(0);
+ expect(stderr.join("")).toContain(t.client.latestSession(helperSession.sessionId));
+ });
+
+ it("an explicit session id still wins over the default", async () => {
+ server.history = [assistantText("history")];
+ const { older } = twoSessions();
+ const code = await cli(["logs", "1a7e0001"]);
+ expect(code).toBe(0);
+ expect(stderr.join("")).not.toContain("[latest]");
+ expect(server.requests.some((r) => r.path === `/api/sessions/${older}/messages`)).toBe(true);
+ });
+
+ it("no sessions at all: one line pointing at run/chat, non-zero exit, no commander noise", async () => {
+ for (const argv of [["logs"], ["input"]]) {
+ stderr.length = 0;
+ const code = await cli(argv);
+ expect(code).toBe(1);
+ const errText = stderr.join("");
+ expect(errText).toContain(t.client.noSessionsYet("default_agent", "default_project"));
+ expect(errText).toContain("penguin chat");
+ expect(errText).not.toContain("missing required argument");
+ expect(errText).not.toContain(" at "); // no stack trace
+ }
+ });
+});
+
+describe("penguin ls --days", () => {
+ it("keeps sessions last active within the trailing calendar window (today = day 1) and combines with -a", async () => {
+ const now = new Date();
+ const at = (daysAgo: number) =>
+ new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo, 12).toISOString();
+ server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-da150001",
+ lastActiveAt: at(0), // today
+ });
+ server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-da150002",
+ lastActiveAt: at(1), // yesterday: inside --days 2
+ });
+ server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-da150003",
+ lastActiveAt: at(2), // two days back: outside --days 2, inside --days 3
+ });
+ server.addSession({
+ sessionId: "session-2026-08-25-10-00-00-da150004",
+ lastActiveAt: at(1),
+ archived: true, // only visible with -a
+ });
+
+ await cli(["ls", "--days", "2"]);
+ expect(out()).toContain("da150001");
+ expect(out()).toContain("da150002");
+ expect(out()).not.toContain("da150003");
+ expect(out()).not.toContain("da150004");
+
+ stdout.length = 0;
+ await cli(["ls", "--days", "2", "-a", "--json"]);
+ const ids = (JSON.parse(out()) as Array<{ sessionId: string }>).map((r) => r.sessionId);
+ expect(ids.some((id) => id.endsWith("da150004"))).toBe(true);
+ expect(ids.some((id) => id.endsWith("da150003"))).toBe(false);
+
+ stdout.length = 0;
+ await cli(["ls", "--days", "3"]);
+ expect(out()).toContain("da150003");
+
+ expect(await cli(["ls", "--days", "0"])).toBe(1);
+ expect(await cli(["ls", "--days", "x"])).toBe(1);
+ });
+});
+
+describe("penguin schedule add/update/rm (validated writer over the API)", () => {
+ it("add posts the full definition, ENABLED by default (the deliberate divergence); --disabled opts out", async () => {
+ const code = await cli([
+ "schedule",
+ "add",
+ "daily-report",
+ "--prompt",
+ "summarize the day",
+ "--start-at",
+ "2026-08-27T09:00:00.000Z",
+ "--period",
+ "1d",
+ "--session-id",
+ "session-2026-08-25-10-00-00-dead0001",
+ ]);
+ expect(code).toBe(0);
+ const create = server.requests.find(
+ (r) => r.method === "POST" && r.path.endsWith("/schedules"),
+ );
+ expect(create?.body).toMatchObject({
+ name: "daily-report",
+ enabled: true,
+ prompt: "summarize the day",
+ startAt: "2026-08-27T09:00:00.000Z",
+ period: "1d",
+ sessionId: "session-2026-08-25-10-00-00-dead0001",
+ });
+ expect(out()).toContain("daily-report");
+
+ stdout.length = 0;
+ const disabled = await cli([
+ "schedule",
+ "add",
+ "paused-task",
+ "--prompt",
+ "p",
+ "--start-at",
+ "2026-08-27T09:00:00.000Z",
+ "--disabled",
+ ]);
+ expect(disabled).toBe(0);
+ expect(server.scheduleItems.get("paused-task")).toMatchObject({ enabled: false });
+ });
+
+ it("--start-at now resolves to the current instant before the request", async () => {
+ const before = Date.now();
+ await cli(["schedule", "add", "one-shot", "--prompt", "p", "--start-at", "now"]);
+ const stored = server.scheduleItems.get("one-shot") as { startAt: string };
+ const ms = Date.parse(stored.startAt);
+ expect(ms).toBeGreaterThanOrEqual(before - 1000);
+ expect(ms).toBeLessThanOrEqual(Date.now() + 1000);
+ });
+
+ it("target is --session-id XOR the new-session form; the model pair stays both-or-neither", async () => {
+ let code = await cli([
+ "schedule",
+ "add",
+ "bad-target",
+ "--prompt",
+ "p",
+ "--start-at",
+ "now",
+ "--session-id",
+ "session-x",
+ "--workspace",
+ "/w",
+ ]);
+ expect(code).toBe(1);
+ expect(stderr.join("")).toContain("--session-id");
+ stderr.length = 0;
+ code = await cli([
+ "schedule",
+ "add",
+ "bad-pair",
+ "--prompt",
+ "p",
+ "--start-at",
+ "now",
+ "--model-id",
+ "m",
+ ]);
+ expect(code).toBe(1);
+ expect(server.scheduleItems.has("bad-target")).toBe(false);
+ expect(server.scheduleItems.has("bad-pair")).toBe(false);
+ });
+
+ it("update is read-modify-write: unspecified fields keep stored values; --disable flips; switching target clears the other kind", async () => {
+ await cli([
+ "schedule",
+ "add",
+ "evolving",
+ "--prompt",
+ "original prompt",
+ "--start-at",
+ "2026-08-27T09:00:00.000Z",
+ "--period",
+ "1d",
+ "--workspace",
+ "/stored/ws",
+ "--model-id",
+ "m1",
+ "--provider",
+ "p1",
+ ]);
+ stdout.length = 0;
+ // Change the period only: prompt/startAt/workspace/model survive.
+ let code = await cli(["schedule", "update", "evolving", "--period", "12h", "--disable"]);
+ expect(code).toBe(0);
+ expect(server.scheduleItems.get("evolving")).toMatchObject({
+ prompt: "original prompt",
+ startAt: "2026-08-27T09:00:00.000Z",
+ period: "12h",
+ workspace: "/stored/ws",
+ modelId: "m1",
+ provider: "p1",
+ enabled: false,
+ });
+ // Switch to a bound session: the new-session fields are cleared, --enable flips back.
+ code = await cli([
+ "schedule",
+ "update",
+ "evolving",
+ "--session-id",
+ "session-2026-08-25-10-00-00-dead0002",
+ "--enable",
+ ]);
+ expect(code).toBe(0);
+ const after = server.scheduleItems.get("evolving") as Record<string, unknown>;
+ expect(after.sessionId).toBe("session-2026-08-25-10-00-00-dead0002");
+ expect(after.enabled).toBe(true);
+ expect(after.workspace).toBeUndefined();
+ expect(after.modelId).toBeUndefined();
+ // --enable with --disable is refused.
+ expect(await cli(["schedule", "update", "evolving", "--enable", "--disable"])).toBe(1);
+ });
+
+ it("rm deletes without prompting; API errors surface verbatim", async () => {
+ await cli(["schedule", "add", "doomed", "--prompt", "p", "--start-at", "now"]);
+ stdout.length = 0;
+ const code = await cli(["schedule", "rm", "doomed"]);
+ expect(code).toBe(0);
+ expect(server.scheduleItems.has("doomed")).toBe(false);
+ expect(out()).toContain("doomed");
+ // A second rm surfaces the server's 404 verbatim.
+ stderr.length = 0;
+ expect(await cli(["schedule", "rm", "doomed"])).toBe(1);
+ expect(stderr.join("")).toContain("schedule_not_found");
+ });
+});
diff --git a/packages/cli/test/task-loop.test.ts b/packages/cli/test/task-loop.test.ts
deleted file mode 100644
index 850b1f6c..00000000
--- a/packages/cli/test/task-loop.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * runTask's result reporting: when a Task ends with a main-session abort event (LLM
- * failure / reconnect exhausted / user interrupt), it reports aborted=true, which
- * `penguin run` maps to a non-zero exit code; a sub-session abort does not count.
- */
-import { describe, expect, it } from "vitest";
-import { Writable } from "node:stream";
-import { abortEvent, assistantText, withOrigin } from "@prismshadow/penguin-core";
-import type { OmniMessage, Session } from "@prismshadow/penguin-core";
-import { StreamRenderer } from "../src/render.js";
-import { runTask } from "../src/task-loop.js";
-import { getMessages } from "../src/i18n.js";
-
-const t = getMessages("en");
-
-function fakeSession(messages: OmniMessage[]): Session {
- return {
- async *run() {
- for (const m of messages) yield m;
- },
- toolPermission: () => "rw",
- } as unknown as Session;
-}
-
-function silentRenderer(): StreamRenderer {
- const stream = new Writable({
- write(_chunk, _enc, cb) {
- cb();
- },
- });
- return new StreamRenderer(stream, t);
-}
-
-describe("runTask abort reporting", () => {
- it("reports aborted=true when the task ends with a main-session abort event", async () => {
- const result = await runTask(fakeSession([abortEvent()]), [], {
- renderer: silentRenderer(),
- t,
- });
- expect(result.aborted).toBe(true);
- });
-
- it("reports aborted=false on normal completion; child-session aborts do not count", async () => {
- const result = await runTask(
- fakeSession([withOrigin(abortEvent(), "sess_child"), assistantText("done")]),
- [],
- { renderer: silentRenderer(), t },
- );
- 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/usage-error.test.ts b/packages/cli/test/usage-error.test.ts
new file mode 100644
index 00000000..a1c0d3d2
--- /dev/null
+++ b/packages/cli/test/usage-error.test.ts
@@ -0,0 +1,138 @@
+/**
+ * Commander's parse failures, driven through `cli()`: the raw English line is gone, what
+ * the user reads is one localized sentence plus the failing command's own usage — for a
+ * positional (`logs`, once its argument is required again by `schedule rm`) and for a
+ * flag (`schedule add`), in both locales. Exit codes stay commander's.
+ */
+import { Command } from "commander";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cli } from "../src/index.js";
+import { getMessages } from "../src/i18n.js";
+import { commandForArgv } from "../src/usage-error.js";
+
+let stdout: string[];
+let stderr: string[];
+let outSpy: { mockRestore(): void };
+let errSpy: { mockRestore(): void };
+let priorLang: string | undefined;
+
+beforeEach(() => {
+ stdout = [];
+ stderr = [];
+ priorLang = process.env.PENGUIN_LANG;
+ outSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ stdout.push(String(chunk));
+ return true;
+ });
+ errSpy = vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ stderr.push(String(chunk));
+ return true;
+ });
+});
+afterEach(() => {
+ outSpy.mockRestore();
+ errSpy.mockRestore();
+ if (priorLang === undefined) delete process.env.PENGUIN_LANG;
+ else process.env.PENGUIN_LANG = priorLang;
+});
+
+const err = () => stderr.join("");
+
+describe("missing positional argument", () => {
+ it("names the argument and the command's usage, in each language", async () => {
+ for (const lang of ["en", "zh"] as const) {
+ process.env.PENGUIN_LANG = lang;
+ stderr.length = 0;
+ const t = getMessages(lang);
+ const code = await cli(["schedule", "rm"]);
+ expect(code).toBe(1);
+ expect(err()).toContain(t.usage.missingArgument("name"));
+ expect(err()).toContain("penguin schedule rm");
+ // Commander's own English wording never reaches the terminal.
+ expect(err()).not.toContain("missing required argument 'name'");
+ }
+ });
+});
+
+describe("missing required option", () => {
+ it("PENGUIN_LANG=zh explains `schedule add` in Chinese", async () => {
+ process.env.PENGUIN_LANG = "zh";
+ const t = getMessages("zh");
+ const code = await cli(["schedule", "add", "daily"]);
+ expect(code).toBe(1);
+ expect(err()).toContain(t.usage.missingOption("--prompt <text>"));
+ // The usage line quotes the failing subcommand, not the program.
+ expect(err()).toContain("penguin schedule add");
+ expect(err()).toContain("--help");
+ expect(err()).not.toContain("required option");
+ });
+
+ it("says the same thing in English", async () => {
+ process.env.PENGUIN_LANG = "en";
+ const t = getMessages("en");
+ const code = await cli(["schedule", "add", "daily"]);
+ expect(code).toBe(1);
+ expect(err()).toContain(t.usage.missingOption("--prompt <text>"));
+ expect(err()).toContain("penguin schedule add");
+ });
+});
+
+describe("unknown option and unknown command", () => {
+ it("both are localized and carry a usage line", async () => {
+ for (const lang of ["en", "zh"] as const) {
+ process.env.PENGUIN_LANG = lang;
+ const t = getMessages(lang);
+
+ stderr.length = 0;
+ expect(await cli(["ls", "--nope"])).toBe(1);
+ expect(err()).toContain(t.usage.unknownOption("--nope"));
+ expect(err()).toContain("penguin ls");
+
+ stderr.length = 0;
+ expect(await cli(["nosuchthing"])).toBe(1);
+ expect(err()).toContain(t.usage.unknownCommand("nosuchthing"));
+ expect(err()).toContain("penguin");
+ }
+ });
+});
+
+describe("what must not change", () => {
+ it("--help and --version print their own output and exit 0", async () => {
+ expect(await cli(["--help"])).toBe(0);
+ expect(stdout.join("")).toContain("penguin");
+ expect(err()).toBe("");
+ stdout.length = 0;
+ expect(await cli(["--version"])).toBe(0);
+ expect(stdout.join("").trim().length).toBeGreaterThan(0);
+ expect(err()).toBe("");
+ });
+
+ it("bare `penguin` still prints help, not an error", async () => {
+ expect(await cli([])).toBe(0);
+ expect(stdout.join("")).toContain("Usage:");
+ expect(err()).toBe("");
+ });
+});
+
+describe("commandForArgv", () => {
+ const program = new Command().name("penguin");
+ const schedule = program.command("schedule");
+ const add = schedule.command("add <name>");
+ const ls = program.command("ls");
+
+ it("walks to the deepest named subcommand", () => {
+ expect(commandForArgv(program, ["schedule", "add", "daily"])).toBe(add);
+ expect(commandForArgv(program, ["schedule"])).toBe(schedule);
+ expect(commandForArgv(program, ["ls", "--json"])).toBe(ls);
+ });
+
+ it("skips option flags and stops at the first non-command word", () => {
+ expect(commandForArgv(program, ["--json", "ls"])).toBe(ls);
+ expect(commandForArgv(program, ["ls", "extra", "add"])).toBe(ls);
+ expect(commandForArgv(program, [])).toBe(program);
+ expect(commandForArgv(program, ["unknown"])).toBe(program);
+ // An option's value is a bare word too, and stops the walk — landing on the parent
+ // is the safe outcome, never a wrong command.
+ expect(commandForArgv(program, ["--server", "http://x", "ls"])).toBe(program);
+ });
+});
diff --git a/packages/cli/test/warnings.test.ts b/packages/cli/test/warnings.test.ts
new file mode 100644
index 00000000..62dbffb6
--- /dev/null
+++ b/packages/cli/test/warnings.test.ts
@@ -0,0 +1,60 @@
+/**
+ * The node:sqlite warning filter: exactly one warning is dropped, every other one still
+ * reaches the terminal. Importing the module installs the filter as a side effect (the
+ * entry does nothing else), so the install is exercised here too.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { installWarningFilter, isSqliteExperimentalWarning } from "../src/warnings.js";
+
+describe("isSqliteExperimentalWarning", () => {
+ it("matches the builtin's notice, whichever shape emitWarning was called in", () => {
+ const text = "SQLite is an experimental feature and might change at any time";
+ expect(isSqliteExperimentalWarning(text, "ExperimentalWarning")).toBe(true);
+ expect(isSqliteExperimentalWarning(text, { type: "ExperimentalWarning" })).toBe(true);
+ const asError = Object.assign(new Error(text), { name: "ExperimentalWarning" });
+ expect(isSqliteExperimentalWarning(asError)).toBe(true);
+ });
+
+ it("leaves every other warning alone", () => {
+ expect(isSqliteExperimentalWarning("Something else", "ExperimentalWarning")).toBe(false);
+ expect(
+ isSqliteExperimentalWarning("SQLite is an experimental feature", "DeprecationWarning"),
+ ).toBe(false);
+ expect(isSqliteExperimentalWarning("a plain warning")).toBe(false);
+ });
+});
+
+describe("installWarningFilter", () => {
+ let uninstall: (() => void) | null = null;
+ afterEach(() => {
+ uninstall?.();
+ uninstall = null;
+ vi.restoreAllMocks();
+ });
+
+ it("swallows the sqlite notice and forwards the rest verbatim", () => {
+ const emitted: unknown[][] = [];
+ vi.spyOn(process, "emitWarning").mockImplementation(((...args: unknown[]) => {
+ emitted.push(args);
+ }) as typeof process.emitWarning);
+ uninstall = installWarningFilter();
+
+ process.emitWarning(
+ "SQLite is an experimental feature and might change at any time",
+ "ExperimentalWarning",
+ );
+ process.emitWarning("Type stripping is an experimental feature", "ExperimentalWarning");
+ process.emitWarning("something deprecated", "DeprecationWarning", "DEP0001");
+
+ expect(emitted).toEqual([
+ ["Type stripping is an experimental feature", "ExperimentalWarning"],
+ ["something deprecated", "DeprecationWarning", "DEP0001"],
+ ]);
+ });
+
+ it("restores the original emitter", () => {
+ const original = process.emitWarning;
+ installWarningFilter()();
+ expect(process.emitWarning).toBe(original);
+ });
+});
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 2d1d776e..59e2ee44 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -92,6 +92,23 @@ export interface CreateAgentOptions {
* user's own shell environment).
*/
proxyEnv?: () => ProxyEnvPolicy | null;
+ /**
+ * Harness-control variables for the command subprocesses of every Session this Agent
+ * creates or resumes. The hosting server passes a policy getter here; core evaluates it
+ * with each Session's own coordinates (subagent Sessions get their own agent/session
+ * ids — a child Agent inherits the getter like `proxyEnv`, and its Sessions call it with
+ * their own context). The returned entries override vault entries of the same name (see
+ * {@link EnvironmentConfig.controlEnv}). Absent = nothing is injected (SDK/CLI
+ * standalone use).
+ */
+ controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;
+}
+
+/** The Session coordinates a {@link CreateAgentOptions.controlEnv} policy is evaluated with. */
+export interface ControlEnvContext {
+ projectId: string;
+ agentId: string;
+ sessionId: string;
}
export interface CreateSessionOptions {
@@ -156,7 +173,7 @@ export function metaMaxTokens(budget: number, modelCap: number | undefined): num
export async function createAgent(opts: CreateAgentOptions = {}): Promise<Agent> {
const state = await loadOrInitAgentState(opts);
const projectConfig = await loadProjectConfig(state.root, state.projectId);
- return new Agent(state, projectConfig, opts.proxyEnv);
+ return new Agent(state, projectConfig, opts.proxyEnv, opts.controlEnv);
}
export class Agent {
@@ -165,6 +182,8 @@ export class Agent {
readonly projectConfig: ProjectConfig,
/** See {@link CreateAgentOptions.proxyEnv}; forwarded into every Session's Environment. */
private readonly proxyEnv?: () => ProxyEnvPolicy | null,
+ /** See {@link CreateAgentOptions.controlEnv}; evaluated per Session with that Session's coordinates. */
+ private readonly controlEnv?: (ctx: ControlEnvContext) => Record<string, string>,
) {}
/**
@@ -670,10 +689,13 @@ export class Agent {
root,
projectId,
agentId,
- // A child Agent loads its own vault/config, but the proxy-env policy
- // getter is host policy, not Agent state: the subagent's commands run in
- // the same serving process, so they follow the same settings as the parent's.
+ // A child Agent loads its own vault/config, but the proxy-env and
+ // control-env policy getters are host policy, not Agent state: the
+ // subagent's commands run in the same serving process, so they follow the
+ // same settings as the parent's — controlEnv is then evaluated with the
+ // child Session's own coordinates.
...(parentAgent.proxyEnv ? { proxyEnv: parentAgent.proxyEnv } : {}),
+ ...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),
})
: parentAgent;
// The child Session follows the PARENT Session, never the Project default: with the
@@ -717,6 +739,7 @@ export class Agent {
projectId,
agentId,
...(parentAgent.proxyEnv ? { proxyEnv: parentAgent.proxyEnv } : {}),
+ ...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),
});
const childSession = await childAgent.resumeSession({ sessionId });
return subagentHandleFor(childSession);
@@ -880,6 +903,19 @@ export class Agent {
services: { subagentRunner, ...(visionDescriber ? { visionDescriber } : {}) },
...(Object.keys(vault).length > 0 ? { vault } : {}),
...(this.proxyEnv ? { proxyEnv: this.proxyEnv } : {}),
+ // The control-env policy is bound to THIS Session's coordinates here (sessionId is
+ // final by now); the getter shape keeps it re-evaluated at every command spawn, so
+ // the host can rotate what it injects (e.g. its API token) without a rebuild.
+ ...(this.controlEnv
+ ? {
+ controlEnv: () =>
+ this.controlEnv!({
+ projectId: this.state.projectId,
+ agentId: this.state.agentId,
+ sessionId,
+ }),
+ }
+ : {}),
});
// Configured output cap: the entry's per-model annotation wins over the Agent's
diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts
index 2d870f1f..c6e5f3c6 100644
--- a/packages/core/src/environment/environment.ts
+++ b/packages/core/src/environment/environment.ts
@@ -170,6 +170,7 @@ export class Environment implements EnvironmentInterface {
this.commandSessions = new CommandSessionManager({
...(config.vault !== undefined ? { vault: config.vault } : {}),
...(config.proxyEnv !== undefined ? { proxyEnv: config.proxyEnv } : {}),
+ ...(config.controlEnv !== undefined ? { controlEnv: config.controlEnv } : {}),
});
this.subagentSessions = new SubagentSessionManager();
this.subagentRunner = config.services?.subagentRunner ?? null;
diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.ts
index 2cfce191..26b1d425 100644
--- a/packages/core/src/environment/tools/command/session-manager.ts
+++ b/packages/core/src/environment/tools/command/session-manager.ts
@@ -172,10 +172,22 @@ export class CommandSessionManager {
* are already running. Absent = pass through (SDK/CLI standalone use).
*/
private readonly proxyEnv: (() => ProxyEnvPolicy | null) | undefined;
+ /**
+ * Harness-control variables (PENGUIN_API_URL / PENGUIN_API_TOKEN / the Session
+ * coordinates, see {@link EnvironmentConfig.controlEnv}): injected on every spawn AFTER
+ * the vault, so the host's sanctioned wiring wins over a vault entry of the same name.
+ * A getter like `proxyEnv`, re-read at every spawn. Absent = nothing injected.
+ */
+ private readonly controlEnv: (() => Record<string, string>) | undefined;
- constructor(opts?: { vault?: Record<string, string>; proxyEnv?: () => ProxyEnvPolicy | null }) {
+ constructor(opts?: {
+ vault?: Record<string, string>;
+ proxyEnv?: () => ProxyEnvPolicy | null;
+ controlEnv?: () => Record<string, string>;
+ }) {
this.vault = opts?.vault ?? {};
this.proxyEnv = opts?.proxyEnv;
+ this.controlEnv = opts?.controlEnv;
}
/** Starts a command, returning an **unregistered** session (no process_id yet). */
@@ -186,22 +198,29 @@ export class CommandSessionManager {
return new ManagedSession({
cmd: opts.cmd,
cwd: opts.cwd,
- // Spread order is priority: vault overrides host variables of the same name, but must
- // come before HARDENED_ENV — the hardening entries (GIT_EDITOR/PAGER etc. that prevent
- // interactive hangs) must never be overridable by vault. The host side is stripped of
- // the harness's own variables first (see STRIPPED_ENV_KEYS) and has the proxyEnv
- // policy applied (strip or inject); the vault still wins — over an injected proxy
- // too — so a user who genuinely wants PORT, or their own proxy, in commands can set
- // it there.
+ // Spread order is priority: vault overrides host variables of the same name; the
+ // host's control variables (controlEnv) override the vault — they are the hosting
+ // server's own wiring (API URL/token, Session coordinates) and a vault entry must
+ // not silently point commands at another server; and HARDENED_ENV comes last — the
+ // hardening entries (GIT_EDITOR/PAGER etc. that prevent interactive hangs) are never
+ // overridable by anything. The host side is stripped of the harness's own variables
+ // first (see STRIPPED_ENV_KEYS) and has the proxyEnv policy applied (strip or
+ // inject); the vault still wins over the host env — over an injected proxy too — so
+ // a user who genuinely wants PORT, or their own proxy, in commands can set it there.
//
// The strip governs inheritance only: it runs inside hostEnvForChild and never
- // re-applies to later spread entries, so anything the harness deliberately layers
- // into this spread after the host env carries authoritative values into the child,
- // stripped names — PENGUIN_* included — and all. An injection layer added to this
- // spread later composes with the strip for free: the inherited copy is gone, the
- // injected value stands (pinned by the "an explicit injection layered after the
- // strip wins" test).
- env: { ...hostEnvForChild(this.proxyEnv?.() ?? null), ...this.vault, ...HARDENED_ENV },
+ // re-applies to entries spread in after it, so the vault and controlEnv carry
+ // authoritative values into the child — stripped names, PENGUIN_* included, and all.
+ // Both guarantees hold because of that order: no PENGUIN_* reaches a command by
+ // inheritance, while the control variables the host does sanction arrive as injected
+ // values rather than as surviving copies. Pinned by the "an explicit injection
+ // layered after the strip wins" test.
+ env: {
+ ...hostEnvForChild(this.proxyEnv?.() ?? null),
+ ...this.vault,
+ ...(this.controlEnv?.() ?? {}),
+ ...HARDENED_ENV,
+ },
});
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index ca9a43e8..94432af9 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -66,7 +66,12 @@ export { modelVisiblePath } from "./internal/model-visible-path.js";
export { atomicWriteFile } from "./internal/atomic-write.js";
export type { AtomicWriteOptions } from "./internal/atomic-write.js";
export { Agent, createAgent } from "./agent.js";
-export type { CreateAgentOptions, CreateSessionOptions, ResumeSessionOptions } from "./agent.js";
+export type {
+ ControlEnvContext,
+ CreateAgentOptions,
+ CreateSessionOptions,
+ ResumeSessionOptions,
+} from "./agent.js";
/** SDK version number. */
export const VERSION = "0.2.4";
diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.ts
index 08549913..91d9f04a 100644
--- a/packages/core/src/interfaces/environment.ts
+++ b/packages/core/src/interfaces/environment.ts
@@ -291,6 +291,16 @@ export interface EnvironmentConfig {
* for SDK/CLI standalone use).
*/
proxyEnv?: () => ProxyEnvPolicy | null;
+ /**
+ * Harness-control variables for exec_command / input_command subprocess environments
+ * (see {@link CreateAgentOptions.controlEnv}): the hosting server injects its own API
+ * address, its local API token and this Session's coordinates so commands the Agent
+ * runs can drive the harness back through the CLI/API. Re-read at every spawn like
+ * `proxyEnv`. These entries override vault entries of the same name (sanctioned host
+ * wiring outranks per-Agent variables) but never the hardened entries. Absent = nothing
+ * is injected (SDK/CLI standalone use).
+ */
+ controlEnv?: () => Record<string, string>;
}
/**
diff --git a/packages/core/test/exec-session.test.ts b/packages/core/test/exec-session.test.ts
index fea85c91..65b79b20 100644
--- a/packages/core/test/exec-session.test.ts
+++ b/packages/core/test/exec-session.test.ts
@@ -609,3 +609,70 @@ describe("proxyEnv policy governs the proxy variables commands inherit", () => {
expect(res.output).toContain("H=[http://proxy.corp.example:8080]");
});
});
+
+describe("controlEnv injects the host's harness-control variables into commands", () => {
+ // The hosting server threads a controlEnv getter through Environment ->
+ // CommandSessionManager so commands the Agent runs can drive the harness back through
+ // the CLI/API (PENGUIN_API_URL / PENGUIN_API_TOKEN / the Session coordinates).
+
+ it("injected PENGUIN_* variables reach the child even though inherited ones are stripped", async () => {
+ // The host process's own PENGUIN_API_URL must NOT leak through inheritance; the same
+ // name from controlEnv must arrive — injection happens after the prefix strip.
+ process.env.PENGUIN_API_URL = "http://inherited.example:1";
+ const controlled = new Environment({
+ workspaceDir: tmp,
+ toolConfig: sessionConfig(),
+ controlEnv: () => ({
+ PENGUIN_API_URL: "http://localhost:7364",
+ PENGUIN_SESSION_ID: "session-x",
+ }),
+ });
+ try {
+ const res = await runTool(controlled, "exec_command", {
+ cmd: `node -e "console.log('U=[' + (process.env.PENGUIN_API_URL ?? '') + '] S=[' + (process.env.PENGUIN_SESSION_ID ?? '') + ']')"`,
+ });
+ expect(res.output).toContain("U=[http://localhost:7364] S=[session-x]");
+ } finally {
+ controlled.dispose();
+ delete process.env.PENGUIN_API_URL;
+ }
+ });
+
+ it("controlEnv overrides a vault entry of the same name (sanctioned host wiring wins)", async () => {
+ const controlled = new Environment({
+ workspaceDir: tmp,
+ toolConfig: sessionConfig(),
+ vault: { PENGUIN_API_TOKEN: "vault-token", KEEP_ME: "vault-kept" },
+ controlEnv: () => ({ PENGUIN_API_TOKEN: "boot-token" }),
+ });
+ try {
+ const res = await runTool(controlled, "exec_command", {
+ cmd: `node -e "console.log('T=[' + (process.env.PENGUIN_API_TOKEN ?? '') + '] K=[' + (process.env.KEEP_ME ?? '') + ']')"`,
+ });
+ expect(res.output).toContain("T=[boot-token] K=[vault-kept]");
+ } finally {
+ controlled.dispose();
+ }
+ });
+
+ it("the getter is re-read at every spawn, so a rotated token reaches running Sessions", async () => {
+ let token = "first";
+ const controlled = new Environment({
+ workspaceDir: tmp,
+ toolConfig: sessionConfig(),
+ controlEnv: () => ({ PENGUIN_API_TOKEN: token }),
+ });
+ try {
+ const read = `node -e "console.log('T=[' + (process.env.PENGUIN_API_TOKEN ?? '') + ']')"`;
+ expect((await runTool(controlled, "exec_command", { cmd: read })).output).toContain(
+ "T=[first]",
+ );
+ token = "second";
+ expect((await runTool(controlled, "exec_command", { cmd: read })).output).toContain(
+ "T=[second]",
+ );
+ } finally {
+ controlled.dispose();
+ }
+ });
+});
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 6496a2b0..b602abf4 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -5,29 +5,57 @@ description: Complete reference for the penguin command, its subcommands, and op
The CLI ships as the npm package `@prismshadow/penguin-cli`; the command is `penguin`. Running bare `penguin` prints help; `-v, --version` prints the running build's one-line identity, and `penguin version --json` prints the whole of it. A `.env` file in the working directory is loaded automatically on startup.
+The CLI is a thin client of the server: every session-facing command (`run`, `chat`, `ls`, `input`, `logs`, `agent`, `project`, `cost`, `schedule`) sends HTTP requests to a PenguinHarness server and renders the replies — tasks execute on the server, sessions live in its index, and the Web App sees everything the CLI creates (and vice versa). Only `config` still edits the Project's files directly, and `server` / `web` start the service itself.
+
+## Server connection
+
+A CLI talking to the local machine's server needs no login. The connection resolves in this order, first hit wins:
+
+1. `--server <url>` — an explicit target.
+2. `PENGUIN_API_URL` — the same, from the environment. Server-driven sessions inject it (together with `PENGUIN_API_TOKEN`, `PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID`, `PENGUIN_SESSION_ID`) into every tool subprocess, so an agent's own `penguin` calls reach the server that runs them.
+3. A live `server.lock` at the data root (`PENGUIN_HOME`, else `~/.penguin/data`): attach to the running local server.
+4. Auto-start: spawn a detached local server on an ephemeral port (its output goes to `<root>/logs/server-auto-<date>.log`), wait for it, attach. If two CLIs race, the loser's spawn exits and both attach to the winner.
+
+Authentication is the local API token: the server writes a fresh one to `<root>/api-token` (owner-only, rotated every boot), and the CLI sends it as `Authorization: Bearer`. `PENGUIN_API_TOKEN` overrides the file; the file is only read for loopback targets — connecting to a remote `--server` requires `PENGUIN_API_TOKEN` explicitly. Holding the file is admin authority by design: local filesystem access to the data root already is (the same rule `penguin server reset-admin-password` stands on).
+
## Global conventions
- Model references: a model's identity is always the `(provider, model_id)` pair. `--model-id` takes the upstream model id and `--provider` the group it belongs to; the provider is never inferred, guessed, or defaulted. On `run` / `chat` the pair as a whole is optional — pass both to pick a model, or neither to use the Project's default model — but passing one without the other is an error.
-- Data root: `--root <dir>` overrides the data root directory. Priority: `--root` > the `PENGUIN_HOME` env var > `~/.penguin/data`.
+- Project and agent defaults: `--project-id` falls back to `PENGUIN_PROJECT_ID`, then `default_project`; `--agent-id` falls back to `PENGUIN_AGENT_ID`, then `default_agent`. Inside a server-driven session those env vars name the session's own coordinates.
+- Session references: wherever a command takes a session id (`input`, `logs`, `run --session`, `chat --resume`), the full id or any unique fragment works — the 8-hex tail `penguin ls` prints is the intended shorthand. An ambiguous fragment errors listing the candidates.
+- The latest-session default: where the session id is optional — `input [session_id]`, `logs [session_id]`, `chat --resume` — omitting it means **the agent's most recent session** (`--agent-id` picks whose, with the env default above). `input` and `logs` name the session they picked in a dim `[latest]` line on stderr, so the target is never ambiguous and `--json` on stdout stays parseable. When the agent has no session at all, they print one line pointing at `penguin run` / `penguin chat` and exit non-zero.
+- `--json` prints raw JSON instead of the rendered/tabular output; `--server <url>` targets a specific server (see above).
+- Caller-context defaults: inside a harness agent (`PENGUIN_SESSION_ID` present in the environment), a session created by `run` / `chat` defaults each **unspecified** field to the calling session's live values — the Workspace, the model pair, the approval mode and the thinking level — the same inheritance `run_subagent` applies to spawned children, so the two surfaces follow one convention. Per field the precedence is explicit flag > caller value > the plain fallback; a failed lookup prints a dim warning and falls back; outside an agent nothing changes. (`--project-id` / `--agent-id` keep their env-var defaults above.)
+- `--timeout <duration>` (on `run`, `input`, and `logs -f`) bounds the wait with soft-yield semantics — the `exec_command` yield-window model applied to the CLI's wait: at expiry the command detaches cleanly and exits 0, and the task keeps running server-side for a later `penguin input` / `penguin logs` to pick up. Accepted shapes: `30s`, `5m`, `2h`, or a bare integer meaning seconds; anything else is rejected. `--timeout 0` is the degenerate window — return immediately after delivery (`{sessionId, status: "running"}` under `--json`); the one knob covers "don't wait" too. No flag = wait indefinitely. (`run --background` remains the idiomatic fire-and-forget for NEW tasks: it prints the bare session id for scripts and detaches at creation time.)
+- Argument errors speak the interface language: a missing argument, a missing required option, an unknown option or a mistyped command prints one localized line plus that command's own usage and a pointer at its `--help`, and exits non-zero.
+- Data root (`config` only): `--root <dir>` overrides the data root directory. Priority: `--root` > the `PENGUIN_HOME` env var > `~/.penguin/data`.
## penguin run
-Send a single message, execute one Task, then exit. If the Task aborted, the exit code is non-zero, so scripts / CI can check it.
+Create a session on the server (or reuse one), send a single message, stream and render the task until it ends, print the stats line, then exit. Exit code 0 on completed; a goal run exits 0 only when the goal outcome is `complete`.
```bash
penguin run -m "Summarize the code structure of this directory"
+penguin run -m "keep going" --session 402a2e24 # reuse a session by fragment
+penguin run -m "long job" --background # returns the session id immediately
```
| Option | Description |
| --- | --- |
| `-m, --message <message>` | Required; the message to send |
+| `--project-id <id>` | Project to use (default: `PENGUIN_PROJECT_ID`, else `default_project`) |
+| `--agent-id <id>` | Agent to use (default: `PENGUIN_AGENT_ID`, else `default_agent`) |
+| `--workspace <path>` | Workspace directory; a relative path resolves against the CLI's cwd, and the default is the cwd itself. It must exist on the server's machine — in the default local flow that is this machine |
| `--model-id <id>` | Upstream id of the model to use; requires `--provider`. Omit both to use the Project's default model |
| `--provider <group>` | Provider group of the model; required whenever `--model-id` is given |
-| `--project-id <id>` | Project to use |
-| `--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` / `max`. 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 |
+| `--approve <mode>` | Approval mode, see below (default `allow-all`). With `--session` it PATCHes the session's sticky mode |
+| `--thinking <level>` | Thinking level for this task: `low` / `medium` / `high` / `xhigh` / `max`; rides the task request. Omitted, the session's pinned level (else the Agent config) applies |
+| `--session <sessionId>` | Reuse an existing session (full id or unique fragment) instead of creating one; excludes `--workspace` and the model pair |
+| `--background` | POST the task and exit immediately, printing the session id (`{"sessionId"}` under `--json`); the task keeps running on the server — follow it with `penguin logs -f` |
+| `--timeout <duration>` | Soft-yield wait budget (see Global conventions): at expiry, print what has rendered plus a dim still-running line with the session id (`{sessionId, status: "running", text}` under `--json`) and exit 0 — the task is not aborted. `--timeout 0` returns right after the POST (`{sessionId, status: "running"}` under `--json`, no `text`). Excludes `--background` |
+| `--goal [budget]` | Goal mode: the message is the objective and the server loops until a terminal state; the optional value is a token budget (e.g. `500k`) |
+| `--json` | Print a final `{sessionId, status, text}` object instead of the rendered stream (`text` joins the main session's assistant text messages) |
+| `--server <url>` | Target server (see Server connection) |
## penguin chat
@@ -35,8 +63,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 |
+| `--resume [sessionId]` | Resume a Session (full id or unique fragment); without an id, resumes the Agent's latest Session |
| `--verbose` | Show full tool output; by default long tool outputs are collapsed (see below) |
+| `--server <url>` | Target server (see Server connection) |
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.
@@ -63,6 +92,129 @@ Ctrl-C is state-dependent:
| Input buffer non-empty | Clear the current input |
| Idle with empty buffer | Show an exit confirmation (y/N) |
+## penguin ls
+
+List the project's sessions — all agents, or one with `--agent-id`. Columns: short id (the 8-hex tail other commands accept as a fragment), agent, title, running/idle, last active, workspace tail. Archived sessions appear only with `-a`.
+
+```bash
+penguin ls
+penguin ls --agent-id default_agent -a
+penguin ls --json
+```
+
+| Option | Description |
+| --- | --- |
+| `--project-id <id>` / `--agent-id <id>` | Scope (see Global conventions for the defaults; without `--agent-id` every agent of the project is listed) |
+| `-a, --all` | Include archived sessions |
+| `--days <n>` | Only sessions whose last activity falls within the trailing n calendar days — today counts as day 1, so `--days 2` covers yesterday and today (the `cost --days` calendar semantics). Combines with `-a` and `--json` |
+| `--json` / `--server <url>` | As everywhere |
+
+## penguin input
+
+Send a message into a session — or, without `-m`, poll its last answer. The session id is optional: omitted, it is the agent's most recent session (see Global conventions), which makes bare `penguin input` the answer to "what did my agent last say". With `-m`, a running session receives the text as steering (delivered between turns) and an idle one gets a new task; by default the command waits and renders until the turn completes, and `--timeout` bounds the wait (soft yield — see Global conventions; `--timeout 0` returns right after delivery).
+
+Without `-m`, the command is a **poll**, mirroring `input_subagent`'s empty-prompt semantics: it prints the session's most recent complete assistant text (an idempotent last-answer snapshot from the history tail; thinking and tool output are skipped), queueing and steering nothing. A running session is waited on silently first — bounded by `--timeout` when given, with `--timeout 0` snapshotting immediately — and if it is still running at expiry, the current latest text is printed together with the still-running note (exit 0).
+
+```bash
+penguin input 402a2e24 -m "also check the tests"
+penguin input 402a2e24 -m "queue this" --timeout 0 # deliver and return immediately
+penguin input 402a2e24 # poll: print the last assistant reply
+penguin input # poll the agent's most recent session
+penguin input 402a2e24 --timeout 5m # poll, waiting out a running turn up to 5 minutes
+```
+
+| Option | Description |
+| --- | --- |
+| `-m, --message <text>` | The message text; omit it to poll the last assistant reply instead |
+| `--timeout <duration>` | Soft-yield wait budget: with `-m`, detach at expiry like `run` (`{sessionId, status: "running", text}` under `--json`), and `--timeout 0` returns right after delivery (`{sessionId, status: "running"}`); without `-m`, take the snapshot at expiry — `0` immediately — and note the session is still running |
+| `--project-id <id>` | Fragment-search scope (a full session id needs none) |
+| `--agent-id <id>` | Whose most recent session the omitted session id means |
+| `--json` / `--server <url>` | As everywhere; `--json` with `-m` prints `{sessionId, status, text}` (status `completed` / `aborted` / `running`; the `--timeout 0` shape drops `text`), and the poll form `{sessionId, status, text}` with status `idle` / `running` (text `""` when there is no reply yet) |
+
+## penguin logs
+
+Render a session's history through the same renderer the REPL uses. The session id is optional: omitted, it is the agent's most recent session (see Global conventions), so bare `penguin logs` shows what just happened.
+
+```bash
+penguin logs # the agent's most recent session
+penguin logs 402a2e24 --tail 20
+penguin logs 402a2e24 -f
+```
+
+| Option | Description |
+| --- | --- |
+| `--tail <n>` | Show only the last n entries |
+| `-f, --follow` | Keep following the live stream after the history (read-only; Ctrl-C detaches without touching the session) |
+| `--timeout <duration>` | Stop following after this long (soft yield, exit 0); only meaningful with `-f` |
+| `--project-id <id>` | Fragment-search scope |
+| `--agent-id <id>` | Whose most recent session the omitted session id means |
+| `--json` / `--server <url>` | As everywhere; `--json` prints the raw message array (and, with `-f`, one JSON message per line as they arrive) |
+
+## penguin agent
+
+```bash
+penguin agent ls
+penguin agent create --agent-id helper --name "Helper" --skills web-search,pdf
+```
+
+`agent ls` lists the project's agents (id, name, session count, description). `agent create` creates one:
+
+| Option | Description |
+| --- | --- |
+| `--agent-id <id>` | Required; the agent id (directory name) |
+| `--name <s>` / `--description <s>` | Display name and description |
+| `--skills <a,b>` | Comma-separated library skill names to preinstall; unknown names are rejected before anything is created |
+| `--project-id <id>` / `--json` / `--server <url>` | As everywhere |
+
+## penguin project
+
+`penguin project ls` lists the projects this account can reach (own and shared), with id, display name and role. `--json` / `--server` as everywhere.
+
+## penguin cost
+
+Token usage and cost from the server's usage aggregates. The default prints the summary card — today / last 7 days / total (computed regardless of any range) — and `--by` prints a grouped table instead.
+
+```bash
+penguin cost
+penguin cost --days 7 --by model
+penguin cost --from 2026-08-01 --to 2026-08-25 --by agent
+```
+
+| Option | Description |
+| --- | --- |
+| `--days <n>` | Trailing window of n days (sets from/to) |
+| `--from <d>` / `--to <d>` | Explicit range (`yyyy-mm-dd`, always as a pair) |
+| `--by <dim>` | Group by `date`, `agent`, `model` or `session` |
+| `--project-id <id>` / `--agent-id <id>` | Scope; `--agent-id` filters (no default agent here — costs are a project view unless narrowed) |
+| `--json` / `--server <url>` | As everywhere |
+
+A `+` after a cost marks a partial sum (some model in the bucket has no pricing configured); `-` means no priced usage at all.
+
+## penguin schedule
+
+`penguin schedule ls` lists the project's scheduled tasks — all agents, or one with `--agent-id`. Columns: agent, name, enabled, start time, period (`once` for one-shot tasks), target (a bound session's short id or `new session`), last fired, and a status marker for every non-active state (`expired` / `done` / `missed` / `invalid`; unparsable schedule files are listed too, marked invalid). `--json` / `--server` as everywhere.
+
+`add` / `update` / `rm` manage schedules through the API, which writes the schedule's TOML file — **the file remains the single source of truth**, and the CLI is a validated writer (the same pattern model config and the vault follow: updates go through the system interface, validation converges at the interface layer, and hand edits stay possible). API errors surface verbatim, so an agent gets synchronous validation instead of the reconcile lag a hand edit hits.
+
+```bash
+penguin schedule add daily-report --prompt "summarize the day" --start-at 2026-09-01T09:00:00Z --period 1d
+penguin schedule add once-now --prompt "check the deploy" --start-at now --session-id 402a2e24
+penguin schedule update daily-report --period 12h --disable
+penguin schedule rm daily-report
+```
+
+| Option | Description |
+| --- | --- |
+| `--prompt <s>` | The text each firing sends (required on `add`) |
+| `--start-at <ISO\|now>` | First fire time, ISO 8601, or the literal `now` for the current instant (required on `add`) |
+| `--period <dur>` | Fixed interval, minimum `5m` (e.g. `30m`, `12h`, `1d`, `7d`); omitted = one-shot |
+| `--end-at <ISO>` | Stop firing after this instant |
+| `--session-id <id>` | Bind firings to one session — XOR with the new-session form below |
+| `--workspace <path>` / `--model-id <id> --provider <p>` | New-session mode: each firing creates a session on this workspace/model (workspace omitted = a temp workspace; the model pair is both-or-neither, omitted = the Project default) |
+| `--disabled` (`add`) | One deliberate divergence from the raw file: `add` creates the task **enabled** — you are adding a task to run — while the raw-file default of `enabled = false` stays for hand edits. `--disabled` opts out |
+| `--enable` / `--disable` (`update`) | Flip the enabled flag; `update` is read-modify-write against the stored item, so unspecified fields keep their values, and switching target kinds clears the other kind's fields |
+| `--project-id` / `--agent-id` / `--json` / `--server` | As everywhere; `rm` deletes without prompting (the server's owner authorization still applies) |
+
## Approval modes (--approve)
| Mode | Behavior |
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index d4faa173..1e998674 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -5,29 +5,57 @@ description: penguin 命令的子命令与选项完整参考。
CLI 由 npm 包 `@prismshadow/penguin-cli` 提供,命令为 `penguin`。不带子命令执行 `penguin` 时打印帮助;`-v, --version` 打印当前构建的单行身份,`penguin version --json` 打印其完整信息。启动时自动加载工作目录下的 `.env`。
+CLI 是服务端的瘦客户端:所有会话相关命令(`run`、`chat`、`ls`、`input`、`logs`、`agent`、`project`、`cost`、`schedule`)都向 PenguinHarness 服务端发 HTTP 请求并渲染回复——Task 在服务端执行,Session 记录在服务端索引里,Web App 能看到 CLI 创建的一切(反之亦然)。只有 `config` 仍直接编辑 Project 配置文件,`server` / `web` 则负责启动服务本身。
+
+## 服务器连接
+
+连接本机服务器的 CLI 无需登录。连接按以下顺序解析,先命中先用:
+
+1. `--server <url>`——显式指定目标。
+2. `PENGUIN_API_URL`——同上,来自环境变量。服务端驱动的会话会把它(连同 `PENGUIN_API_TOKEN`、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID`、`PENGUIN_SESSION_ID`)注入每个工具子进程,因此 Agent 自己执行的 `penguin` 命令天然连回运行它的那台服务器。
+3. 数据根目录(`PENGUIN_HOME`,否则 `~/.penguin/data`)下存活的 `server.lock`:附着到本机正在运行的服务器。
+4. 自动拉起:以随机端口分离启动一个本机服务器(输出写入 `<root>/logs/server-auto-<date>.log`),等待就绪后附着。两个 CLI 竞争拉起时,输家的子进程自行退出,双方都附着到赢家。
+
+鉴权使用本机 API token:服务端每次启动都把新 token 写入 `<root>/api-token`(仅属主可读,逐次启动轮换),CLI 以 `Authorization: Bearer` 发送。`PENGUIN_API_TOKEN` 优先于文件;文件只在目标为回环地址时读取——连接远端 `--server` 必须显式设置 `PENGUIN_API_TOKEN`。持有该文件即等于管理员权限,这是有意设计:对数据根目录的本机文件系统访问本就等于管理员权限(与 `penguin server reset-admin-password` 同一条规则)。
+
## 全局约定
- 模型引用:模型身份始终是 `(provider, model_id)` 二元组。`--model-id` 填上游模型 id,`--provider` 填其所属分组;provider 绝不推断、绝不猜测、也没有缺省值。`run` / `chat` 上这对参数整体可选——两个都给即指定模型,两个都不给则使用 Project 默认模型——但只给其中一个是错误。
-- 数据根目录:`--root <dir>` 覆盖数据根目录,优先级为 `--root` > 环境变量 `PENGUIN_HOME` > `~/.penguin/data`。
+- Project 与 Agent 缺省值:`--project-id` 依次回落到 `PENGUIN_PROJECT_ID`、`default_project`;`--agent-id` 依次回落到 `PENGUIN_AGENT_ID`、`default_agent`。在服务端驱动的会话内,这些环境变量即会话自身的坐标。
+- Session 引用:凡接受 session id 的地方(`input`、`logs`、`run --session`、`chat --resume`),完整 id 或任何唯一片段皆可——`penguin ls` 打印的末尾 8 位十六进制就是为此准备的简写。片段有歧义时报错并列出候选。
+- 最近会话缺省:凡 session id 可省的地方——`input [session_id]`、`logs [session_id]`、`chat --resume`——省略即指**当前 Agent 最近一次会话**(`--agent-id` 决定是哪个 Agent,回落规则同上)。`input` 与 `logs` 会在 stderr 打印一行暗色 `[latest]` 说明选中了哪个会话,目标因此从不含糊,stdout 上的 `--json` 也仍可解析。该 Agent 一个会话都没有时,打印一行指向 `penguin run` / `penguin chat` 的提示并以非零码退出。
+- `--json` 输出原始 JSON 而非渲染 / 表格形式;`--server <url>` 指定目标服务器(见上)。
+- 调用方上下文缺省值:在 harness Agent 内部(环境里存在 `PENGUIN_SESSION_ID`)时,`run` / `chat` 新建会话的每个**未指定**字段都缺省取调用方会话的实时值——Workspace、模型对、审批模式与思考等级——与 `run_subagent` 派生子会话的继承是同一条约定,两个入口因此读作一套规则。逐字段优先级为显式选项 > 调用方值 > 普通缺省;查询失败打印一行暗色警告并回落普通缺省;不在 Agent 内时一切不变。(`--project-id` / `--agent-id` 保持上文的环境变量缺省。)
+- `--timeout <duration>`(`run`、`input` 与 `logs -f` 上)以软让出语义限定等待——即 `exec_command` yield 窗口的模型应用在 CLI 的等待上:到时命令干净脱开并以 0 退出,任务继续在服务端运行,之后可用 `penguin input` / `penguin logs` 接续。接受形式:`30s`、`5m`、`2h`,或表示秒数的纯整数;其余形式一律拒绝。`--timeout 0` 是窗口的退化形式——送达后立即返回(`--json` 下为 `{sessionId, status: "running"}`):一个旋钮同时覆盖「不等待」。不带该选项 = 无限等待。(`run --background` 仍是**新建任务**的惯用「发完即走」:它为脚本打印裸 session id,在创建时刻即脱开。)
+- 参数错误按界面语言呈现:缺少参数、缺少必填选项、未知选项或命令拼错时,打印一行本地化说明,附上该命令自身的用法与 `--help` 指引,并以非零码退出。
+- 数据根目录(仅 `config`):`--root <dir>` 覆盖数据根目录,优先级为 `--root` > 环境变量 `PENGUIN_HOME` > `~/.penguin/data`。
## penguin run
-发送单条消息执行一个 Task,结束后退出;Task 被中止时以非零码退出,便于脚本 / CI 判断。
+在服务端创建(或复用)一个 Session,发送单条消息,流式渲染直至 Task 结束,打印统计行后退出。完成时退出码为 0;goal 模式仅目标 `complete` 时退出 0。
```bash
penguin run -m "总结当前目录的代码结构"
+penguin run -m "继续" --session 402a2e24 # 用片段复用既有会话
+penguin run -m "长任务" --background # 立即返回 session id
```
| 选项 | 说明 |
| --- | --- |
| `-m, --message <message>` | 必填,要发送的消息 |
+| `--project-id <id>` | 指定 Project(缺省依次取 `PENGUIN_PROJECT_ID`、`default_project`) |
+| `--agent-id <id>` | 指定 Agent(缺省依次取 `PENGUIN_AGENT_ID`、`default_agent`) |
+| `--workspace <path>` | Workspace 目录;相对路径按 CLI 的当前目录解析,缺省即当前目录。目录必须存在于服务器所在机器——本机默认流程里就是这台机器 |
| `--model-id <id>` | 指定模型的上游 id,须与 `--provider` 同时给出;两者都不给时使用 Project 默认模型 |
| `--provider <group>` | 模型所属 Provider 分组,给出 `--model-id` 时必填 |
-| `--project-id <id>` | 指定 Project |
-| `--agent-id <id>` | 指定 Agent |
-| `--workspace <path>` | Workspace 目录,默认当前目录,必须已存在 |
-| `--approve <mode>` | 审批模式,见下文 |
-| `--thinking <level>` | 本 Session 的思考等级:`low` / `medium` / `high` / `xhigh` / `max`。省略时按配置链取值(Agent 的 `model.thinking_level`,其次 Project 的 `default_chat.thinking_level`,最后 `medium`)。在 Session 创建时钉定,派生的子会话随之生效 |
+| `--approve <mode>` | 审批模式,见下文(缺省 `allow-all`)。与 `--session` 同用时 PATCH 该会话的粘性模式 |
+| `--thinking <level>` | 本次 Task 的思考等级:`low` / `medium` / `high` / `xhigh` / `max`,随任务请求下发。省略时按会话钉定值(否则 Agent 配置)生效 |
+| `--session <sessionId>` | 复用既有 Session(完整 id 或唯一片段),不再新建;不能与 `--workspace` 及模型对同用 |
+| `--background` | 提交任务后立即退出并打印 session id(`--json` 下为 `{"sessionId"}`);任务在服务端继续运行,可用 `penguin logs -f` 跟随 |
+| `--timeout <duration>` | 软让出等待预算(见「全局约定」):到时打印已渲染内容与一行暗色「仍在运行」提示(含 session id;`--json` 下为 `{sessionId, status: "running", text}`)并以 0 退出——任务不被中止。`--timeout 0` 在 POST 后立即返回(`--json` 下为 `{sessionId, status: "running"}`,无 `text`)。不能与 `--background` 同用 |
+| `--goal [budget]` | 目标模式:消息即目标,服务端循环直至终态;可选值为 token 预算(如 `500k`) |
+| `--json` | 输出最终的 `{sessionId, status, text}` 对象而非渲染流(`text` 为主会话各条助手文本消息拼接) |
+| `--server <url>` | 目标服务器(见「服务器连接」) |
## penguin chat
@@ -35,8 +63,9 @@ penguin run -m "总结当前目录的代码结构"
| 选项 | 说明 |
| --- | --- |
-| `--resume [sessionId]` | 恢复指定 Session;省略 id 时恢复该 Agent 最近的 Session |
+| `--resume [sessionId]` | 恢复指定 Session(完整 id 或唯一片段);省略 id 时恢复该 Agent 最近的 Session |
| `--verbose` | 显示完整工具输出;缺省折叠过长的工具输出(见下文) |
+| `--server <url>` | 目标服务器(见「服务器连接」) |
使用 `--resume` 时,Workspace 与模型由原 Session 锁定,不可再用 `--workspace` / `--model-id` / `--provider` 覆盖。思考等级是逐轮参数,`--resume` 下仍接受 `--thinking`:它作为初始的 `/thinking` 覆盖生效,而不是创建时的缺省值。退出时会打印可直接复制的 `penguin chat --resume <sessionId>` 命令。
@@ -63,6 +92,129 @@ Ctrl-C 的行为依状态而定:
| 输入缓冲非空 | 清空当前输入 |
| 空闲且缓冲为空 | 显示退出确认(y/N) |
+## penguin ls
+
+列出 Project 的会话——覆盖全部 Agent,或用 `--agent-id` 限定一个。列依次为:短 id(其余命令可作片段使用的末尾 8 位十六进制)、Agent、标题、运行中 / 空闲、最近活动、Workspace 尾段。已归档会话仅在 `-a` 下出现。
+
+```bash
+penguin ls
+penguin ls --agent-id default_agent -a
+penguin ls --json
+```
+
+| 选项 | 说明 |
+| --- | --- |
+| `--project-id <id>` / `--agent-id <id>` | 作用域(缺省值见「全局约定」;未给 `--agent-id` 时列出 Project 的全部 Agent) |
+| `-a, --all` | 包含已归档会话 |
+| `--days <n>` | 只列最近 n 个自然日内活跃过的会话——今天算第 1 天,`--days 2` 即昨天加今天(与 `cost --days` 同一自然日口径)。可与 `-a`、`--json` 组合 |
+| `--json` / `--server <url>` | 同各处约定 |
+
+## penguin input
+
+向会话发送消息——或在不带 `-m` 时轮询其最近回复。session id 可以省略:省略即取当前 Agent 最近一次会话(见「全局约定」),于是裸 `penguin input` 正好回答「我的 Agent 最后说了什么」。带 `-m` 时:运行中的会话按插话(steering)送达(随下一轮交给模型),空闲会话则发起新 Task;缺省等待并渲染直至本轮结束,`--timeout` 限定等待(软让出,见「全局约定」;`--timeout 0` 在送达后立即返回)。
+
+不带 `-m` 时是**轮询**,与 `input_subagent` 的空 prompt 语义互为镜像:打印该会话最近一条完整助手文本(取自历史尾部的幂等「最新答案」快照;跳过思考与工具输出),不排队也不插话。运行中的会话先静默等待——给出 `--timeout` 时以其为上限,`--timeout 0` 立即取快照——到时仍在运行则打印当前最新文本并附「仍在运行」提示(退出码 0)。
+
+```bash
+penguin input 402a2e24 -m "顺便检查一下测试"
+penguin input 402a2e24 -m "排个队" --timeout 0 # 送达后立即返回
+penguin input 402a2e24 # 轮询:打印最近一条助手回复
+penguin input # 轮询当前 Agent 最近一次会话
+penguin input 402a2e24 --timeout 5m # 轮询,最多等运行中的一轮 5 分钟
+```
+
+| 选项 | 说明 |
+| --- | --- |
+| `-m, --message <text>` | 消息文本;省略即改为轮询最近助手回复 |
+| `--timeout <duration>` | 软让出等待预算:带 `-m` 时到期脱开、行为同 `run`(`--json` 下为 `{sessionId, status: "running", text}`),`--timeout 0` 送达后立即返回(`{sessionId, status: "running"}`);不带 `-m` 时到期取快照——`0` 即立即——并附仍在运行提示 |
+| `--project-id <id>` | 片段检索的作用域(完整 session id 不需要) |
+| `--agent-id <id>` | 省略 session id 时,取哪个 Agent 的最近一次会话 |
+| `--json` / `--server <url>` | 同各处约定;带 `-m` 的 `--json` 输出 `{sessionId, status, text}`(status 为 `completed` / `aborted` / `running`;`--timeout 0` 的形状不含 `text`),轮询形式输出 `{sessionId, status, text}`(status 为 `idle` / `running`,尚无回复时 text 为 `""`) |
+
+## penguin logs
+
+用与 REPL 相同的渲染器渲染会话历史。session id 可以省略:省略即取当前 Agent 最近一次会话(见「全局约定」),裸 `penguin logs` 因此就是「刚才发生了什么」。
+
+```bash
+penguin logs # 当前 Agent 最近一次会话
+penguin logs 402a2e24 --tail 20
+penguin logs 402a2e24 -f
+```
+
+| 选项 | 说明 |
+| --- | --- |
+| `--tail <n>` | 只显示最后 n 条 |
+| `-f, --follow` | 渲染历史后继续跟随实时输出流(只读;Ctrl-C 仅断开,不影响会话) |
+| `--timeout <duration>` | 跟随该时长后停止(软让出,退出码 0);仅与 `-f` 搭配有意义 |
+| `--project-id <id>` | 片段检索的作用域 |
+| `--agent-id <id>` | 省略 session id 时,取哪个 Agent 的最近一次会话 |
+| `--json` / `--server <url>` | 同各处约定;`--json` 输出原始消息数组(`-f` 下按行追加到达的 JSON 消息) |
+
+## penguin agent
+
+```bash
+penguin agent ls
+penguin agent create --agent-id helper --name "Helper" --skills web-search,pdf
+```
+
+`agent ls` 列出 Project 的 Agent(id、名称、会话数、描述)。`agent create` 创建一个:
+
+| 选项 | 说明 |
+| --- | --- |
+| `--agent-id <id>` | 必填,Agent id(即目录名) |
+| `--name <s>` / `--description <s>` | 显示名与描述 |
+| `--skills <a,b>` | 逗号分隔的技能库 Skill 名,预装进新 Agent;未知名称在创建任何东西之前即被拒绝 |
+| `--project-id <id>` / `--json` / `--server <url>` | 同各处约定 |
+
+## penguin project
+
+`penguin project ls` 列出当前账号可用的 Project(自有与被授权),含 id、显示名与角色。`--json` / `--server` 同各处约定。
+
+## penguin cost
+
+来自服务端用量聚合的 Token 用量与成本。缺省打印汇总卡片——今日 / 近 7 天 / 累计(与任何范围参数无关,恒计算);`--by` 改为打印分组表格。
+
+```bash
+penguin cost
+penguin cost --days 7 --by model
+penguin cost --from 2026-08-01 --to 2026-08-25 --by agent
+```
+
+| 选项 | 说明 |
+| --- | --- |
+| `--days <n>` | 最近 n 天(自动换算为 from/to) |
+| `--from <d>` / `--to <d>` | 显式范围(`yyyy-mm-dd`,恒成对) |
+| `--by <dim>` | 按 `date`、`agent`、`model` 或 `session` 分组 |
+| `--project-id <id>` / `--agent-id <id>` | 作用域;`--agent-id` 为过滤条件(此处没有缺省 Agent——成本是 Project 视图,除非显式收窄) |
+| `--json` / `--server <url>` | 同各处约定 |
+
+成本后缀 `+` 表示部分和(该桶里有模型未配置价格);`-` 表示完全没有计价用量。
+
+## penguin schedule
+
+`penguin schedule ls` 列出 Project 的定时任务——覆盖全部 Agent,或用 `--agent-id` 限定。列依次为:Agent、名称、启用与否、开始时刻、周期(一次性任务为「一次性」)、目标(绑定会话的短 id 或「新建会话」)、最近触发,以及非 active 状态的标记(`expired` / `done` / `missed` / `invalid`;无法解析的任务文件也会列出并标记 invalid)。`--json` / `--server` 同各处约定。
+
+`add` / `update` / `rm` 经 API 管理定时任务,由 API 写入任务的 TOML 文件——**文件仍是唯一真相源**,CLI 是带校验的写入器(与模型配置、vault 同一模式:一律经系统接口更新、校验收敛在接口层,手编依然可行)。API 错误原样透出,Agent 因此获得同步校验,而非手编 TOML 时要等对账周期的滞后。
+
+```bash
+penguin schedule add daily-report --prompt "总结今天的进展" --start-at 2026-09-01T09:00:00Z --period 1d
+penguin schedule add once-now --prompt "检查部署" --start-at now --session-id 402a2e24
+penguin schedule update daily-report --period 12h --disable
+penguin schedule rm daily-report
+```
+
+| 选项 | 说明 |
+| --- | --- |
+| `--prompt <s>` | 每次触发要发送的内容(`add` 必填) |
+| `--start-at <ISO\|now>` | 首次触发时刻,ISO 8601,或字面量 `now` 表示当前时刻(`add` 必填) |
+| `--period <dur>` | 固定间隔,下限 `5m`(如 `30m`、`12h`、`1d`、`7d`);省略即一次性任务 |
+| `--end-at <ISO>` | 此时刻之后不再触发 |
+| `--session-id <id>` | 绑定到某个会话触发——与下面的新建会话形式互斥(XOR) |
+| `--workspace <path>` / `--model-id <id> --provider <p>` | 新建会话模式:每次触发在该 Workspace / 模型上开新会话(Workspace 省略即临时工作区;模型对「都给或都不给」,省略即 Project 默认) |
+| `--disabled`(`add`) | 与原始文件的一处有意分歧:`add` 缺省即**启用**——添加任务就是要它运行——原始文件的 `enabled = false` 缺省仍留给手编。`--disabled` 关闭 |
+| `--enable` / `--disable`(`update`) | 翻转启用位;`update` 对存储项读改写:未指定的字段保留原值,切换目标类型时清掉另一类字段 |
+| `--project-id` / `--agent-id` / `--json` / `--server` | 同各处约定;`rm` 直接删除、不做确认(服务端的 owner 授权照旧生效) |
+
## 审批模式(--approve)
| 模式 | 行为 |
diff --git a/packages/docs/content/quickstart-cli.en.md b/packages/docs/content/quickstart-cli.en.md
index fef6ac96..eedcd5e7 100644
--- a/packages/docs/content/quickstart-cli.en.md
+++ b/packages/docs/content/quickstart-cli.en.md
@@ -58,6 +58,8 @@ penguin run -m "Create hello.txt containing Hello, Penguin"
The Workspace defaults to the current directory; pass `--workspace /path` to change it. The target directory must already exist.
+`run`, `chat` and the other session commands are thin clients of the server: they attach to the local server when one is running and quietly start one when none is (no login needed on the local machine — see the [CLI Reference](/cli) for the connection rules). Everything they create shows up in the Web App too, and `penguin ls` / `penguin logs` / `penguin input` address those sessions from the terminal.
+
## Interactive chat
```bash
diff --git a/packages/docs/content/quickstart-cli.zh.md b/packages/docs/content/quickstart-cli.zh.md
index 7058b166..1aa6c86d 100644
--- a/packages/docs/content/quickstart-cli.zh.md
+++ b/packages/docs/content/quickstart-cli.zh.md
@@ -58,6 +58,8 @@ penguin run -m "创建 hello.txt,内容为 Hello, Penguin"
Workspace 默认为当前目录,可用 `--workspace /path` 指定;目标目录必须已存在。
+`run`、`chat` 与其余会话命令都是服务端的瘦客户端:本机有服务器运行时直接附着,没有时静默拉起一个(连接本机无需登录——连接规则见 [CLI 参考](/cli))。它们创建的一切同样出现在 Web App 里,也可以在终端用 `penguin ls` / `penguin logs` / `penguin input` 继续操作这些会话。
+
## 交互式对话
```bash
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index e400cd6a..18897641 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -45,6 +45,21 @@ curl -c cookies.txt -H "Content-Type: application/json" \
http://127.0.0.1:7364/api/auth/login
```
+### Local API token (Bearer)
+
+Every protected route also accepts `Authorization: Bearer <token>` carrying the **local API token** — the machine-local credential the CLI (and agents driving the harness through it) use instead of a login:
+
+- The server mints a fresh token at every boot and writes it to `<root>/api-token` (owner-only permissions, `0600`); the previous boot's token stops working the moment a new one is minted.
+- A valid Bearer authenticates as the built-in `admin`. That equivalence is the authorization model, not an accident: local filesystem access to the data root already **is** admin authority — whoever can read `api-token` can read `web.db` next to it, and it is the same rule `penguin server reset-admin-password` stands on.
+- Server-driven sessions inject the current token into every tool subprocess as `PENGUIN_API_TOKEN` (together with `PENGUIN_API_URL`, `PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID`, `PENGUIN_SESSION_ID`), which is how an agent's own `penguin` / API calls are sanctioned to reach the server that runs them.
+- SSE endpoints accept the header like any other route (consume them with `fetch`, not `EventSource` — the latter cannot send headers).
+- The JSON-only Content-Type check on writes still applies to Bearer requests.
+
+```bash
+curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
+ http://127.0.0.1:7364/api/me
+```
+
## Route Reference
### Auth and Account
@@ -177,8 +192,8 @@ Schedule writes are owner-only. A task in new-Session mode carries `modelId` and
| Method | Path | Description |
| --- | --- | --- |
-| GET | /agents/:agentId/sessions | List Sessions (including run state) |
-| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?}` → 201 |
+| GET | /agents/:agentId/sessions | List Sessions (including run state); every row is listed whichever client created it |
+| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?, client?}` → 201. `client` is the creating-client hint stored on the row (`"cli"` from the CLI; default `"web"`) — informational provenance, never a list filter |
| GET | /dirs?path= | Server-side directory browser (backs the Workspace picker) |
On Session creation, `modelId` and `provider` are both-or-neither: send the complete pair to pick a model, or omit both to take the Project's default model — one without the other is a 400. The Workspace defaults to an auto-created temporary workspace, and the approval mode defaults to `allow-all`.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 5b7d892d..3d4223e7 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -45,6 +45,21 @@ curl -c cookies.txt -H "Content-Type: application/json" \
http://127.0.0.1:7364/api/auth/login
```
+### 本机 API token(Bearer)
+
+所有受保护路由同时接受携带**本机 API token** 的 `Authorization: Bearer <token>`——这是 CLI(以及经 CLI 驱动 harness 的 Agent)用来替代登录的本机凭据:
+
+- 服务端每次启动铸造新 token 并写入 `<root>/api-token`(仅属主可读,`0600`);新 token 铸造的那一刻,上一次启动的 token 即失效。
+- 有效的 Bearer 即以内置 `admin` 身份通过认证。这个等价关系是授权模型本身,不是疏漏:对数据根目录的本机文件系统访问本就等于管理员权限——能读 `api-token` 的人也能读旁边的 `web.db`,与 `penguin server reset-admin-password` 是同一条规则。
+- 服务端驱动的会话把当前 token 以 `PENGUIN_API_TOKEN` 注入每个工具子进程(连同 `PENGUIN_API_URL`、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID`、`PENGUIN_SESSION_ID`),Agent 自己的 `penguin` / API 调用由此获得连回运行它的服务器的授权。
+- SSE 端点与其它路由一样接受该请求头(用 `fetch` 消费,不要用 `EventSource`——后者无法携带请求头)。
+- 写请求的 JSON-only Content-Type 检查对 Bearer 请求同样生效。
+
+```bash
+curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
+ http://127.0.0.1:7364/api/me
+```
+
## 路由参考
### 认证与账户
@@ -177,8 +192,8 @@ Schedule 写操作仅限 Owner。新建 Session 模式的任务,`modelId` 与
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /agents/:agentId/sessions | Session 列表(含运行状态) |
-| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?}` → 201 |
+| GET | /agents/:agentId/sessions | Session 列表(含运行状态);无论由哪个客户端创建,所有行都会列出 |
+| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?}` → 201。`client` 是存入索引行的创建客户端标记(CLI 传 `"cli"`,缺省 `"web"`)——仅作来源信息,绝不参与列表过滤 |
| GET | /dirs?path= | 服务器端目录浏览(Workspace 选择器数据源) |
创建 Session 时,`modelId` 与 `provider` 要么成对给出、要么都不给:给出完整二元组即指定模型,两个都省略则取 Project 默认模型,只给一个返回 400。Workspace 默认自动创建临时工作区,审批模式默认 `allow-all`。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 40e38ccb..1fafafa1 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -90,9 +90,10 @@ export interface MeResponse {
* How THIS session was established. Distinct from desktopMode: a browser signed into a
* desktop-mode server holds a "password" session and must still provide the old
* password when changing it — only "desktop" sessions (opened by the shell's one-shot
- * token) may omit it.
+ * token) may omit it. "token" marks a request authenticated by the local API token's
+ * Bearer header (the CLI and agent-driven calls).
*/
- sessionVia: "password" | "desktop";
+ sessionVia: "password" | "desktop" | "token";
/**
* The upload limits currently in force, so the composer can refuse an oversize pick before
* reading it and can name the real number in the message. They are admin-settable and ride
@@ -252,12 +253,6 @@ export interface UiPrefs {
lastProjectId?: string;
/** Whether the "no API key configured" guide has already been shown: once ever (on first visit to the chat page). */
credentialGuideSeen?: boolean;
- /**
- * Also list CLI-created Sessions in the sidebar (`cli=1` on the sessions list). Default
- * off: the list then serves web rows straight from the DB, with no Trace-directory
- * scanning (#139).
- */
- showCliSessions?: boolean;
/** The initial-password notice banner (app layout) was permanently dismissed by the user. */
initialPasswordBannerDismissed?: boolean;
/**
@@ -1251,6 +1246,12 @@ export interface SessionCreateRequest {
workspace?: string;
/** Defaults to allow-all. */
approvalMode?: ApprovalMode;
+ /**
+ * Creating-client hint stored on the Session row: "cli" when the CLI creates the
+ * Session through the API; defaults to "web". Informational provenance only — lists
+ * serve every row regardless of client.
+ */
+ client?: "web" | "cli";
}
export interface SessionCreateResponse {
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 80bdc48f..e87052e4 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -51,6 +51,7 @@ import { UiPrefsRepo } from "./db/repos/ui-prefs.js";
import { UsersRepo } from "./db/repos/users.js";
import type { UserRow } from "./db/repos/users.js";
import { authMiddleware, jsonOnlyWrites } from "./auth/middleware.js";
+import { mintApiToken, storeApiToken } from "./auth/api-token.js";
import type { Identity } from "./terminal/identity.js";
import { terminalRoutes } from "./terminal/routes.js";
import type { TerminalManager } from "./terminal/manager.js";
@@ -98,7 +99,7 @@ import {
} from "./services/preview-token.js";
import type { PreviewTokenSigner } from "./services/preview-token.js";
-import type { ProxyEnvPolicy } from "@prismshadow/penguin-core";
+import type { ControlEnvContext, ProxyEnvPolicy } from "@prismshadow/penguin-core";
import { declined } from "./hmr/hono-seam.js";
import { AgentsRepo } from "./db/repos/agents.js";
import { MembersRepo } from "./db/repos/members.js";
@@ -253,6 +254,15 @@ export async function bootAppDeps(
...(overrides.now ? { now: overrides.now } : {}),
});
+ // Local API token: minted per boot, persisted at <root>/api-token (0600) and installed
+ // on the runtime auth service, so authMiddleware accepts it as the admin for this
+ // process's whole life — across hot swaps too (the auth service is a runtime
+ // singleton). Local filesystem access to the data root is admin authority (the
+ // reset-admin-password rule); see auth/api-token.ts.
+ const apiToken = mintApiToken();
+ storeApiToken(config.root, apiToken);
+ authService.setLocalApiToken(apiToken);
+
// The capability set buildAppDeps claims (see hmr/capabilities.ts) — every
// entry must be in place before ensure() below performs the first boot. The interface
// descriptor leads: it is what a bundle's handshake reads before trusting any of the rest.
@@ -549,6 +559,31 @@ export function buildAppDeps(
const url = serverSettingsRepo.getProxyUrl();
return url === null ? null : { mode: "inject", url, noProxy: mergedNoProxy() };
};
+ // Harness-control env for command subprocesses of server-driven Sessions: the server's
+ // own canonical URL, its boot API token, and the Session's coordinates — what lets
+ // commands the Agent runs drive this harness back through the CLI/API. Threaded like
+ // proxyEnv through BOTH core entry paths (loader + SessionService), and evaluated per
+ // spawn: config.port is written back by index.ts once the real port is bound (PORT=0),
+ // so the URL must not be captured at assembly time. On a loopback bind the URL uses the
+ // canonical App host (`localhost`) — the counterpart name serves only /preview/*; a
+ // wildcard bind falls back to 127.0.0.1.
+ const canonicalApiUrl = (): string => {
+ const host =
+ config.host === "0.0.0.0" || config.host === "::"
+ ? "127.0.0.1"
+ : (loopbackHostRoles(config.host)?.app ?? config.host);
+ return `http://${host}:${config.port}`;
+ };
+ const controlEnv = (ctx: ControlEnvContext): Record<string, string> => {
+ const token = authService.localApiToken();
+ return {
+ PENGUIN_API_URL: canonicalApiUrl(),
+ ...(token !== null ? { PENGUIN_API_TOKEN: token } : {}),
+ PENGUIN_PROJECT_ID: ctx.projectId,
+ PENGUIN_AGENT_ID: ctx.agentId,
+ PENGUIN_SESSION_ID: ctx.sessionId,
+ };
+ };
const schedulesRepo = new SchedulesRepo(db);
const goalsRepo = new GoalsRepo(db);
@@ -625,7 +660,9 @@ export function buildAppDeps(
const manager = new SessionManager({
sessions: sessionsRepo,
channels,
- loader: overrides.loader ?? createCoreSessionLoader(config.root, sessionSources, { proxyEnv }),
+ loader:
+ overrides.loader ??
+ createCoreSessionLoader(config.root, sessionSources, { proxyEnv, controlEnv }),
sources: sessionSources,
recorder,
errors,
@@ -680,6 +717,7 @@ export function buildAppDeps(
sources: sessionSources,
traceIndex,
proxyEnv,
+ controlEnv,
});
// Schedule scheduler: assembled here, started by platform.ts's create() (tests drive it
// via tickOnce, no real timer), stopped by the same create()'s dispose effect.
diff --git a/packages/server/src/auth/api-token.ts b/packages/server/src/auth/api-token.ts
new file mode 100644
index 00000000..c8825940
--- /dev/null
+++ b/packages/server/src/auth/api-token.ts
@@ -0,0 +1,64 @@
+/**
+ * Local API token (`<root>/api-token`): the machine-local credential behind
+ * `Authorization: Bearer`.
+ *
+ * Minted fresh at every server boot (same recipe as auth-session tokens) and written to
+ * the data root with owner-only permissions, so anything that can read the file can call
+ * the API as the admin. That equivalence is the authorization model, not an accident:
+ * local filesystem access to the data root already IS admin authority — the same rule
+ * `penguin server reset-admin-password` stands on (whoever can run it owns web.db
+ * anyway) — and agents driving their own harness through the CLI is the product feature
+ * this token exists for (server-driven Sessions hand it to tool subprocesses as
+ * PENGUIN_API_TOKEN). Rotation per boot bounds the life of any leaked copy to the
+ * process that minted it.
+ */
+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+export function apiTokenPath(root: string): string {
+ return path.join(root, "api-token");
+}
+
+/** Mints a boot-scoped local API token (the auth-session token recipe). */
+export function mintApiToken(): string {
+ return randomBytes(32).toString("base64url");
+}
+
+/**
+ * Persists the boot token (owner-only file, tmp + rename so a concurrent reader never
+ * sees a partial write). Best-effort like the initial-password file: an exotic read-only
+ * root must not stop the server — local CLI callers then fall back to
+ * PENGUIN_API_TOKEN.
+ */
+export function storeApiToken(root: string, token: string): void {
+ try {
+ fs.mkdirSync(root, { recursive: true });
+ const target = apiTokenPath(root);
+ const tmp = `${target}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, `${token}\n`, { mode: 0o600 });
+ fs.renameSync(tmp, target);
+ } catch {
+ // Best-effort: Bearer auth still works for callers holding the token some other way.
+ }
+}
+
+/** The stored token, or null when absent/unreadable/empty (shared with the CLI's file fallback). */
+export function readApiToken(root: string): string | null {
+ try {
+ const value = fs.readFileSync(apiTokenPath(root), "utf8").trim();
+ return value === "" ? null : value;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Constant-time equality for token checks: both sides are reduced to fixed-size sha256
+ * digests first, so the comparison's timing depends on neither the content nor the
+ * length of an attacker-supplied value.
+ */
+export function tokensEqual(a: string, b: string): boolean {
+ const digest = (v: string): Buffer => createHash("sha256").update(v).digest();
+ return timingSafeEqual(digest(a), digest(b));
+}
diff --git a/packages/server/src/auth/middleware.ts b/packages/server/src/auth/middleware.ts
index d103d564..af6f4463 100644
--- a/packages/server/src/auth/middleware.ts
+++ b/packages/server/src/auth/middleware.ts
@@ -1,11 +1,19 @@
/**
- * Auth middleware: cookie -> auth_session ->
- * user injected into c.var.
+ * Auth middleware: `Authorization: Bearer <local API token>` -> the built-in admin, or
+ * cookie -> auth_session -> user; either way the user is injected into c.var.
+ *
+ * The Bearer path authenticates the boot's local API token (`<root>/api-token`, see
+ * auth/api-token.ts) as the admin — the CLI's and agents' machine-local credential; it
+ * applies to every route behind this middleware, SSE endpoints included (the CLI
+ * consumes SSE via fetch with headers). A Bearer header that does not match fails the
+ * request rather than falling back to the cookie: silently downgrading a wrong explicit
+ * credential would mask misconfiguration.
*
* Accessing a protected API while logged out -> 401 `{error:{code:"unauthorized"}}`.
* CSRF (MVP): SameSite=Lax cookie + write requests only accept
* `Content-Type: application/json` (an HTML form can't forge that Content-Type),
- * see the README security notes.
+ * see the README security notes. The Content-Type guard stays for Bearer requests too —
+ * the CLI always sends application/json.
*/
import type { MiddlewareHandler } from "hono";
import { getCookie } from "hono/cookie";
@@ -32,6 +40,19 @@ export function currentUser(c: { var: { user: UserRow } }): UserRow {
export function authMiddleware(auth: AuthService): MiddlewareHandler<AppEnv> {
return async (c, next) => {
+ // Bearer first: an explicit credential on the request outranks ambient cookies, and
+ // a wrong one is an error, never a silent fallback (see the module doc).
+ const bearer = bearerToken(c.req.header("authorization"));
+ if (bearer !== null) {
+ const viaToken = auth.authenticateApiToken(bearer);
+ if (!viaToken) {
+ throw new HttpError(401, "unauthorized", "Invalid API token.");
+ }
+ c.set("user", viaToken.user);
+ c.set("sessionVia", viaToken.via);
+ await next();
+ return;
+ }
const token = getCookie(c, SESSION_COOKIE);
const authed = token ? auth.authenticateWithMeta(token) : null;
if (!authed) {
@@ -43,6 +64,13 @@ export function authMiddleware(auth: AuthService): MiddlewareHandler<AppEnv> {
};
}
+/** The token of an `Authorization: Bearer <token>` header (scheme matched case-insensitively); null for any other shape. */
+export function bearerToken(header: string | undefined): string | null {
+ if (header === undefined) return null;
+ const m = /^Bearer\s+(.+)$/i.exec(header.trim());
+ return m === null ? null : m[1]!.trim();
+}
+
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
/**
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index 435612c1..9096af9e 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -13,6 +13,7 @@
* valid for 7 days, with sliding renewal once less than 6 days remain.
*/
import { createHash, randomBytes, randomInt } from "node:crypto";
+import { tokensEqual } from "./api-token.js";
import type { UserInfo } from "../api/types.js";
import { HttpError } from "../http/errors.js";
import type { AuthSessionsRepo } from "../db/repos/auth-sessions.js";
@@ -59,11 +60,12 @@ function sha256Hex(value: string): string {
/**
* How a session was established: "password" via the login form, "desktop" via the
- * desktop shell's one-shot token. Persisted per session so desktop-specific allowances
- * (password change without the old password) apply only to sessions the shell itself
- * opened. Legacy rows (NULL) read as "password".
+ * desktop shell's one-shot token, "token" via the local API token's Bearer header (no
+ * stored session — the value is per request). Persisted per session (Bearer excepted) so
+ * desktop-specific allowances (password change without the old password) apply only to
+ * sessions the shell itself opened. Legacy rows (NULL) read as "password".
*/
-export type SessionVia = "password" | "desktop";
+export type SessionVia = "password" | "desktop" | "token";
export function toUserInfo(row: UserRow): UserInfo {
return {
@@ -249,6 +251,37 @@ export class AuthService {
this.deps.authSessions.delete(sha256Hex(token));
}
+ /**
+ * The boot-scoped local API token (`<root>/api-token`, see auth/api-token.ts): held in
+ * memory by the process that minted it. Null until the startup assembly installs it
+ * (standalone/test constructions without one simply never authenticate a Bearer
+ * header).
+ */
+ private apiToken: string | null = null;
+
+ /** Installs the boot's local API token (called once by the startup assembly). */
+ setLocalApiToken(token: string): void {
+ this.apiToken = token;
+ }
+
+ /** The current boot's local API token (what control-env injection hands to tool subprocesses); null when none was installed. */
+ localApiToken(): string | null {
+ return this.apiToken;
+ }
+
+ /**
+ * Validates a Bearer token against the boot's local API token (constant-time compare):
+ * a match authenticates as the built-in admin — holding the token proves filesystem
+ * access to the data root, which is admin authority (see auth/api-token.ts). Returns
+ * null on mismatch, when no token is installed, or when the admin row is missing.
+ */
+ authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null {
+ if (this.apiToken === null || token.length === 0) return null;
+ if (!tokensEqual(token, this.apiToken)) return null;
+ const user = this.deps.users.findById(ADMIN_USER_ID);
+ return user === null ? null : { user, via: "token" };
+ }
+
/** Validates the cookie token: returns null if expired/unknown; sliding renewal once less than 6 days remain. */
authenticateWithMeta(token: string): { user: UserRow; via: SessionVia } | null {
const tokenHash = sha256Hex(token);
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index 8eac5b85..ff768342 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -27,11 +27,13 @@ export interface SessionRow {
/** Archive timestamp, ISO; NULL = not archived (omitting on insert defaults to NULL). */
archivedAt?: string | null;
/**
- * Creating client: "web" (created via the Web App/server) or "cli" (adopted from a Trace
- * the CLI left behind); NULL = legacy row from before the column existed, treated as web.
- * The schedule/subagent SOURCE is deliberately NOT a row field — core session_meta in the
- * Trace stays the single source of truth for it (runtime/session-sources.ts); `client` is
- * a separate, DB-only axis that meta never records.
+ * Creating client: "web" (created via the Web App), "cli" (created through the API by
+ * the CLI, or adopted from a Trace a legacy CLI-direct run left behind); NULL = legacy
+ * row from before the column existed, treated as web. Informational provenance only —
+ * no list filters on it. The schedule/subagent SOURCE is deliberately NOT a row field —
+ * core session_meta in the Trace stays the single source of truth for it
+ * (runtime/session-sources.ts); `client` is a separate, DB-only axis that meta never
+ * records.
*/
client?: "web" | "cli" | null;
/** Cache: a Trace record exists (set at task start / adoption / subagent registration; backfilled by list hydration). */
@@ -178,14 +180,13 @@ export class SessionsRepo {
/**
* An Agent's rows, newest first (the list order the sidebar shows; served by
- * idx_sessions_agent_created). `webOnly` keeps only web-created rows — NULL counts as
- * web (legacy rows predate the column and the user chose to grandfather them as visible).
+ * idx_sessions_agent_created). Never filtered by `client` — every row is listed
+ * whichever client created it.
*/
- listByAgent(projectId: string, agentId: string, opts: { webOnly?: boolean } = {}): SessionRow[] {
- const filter = opts.webOnly ? " AND (client IS NULL OR client = 'web')" : "";
+ listByAgent(projectId: string, agentId: string): SessionRow[] {
const rows = this.db
.prepare(
- `SELECT * FROM sessions WHERE project_id = ? AND agent_id = ?${filter}
+ `SELECT * FROM sessions WHERE project_id = ? AND agent_id = ?
ORDER BY created_at DESC, session_id DESC`,
)
.all(projectId, agentId);
diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.ts
index b98417e3..e691baa9 100644
--- a/packages/server/src/hmr/platform.ts
+++ b/packages/server/src/hmr/platform.ts
@@ -208,6 +208,15 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// now — nothing is running in THIS App yet — so the chat banner never restores a
// phantom "running" goal. GOAL.yaml on disk stays `active` as the resume point.
deps.goalsRepo.abortOrphanedActive();
+ // Startup adoption sweep: fold Trace-only Sessions (legacy CLI-direct runs) into
+ // the sessions index as client:'cli' rows, so every later list is pure SQLite.
+ // Fire-and-forget — a broken trace shard must not block the boot — with failures
+ // recorded like any background capture point. Idempotent and mtime-gated, so the
+ // re-run after a hot swap costs only the gate checks.
+ const errors = deps.errors;
+ void deps.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {
+ errors.record({ source: "process", err, code: "trace_adoption_failed" });
+ });
}
// ONE app, ONE pointer: every route this App serves — terminal group and business
diff --git a/packages/server/src/hmr/routes.ts b/packages/server/src/hmr/routes.ts
index d417dd10..677b1be1 100644
--- a/packages/server/src/hmr/routes.ts
+++ b/packages/server/src/hmr/routes.ts
@@ -67,16 +67,17 @@ export function hmrRoutes(deps: AppDeps): Hono<AppEnv> {
if (!c.req.path.endsWith("/upgrade")) await hmr.waitIdle();
await next();
};
- // Admin cookie session only. There used to be a second credential here — a
- // per-boot Bearer token published to $PENGUIN_HOME/hmr/api.json — for local
- // tools to call in without a browser session. It was removed: it ran as
- // plaintext on disk, readable by anything running as the same OS user
- // (including an agent's own shell/exec tools, which inherit that user and
- // PENGUIN_HOME), and it was admin-equivalent — making it the single
- // plaintext admin-equivalent secret on disk, i.e. the vulnerability itself.
- // Session tokens and passwords are hashed at rest (auth/service.ts); a local
- // caller now authenticates the same way an operator does: log in with the
- // admin password and present the resulting cookie.
+ // Admin credential required. An earlier per-boot Bearer token published to
+ // $PENGUIN_HOME/hmr/api.json was removed over the on-disk-plaintext objection
+ // (readable by any process of the same OS user, agent shells included, and
+ // admin-equivalent). That objection has since been deliberately reversed as a
+ // product decision, harness-wide: agents driving their own server through the
+ // CLI is the feature, and local filesystem access to the data root is defined
+ // as admin authority (exactly the reset-admin-password rule). The mechanism now
+ // lives at the general auth layer instead of here: the per-boot local API token
+ // at <root>/api-token (auth/api-token.ts), which authMiddleware — reused below —
+ // accepts as `Authorization: Bearer` and authenticates as the admin. A local
+ // caller may therefore present either that token or an admin cookie session.
return cookieAuth(c, async () => {
if (!c.get("user").isAdmin) {
throw new HttpError(403, "forbidden", "Hot platform APIs are admin-only.");
diff --git a/packages/server/src/http/routes/agent-traces.ts b/packages/server/src/http/routes/agent-traces.ts
index 0bcea8c7..7b00b9db 100644
--- a/packages/server/src/http/routes/agent-traces.ts
+++ b/packages/server/src/http/routes/agent-traces.ts
@@ -4,13 +4,11 @@
* trace-file index (mtime-gated reconcile, then pure DB — see services/trace-index.ts).
* Without `limit`: the legacy full drill-down (Agent -> date -> Session -> index,
* reverse order), never filtered. With optional `offset`/`limit` (+ optional
- * `category`, `cli`): pages Session groups newest-first (within the category when
+ * `category`): pages Session groups newest-first (within the category when
* given), stat-ing only the returned page for fresh sizes, and resolves per group a
* display title (sessions DB title, else the registration-time first-prompt
- * fallback) plus its sidebar category / Workspace and per-category totals.
- * CLI-origin Sessions (no web sessions-table row, not subagent/schedule) are
- * excluded unless `cli=1` — the same "show CLI sessions" preference the sessions
- * list honors, applied server-side to rows, counts and workspace groups alike.
+ * fallback) plus its sidebar category / Workspace and per-category totals. Every
+ * Session is listed whichever client created it.
* The listing consults the sessions table read-only (titles, archived, workspace,
* client); discovery itself still comes from the Trace directory tree via the index.
* - GET /api/projects/:p/agents/:a/traces/:sessionId/:index (including /analysis, /download) —
@@ -69,15 +67,9 @@ export function agentTracesRoutes(deps: AppDeps): Hono<AppEnv> {
throw badRequest(`category must be one of ${SESSION_CATEGORIES.join(" / ")}.`);
}
if (rawCategory !== undefined && paging === null) throw badRequest("category requires limit.");
- // `cli=1` widens the paginated listing to CLI-origin Sessions (mirroring the sessions
- // list's parameter): the default follows the "show CLI sessions" preference's OFF
- // state. The legacy unpaged shape is never filtered (back-compat).
- const rawCli = c.req.query("cli");
- if (rawCli !== undefined && rawCli !== "1") throw badRequest("cli only accepts 1.");
return c.json(
await deps.traceService.agentTraces(projectId, agentId, paging, {
...(rawCategory !== undefined ? { category: rawCategory as SessionCategory } : {}),
- ...(rawCli !== undefined ? { includeCli: true } : {}),
}),
);
});
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index ba046319..16dab265 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -429,8 +429,8 @@ function parseGoalField(body: Record<string, unknown>): { budget: number } | nul
export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
- // `cli=1` widens the list to CLI-created Sessions (Trace-directory discovery + adoption);
- // the default serves web rows straight from the DB (see SessionService.listSessions).
+ // Serves every row straight from the DB, whichever client created it (legacy CLI-direct
+ // Traces were adopted by the boot sweep; see SessionService.listSessions).
app.get("/", async (c) => {
// Id validity is checked before any path is constructed: guards against agentId path traversal across Projects.
const projectId = requireValidId(c, "projectId");
@@ -455,8 +455,6 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
}
const rawCounts = c.req.query("counts");
if (rawCounts !== undefined && rawCounts !== "1") throw badRequest("counts only accepts 1.");
- const rawCli = c.req.query("cli");
- if (rawCli !== undefined && rawCli !== "1") throw badRequest("cli only accepts 1.");
const { sessions, counts, workspaceCounts } = await deps.sessionService.listSessions(
projectId,
agentId,
@@ -465,7 +463,6 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
...(rawCategory !== undefined ? { category: rawCategory as SessionCategory } : {}),
...(rawWorkspaceGroup !== undefined ? { workspaceGroup: rawWorkspaceGroup } : {}),
...(rawCounts !== undefined ? { withCounts: true } : {}),
- ...(rawCli !== undefined ? { includeCli: true } : {}),
},
);
return c.json({
@@ -493,6 +490,9 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
);
}
const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);
+ // Creating-client hint stored on the row ("cli" from the CLI; default "web").
+ // Informational provenance only — lists serve every row regardless.
+ const client = optionalEnum(body, "client", ["web", "cli"] as const);
let workspace = optionalString(body, "workspace", { minLen: 1, label: "workspace" });
if (workspace !== undefined) {
// An explicitly specified Workspace must be an existing directory (never auto-created); reachability is determined by file permissions.
@@ -505,6 +505,7 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
...(provider !== undefined ? { provider } : {}),
...(workspace !== undefined ? { workspace } : {}),
...(approvalMode !== undefined ? { approvalMode } : {}),
+ ...(client !== undefined ? { client } : {}),
});
return c.json({ session } satisfies SessionCreateResponse, 201);
});
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 1cc59e37..bf4ef193 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -44,6 +44,7 @@ import type {
BackgroundCommandInfo,
BackgroundSubagentInfo,
CompactAvailability,
+ ControlEnvContext,
OmniMessage,
ProxyEnvPolicy,
SessionMetaPayload,
@@ -199,12 +200,17 @@ export interface SessionLoader {
* rebuilt Session is unsourced — session_meta is the single source of truth, and none survived.
* `opts.proxyEnv` threads the admin proxy settings into core (a live getter returning the
* agent-command-subprocess policy: strip the proxy variables, inject the explicit proxy
- * address, or null = pass the environment through).
+ * address, or null = pass the environment through). `opts.controlEnv` threads the
+ * harness-control injection the same way (the server's API URL/token plus the Session's
+ * coordinates; core evaluates it per Session — see CreateAgentOptions.controlEnv).
*/
export function createCoreSessionLoader(
root: string,
sources?: SessionSources,
- opts: { proxyEnv?: () => ProxyEnvPolicy | null } = {},
+ opts: {
+ proxyEnv?: () => ProxyEnvPolicy | null;
+ controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;
+ } = {},
): SessionLoader {
return {
async load(row: SessionRow): Promise<RuntimeSession> {
@@ -213,6 +219,7 @@ export function createCoreSessionLoader(
projectId: row.projectId,
agentId: row.agentId,
...(opts.proxyEnv ? { proxyEnv: opts.proxyEnv } : {}),
+ ...(opts.controlEnv ? { controlEnv: opts.controlEnv } : {}),
});
const located = await findLatestTraceFile(
tracesDir(root, row.projectId, row.agentId),
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 61353804..7c480f58 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -1,21 +1,21 @@
/**
* Session index service.
*
- * The default list is served from the DB index alone (web rows: `client` web/NULL) — no
- * Trace directory scanning in steady state (#139). `includeCli` widens it to DB ∪ Trace
- * directory discovery: scans `<agent>/traces/<date>/<session_id>_<index3>.jsonl`; an
- * unmanaged Session (one started via the CLI) has its first line's session_meta read for
- * (provider, model_id) / workspace, which is backfilled into a DB row marked
- * `client: "cli"` (approval_mode defaults, createdAt is taken from the timestamp embedded
- * in session_id) — the default list keeps excluding it, but it becomes individually
- * reachable (deep links).
+ * Lists are served from the DB index alone — no Trace directory scanning in steady state
+ * (#139), and no client-side filtering: every row is listed whichever client created it.
+ * Sessions that exist only as Trace files (left behind by a pre-server CLI) are adopted
+ * into the index once per boot by the startup sweep (`adoptUnmanagedTraceSessions`):
+ * the trace index's registration-time facts supply (provider, model_id) / workspace,
+ * and the row is stamped `client: "cli"` (approval_mode defaults, createdAt taken from
+ * the timestamp embedded in session_id).
* Create: via core's `agent.createSession` (the model reference is always a complete
* (provider, modelId) pair — both or neither; omitting both falls back to the
* Project's default reference, 400 if there is none); the new Session is
* added to session-manager's active table (state idle).
*/
-import { createAgent, isSessionMeta } from "@prismshadow/penguin-core";
-import type { ProxyEnvPolicy } from "@prismshadow/penguin-core";
+import fs from "node:fs/promises";
+import { agentsDir, createAgent, isSessionMeta } from "@prismshadow/penguin-core";
+import type { ControlEnvContext, ProxyEnvPolicy } from "@prismshadow/penguin-core";
import type {
ApprovalMode,
SessionCategory,
@@ -59,6 +59,12 @@ export interface SessionServiceDeps {
* runs the Session's first Task, so it needs the command-subprocess proxy policy too.
*/
proxyEnv?: () => ProxyEnvPolicy | null;
+ /**
+ * Harness-control env threading (same policy the session loader passes): the server's
+ * API URL/token plus the Session coordinates, injected into command subprocesses so
+ * agents can drive the harness back through the CLI/API.
+ */
+ controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;
}
export class SessionService {
@@ -129,15 +135,15 @@ export class SessionService {
}
/**
- * List, sorted by createdAt descending. The default serves **web sessions straight from
- * the DB** (`client` web/NULL rows) with no Trace directory scanning — the answer to
- * many-session sidebar reloads re-walking the filesystem on every request (#139). One
- * lazy discovery walk still runs for a list call that contains rows this process has not
- * classified yet (no in-process source entry): it supplies the Trace locations for the
- * one-time head reads and backfills the `has_trace` cache; once every row is classified,
- * list calls touch only the DB. `includeCli` widens the list to DB ∪ Trace directory
- * discovery (adopting unmanaged CLI Traces as `client: "cli"` rows), which inherently
- * scans — that path is opt-in via the "show CLI sessions" preference.
+ * List, sorted by createdAt descending. Every row is served **straight from the DB**,
+ * whichever client created it, with no Trace directory scanning — the answer to
+ * many-session sidebar reloads re-walking the filesystem on every request (#139).
+ * Sessions living only in the Trace directory were adopted into the index by the
+ * boot-time sweep (`adoptUnmanagedTraceSessions`), so listing never discovers. One
+ * lazy discovery walk still runs for a list call that contains rows this process has
+ * not classified yet (no in-process source entry): it supplies the Trace locations for
+ * the one-time head reads and backfills the `has_trace` cache; once every row is
+ * classified, list calls touch only the DB.
*
* Optional `paging` returns just that slice (the sidebar pages with limit+1 to detect
* "has more"); slicing happens before toInfo, so per-request source derivation (lazy
@@ -165,32 +171,19 @@ export class SessionService {
category?: SessionCategory;
workspaceGroup?: string;
withCounts?: boolean;
- includeCli?: boolean;
} = {},
): Promise<{
sessions: SessionInfo[];
counts?: SessionCategoryCounts;
workspaceCounts?: Record<string, SessionCategoryCounts>;
}> {
- const { paging, category, workspaceGroup, withCounts, includeCli } = opts;
+ const { paging, category, workspaceGroup, withCounts } = opts;
const rows = new Map(
- this.deps.sessions
- .listByAgent(projectId, agentId, { webOnly: !includeCli })
- .map((r) => [r.sessionId, r]),
+ this.deps.sessions.listByAgent(projectId, agentId).map((r) => [r.sessionId, r]),
);
let traces: ReadonlySet<string> | undefined;
- if (includeCli) {
- traces = await this.discoverTraces(projectId, agentId);
- // Unmanaged Trace Sessions (the CLI's): backfill an index row from the trace
- // index's registration-time facts, marked client "cli" so the default list can
- // exclude them.
- for (const sessionId of traces) {
- if (rows.has(sessionId)) continue;
- const discovered = this.adoptTraceSession(projectId, agentId, sessionId);
- if (discovered) rows.set(sessionId, discovered);
- }
- } else if ([...rows.values()].some((r) => this.deps.sources.get(r.sessionId) === undefined)) {
+ if ([...rows.values()].some((r) => this.deps.sources.get(r.sessionId) === undefined)) {
// Hydration pass: some rows predate this process and are unclassified — one
// reconciled index read supplies discovery so sourceOf's facts lookups and the
// has_trace cache need no per-row work. Steady state (everything classified)
@@ -311,6 +304,12 @@ export class SessionService {
approvalMode?: ApprovalMode;
/** Session source marker (schedule when triggered by a scheduled task; defaults to user-created). */
source?: "schedule";
+ /**
+ * Creating-client hint stored on the index row (`POST .../sessions` body `client`):
+ * "cli" from the CLI, defaulting to "web". Purely informational — lists no longer
+ * filter on it.
+ */
+ client?: "web" | "cli";
}): Promise<SessionInfo> {
if ((args.modelId === undefined) !== (args.provider === undefined)) {
throw badRequest(
@@ -340,6 +339,7 @@ export class SessionService {
projectId: args.projectId,
agentId: args.agentId,
...(this.deps.proxyEnv ? { proxyEnv: this.deps.proxyEnv } : {}),
+ ...(this.deps.controlEnv ? { controlEnv: this.deps.controlEnv } : {}),
});
let session;
try {
@@ -379,9 +379,10 @@ export class SessionService {
workspace: session.workspaceDir,
approvalMode: args.approvalMode ?? "allow-all",
title: null,
- // Everything created through this service is the Web App's (schedule runs included);
- // "cli" is stamped only by Trace adoption. NULL means a legacy row, treated as web.
- client: "web",
+ // The creator's hint: "cli" when the CLI created this Session through the API,
+ // otherwise "web" (schedule runs included). NULL means a legacy row, treated as
+ // web. Informational only — lists serve every row.
+ client: args.client ?? "web",
// Creation is the first activity; the first driven run advances it (see SessionManager.drive).
lastActiveAt: createdAt,
createdAt,
@@ -434,6 +435,34 @@ export class SessionService {
return out;
}
+ /**
+ * Startup adoption sweep: walks the whole trace tree once per boot and adopts every
+ * unmanaged Session (a Trace with no index row — legacy CLI-direct runs) as a
+ * `client: "cli"` row, so lists stay pure-SQLite afterwards. Enumerates
+ * `<root>/<project>/agents/<agent>/` directories directly — legacy Traces can live
+ * under Projects the DB has never seen — and reuses the existing discovery/adoption
+ * path per Agent (mtime-gated TraceIndexService reconcile, then registration-time
+ * facts; adoption reads no file itself). Idempotent (insertOrIgnore), so re-running —
+ * e.g. after a hot swap re-assembles the business surface — only costs the gated
+ * reconcile. Returns the number of rows adopted.
+ */
+ async adoptUnmanagedTraceSessions(): Promise<number> {
+ let adopted = 0;
+ for (const projectId of await listChildDirs(this.deps.root)) {
+ const agentIds = await listChildDirs(agentsDir(this.deps.root, projectId));
+ for (const agentId of agentIds) {
+ const known = new Set(
+ this.deps.sessions.listByAgent(projectId, agentId).map((r) => r.sessionId),
+ );
+ for (const sessionId of await this.discoverTraces(projectId, agentId)) {
+ if (known.has(sessionId)) continue;
+ if (this.adoptTraceSession(projectId, agentId, sessionId) !== null) adopted += 1;
+ }
+ }
+ }
+ return adopted;
+ }
+
/**
* Adopts a Session that exists only in the Trace directory, from the index's
* registration-time facts (the reconciler head-read the earliest shard's session_meta
@@ -464,8 +493,8 @@ export class SessionService {
// The approval mode for an unmanaged Session (started via the CLI) isn't in the Trace, so it's backfilled with the default value.
approvalMode: "allow-all",
title: null,
- // Adopted = a Trace this server never created, i.e. the CLI's: the default list
- // (web-only) excludes these rows; the "show CLI sessions" preference includes them.
+ // Adopted = a Trace this server never created, i.e. a legacy CLI-direct run: the
+ // row keeps that provenance, and lists serve it like any other.
client: "cli",
hasTrace: true,
createdAt,
@@ -480,6 +509,16 @@ export class SessionService {
}
}
+/** Child directory names of `dir` (empty on a missing/unreadable directory — a fresh root has no Projects yet). */
+async function listChildDirs(dir: string): Promise<string[]> {
+ try {
+ const entries = await fs.readdir(dir, { withFileTypes: true });
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name);
+ } catch {
+ return [];
+ }
+}
+
/** Local date as yyyy-mm-dd (matches the Trace date directory convention: core's internal formatLocalDate, not publicly exported). */
function localDate(d: Date): string {
const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 9d1ecd79..7b2e87e7 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -1345,16 +1345,15 @@ export class TraceService {
* drill-down (newest first: Agent -> date -> Session -> Trace files; sizes are the
* index's last observed values). With `paging`: session-group-centric — Sessions
* ordered by id descending (ids embed a timestamp, so that is reverse chronological),
- * optionally filtered to one sidebar `category`, CLI-origin Sessions excluded unless
- * `includeCli` (the "show CLI sessions" preference; the legacy shape is never
- * filtered — back-compat), and only the returned slice gets per-file `fs.stat` for
+ * optionally filtered to one sidebar `category` — every Session is listed whichever
+ * client created it — and only the returned slice gets per-file `fs.stat` for
* fresh sizes (written back to the index).
*/
async agentTraces(
projectId: string,
agentId: string,
paging?: { offset: number; limit: number } | null,
- opts: { category?: SessionCategory; includeCli?: boolean } = {},
+ opts: { category?: SessionCategory } = {},
): Promise<AgentTracesResponse> {
await this.deps.index.reconcileAgent(projectId, agentId);
const files = this.deps.index.repo.listFilesByAgent(projectId, agentId);
@@ -1415,7 +1414,7 @@ export class TraceService {
agentId: string,
files: TraceFileRow[],
paging: { offset: number; limit: number },
- opts: { category?: SessionCategory; includeCli?: boolean },
+ opts: { category?: SessionCategory },
): Promise<AgentTracesResponse> {
const bySession = new Map<string, TraceFileRow[]>();
for (const f of files) {
@@ -1424,39 +1423,23 @@ export class TraceService {
bySession.set(f.sessionId, list);
}
// One indexed query per source: the Agent's DB rows (title / archived / workspace /
- // client — CLI rows included) and the registration-time facts.
+ // client) and the registration-time facts.
const rows = new Map(
(this.deps.sessions?.listByAgent(projectId, agentId) ?? []).map((r) => [r.sessionId, r]),
);
const factsBySession = new Map(
this.deps.index.repo.listSessionsByAgent(projectId, agentId).map((r) => [r.sessionId, r]),
);
- /**
- * CLI-origin = no web-created DB row AND not a subagent/schedule Session. Server-created
- * Sessions always have a row (creation / subagent registration insert one), so rowless =
- * external CLI; adopted CLI rows carry client='cli'. The default listing excludes these —
- * the same "show CLI sessions" preference the sidebar applies — while subagent/schedule
- * Sessions stay in their folders regardless of which process ran them.
- */
- const cliOrigin = (sessionId: string, facts: TraceSessionFacts): boolean => {
- if (facts.category === "subagent" || facts.category === "schedule") return false;
- const row = rows.get(sessionId);
- return !(
- row !== undefined &&
- (row.client === null || row.client === undefined || row.client === "web")
- );
- };
const ids = [...bySession.keys()].sort((a, b) => b.localeCompare(a));
- // Classify every group once; the same result drives the CLI/category filters, the
+ // Classify every group once; the same result drives the category filter, the
// counts AND the returned fields, so a row can never appear in a bucket its own
- // `category` denies. Hidden CLI-origin groups are excluded from counts too.
+ // `category` denies. Every Session is listed whichever client created it.
const counts: SessionCategoryCounts = { active: 0, subagent: 0, schedule: 0, archived: 0 };
const workspaceCounts: Record<string, SessionCategoryCounts> = {};
const factsById = new Map<string, TraceSessionFacts>();
const visible: string[] = [];
for (const id of ids) {
const facts = this.classify(id, rows.get(id), factsBySession.get(id));
- if (opts.includeCli !== true && cliOrigin(id, facts)) continue;
factsById.set(id, facts);
visible.push(id);
counts[facts.category] += 1;
diff --git a/packages/server/test/agent-trace-detail.test.ts b/packages/server/test/agent-trace-detail.test.ts
index 57f29a26..6fa6bfa6 100644
--- a/packages/server/test/agent-trace-detail.test.ts
+++ b/packages/server/test/agent-trace-detail.test.ts
@@ -103,20 +103,12 @@ describe("agent-trace-detail", () => {
expect(legacy.sessions).toBeUndefined();
expect(legacy.totalSessions).toBeUndefined();
- // Default paged request: the unmanaged Session is CLI-origin (no web sessions-table
- // row, not subagent/schedule), so the "show CLI sessions" OFF default excludes it
- // from the listing AND the counts.
- const hidden = (await (await owner.get(`${base()}?limit=10`)).json()) as AgentTracesResponse;
- expect(hidden.sessions).toEqual([]);
- expect(hidden.totalSessions).toBe(0);
- expect(hidden.counts).toEqual({ active: 0, subagent: 0, schedule: 0, archived: 0 });
-
- // cli=1: visible, with title derived from the first user prompt and category /
- // workspace from the registration-time facts (the index head-read the earliest
- // shard once when the file was first seen — exact on the FIRST request).
- const paged = (await (
- await owner.get(`${base()}?limit=10&cli=1`)
- ).json()) as AgentTracesResponse;
+ // Paged request: every Session is listed whichever client created it — the unmanaged
+ // (legacy CLI-direct) Session is visible with title derived from the first user
+ // prompt and category / workspace from the registration-time facts (the index
+ // head-read the earliest shard once when the file was first seen — exact on the
+ // FIRST request).
+ const paged = (await (await owner.get(`${base()}?limit=10`)).json()) as AgentTracesResponse;
expect(paged.totalSessions).toBe(1);
expect(paged.sessions!.map((s) => s.sessionId)).toEqual([UNMANAGED]);
expect(paged.sessions![0]!.title).toBe("child session input");
@@ -147,34 +139,28 @@ describe("agent-trace-detail", () => {
createdAt: "2026-07-06T09:00:00.000Z",
lastActiveAt: "2026-07-06T09:00:00.000Z",
});
- const titled = (await (
- await owner.get(`${base()}?limit=10&cli=1`)
- ).json()) as AgentTracesResponse;
+ const titled = (await (await owner.get(`${base()}?limit=10`)).json()) as AgentTracesResponse;
expect(titled.sessions![0]!.title).toBe("已生成的标题");
- // The adopted row carries client='cli': it stays behind the preference by default.
- const stillHidden = (await (
- await owner.get(`${base()}?limit=10`)
- ).json()) as AgentTracesResponse;
- expect(stillHidden.sessions).toEqual([]);
+ // The adopted row carries client='cli' as provenance; it is listed like any other.
+ expect(t.deps.sessionsRepo.findById(UNMANAGED)!.client).toBe("cli");
// offset pages past the only group; offset without limit is a client error.
const empty = (await (
- await owner.get(`${base()}?limit=10&offset=10&cli=1`)
+ await owner.get(`${base()}?limit=10&offset=10`)
).json()) as AgentTracesResponse;
expect(empty.sessions).toEqual([]);
expect(empty.totalSessions).toBe(1);
expect((await owner.get(`${base()}?offset=1`)).status).toBe(400);
// Category filter: pages within one bucket (totalSessions = the bucket's count);
- // unknown values, category-without-limit, and a bad cli value are client errors.
+ // unknown values and category-without-limit are client errors.
const filtered = (await (
- await owner.get(`${base()}?limit=10&category=subagent&cli=1`)
+ await owner.get(`${base()}?limit=10&category=subagent`)
).json()) as AgentTracesResponse;
expect(filtered.sessions).toEqual([]);
expect(filtered.totalSessions).toBe(0);
expect((await owner.get(`${base()}?limit=10&category=bogus`)).status).toBe(400);
expect((await owner.get(`${base()}?category=active`)).status).toBe(400);
- expect((await owner.get(`${base()}?limit=10&cli=2`)).status).toBe(400);
});
it("user without access → 404 (requireProjectAccess)", async () => {
diff --git a/packages/server/test/api-token.test.ts b/packages/server/test/api-token.test.ts
new file mode 100644
index 00000000..25cb4ae6
--- /dev/null
+++ b/packages/server/test/api-token.test.ts
@@ -0,0 +1,159 @@
+/**
+ * Local API token: minted per boot, persisted at <root>/api-token (0600), and accepted
+ * by authMiddleware as `Authorization: Bearer` — authenticating as the built-in admin on
+ * every protected route, SSE endpoints included (the CLI consumes SSE via fetch with
+ * headers, so header auth must reach them).
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { MeResponse, SessionCreateResponse } from "../src/api/types.js";
+import { apiTokenPath, readApiToken, storeApiToken, tokensEqual } from "../src/auth/api-token.js";
+import { bearerToken } from "../src/auth/middleware.js";
+import { createTestApp } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+describe("local API token", () => {
+ let t: TestApp;
+ let token: string;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const stored = readApiToken(t.root);
+ expect(stored).not.toBeNull();
+ token = stored!;
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ const bearer = (value: string, init: RequestInit = {}, apiPath = "/api/me") =>
+ t.app.request(apiPath, {
+ ...init,
+ headers: {
+ authorization: `Bearer ${value}`,
+ ...(init.body !== undefined ? { "content-type": "application/json" } : {}),
+ ...((init.headers as Record<string, string>) ?? {}),
+ },
+ });
+
+ it("boot persists the token at <root>/api-token with owner-only permissions", () => {
+ expect(t.deps.authService.localApiToken()).toBe(token);
+ if (process.platform !== "win32") {
+ const mode = fs.statSync(apiTokenPath(t.root)).mode & 0o777;
+ expect(mode).toBe(0o600);
+ }
+ });
+
+ it("a valid Bearer authenticates as the admin (sessionVia 'token'), with no cookie at all", async () => {
+ const res = await bearer(token);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as MeResponse;
+ expect(body.user.userId).toBe("admin");
+ expect(body.user.isAdmin).toBe(true);
+ expect(body.sessionVia).toBe("token");
+ });
+
+ it("a wrong Bearer is 401 — even alongside a valid cookie (no silent fallback)", async () => {
+ expect((await bearer("not-the-token")).status).toBe(401);
+ const { loginAdmin } = await import("./helpers.js");
+ const { cookie } = await loginAdmin(t.app);
+ const res = await t.app.request("/api/me", {
+ headers: { authorization: "Bearer not-the-token", cookie },
+ });
+ expect(res.status).toBe(401);
+ // Without the header the same cookie works (the cookie path is untouched).
+ const cookieOnly = await t.app.request("/api/me", { headers: { cookie } });
+ expect(cookieOnly.status).toBe(200);
+ });
+
+ it("Bearer works on writes (the JSON-only CSRF guard still applies) and on SSE endpoints", async () => {
+ // Pin a model whose client constructs without a credential (the anthropic protocol);
+ // the seeded preset default may need an env key this machine does not have. The PUT
+ // itself is a Bearer-authenticated write too.
+ const models = await bearer(
+ token,
+ {
+ method: "PUT",
+ body: JSON.stringify({
+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],
+ }),
+ },
+ "/api/projects/default_project/models",
+ );
+ expect(models.status).toBe(200);
+ // Write path: create a Session in default_project as the admin, Bearer-only.
+ const create = await bearer(
+ token,
+ { method: "POST", body: JSON.stringify({ client: "cli" }) },
+ "/api/projects/default_project/agents/default_agent/sessions",
+ );
+ expect(create.status).toBe(201);
+ const { session } = (await create.json()) as SessionCreateResponse;
+ expect(t.deps.sessionsRepo.findById(session.sessionId)!.client).toBe("cli");
+
+ // A write with a form Content-Type is still refused (the CSRF guard is not bypassed).
+ const form = await t.app.request(
+ "/api/projects/default_project/agents/default_agent/sessions",
+ {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${token}`,
+ "content-type": "application/x-www-form-urlencoded",
+ },
+ body: "client=cli",
+ },
+ );
+ expect(form.status).toBe(415);
+
+ // SSE: the session stream answers a Bearer-authenticated subscribe.
+ const sse = await bearer(token, {}, `/api/sessions/${session.sessionId}/stream`);
+ expect(sse.status).toBe(200);
+ expect(sse.headers.get("content-type")).toContain("text/event-stream");
+ await sse.body?.cancel();
+ });
+
+ it("hot-update APIs accept the Bearer token as the admin credential", async () => {
+ // /api/hmr/status goes through the same middleware plus the admin check; the local
+ // token IS admin authority, so it must pass the gate (the malformed body then 404s
+ // or answers, but never 401/403).
+ const res = await bearer(token, {}, "/api/hmr/status");
+ expect(res.status).not.toBe(401);
+ expect(res.status).not.toBe(403);
+ });
+
+ it("storeApiToken overwrites the previous boot's file (per-boot rotation)", () => {
+ storeApiToken(t.root, "next-boot-token");
+ expect(readApiToken(t.root)).toBe("next-boot-token");
+ if (process.platform !== "win32") {
+ const mode = fs.statSync(apiTokenPath(t.root)).mode & 0o777;
+ expect(mode).toBe(0o600);
+ }
+ // No tmp file left behind by the atomic write.
+ const leftovers = fs.readdirSync(t.root).filter((f) => f.startsWith("api-token."));
+ expect(leftovers).toEqual([]);
+ });
+
+ it("tokensEqual: constant-time compare semantics (equal / different / different length)", () => {
+ expect(tokensEqual("abc", "abc")).toBe(true);
+ expect(tokensEqual("abc", "abd")).toBe(false);
+ expect(tokensEqual("abc", "abcd")).toBe(false);
+ expect(tokensEqual("", "")).toBe(true);
+ });
+
+ it("bearerToken parses the header shape and nothing else", () => {
+ expect(bearerToken("Bearer tok")).toBe("tok");
+ expect(bearerToken("bearer tok")).toBe("tok");
+ expect(bearerToken(" Bearer tok ")).toBe("tok");
+ expect(bearerToken("Basic dXNlcjpwYXNz")).toBeNull();
+ expect(bearerToken(undefined)).toBeNull();
+ expect(bearerToken("Bearer")).toBeNull();
+ });
+
+ it("readApiToken: absent or empty file reads as null", () => {
+ expect(readApiToken(path.join(t.root, "no-such-subdir"))).toBeNull();
+ fs.writeFileSync(apiTokenPath(t.root), "\n");
+ expect(readApiToken(t.root)).toBeNull();
+ });
+});
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.ts
index 2bbdaccf..714d2e0d 100644
--- a/packages/server/test/db-upgrade.test.ts
+++ b/packages/server/test/db-upgrade.test.ts
@@ -93,9 +93,7 @@ describe("openDatabase column upgrade", () => {
).toEqual({ fork_count: 0 });
// last_active_at is ALTERed in too; with no usage_records the backfill falls to created_at.
expect(legacy!.lastActiveAt).toBe("2026-01-01T00:00:00.000Z");
- expect(repo.listByAgent("p1", "a1", { webOnly: true }).map((r) => r.sessionId)).toEqual([
- "session-legacy",
- ]);
+ expect(repo.listByAgent("p1", "a1").map((r) => r.sessionId)).toEqual(["session-legacy"]);
// The upgraded table accepts writes to the new columns.
repo.insert({
sessionId: "session-new",
@@ -112,7 +110,10 @@ describe("openDatabase column upgrade", () => {
lastActiveAt: "2026-01-02T00:00:00.000Z",
});
expect(repo.findById("session-new")!.client).toBe("cli");
- expect(repo.listByAgent("p1", "a1", { webOnly: true }).map((r) => r.sessionId)).toEqual([
+ // Listing carries every row whichever client created it — the client column is
+ // provenance, not a filter.
+ expect(repo.listByAgent("p1", "a1").map((r) => r.sessionId)).toEqual([
+ "session-new",
"session-legacy",
]);
repo.markHasTrace("session-legacy");
diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.ts
index 0189bd6e..36747ef2 100644
--- a/packages/server/test/session-index.test.ts
+++ b/packages/server/test/session-index.test.ts
@@ -234,7 +234,8 @@ describe("session-index", () => {
sessionMeta(junkMeta),
userText("junk"),
]);
- const list = (await (await api.get(`${base()}?cli=1`)).json()) as SessionsResponse;
+ await t.deps.sessionService.adoptUnmanagedTraceSessions();
+ const list = (await (await api.get(base())).json()) as SessionsResponse;
expect(list.sessions.find((s) => s.sessionId === adopted)?.source).toBe("schedule");
expect(list.sessions.find((s) => s.sessionId === junk)?.source).toBeUndefined();
});
@@ -506,7 +507,7 @@ describe("session-index", () => {
).toBe(400);
});
- it("list union: Trace directory discovery finds unmanaged Sessions and backfills index rows", async () => {
+ it("startup adoption sweep: an unmanaged Trace becomes a client:'cli' row, and lists serve it from the DB", async () => {
await configureModels();
const discovered = "session-2026-07-01-08-30-00-deadbeef";
const meta: SessionMetaPayload = {
@@ -523,13 +524,16 @@ describe("session-index", () => {
userText("cli session"),
]);
- // The default list is DB-only (web rows): an unmanaged CLI Trace is neither listed
- // nor adopted by it (#139 — no Trace-directory scanning on the default path).
- const webOnly = (await (await api.get(base())).json()) as SessionsResponse;
- expect(webOnly.sessions.find((s) => s.sessionId === discovered)).toBeUndefined();
+ // Lists are DB-only (#139 — no Trace-directory scanning per request): before the
+ // sweep runs, the unmanaged Trace is neither listed nor reachable.
+ const before = (await (await api.get(base())).json()) as SessionsResponse;
+ expect(before.sessions.find((s) => s.sessionId === discovered)).toBeUndefined();
expect((await api.get(`/api/sessions/${discovered}`)).status).toBe(404);
- const list = (await (await api.get(`${base()}?cli=1`)).json()) as SessionsResponse;
+ // The boot-time sweep (fired at platform create; called directly here) adopts it.
+ const adopted = await t.deps.sessionService.adoptUnmanagedTraceSessions();
+ expect(adopted).toBe(1);
+ const list = (await (await api.get(base())).json()) as SessionsResponse;
const found = list.sessions.find((s) => s.sessionId === discovered);
expect(found).toBeDefined();
expect(found!.modelId).toBe("cli-model");
@@ -537,15 +541,28 @@ describe("session-index", () => {
expect(found!.approvalMode).toBe("allow-all");
expect(found!.hasTrace).toBe(true);
expect(found!.createdAt).toBe(sessionIdCreatedAt(discovered));
+ expect(t.deps.sessionsRepo.findById(discovered)!.client).toBe("cli");
- // Adopted as client "cli": the default list still excludes it afterwards, and counts
- // follow the same filter…
+ // Counts include the adopted row, the deep link works, and a re-run adopts nothing new.
const after = (await (await api.get(`${base()}?counts=1`)).json()) as SessionsResponse;
- expect(after.sessions.find((s) => s.sessionId === discovered)).toBeUndefined();
- expect(after.counts!.active).toBe(0);
- // …but the adopted row makes the Session individually reachable (deep links work).
- const single = await api.get(`/api/sessions/${discovered}`);
- expect(single.status).toBe(200);
+ expect(after.counts!.active).toBe(1);
+ expect((await api.get(`/api/sessions/${discovered}`)).status).toBe(200);
+ expect(await t.deps.sessionService.adoptUnmanagedTraceSessions()).toBe(0);
+ });
+
+ it("create stores the client hint: 'cli' when sent, 'web' by default, junk 400s; lists carry both", async () => {
+ await configureModels();
+ const fromCli = (await (
+ await api.post(base(), { client: "cli" })
+ ).json()) as SessionCreateResponse;
+ const fromWeb = (await (await api.post(base(), {})).json()) as SessionCreateResponse;
+ expect(t.deps.sessionsRepo.findById(fromCli.session.sessionId)!.client).toBe("cli");
+ expect(t.deps.sessionsRepo.findById(fromWeb.session.sessionId)!.client).toBe("web");
+ expect((await api.post(base(), { client: "carrier-pigeon" })).status).toBe(400);
+ const list = (await (await api.get(base())).json()) as SessionsResponse;
+ const ids = list.sessions.map((s) => s.sessionId);
+ expect(ids).toContain(fromCli.session.sessionId);
+ expect(ids).toContain(fromWeb.session.sessionId);
});
it("legacy rows without a client marker stay visible by default (grandfathered as web)", async () => {
@@ -639,7 +656,8 @@ describe("session-index", () => {
}),
]);
const created = (await (await api.post(base(), {})).json()) as SessionCreateResponse;
- const list = (await (await api.get(`${base()}?cli=1`)).json()) as SessionsResponse;
+ await t.deps.sessionService.adoptUnmanagedTraceSessions();
+ const list = (await (await api.get(base())).json()) as SessionsResponse;
expect(list.sessions[0]!.sessionId).toBe(created.session.sessionId);
expect(list.sessions[list.sessions.length - 1]!.sessionId).toBe(older);
});
diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.ts
index 35973dba..1d616ae6 100644
--- a/packages/server/test/trace-service.test.ts
+++ b/packages/server/test/trace-service.test.ts
@@ -621,12 +621,12 @@ describe("trace-service", () => {
await writeTraceFile(root, P, A, "2026-07-06", s2, 1, [userText("c")]);
await writeTraceFile(root, P, A, "2026-07-07", s3, 1, [userText("d")]);
- const page1 = await service.agentTraces(P, A, { offset: 0, limit: 2 }, { includeCli: true });
+ const page1 = await service.agentTraces(P, A, { offset: 0, limit: 2 });
expect(page1.totalSessions).toBe(3);
expect(page1.dates).toEqual([]); // paged responses are session-centric; per-file stats happen only for the slice
expect(page1.sessions!.map((s) => s.sessionId)).toEqual([s3, s2]);
- const page2 = await service.agentTraces(P, A, { offset: 2, limit: 2 }, { includeCli: true });
+ const page2 = await service.agentTraces(P, A, { offset: 2, limit: 2 });
expect(page2.totalSessions).toBe(3);
expect(page2.sessions!.map((s) => s.sessionId)).toEqual([S]);
expect(page2.sessions![0]!.files.map((f) => ({ index: f.index, date: f.date }))).toEqual([
@@ -636,12 +636,7 @@ describe("trace-service", () => {
expect(page2.sessions![0]!.files.every((f) => f.sizeBytes > 0)).toBe(true);
// Paging an empty Agent stays well-formed.
- const empty = await service.agentTraces(
- P,
- "agent-none",
- { offset: 0, limit: 2 },
- { includeCli: true },
- );
+ const empty = await service.agentTraces(P, "agent-none", { offset: 0, limit: 2 });
expect(empty.sessions).toEqual([]);
expect(empty.totalSessions).toBe(0);
});
@@ -678,7 +673,7 @@ describe("trace-service", () => {
},
});
- const res = await h.service.agentTraces(P, A, { offset: 0, limit: 10 }, { includeCli: true });
+ const res = await h.service.agentTraces(P, A, { offset: 0, limit: 10 });
const byId = new Map(res.sessions!.map((x) => [x.sessionId, x]));
expect(byId.get(S)!.category).toBe("archived");
expect(byId.get(S)!.workspace).toBe("/ws/one");
@@ -703,7 +698,7 @@ describe("trace-service", () => {
P,
A,
{ offset: 0, limit: 10 },
- { category: "active", includeCli: true },
+ { category: "active" },
);
expect(active.sessions!.map((x) => x.sessionId)).toEqual([s3]);
expect(active.totalSessions).toBe(1);
@@ -712,7 +707,7 @@ describe("trace-service", () => {
P,
A,
{ offset: 0, limit: 10 },
- { category: "archived", includeCli: true },
+ { category: "archived" },
);
expect(archived.sessions!.map((x) => x.sessionId)).toEqual([S]);
h.close();
@@ -727,7 +722,7 @@ describe("trace-service", () => {
userText("child prompt"),
]);
- const first = await service.agentTraces(P, A, { offset: 0, limit: 10 }, { includeCli: true });
+ const first = await service.agentTraces(P, A, { offset: 0, limit: 10 });
expect(first.sessions![0]!.category).toBe("subagent");
expect(first.sessions![0]!.workspace).toBe("/ws/child");
expect(first.counts).toEqual({ active: 0, subagent: 1, schedule: 0, archived: 0 });
@@ -735,14 +730,14 @@ describe("trace-service", () => {
expect(harness.sources.get(S)).toBe("subagent");
const reads = harness.traceIndex.counters.headReads;
- const second = await service.agentTraces(P, A, { offset: 0, limit: 10 }, { includeCli: true });
+ const second = await service.agentTraces(P, A, { offset: 0, limit: 10 });
expect(second.sessions![0]!.category).toBe("subagent");
expect(harness.traceIndex.counters.headReads).toBe(reads); // classification never re-reads
});
- it("Agent-level paging: CLI-origin Sessions are hidden by default and shown with includeCli (subagent/schedule stay visible)", async () => {
- const cliSid = "session-2026-07-06-09-00-00-11112222"; // untracked, user-created meta -> CLI-origin
- const childSid = "session-2026-07-07-08-00-00-33334444"; // untracked but subagent-origin -> its folder, regardless
+ it("Agent-level paging: every Session is listed whichever client created it (no CLI filter)", async () => {
+ const cliSid = "session-2026-07-06-09-00-00-11112222"; // untracked, user-created meta (a legacy CLI-direct run)
+ const childSid = "session-2026-07-07-08-00-00-33334444"; // untracked but subagent-origin -> its folder
await writeTraceFile(root, P, A, "2026-07-06", cliSid, 1, [
sessionMeta(metaPayload({ session_id: cliSid })),
userText("cli run"),
@@ -760,20 +755,16 @@ describe("trace-service", () => {
sessions: { listByAgent: () => [dbRow({ sessionId: webSid, workspace: "/ws/web" })] },
});
- const hidden = await h.service.agentTraces(P, A, { offset: 0, limit: 10 });
- expect(hidden.sessions!.map((x) => x.sessionId)).toEqual([childSid, webSid]);
- expect(hidden.totalSessions).toBe(2);
- expect(hidden.counts).toEqual({ active: 1, subagent: 1, schedule: 0, archived: 0 });
-
- const shown = await h.service.agentTraces(P, A, { offset: 0, limit: 10 }, { includeCli: true });
- expect(shown.sessions!.map((x) => x.sessionId)).toEqual([childSid, cliSid, webSid]);
- expect(shown.counts).toEqual({ active: 2, subagent: 1, schedule: 0, archived: 0 });
+ const listed = await h.service.agentTraces(P, A, { offset: 0, limit: 10 });
+ expect(listed.sessions!.map((x) => x.sessionId)).toEqual([childSid, cliSid, webSid]);
+ expect(listed.totalSessions).toBe(3);
+ expect(listed.counts).toEqual({ active: 2, subagent: 1, schedule: 0, archived: 0 });
h.close();
});
it("Agent-level paging: a Session whose head has no user text gets no title (the client falls back to its default)", async () => {
await writeTraceFile(root, P, A, "2026-07-05", S, 1, [sessionMeta(metaPayload())]);
- const res = await service.agentTraces(P, A, { offset: 0, limit: 10 }, { includeCli: true });
+ const res = await service.agentTraces(P, A, { offset: 0, limit: 10 });
expect(res.sessions![0]!.title).toBeUndefined();
});
diff --git a/packages/skills/skills/penguin-orchestration/SKILL.md b/packages/skills/skills/penguin-orchestration/SKILL.md
index 40c36cec..bf421a08 100644
--- a/packages/skills/skills/penguin-orchestration/SKILL.md
+++ b/packages/skills/skills/penguin-orchestration/SKILL.md
@@ -3,8 +3,8 @@ name: penguin-orchestration
description: Drive PenguinHarness itself from a shell — list and create agents and sessions, send and steer messages mid-flight, and query costs and scheduled tasks via the penguin CLI over the local server.
short_description: Orchestrate agents, sessions, costs and schedules with the penguin CLI.
short_description_zh: 用 penguin CLI 编排智能体、会话、成本与定时任务。
-version: 1
-updated: 2026-08-25T00:00:00Z
+version: 2
+updated: 2026-08-26T18:46:22Z
---
# Penguin Orchestration
@@ -42,10 +42,10 @@ penguin run -m <msg> [--project-id <id>] [--agent-id <id>] [--workspace <path>]
[--session <session_id>] [--background] [--timeout <duration>]
[--goal [budget]] [--json]
penguin ls [--project-id <id>] [--agent-id <id>] [--days <n>] [-a|--all] [--json]
-penguin input <session_id> [-m <text>] [--timeout <duration>]
- [--project-id <id>] [--json] [--server <url>]
-penguin logs <session_id> [--project-id <id>] [--tail <n>] [-f|--follow]
- [--timeout <duration>] [--json]
+penguin input [session_id] [-m <text>] [--timeout <duration>]
+ [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+penguin logs [session_id] [--project-id <id>] [--agent-id <id>] [--tail <n>]
+ [-f|--follow] [--timeout <duration>] [--json]
penguin agent ls [--project-id <id>] [--json]
penguin agent create --agent-id <id> [--name <s>] [--description <s>] [--skills <a,b>]
[--project-id <id>] [--json]
@@ -65,9 +65,10 @@ penguin schedule rm <name> [--project-id <id>] [--agent-id <id>]
- `run` starts a task and waits, rendering the conversation, unless `--background` — then it prints the new session id and exits while the server keeps running the task. `--session <session_id>` runs the task in an existing session instead of creating one; the model reference is the `--provider` + `--model-id` pair (both or neither); `--goal [budget]` runs in goal mode — the session loops until the agent declares the goal complete, with an optional spend budget.
- **Caller-context defaults.** Inside a harness agent, a session-creating `run` fills every field you leave unspecified from your own live session, per field independently: `--workspace`, the `--model-id`/`--provider` pair, `--approve` and `--thinking` inherit the caller's values — the same convention as `run_subagent` parent inheritance. Precedence: explicit flag > caller value > plain fallback (cwd, the Project default model, `allow-all`, none — used wholesale if the caller lookup fails, with a dim stderr note). So inside an agent, `penguin run -m "..."` alone typically does the right thing; pass flags only to diverge.
- `--timeout <duration>` (`30s`, `5m`, `2h`, or bare seconds) bounds the wait of a foreground `run`, an `input`, or a `logs -f`. Expiry is a soft yield, not an error: the command exits 0 while the task keeps running server-side, printing a still-running note that names the follow-up commands (`--json` prints `{sessionId, status: "running", text}` with the text so far). `--timeout 0` (also `0s`) returns immediately after delivery — the same note without collected text (`--json`: `{sessionId, status: "running"}`); on a bare poll it snapshots a running session instantly. `run --background` stays the idiomatic fire-and-forget for new tasks and rejects `--timeout`; `logs --timeout` requires `-f`.
-- `input` with `-m` steers a **running** session mid-turn (the agent absorbs it as a course correction within the current task) or starts a new turn on an idle one; it waits for the reply unless a `--timeout` bounds the wait (`--timeout 0` = deliver and return at once). Bare `input <session_id>` (no `-m`) **polls**: it prints the session's most recent complete assistant text — an idempotent snapshot that skips user/thinking/tool output and never touches approvals, mirroring `input_subagent`'s empty-prompt semantics. A running session is waited on first (bounded by `--timeout`, else indefinitely); a session with no reply yet prints `(no assistant reply yet)`. `--json` reports `{sessionId, status, text}` — `idle`/`running` when polling, `completed`/`aborted`/`running` with `-m`.
+- `input` with `-m` steers a **running** session mid-turn (the agent absorbs it as a course correction within the current task) or starts a new turn on an idle one; it waits for the reply unless a `--timeout` bounds the wait (`--timeout 0` = deliver and return at once). Bare `input [session_id]` (no `-m`) **polls**: it prints the session's most recent complete assistant text — an idempotent snapshot that skips user/thinking/tool output and never touches approvals, mirroring `input_subagent`'s empty-prompt semantics. A running session is waited on first (bounded by `--timeout`, else indefinitely); a session with no reply yet prints `(no assistant reply yet)`. `--json` reports `{sessionId, status, text}` — `idle`/`running` when polling, `completed`/`aborted`/`running` with `-m`.
- `ls` spans every agent of the project, newest first (by last active); archived sessions are left out unless `-a`/`--all` includes them, and `--days <n>` keeps only sessions last active since local midnight n−1 days ago — today counts as day 1, so `--days 2` is yesterday and today, `--days 7` this week. `logs` renders a session's transcript: `--tail <n>` for the last entries, `-f` to follow live.
- Session ids embed their creation timestamp — `session-YYYY-MM-DD-HH-mm-ss-<8hex>`. Every `<session_id>` argument takes any unique substring of an id; the 8-hex tail is the recommended short form, and an ambiguous fragment errors listing the candidates. On `input` and `logs`, `--project-id` scopes that fragment search (unnecessary with a full id).
+- On `input` and `logs` the id is optional altogether: omitted, it is the agent's most recent session, off the same newest-first listing `chat --resume` uses, with `--agent-id` picking whose. The chosen id is announced as a dim `[latest]` line on stderr, so the target is never ambiguous and `--json` on stdout stays parseable. Bare `penguin logs` is therefore "what just happened" and bare `penguin input` is "what did my agent last say"; an agent with no session at all gets one line pointing at `penguin run` and a non-zero exit.
## Recipes
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 47e32e93..1da2a8c1 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -444,16 +444,13 @@ export const listSessions = (
/** One Workspace group's rows only: its path, or the merged temporary group's sentinel (session-grouping.ts). */
workspaceGroup?: string;
withCounts?: boolean;
- /** Also list CLI-created Sessions (Trace discovery + adoption); default = web rows straight from the DB. */
- cli?: boolean;
},
) => {
const qs = opts
? `?limit=${opts.limit}&offset=${opts.offset}` +
(opts.category ? `&category=${opts.category}` : "") +
(opts.workspaceGroup ? `&workspaceGroup=${encodeURIComponent(opts.workspaceGroup)}` : "") +
- (opts.withCounts ? "&counts=1" : "") +
- (opts.cli ? "&cli=1" : "")
+ (opts.withCounts ? "&counts=1" : "")
: "";
return apiFetch<SessionsResponse>(
`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/sessions${qs}`,
diff --git a/packages/web/src/features/settings/general-section.tsx b/packages/web/src/features/settings/general-section.tsx
index 59defc2e..7a3a1b94 100644
--- a/packages/web/src/features/settings/general-section.tsx
+++ b/packages/web/src/features/settings/general-section.tsx
@@ -1,24 +1,21 @@
/**
* General page of System settings: per-account preferences that are neither appearance nor
* credentials. Everything applies the moment it is touched — the stores persist each value
- * (language and currency per browser, the CLI-sessions filter per user via PUT /me/prefs)
- * — so the page carries no Save button and no draft state to lose.
+ * (language and currency per browser) — so the page carries no Save button and no draft
+ * state to lose.
*/
import { S } from "../../lib/strings";
import { Segmented } from "../../components/ui/segmented";
-import { Switch } from "../../components/ui/switch";
import { useLocale } from "../../state/locale";
import type { LangPref } from "../../state/locale";
import { useTheme } from "../../state/theme";
import type { Currency } from "../../state/theme";
-import { useSessions } from "../../state/sessions";
import { PrefRow } from "./setting-row";
import { TraceImportRow } from "./trace-import-row";
export function GeneralSection() {
const { lang, setLang } = useLocale();
const { currency, setCurrency } = useTheme();
- const { showCliSessions, setShowCliSessions } = useSessions();
const langOptions: ReadonlyArray<{ value: LangPref; label: string }> = [
{ value: "en", label: S.settings.langEn },
@@ -38,12 +35,6 @@ export function GeneralSection() {
<PrefRow label={S.models.currency} info={S.settings.currencyInfo}>
<Segmented options={currencyOptions} value={currency} onChange={setCurrency} cols={2} />
</PrefRow>
- {/* Flipping this refetches the whole conversation list under the new filter, so the
- sidebar behind the dialog updates without a reload. */}
- <PrefRow label={S.settings.showCliSessions} info={S.settings.showCliSessionsInfo}>
- <Switch checked={showCliSessions} onChange={setShowCliSessions} />
- </PrefRow>
- {/* Beside the filter above: both rows decide what the conversation list holds. */}
<TraceImportRow />
</div>
);
diff --git a/packages/web/src/lib/group-order.ts b/packages/web/src/lib/group-order.ts
index 9ef3632d..355d3197 100644
--- a/packages/web/src/lib/group-order.ts
+++ b/packages/web/src/lib/group-order.ts
@@ -27,10 +27,10 @@
* is only ever a failed membership lookup (applyManualOrder), so it costs a map entry
* and changes nothing on screen. Pruning was tried at the drop and removed: deciding a
* group is *gone* needs the mode's complete live key set, and the client cannot prove
- * one. In Workspace mode the per-Agent `workspaceCounts` look like such a proof but are
- * filtered by the "show CLI sessions" preference (the server builds its row set with
- * `webOnly: !includeCli` before counting), so a Workspace used only from the CLI is
- * absent from a complete-looking picture; in Agent mode `agentsLoading === false` is not
+ * one. In Workspace mode the per-Agent `workspaceCounts` look like such a proof but
+ * describe only the rows the server's index knew at fetch time, so a Workspace whose
+ * Sessions arrive later (a boot-time adoption, an import) can be absent from a
+ * complete-looking picture; in Agent mode `agentsLoading === false` is not
* proof of a *successful* fetch, and an empty Agent list is indistinguishable from a
* failed one. A wrong proof silently discards an arrangement the user cannot restore,
* which is a bad trade against a few hundred short strings in localStorage. If a group
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 427babd4..53b42d4c 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -87,11 +87,7 @@ export const en: Strings = {
generalTitle: "General",
appearanceTitle: "Appearance",
accountTitle: "Account",
- /** Sidebar Session list: also show CLI-created Sessions (default off — the list then never scans the Trace directories). */
- showCliSessions: "Show CLI sessions",
- showCliSessionsInfo:
- "Off, the conversation list holds only Sessions created in the Web App and is served straight from the database. On, the Trace directories are scanned too and CLI-created Sessions are listed alongside them. Applies to this account only.",
- /** Trace import (below the CLI-sessions filter): the two pickers' accessible names, the pick-a-file action, and its outcomes. */
+ /** Trace import: the two pickers' accessible names, the pick-a-file action, and its outcomes. */
importTrace: "Import Trace",
importTraceInfo:
"Upload a .jsonl Trace exported from another install and it becomes a conversation of the chosen Agent. Both halves of the destination are picked here: the endpoint is per-Agent — a Trace file's own session_meta cannot name a local Agent, since its agent_state path belongs to the machine that exported it — and the Project is asked for because this dialog does not show which one is open, which also means a Trace can go to a Project other than the open one. Exporting happens in a conversation's Trace panel.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index ebe676d9..b7ebc8ee 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -95,11 +95,7 @@ export const zh = {
generalTitle: "通用",
appearanceTitle: "外观",
accountTitle: "账户",
- /** Sidebar Session list: also show CLI-created Sessions (default off — the list then never scans the Trace directories). */
- showCliSessions: "显示 CLI 会话",
- showCliSessionsInfo:
- "关闭时会话列表只列出在 Web 端创建的会话,直接由数据库返回;开启后会额外扫描轨迹目录,把 CLI 创建的会话一并列出。仅影响当前账号。",
- /** Trace import (below the CLI-sessions filter): the two pickers' accessible names, the pick-a-file action, and its outcomes. */
+ /** Trace import: the two pickers' accessible names, the pick-a-file action, and its outcomes. */
importTrace: "导入 Trace",
importTraceInfo:
"上传从其他部署导出的 .jsonl 轨迹文件,它会成为所选 Agent 的一个会话。目的地的两个部分都在这里选择:导入接口按 Agent 划分——轨迹文件自带的 session_meta 无法指认本机的 Agent,其中的 agent_state 路径属于导出它的那台机器——而 Project 需要明确指定,因为本对话框不显示当前是哪一个,也因此可以导入到当前打开之外的 Project。导出在对话的 Trace 面板中进行。",
diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsx
index 79921d77..40523238 100644
--- a/packages/web/src/state/auth.tsx
+++ b/packages/web/src/state/auth.tsx
@@ -44,9 +44,10 @@ interface AuthContextValue {
/**
* How THIS session was established. A browser signed into a desktop-mode server holds
* a "password" session; only "desktop" sessions (the shell's window) may change the
- * password without the old one.
+ * password without the old one. ("token" marks Bearer-authenticated API callers and
+ * never occurs in a browser session; it is carried for type parity with the server.)
*/
- sessionVia: "password" | "desktop";
+ sessionVia: "password" | "desktop" | "token";
/**
* Upload limits in force on this server (admin-settable). The composer reads them to refuse an
* oversize pick before reading it and to name the real number in the message, so the client
@@ -67,7 +68,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// flashing it during initialization would be noise.
const [previewIsolated, setPreviewIsolated] = useState(true);
const [desktopMode, setDesktopMode] = useState(false);
- const [sessionVia, setSessionVia] = useState<"password" | "desktop">("password");
+ const [sessionVia, setSessionVia] = useState<"password" | "desktop" | "token">("password");
const [uploadLimits, setUploadLimits] = useState<UploadLimits>(DEFAULT_UPLOAD_LIMITS);
// Any API returning 401 (session expired / database rebuilt) clears the current user, and
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index 15d67146..646713af 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -92,10 +92,6 @@ interface SessionsContextValue {
setStatus: (sessionId: string, status: SessionStatus, row?: LiveRowFields) => void;
/** session_title server event → update the title in place. */
setTitle: (sessionId: string, title: string) => void;
- /** Whether CLI-created Sessions are listed too (persisted per user; default off = the list is served from the DB without Trace scanning). */
- showCliSessions: boolean;
- /** Flip the CLI-session preference: persists it and refetches the whole list under the new filter. */
- setShowCliSessions: (value: boolean) => void;
}
/**
@@ -170,10 +166,6 @@ interface SessionsStoreState {
countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;
workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;
loading: boolean;
- // "Show CLI sessions" preference: server-persisted per user (ui_prefs); hydrated once by the
- // Provider on mount, default off. Changing it makes the Provider's reset effect refetch the
- // whole list under the new filter.
- showCliSessions: boolean;
reload: () => Promise<void>;
loadMoreFor: (
@@ -186,7 +178,6 @@ interface SessionsStoreState {
replace: (session: SessionInfo) => void;
setStatus: (sessionId: string, status: SessionStatus, row?: LiveRowFields) => void;
setTitle: (sessionId: string, title: string) => void;
- setShowCliSessions: (value: boolean) => void;
}
/**
@@ -241,10 +232,9 @@ export function createSessionsStore() {
countsByAgent: new Map(),
workspaceCountsByAgent: new Map(),
loading: true,
- showCliSessions: false,
reload: async () => {
- const { projectId, agentIds, showCliSessions } = get();
+ const { projectId, agentIds } = get();
if (!projectId || agentIds.length === 0) return;
const g = ++gen;
set({ loading: true });
@@ -273,7 +263,6 @@ export function createSessionsStore() {
category,
...(scope === "" ? {} : { workspaceGroup: scope }),
...(category === "active" && scope === "" ? { withCounts: true } : {}),
- ...(showCliSessions ? { cli: true } : {}),
});
return {
category,
@@ -343,7 +332,7 @@ export function createSessionsStore() {
* walked, so the pool absorbs any overlap by sessionId.
*/
loadMoreFor: async (agentIds, category, workspaceGroup) => {
- const { projectId, showCliSessions } = get();
+ const { projectId } = get();
if (!projectId) return;
const scope = scopeOf(workspaceGroup);
const targets = [...new Set(agentIds)].filter((agentId) => {
@@ -387,7 +376,6 @@ export function createSessionsStore() {
limit: SIDEBAR_PAGE_SIZE + 1,
category,
...(scope === "" ? {} : { workspaceGroup: scope }),
- ...(showCliSessions ? { cli: true } : {}),
})
).sessions;
return { agentId, offset, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };
@@ -535,13 +523,6 @@ export function createSessionsStore() {
sessions: prev.map((s) => (s.sessionId === sessionId ? { ...s, title } : s)),
});
},
-
- setShowCliSessions: (value) => {
- set({ showCliSessions: value });
- // Fire-and-forget: PUT /me/prefs merges shallowly; a lost write only costs persistence,
- // the in-memory toggle already took effect.
- void api.putPrefs({ showCliSessions: value }).catch(() => undefined);
- },
};
});
}
@@ -615,29 +596,11 @@ export function SessionsProvider({ children }: { children: ReactNode }) {
const [store] = useState(createSessionsStore);
const state = useStore(store);
- // Hydrate the "show CLI sessions" preference once on mount (a bare setState, not the
- // setShowCliSessions action: hydration must not write the preference back).
- useEffect(() => {
- let cancelled = false;
- void api
- .getPrefs()
- .then((res) => {
- if (!cancelled && res.prefs.showCliSessions === true)
- store.setState({ showCliSessions: true });
- })
- .catch(() => undefined); // Unreachable prefs: stay with the default (web only).
- return () => {
- cancelled = true;
- };
- }, [store]);
-
- const { showCliSessions } = state;
useEffect(() => {
// Sync the fetch context and reset the loaded pages in the same synchronous step:
// reload() picks the categories to refetch from pageState, so a Project switch can't
// carry folder page state across via shared Agent ids (default_agent exists in every
- // Project). Also reruns on a showCliSessions flip: refetch the whole list under the
- // new filter.
+ // Project).
// deletedSessionIds is deliberately NOT reset: session ids are globally unique and never
// reused, so a Session deleted before a Project switch is still deleted after it — and
// re-arming its lookup would just re-create the 404 this set exists to prevent.
@@ -650,7 +613,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {
workspaceCountsByAgent: new Map(),
});
void store.getState().reload();
- }, [store, projectId, agentIdsKey, showCliSessions]);
+ }, [store, projectId, agentIdsKey]);
// User-level event stream (/api/events); see applyUserEvent for what each event does. The
// connection stays a single one for the whole login session and doesn't reconnect on Project
@@ -723,8 +686,6 @@ export function SessionsProvider({ children }: { children: ReactNode }) {
replace: state.replace,
setStatus: state.setStatus,
setTitle: state.setTitle,
- showCliSessions: state.showCliSessions,
- setShowCliSessions: state.setShowCliSessions,
};
}, [state, isLoadedFor, hasMoreFor, isDeleted]);
diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.ts
index 9262cf92..13bd81c9 100644
--- a/packages/web/test/account-menu.test.ts
+++ b/packages/web/test/account-menu.test.ts
@@ -89,7 +89,7 @@ describe("the sidebar user menu", () => {
// with the admin ones.
expect(source).toContain("setSettingsOpen(true)");
expect(source).not.toContain("offersChangePassword");
- expect(source).not.toContain("S.settings.showCliSessions");
+ expect(source).not.toContain("S.settings.language");
expect(source).not.toContain("S.settings.theme");
expect(source).not.toContain('go("/settings")');
expect(source).not.toContain('go("/admin/users")');