Skip to content

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

docs: reorganize the docs site around tasks and rewrite every page (#758)

Yaowei Zhengf478bf8bbd96
diff --git a/changelog/unreleased/2026-09-16-docs-restructure.md b/changelog/unreleased/2026-09-16-docs-restructure.md
new file mode 100644
index 00000000..61b76e4e
--- /dev/null
+++ b/changelog/unreleased/2026-09-16-docs-restructure.md
@@ -0,0 +1,35 @@
+# The docs site reorganized around tasks, with every page rewritten
+
+- **Date:** 2026-09-16
+- **Type:** process
+- **Scope:** `docs`
+- **PR:** [#758](https://github.com/Prism-Shadow/penguin-harness/pull/758)
+
+[中文版](2026-09-16-docs-restructure.zh.md)
+
+The documentation site was reorganized in the spirit of a help center, and every page was
+rewritten in both languages: English first, then Chinese translated from it, with each draft
+checked against the code and the Web App's UI strings. Every existing page slug still works.
+
+## Details
+
+- The sidebar has five sections. **Get Started**: introduction, quickstart (desktop, CLI, Docker,
+ SDK), and the new Key concepts and Update pages. **Guides**: Web App, Conversations, Files panel,
+ Scheduled tasks, Remote control, Agents, Skills, Models, Cost Center and Settings. **Advanced**:
+ Evaluation Center, self-improvement, goal mode and company mode. **How It Works**: architecture,
+ server boot, OmniMessage, the agent loop, message flow, core interfaces, tools and
+ Sessions & Traces. **Reference**: CLI, Server API, configuration and security.
+- The 63,000-character Web App guide was split: `web-app` became an overview, and conversations,
+ the Files panel, scheduled tasks, agents, the Cost Center, the Evaluation Center, settings and
+ updates each got a page of their own. Its plugin-library and model-configuration sections moved
+ into `skills` and `models`, which moved from the design section into Guides.
+- Three pages are new: `concepts` (a glossary grouped by topic), `remote-control` (binding a
+ conversation to Feishu, Telegram, QQ or WeChat) and `updates`.
+- Guide pages lead with tasks and numbered steps and keep implementation detail in a closing
+ "How it works" section; reference pages give every command, route and key the same shape.
+- Content that had drifted from the code was corrected, among it: the four stop reasons and error
+ codes, compaction outcomes, the server boot sequence and HMR platform, the CLI running as a
+ client of the server, the goal-image rule, the enforced and advisory parts of company mode, the
+ Optimizer and Evaluator information barrier, and dozens of previously undocumented routes,
+ options and settings.
+- A source comment in `packages/core/src/state/agent-state.ts` cites the renamed skills-page heading.
diff --git a/changelog/unreleased/2026-09-16-docs-restructure.zh.md b/changelog/unreleased/2026-09-16-docs-restructure.zh.md
new file mode 100644
index 00000000..e4466645
--- /dev/null
+++ b/changelog/unreleased/2026-09-16-docs-restructure.zh.md
@@ -0,0 +1,19 @@
+# 文档站按任务重新组织,全部页面重写
+
+- **Date:** 2026-09-16
+- **Type:** process
+- **Scope:** `docs`
+- **PR:** [#758](https://github.com/Prism-Shadow/penguin-harness/pull/758)
+
+[English](2026-09-16-docs-restructure.md)
+
+文档站参照帮助中心的思路重新组织,全部页面的中英文版本都已重写:先写英文,再由英文翻译出中文,每份草稿都对照代码和 Web App 的界面文案核对过。原有页面的地址全部保持可用。
+
+## 细节
+
+- 侧栏分为五个部分。**开始**:产品介绍、快速开始(桌面应用、CLI、Docker、SDK),以及新增的核心概念和更新页面。**使用指南**:Web App、对话、文件面板、定时任务、远程控制、Agent、Skill、模型、成本中心和系统设置。**进阶功能**:评估中心、自我进化、目标模式和公司模式。**工作原理**:架构、服务端启动、OmniMessage、Agent 循环、消息流、核心接口、工具、会话与 Trace。**参考**:CLI、Server API、配置和安全。
+- 原来长达 6.3 万字符的 Web App 指南被拆开:`web-app` 改为概览页,对话、文件面板、定时任务、Agent、成本中心、评估中心、系统设置和更新各自成页。其中插件库和模型配置两节并入 `skills` 与 `models`,这两页也从设计部分移到了使用指南。
+- 新增三页:`concepts`(按主题分组的术语表)、`remote-control`(把对话绑定到飞书、Telegram、QQ 或微信)和 `updates`。
+- 使用指南以任务和编号步骤为主,实现细节集中放在结尾的「工作原理」一节;参考页面里每条命令、路由和配置项都采用统一格式。
+- 修正了与代码不一致的内容,其中包括:四种停止原因与错误码、压缩的结束状态、服务端启动流程与 HMR 平台、CLI 作为服务端客户端运行、目标模式的图片规则、公司模式中由服务端强制和仅为约定的部分、Optimizer 与 Evaluator 之间的信息隔离,以及此前未写入文档的数十个路由、选项和设置。
+- `packages/core/src/state/agent-state.ts` 中的一条源码注释改为引用 Skill 页面重命名后的标题。
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index 0e38a73a..afe7816f 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -682,7 +682,7 @@ function hookManifestText(manifest: HookManifest): string {
* installed skill does), plus the package's files (relative path → content, subdirectories
* preserved), replacing the whole directory like a skill install does. Each file path is
* checked to stay within the directory.
- * Docs: /docs/skills § "Hooks".
+ * Docs: /docs/skills § "Hook packages".
*/
export async function installHook(
root: string,
diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.md
index 32a9dc8f..fdecbe6f 100644
--- a/packages/docs/content/agent-loop.en.md
+++ b/packages/docs/content/agent-loop.en.md
@@ -1,14 +1,16 @@
---
title: The Agent Loop
-description: The context_engine's master flow diagram and a stage-by-stage breakdown — approvals, concurrent tool execution, interrupt carry-over, automatic reconnect and compaction.
+description: How session.run drives Tasks and turns: approval flow, concurrent tool execution, hooks, mid-run steering, automatic reconnect, and compaction.
---
-The SDK's single execution entry point is `session.run(newMessages, opts?)`: input is the list of new OmniMessages (the Prompt); the return value is an async generator that streams [OmniMessage](/omni-message). One `run` drives one complete Task, until the model produces a final answer with no tool calls — or several Tasks in a row, when a [stop hook](#stop-hooks) asks for more.
+The SDK's single execution entry point is `session.run(newMessages, opts?)`. The input is the list of new OmniMessages, called the Prompt. The return value is an async generator that streams [OmniMessage](/omni-message) outputs. One `run` call drives one complete Task, which ends when the model produces a final answer with no tool calls. A [stop hook](#stop-hooks) can ask for more, in which case the same `run` call drives several Tasks in a row.
-This page shows the context_engine's overall flow first, then breaks down each stage; the message-level observable timeline and ordering guarantees are on [Message Flow & Ordering](/message-flow). Source: `packages/core/src/engine/context-engine.ts`.
+This page shows the `context_engine`'s overall flow first, then breaks down each stage. The message-level observable timeline and the ordering guarantees are covered on [Message Flow & Ordering](/message-flow). Source: `packages/core/src/engine/context-engine.ts`.
## The loop at a glance
+The diagram traces one `run` call from entry to return.
+
```text
session.run(newMessages, { approve, signal })
│ carry-over from a previous interrupt? → prepend to this run's input
@@ -19,15 +21,17 @@ session.run(newMessages, { approve, signal })
│ LLM.streamGenerate(newMessages) │
│ ├─ streams partial_* fragments + complete msgs │
│ ├─ for each complete tool_call: │
+│ │ pre_tool_use hooks (if installed), then │
│ │ approve(toolCall) ──deny──► synthetic aborted output │
│ │ │allow (approvals sequential; │
│ │ ▼ decision audited) │
│ │ Environment.executeTool ──► runs concurrently, │
│ │ output streams back │
│ └─ LLMOutcome: │
-│ failed/timeout/malformed ──► reconnect within the turn │
+│ retryable ──► reconnect within the turn │
│ (≤5 fruitless, with [turn_retried]; tools not rerun) │
-│ token_usage + request_end (at LLM-stream end; not waiting │
+│ fatal ──► keep carry-over, run returns (no abort) │
+│ token_usage + request_end (at LLM-stream end; not waiting │
│ for tools) │
│ │
│ tool outputs reordered to original call order ──► next turn │
@@ -61,38 +65,75 @@ for await (const output of session.run([userText("Clean up the CSV files under d
```ts
interface RunOptions {
- signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
- approve?: ApproveFn; // per-tool approval; denies everything when omitted (conservative default)
+ signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
+ approve?: ApproveFn; // per-tool approval; denies everything when omitted (conservative default)
+ preToolUse?: PreToolUseFn; // pre-tool-use hook consult, called before approve for each complete tool_call
+}
+```
+
+The Session fills in `preToolUse` itself from the agent's installed hook packages (see [Pre-tool-use hooks](#pre-tool-use-hooks)).
+
+The generator's return value says how the run ended: `null` when it ran to completion, otherwise a `RunCutoff`:
+
+```ts
+interface RunCutoff {
+ kind: "abort" | "llm_failure" | "compaction_failure" | "max_turns";
+ errorCode?: ErrorCode;
+ errorMessage?: string;
}
```
## Lifecycle of a turn
-A Task consists of consecutive Requests (turns). Each turn:
+A Task consists of consecutive Requests, also called turns. Each turn proceeds as follows:
-1. emits `request_begin`;
-2. the LLM streams back: `partial_*` fragments followed by complete messages;
-3. every complete `tool_call` triggers exactly one `approve` callback; the decision is recorded as an `approval_decision` event;
-4. approved calls run **concurrently** in the Environment (approvals themselves are one at a time); outputs stream out in completion order;
-5. when the LLM stream ends, its final `token_usage` is emitted and `request_end(status)` follows at once — **without waiting for tools**: still-running tools may emit output after `request_end`;
-6. once the whole batch is terminal, tool results are **reordered to the original call order** and become the next turn's input — the next Request never fires before that.
+1. The engine emits `request_begin`.
+2. The LLM streams back `partial_*` fragments, followed by complete messages.
+3. Every complete `tool_call` is first offered to the installed `pre_tool_use` hooks, then triggers exactly one `approve` callback, unless a hook already decided. The decision is recorded as an `approval_decision` event.
+4. Approved calls run concurrently in the Environment. The approvals themselves happen one at a time. Tool outputs stream out in completion order.
+5. When the LLM stream ends, a completed request emits its final `token_usage`, and `request_end(status)` follows at once. This happens **without waiting for tools**: a tool that is still running may emit output after `request_end`. A request that did not complete emits no `token_usage`.
+6. Once the whole batch of tool calls is terminal, the tool results are **reordered to the original call order** and become the next turn's input. The next Request never fires before that.
-The Task ends when a turn produces no `tool_call`. A denial produces a synthetic `aborted` tool output the model reacts to — "Tool call denied by user.", or "Tool call denied by policy." when the decision is the [command policy](/configuration#command-policy)'s `forbidden` (see [ApproveFn](/interfaces#approvefn)).
+The Task ends when a turn produces no `tool_call`.
+
+A denial produces a synthetic `aborted` tool output that the model reacts to. The output text depends on what denied the call:
+
+| Denial source | Tool output the model receives |
+| --- | --- |
+| The approval callback | `Tool call denied by user.` |
+| The [command policy](/configuration#command-policy)'s `forbidden` decision (see [ApproveFn](/interfaces#approvefn)) | `Tool call denied by policy.` |
+| A `pre_tool_use` hook | `Tool call denied by the <name> hook: <reason>.` |
## Interruption and carry-over
-When `signal` fires, the engine emits an `abort` event and returns immediately, while constructing carry-over content for the next `run`:
+When `signal` fires, the engine emits an `abort` event and returns immediately. It also constructs carry-over content for the next `run` call. A request that ends `fatal` builds the same carry-over but emits no `abort` event (see [Automatic reconnect](#automatic-reconnect)).
+
+What the carry-over contains depends on how far the turn had got:
+
+| Case | When | Carry-over |
+| --- | --- | --- |
+| A | The model's output had completed: the turn's `tool_call`s were committed | Finished tool results are re-sent as structured `tool_call_output`s. Unfinished calls get an `[interrupted: tool aborted by user]` placeholder, keeping `tool_call`/output pairing strictly intact. |
+| B | The model's output was incomplete | The whole turn is flattened into one `[turn_aborted]` user text carrying whatever partial output existed. |
+
+An interruption that lands before the Request is issued keeps the input as-is as carry-over, without flattening it, so multimodal input is not lost.
+
+Carry-over enters the model context only. It is never written to the Trace, which records only what actually happened.
-- **Case A — the model's output had completed** (the turn's `tool_call`s were committed): finished tool results are re-sent as structured `tool_call_output`s; unfinished calls get an `[interrupted: tool aborted by user]` placeholder, keeping `tool_call`/output pairing strictly intact;
-- **Case B — the model's output was incomplete**: the whole turn is flattened into one `[turn_aborted]` user text carrying whatever partial output existed.
+## Hooks
-Carry-over enters the model context only — it is never written to the Trace, which records only what actually happened.
+A **hook** is a function the Session runs at a fixed point of the loop. Three points exist today:
+
+| Hook point | When it runs | Section |
+| --- | --- | --- |
+| `stop` | The moment a Task ends: the model's final reply with no tool call, or a cutoff — user abort, LLM failure, or the `max_turns` cap | [Stop hooks](#stop-hooks) |
+| `pre_tool_use` | Before each tool call's approval | [Pre-tool-use hooks](#pre-tool-use-hooks) |
+| `user_prompt` | When a prompt is submitted | [User-prompt hooks](#user-prompt-hooks) |
-## Stop hooks
+The hooks a Session consults are the hook packages installed in the agent's `agent_state/hooks/` directory. A [plugin](/skills#hook-packages) ships such packages, and the Session reads them fresh per Session, like Skills. SDK embedders can also register in-process functions through `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt`.
-A hook is a function the Session runs at a fixed point of the loop. Three points exist today: **stop** — the moment a Task ends (the model's final reply with no tool call, or a cutoff: user abort, LLM failure, the `max_turns` cap) — **`pre_tool_use`**, before each tool call's approval, and **`user_prompt`**, when a prompt is submitted (their own sections below). The hooks a Session consults are the **hook packages installed in the Agent's `agent_state/hooks/`** — what a [plugin](/skills#hook-packages) ships — read fresh per Session like skills; SDK embedders can also register in-process functions through `SessionConfig.hooks.stop` / `.preToolUse`.
+An installed hook is a plain Node script, run as a subprocess the way Claude Code runs its command hooks. The script is told only where to look; it derives everything else from the Trace: Token usage, turn counts, how the Task ended, and its own state file. A non-zero exit is a failure, and the tail of stderr becomes the reason. A timeout kills the script; the timeout comes from the manifest's `timeout` field and defaults to 60 s.
-An installed hook is a plain Node script, run as a subprocess the way Claude Code runs its command hooks: it is told only where to look, and derives everything else — token usage, turn counts, how the Task ended, its own state file — from the Trace.
+### Stop hooks
```text
stdin { "hook": "stop", "session_id": "…", "trace_path": "/abs/…/<session>_001.jsonl" }
@@ -105,19 +146,27 @@ stdout nothing = no opinion; otherwise
exit non-zero = failure (stderr's tail becomes the reason); a timeout (default 60 s) kills it
```
-`trace_path` is the Trace file being written — the current context segment; a compaction rotates to a new file — and is absent for a Trace-less Session. The rules:
+`trace_path` is the Trace file being written, which is the current context segment. A compaction rotates it to a new file. The field is absent for a Session without a Trace.
+
+The rules:
+
+- Hooks run in registration order after every Task.
+- Every non-empty answer is recorded as one [`hook` event](/omni-message#eventmsg) with the fields `hook`, `name` (the package name), `decision`, `reason` and `output`. The event is streamed and written to the Trace. The injected input is not in the event; it is the user message that follows it.
+- The first `continue` wins. Its input is stamped [`sender: "harness"`](/omni-message#modelmsg-complete-payloads) and yielded onto the stream, and it drives the next Task inside the same `run` call. A plain run never yields its own input; hosts render the injected one from the stream, and the stamp — not the text — is what says the harness sent it. With no `continue`, the call returns.
+- After a cutoff, or once the signal is aborted, a `continue` is recorded but never run. A user's interruption outranks every hook.
+- A `subagent` answer makes the Session spawn a detached background child Session. It runs the same agent, or the `agent_id` from the answer, and its first user message is the prompt. The child inherits the run's approval callback. Its stream is dropped; its own Trace is the record. Its Session id is recorded on the event as `output.session_id`.
+- A hook that fails — it crashes, prints something that is not JSON, or times out — is recorded with the error as its `reason` and treated as having no opinion. It never takes the run down.
+
+Two hook packages ship in the plugin library:
-- hooks run in registration order after every Task; every non-empty answer is recorded as one [`hook` event](/omni-message#event_msg) — `hook`, `name` (the package name), `decision`, `reason`, `output` — streamed and written to the Trace; the injected input is not in the event, it is the user message that follows it;
-- the first `continue` wins: its input is stamped [`sender: "harness"`](/omni-message#model_msg) and yielded onto the stream (a plain run never yields its own input; hosts render the injected one from the stream — the stamp, not the text, is what says the harness sent it) and drives the next Task inside the same `run` call; no `continue` means the call returns;
-- after a cutoff, or once the signal is aborted, a `continue` is recorded but never run — a user's interruption outranks every hook;
-- a `subagent` answer makes the Session spawn a detached background child Session (the same Agent, or `agent_id`) whose first user message is the prompt; it inherits the run's approval callback, its stream is dropped (its own Trace is the record), and its session id is recorded on the event as `output.session_id`;
-- a hook that fails — crashes, prints something that is not JSON, or times out — is recorded with the error as its `reason` and treated as having no opinion; it never takes the run down.
+- [Goal mode](/goal-mode): its stop hook reads the goal file, decides, and hands back the next round's protocol message.
+- The **`continual-learning`** plugin (not preinstalled): it fires when the Task that just ended ran more than 30 completed turns and the agent has at least one installed Skill. It condenses that Task into an excerpt — user and assistant text, tool calls with their arguments, and tool outputs, each clipped, with no thinking or images — and answers with a `subagent` request. The request's prompt names the skills directory and the Skills the Task invoked, and asks the child to fold the durable findings into the relevant `SKILL.md` files, or to change nothing.
-Two hook packages ship in the plugin library. [Goal mode](/goal-mode) is one: its stop hook reads the goal file, decides, and hands back the next round's protocol message. The **`continual-learning`** plugin is the other (not preinstalled): when the Task that just ended ran more than 30 completed turns, it condenses that Task — user and assistant text, tool calls with their arguments, tool outputs, each clipped, no thinking or images — into an excerpt and answers with a `subagent` request whose prompt names the skills directory and the skills the task invoked and asks the child to fold the durable findings into the relevant `SKILL.md` files, or change nothing. The window is the Task itself (its records in the Trace, from its input message; a compaction rotates the file mid-Task and the window is then what the new file holds), so a Task triggers at most once — at its end — and short Tasks never do. An Agent with no installed skill never fires it.
+The continual-learning window is the Task itself: its records in the Trace, starting from its input message. If a compaction rotates the Trace file mid-Task, the window is what the new file holds. A Task therefore triggers the hook at most once, at its end, and short Tasks never do.
### Pre-tool-use hooks
-A hook package can also name `pre_tool_use` commands (`hooks.json`, from the plugin's `hooks.pre_tool_use`). The engine consults them once per complete tool call, **before** the approval callback — the same subprocess contract, with the call inline:
+A hook package can also name `pre_tool_use` commands: they appear in its `hooks.json`, generated from the plugin's `hooks.pre_tool_use`. The engine consults them once per complete tool call, **before** the approval callback. They use the same subprocess contract, with the call itself inline:
```text
stdin { "hook": "pre_tool_use", "session_id", "trace_path",
@@ -128,46 +177,147 @@ stdout nothing = no opinion; otherwise
"output": { "…": scalars } } // the hook's own record
```
-The rules mirror the stop point's — every non-empty answer is one `hook` event, the first decision wins, a crash / non-JSON / timeout is recorded and treated as no opinion — plus three of its own:
+The rules mirror the stop point's: every non-empty answer is one `hook` event, the first decision wins, and a crash, non-JSON output or timeout is recorded and treated as no opinion. Three rules are specific to this point:
-- a **deny** refuses the call without consulting the approval callback; the model reads the refusal as the tool's output, the hook's name and `reason` included;
-- an **allow** approves without asking the host — except that the [command policy](/configuration#command-policy) still outranks it: hook packages live in agent-writable state, the policy is Project-owned security config, so a policy-vetoed call stays `forbidden` no matter what a hook answers. A deny can only ever narrow what would have run;
-- the scripts run **on the hot path** — one consult per tool call, before anything executes — so keep them fast and set a tight `timeout` in the manifest.
+- A **deny** refuses the call without consulting the approval callback. The model reads the refusal as the tool's output, with the hook's name and `reason` included.
+- An **allow** approves the call without asking the host. The [command policy](/configuration#command-policy) still outranks it: hook packages live in agent-writable state, while the policy is Project-owned security config, so a policy-vetoed call stays `forbidden` no matter what a hook answers. A deny can only ever narrow what would have run.
+- The scripts run **on the hot path**: one consult per tool call, before anything executes. Keep them fast, and set a tight `timeout` in the manifest.
-No built-in plugin ships one; the point is there for custom guards — a project-specific sandbox rule, an audit log, an allowlist that skips the approval prompt for known-safe calls.
+No built-in plugin ships one. The point exists for custom guards: a project-specific sandbox rule, an audit log, or an allowlist that skips the approval prompt for known-safe calls.
### User-prompt hooks
-The third point, `user_prompt`, expands a submitted prompt. Hooks run in core and nowhere else: the host triggers this one through `Session.runUserPromptHook(name, prompt, extras)` when it accepts a user prompt for the flow the package owns — the Session supplies its own id and scratchpad directory — and the answer's `context` is sent right behind the user's own message as a harness-stamped message (rendered as a compact collapsed card). [Goal mode's start](/goal-mode) is the one shipped use: the goal plugin's `start.mjs` is its `user_prompt` command — the server asks the Session to run it for `goal: { budget }`, it writes `GOAL.json` and answers with round 1's protocol message.
+The third point, `user_prompt`, expands a submitted prompt. These hooks run in core and nowhere else. The host triggers the point through `Session.runUserPromptHook(name, prompt, extras)` when it accepts a user prompt for the flow that the package owns. The Session supplies its own id and scratchpad directory.
```text
stdin { "hook": "user_prompt", "session_id", "scratchpad_dir", "prompt", …host extras (goal: "budget") }
stdout { "context": "<text appended after the user's message>" }
```
+The answer's `context` is sent right behind the user's own message as a harness-stamped message, which hosts render as a compact collapsed card. The call returns `null` when the package is not installed or names no `user_prompt` command. It records no `hook` event; the expansion message is the record.
+
+[Goal mode](/goal-mode) is the one shipped use. The goal plugin's `start.mjs` is its `user_prompt` command. The Server asks the Session to run it for `goal: { budget }`; the command writes `GOAL.json` and answers with round 1's protocol message.
+
## Mid-run steering
-While a Task is running, the host can queue a user message with `session.steer(input)` — an OmniMessage list, the same shape `run` takes a Prompt in — without interrupting the loop: at the next input assembly the engine delivers it as a **standalone user text message** wrapped in `[user_steering]…[/user_steering]`, sent alongside that turn's tool outputs (or alone as the continuation input when the turn produced no tool calls — the Task keeps going instead of ending). The input's user text becomes the block's body; its images follow it as ordinary user image messages, so an image with no caption is a complete steering message; on a model without vision they fold into `[attached image: <path>]` lines **inside** the block instead, exactly as a Prompt's images do (the block must stay the whole text, or the message would lose its steering identity and read as a new Task). Steering is real user input: written to Trace like any Prompt, yielded to the output stream, and replayed as ordinary turn input on resume; tool outputs are never rewritten. The queue is drained at **every** input assembly — including right after a mid-run compaction, so steering that arrives during the compaction request is delivered, never swallowed. `steer` returns `false` when no Task is running (hosts then submit a normal task); the queue is discarded only when the run exits (abort included).
+While a Task is running, the host can queue a user message with `session.steer(input)`. The input is a list of OmniMessages, the same shape `run` takes a Prompt in. Steering does not interrupt the loop. At the next input assembly, the engine delivers the queued input as part of that turn.
+
+### How a steering message is delivered
+
+- The engine wraps the input's user text in a **standalone user text message** delimited by `[user_steering]…[/user_steering]`.
+- The message is sent alongside that turn's tool outputs. When the turn produced no tool calls, the steering message is sent alone as the continuation input; the Task keeps going instead of ending.
+
+### Text and images in a steering message
+
+- The input's user text becomes the body of the `[user_steering]` block.
+- Its images follow it as ordinary user image messages, so an image with no caption is a complete steering message.
+- On a model without vision, images fold into `[attached image: <path>]` lines **inside** the block, exactly as a Prompt's images do. The block must stay the whole text; otherwise the message would lose its steering identity and read as a new Task.
+
+### Delivery guarantees
+
+- Steering is real user input: it is written to the Trace like any Prompt, yielded to the output stream, and replayed as ordinary turn input on resume. Tool outputs are never rewritten.
+- The queue is drained at **every** input assembly, including right after a mid-run compaction. Steering that arrives during the compaction request is delivered, never swallowed.
+- Queued background-task completion notices are delivered at the same assembly points, ahead of the steering, so the user's own words come last.
+- The queue is discarded only when the run exits, abort included.
+
+### The steering API
+
+| Call | Effect | Return value |
+| --- | --- | --- |
+| `session.steer(input)` | Queues the input while a Task is running | `false` when no Task is running; hosts then submit a normal task |
+| `session.unsteer(input)` | Withdraws a queued input before it is delivered | `false` once the input was delivered or the run exited |
## Input images
-An input image either rides the request as an image message or becomes an `[attached image: <path>]` line pointing at a file in the session scratchpad — the model then views it with `read_file`, and the Web restores the thumbnail from the path. The conversion is one function bound once per Session (it is the only layer that knows both the scratchpad and the model's capability), and **each input path decides for itself whether to apply it**:
+An input image either rides the request as an image message or becomes an `[attached image: <path>]` line pointing at a file in the Session scratchpad. The model then views the file with `read_file`, and the Web App restores the thumbnail from the path. The conversion is one function, bound once per Session; it is the only layer that knows both the scratchpad and the model's capability. Each input path decides for itself whether to apply it:
| Input | Folds when | Applied at |
| --- | --- | --- |
| Prompt (`run`) | the model has no vision | run entry, before Trace and title material |
| Steering (`steer`) | the model has no vision | delivery, at the turn boundary — queuing must stay synchronous, and a queue discarded on abort would otherwise leave orphan files |
-| Goal objective | **always** | before the objective is extracted, so the path lines survive every round's re-injection |
-Goal mode is the exception because its objective is re-injected as text every round: see [Goal mode](/goal-mode).
+Goal mode adds no rule of its own. Images attached to a goal ride round 1 with the user's message and fold like a Prompt's images; later rounds re-inject the objective text only. See [Goal mode](/goal-mode).
## Automatic reconnect
-Every LLM-side failure except `auth` triggers an in-run reconnect — `timeout` (transport-shaped errors: network timeouts, transport disconnects, rate limits, 5xx), `malformed` (truncated streams, JSON parse failures), and **`failed` as well** — every provider rejection that isn't an explicit credential failure, bare 403s and quota/subscription errors included. The statuses are taxonomy, not policy: the classifier only picks the label, and a gateway phrasing a transient fault its own way (`Upstream HTTP/2 stream failed`, say) or a quota that refills mid-ladder retries exactly like a network drop. Retrying a genuinely permanent error costs the ladder and ends the same way; aborting a transient one destroys the turn. Note this changes the *policy*, not the *taxonomy*: a `failed` request is still recorded as `failed` on its `request_end` and in the Cost center, rather than being relabelled a timeout. On a reconnect the engine re-sends the original input plus a `[turn_retried]` block carrying the previous partial output, so tools are never re-executed. Default limit is 5 **consecutive fruitless** reconnects with exponential backoff under a ceiling (base 2s, cap 30s: 2s, 4s, 8s, 16s, 30s ≈ 60s of total patience — one shared schedule for every retryable class, sized so transient provider failures such as restarts and rate limits get a real recovery window instead of five retries burning out in about a second, and so every planned wait clears the Web App's 2s countdown floor and stays visible); beyond that the turn settles as `failed`. An attempt that **received content** before dropping (a `terminated: other side closed (UND_ERR_SOCKET)` mid-response, say) had a working connection and a model writing into it, so its failure restarts the ladder at 2s instead of climbing it — two socket drops in one turn shouldn't add up to a reason to give up while `[turn_retried]` carries the accumulated output into every retry. The bound on that reset is a separate absolute ceiling of 20 attempts per turn, which only an endpoint that streams a little and drops every time ever reaches. `attempt` keeps counting every attempt and never rewinds when the ladder resets. Each failure's `request_end` announces the planned wait as `retry_in_ms` (same formula as the sleep) and stamps `attempt`, the authoritative 1-based ordinal of the request within its retry run (the CLI and Web App display it verbatim); the Web App renders the wait as a live countdown with "retry now" (skips the remaining wait via `Session.skipReconnectWait` — the attempt counter is unchanged) and "give up" (the ordinary abort; the engine's abort-during-backoff path ends the turn) controls; the CLI prints its own `[retry]` line. All three retryable statuses render identically — a retry the user cannot see is a stalled session with no explanation and no way out. A compaction request is an ordinary LLM request and by default retries on the same cap and ladder (an unusable summary draws on the same budget — see "Context compaction"); a compaction that gives up keeps the original context and tries again at the next trigger. Authentication errors are classified before any retry heuristic and never retry: the request ends with its own terminal status `auth` (only the model reference is fixed at Session creation — credentials are read from the current Project config when the Session loads), and the Web App disables that Session's composer until the model's credential is updated (which auto-unlocks it) or the notice is dismissed for a retry. Tool errors are never retried — they are fed back to the model as `tool_call_output` and the model decides what to do next.
+Only a `retryable` LLM failure triggers an in-run reconnect; a `fatal` one ends the run at once.
+
+### Retryable and fatal failures
+
+The `retryable` class is deliberately wide. It covers:
+
+- transport drops and idle timeouts;
+- `408`, `429` and `5xx` responses;
+- malformed or truncated responses, such as a response JSON parse failure or a cleanly truncated stream;
+- every error the classifier cannot place.
+
+The fatal detector is a deterministic allowlist. A gateway that phrases a transient fault its own way — `Upstream HTTP/2 stream failed`, say — therefore keeps its retries. The concrete cause of a retryable failure rides on the request's `error_code` (`timeout`, `network` or `malformed`) and `error_message`.
+
+A `fatal` failure stops the run at once, without retrying. It covers:
+
+- a definitive provider `4xx` rejection, such as invalid parameters or an exhausted quota; `408` and `429` are excluded from this class;
+- a credential failure (`auth`);
+- a deterministic client-side rejection, such as fast mode on a model without a fast tier (`unsupported`);
+- input that cannot be assembled into a request (`invalid_input`).
+
+An identical request can only fail the same way, so the ladder would only delay the actionable error.
+
+### How a turn is retried
+
+On a reconnect, the engine re-sends the original input plus a `[turn_retried]` block carrying the previous partial output. The block carries the accumulated output into every retry. Tools are never re-executed.
+
+### The backoff ladder
+
+The default limits and waits:
+
+| Property | Value |
+| --- | --- |
+| Consecutive fruitless reconnects allowed | 5 |
+| Backoff base | 2 s |
+| Backoff cap | 30 s |
+| Wait sequence | 2 s, 4 s, 8 s, 16 s, 30 s |
+| Total patience | ≈ 60 s |
+| Absolute ceiling per turn | 20 attempts |
+
+There is one shared schedule for every retryable failure. It is sized so that transient provider failures such as restarts and rate limits get a real recovery window, and so every planned wait clears the Web App's 2 s countdown floor and stays visible.
+
+An attempt that **received content** before dropping — a `terminated: other side closed (UND_ERR_SOCKET)` mid-response, say — had a working connection and a model writing into it. Its failure restarts the ladder at 2 s instead of climbing it, because two socket drops in one turn should not add up to a reason to give up. The bound on that reset is the separate absolute ceiling of 20 attempts per turn, which only an endpoint that streams a little and drops every time ever reaches. `attempt` keeps counting every attempt and never rewinds when the ladder resets.
+
+### When the run gives up
+
+A run gives up in two cases: a `fatal` failure, and a `retryable` failure whose retries ran out. In both, the run ends without an `abort` event, because `abort` marks only a user interruption. The `request_end` is the terminal record, and the turn's pending state is kept as carry-over for the next run.
+
+- A `fatal` failure's terminal `request_end` carries status `fatal` with `error_code` and `error_message`.
+- When the retries run out, the terminal `request_end` is `retryable`, with `attempt` and the error pair but no `retry_in_ms`. The retry input — the original input plus its `[turn_retried]` block — is kept as carry-over.
+
+Only the model reference is fixed at Session creation. Credentials are read from the current Project config when the Session loads, so after a credential failure the user updates the model's API key and sends again.
+
+### Retry status and user controls
+
+Each failure that will be retried announces the planned wait on its `request_end` as `retry_in_ms`, using the same formula as the sleep. Every failure stamps `attempt`, the authoritative 1-based ordinal of the request within its retry run; the CLI and the Web App display it verbatim. The wait is visible by design: a retry the user cannot see is a stalled session with no explanation and no way out.
+
+The Web App renders the wait as a live countdown with two controls:
+
+| Control | Effect |
+| --- | --- |
+| **Retry now** | Skips the remaining wait via `Session.skipReconnectWait`; the attempt counter is unchanged |
+| **Give up** | The ordinary abort; the engine's abort-during-backoff path ends the turn |
+
+The CLI prints its own `[retry]` line.
+
+### Retries for compaction requests
+
+A compaction request is an ordinary LLM request. By default it retries on the same cap and ladder; an unusable summary draws on the same budget (see [Compaction](#compaction)). One exception: received content never resets a compaction's ladder. A compaction that gives up keeps the original context and tries again at the next trigger.
+
+Tool errors are never retried. They are fed back to the model as `tool_call_output`, and the model decides what to do next.
## Compaction
-Compaction does more than shorten the history: **every compaction rotates in a brand-new model context**. Once it completes, the Agent's entire runtime configuration is reassembled from the Agent State as it is at that moment — exactly like a new Session's first context — and the Trace starts a new file (one Trace file always equals one model context). An edit you (or the model itself) make to the Agent's configuration mid-conversation therefore takes effect after the next compaction — with one exception: the `compaction` section itself, which the engine re-reads at every compaction checkpoint and applies to the running conversation at once.
+Compaction does more than shorten the history: **every compaction rotates in a brand-new model context**. Once it completes, the agent's entire runtime configuration is reassembled from the Agent State as it is at that moment, exactly like a new Session's first context, and the Trace starts a new file. One Trace file always equals one model context.
+
+An edit made to the agent's configuration mid-conversation therefore takes effect after the next compaction. There is one exception: the `compaction` section itself, which the engine re-reads at every compaction checkpoint and applies to the running conversation at once.
+
+### Settings, triggers and modes
Compaction settings are filled in from `system_config.yaml` by the composition layer:
@@ -180,35 +330,134 @@ interface CompactionSettings {
}
```
-Three triggers (`compaction_begin.reason`):
+Three triggers exist, recorded as `compaction_begin.reason`:
| reason | Condition |
| --- | --- |
-| `context` | last turn's `token_usage.request.total` ≥ `maxContextLength` (default 256000; the effective threshold is the smaller of that and the model's `context_window` − 2048, so a 32k local vLLM compacts at ~30.7k instead of overflowing the window first while a 1M-window model fires at the configured 256000; an entry without `context_window` derives from an assumed 128000 window, i.e. ~126k) |
+| `context` | the last turn's `token_usage.request.total` ≥ the effective context threshold |
| `turns` | Session turn count ≥ `maxSessionTurns` (default -1 = unlimited) |
| `manual` | the user runs `/compact` or calls `session.compact()` |
-Two modes: `summarize` (default) appends the compaction Prompt to the old context, extracts the `[summary]`, wraps it as a `[context_summary]` user text and continues in a **fresh model context**; `discard` simply drops the old context. System markers are written as `[tag]…[/tag]`; the earlier angle-bracket form (`<summary>`, `<context_summary>`, …) is still recognized when reading old Traces and old persisted compaction prompts. Summary extraction applies a tolerance ladder: the first non-empty `[summary]` tag pair wins; when every pair is empty, the text left after stripping the tags is used instead (rescuing models that write the body after the closing tag); with no tags at all, the whole output is used verbatim. Compaction rotates the [Trace file](/sessions-and-traces) (`_002`, `_003`, …) — one Trace file always equals one complete model context. `compactability()` probes feasibility before `session.compact()` (`ok | unsupported | empty | just_compacted`).
+The effective context threshold for the `context` trigger is the smaller of `maxContextLength` (default 256000) and the model's `context_window` − 2048. A 32k local vLLM therefore compacts at ~30.7k instead of overflowing the window first, while a 1M-window model fires at the configured 256000. An entry without a usable `context_window` — unset, or below 4096 — derives from an assumed 128000 window, i.e. ~126k.
+
+Two modes exist:
+
+| Mode | Behavior |
+| --- | --- |
+| `summarize` (default) | Appends the compaction Prompt to the old context, extracts the `[summary]`, wraps it as a `[context_summary]` user text, and continues in a fresh model context |
+| `discard` | Drops the old context. Mid-Task it waits until the Task ends, since dropping the context would lose the Task |
+
+System markers are written as `[tag]…[/tag]`. The earlier angle-bracket form (`<summary>`, `<context_summary>`, …) is still recognized when reading old Traces and old persisted compaction prompts.
+
+Summary extraction applies a tolerance ladder:
+
+1. The first non-empty `[summary]` tag pair wins.
+2. When every pair is empty, the text left after stripping the tags is used instead. This rescues models that write the body after the closing tag.
+3. With no tags at all, the whole output is used verbatim.
+
+Compaction rotates the [Trace file](/sessions-and-traces) (`_002`, `_003`, …); one Trace file always equals one complete model context. `compactability()` probes feasibility before `session.compact()` (`ok | unsupported | empty | just_compacted`).
+
+### Assembling the new context
+
+The new context is **assembled from the Agent State as it is at that moment**, exactly as a new Session's first context is. It takes:
+
+- `system_config.yaml` in full: the prompt template with its section prompts and toggles, the builtin tool entries and MCP Servers, the compaction settings, `max_turns`, and the model defaults;
+- `AGENTS.md`;
+- the vault;
+- the installed Skills' metadata;
+- the Memory indexes;
+- the schedule roster;
+- the Environment's date.
+
+An edit made during the old context — by the model working on its own configuration, or by hand in the agent settings — therefore takes effect at the next compaction rather than the next Session.
+
+### Runtime parameter tiers
+
+Runtime parameters fall into three tiers:
+
+| Tier | Parameters | Rule |
+| --- | --- | --- |
+| Strict | The system prompt, the toolset (MCP included), the model reference | Never change inside a running context. They shape the request prefix, and a context's prefix is fixed from open to close, so the provider's prompt cache stays valid across the whole Trace file. |
+| Soft | The thinking level | A purely per-request parameter, changeable mid-context and never recorded in the Trace, at the cost of the provider's cached messages. |
+| Unrestricted | The approval mode; the `compaction` section (`max_context_length`, `max_session_turns`, `mode`, `prompt`) | Re-read per decision or per compaction checkpoint. Changes apply at once and never touch the request. |
+
+- Every LLM request takes the Session's pinned thinking level: the Web App's in-chat picker, or the CLI's `--thinking` / `/thinking`. Unpinned, it takes the agent config default read when the context opened. The pickers advise compacting first because a mid-context change costs the provider's cached messages.
+- The approval mode is re-read from the database per decision, so an edit applies immediately.
+- The engine re-reads the `compaction` section from `system_config.yaml` at every compaction checkpoint: after each request reports its Token usage, and on a manual `/compact`. The read is cached by the file's mtime, so lowering an agent's threshold applies to conversations already running instead of waiting for a rotation. A read that fails keeps the settings already in force rather than failing the run.
+- Compaction settings never belonged to the request prefix: they decide when a context ends, not what it looks like.
+- The vault, a tool's `r`/`rw` permission, and the Project's command policy never reach the model. They are read once per context, on the same rotation schedule as the strict tier.
+
+### Re-equipping the Environment
+
+The Environment is re-equipped at a rotation:
+
+- The vault's values go straight into the command environment of every command spawned from then on. Processes already running keep the environment they were started with.
+- MCP Servers are cached by config. An entry that did not change keeps its live connection and discovered tools; a removed or changed one is closed. Only new, changed, or previously failed ones connect, and the wait streams as the same `mcp_connect_begin` / `mcp_connect_end` pair the first run brackets it with, followed by the new `tool_list_ready`.
+
+The rotated Trace file opens with the `session_meta` recording the prompt this context runs with, then the connect pair (if any) and the toolset record.
+
+What stays fixed for the Session's lifetime is the Session itself: its id, Workspace, model entry (credentials, window and per-model annotations included) and origin.
+
+An Agent State that cannot be assembled — a config that no longer parses — fails the run with that error, and the engine stays on the old context. This is the same error a new Session would hit. The same rule opens a context that resume finds closed by a completed compaction (see [Sessions & Traces](/sessions-and-traces)).
+
+### The compaction request
+
+The compaction request keeps the Session's toolset **unchanged**. The request prefix, tool list included, stays byte-identical to ordinary turns, so the provider's prompt cache remains valid at the moment the context is largest.
+
+Compaction succeeds only with a valid summary. A response that calls a tool, or whose extracted summary is empty, counts as one more failed attempt:
+
+- Any tool calls in such a response are answered with synthesized failed outputs, keeping `tool_use`/`tool_result` pairing intact.
+- The resent request carries a corrective note ahead of the compaction Prompt, because committed history can only be appended to; rewriting it would invalidate the prompt cache.
+
+Unusable summaries and `retryable` failures alike draw on the one reconnect budget and backoff ladder described under [Automatic reconnect](#automatic-reconnect).
+
+The first **committed** attempt — adopted or rejected — also absorbs whatever turn input was folded into the compaction request into the old context's history, such as mid-Task tool results or the carry-over a manual `/compact` folds in. Retries resend only the repairs and the Prompt; nothing resends the absorbed input afterwards.
+
+### When a compaction gives up
+
+Once the budget is exhausted, the compaction ends `retryable` — abandoned this time. It keeps the original context and Trace file until the next trigger. A `fatal` failure ends the compaction at once as `fatal`; the next trigger would hit the same wall until the configuration or credential changes. A user interruption ends it as `aborted`.
+
+`compaction_end` reuses the unified retry detail block: `attempt` (the final attempt's ordinal, failed attempts included) and, on failure, the last `error_code` and `error_message`, shown on the chat banner and the CLI line. A `retryable` or `fatal` compaction also lands in the cost center as a `compaction_failed` error record.
+
+An abandoned compaction is **made up later**, never patched over:
+
+- Mid-Task, the run ends. The turn's still-pending state is held as carry-over under the same committed/not-committed rule, and the next message resends that carry-over merged with the user's input — where the still-standing threshold triggers the compaction again. The `compaction_end` is the terminal record of such a run; an `abort` event follows only when the user interrupted the compaction.
+- At a Task boundary, the run simply ends with the original context kept.
+
+Either way, nothing synthetic is invented to keep the loop running on a context that was supposed to shrink.
+
+### Tools and a mid-Task compaction
+
+Compaction triggered **mid-Task** never preempts the tools. `runTurn` returns only once every tool call of the turn has completed, so the results are ready and paired before the checkpoint is even reached.
+
+The results then ride the compaction request itself, ahead of the compaction Prompt, in their original call order. Whatever a tool produced — a normal result, a `[tool error]`, a denial — is what the summary is written from. A tool that waits on approval or runs for minutes simply delays the compaction; no clock is running on it, because the compaction request has not been issued yet. Nothing synthetic is inserted to close the exchange.
+
+### Observing a compaction
+
+While the compaction request runs, each attempt's `token_usage`, and the thinking and summary it writes, ride the output stream. The thinking and summary appear as ordinary `partial_thinking` and `partial_text` — or the complete `thinking` / `text` for LLM implementations that stream nothing — positioned between the paired compaction events. There is no separate event type, and the compaction request's other raw messages stay Trace-only as before. The request carries the Session's pinned thinking level, exactly as every other LLM request does; with no pin, the level the model context was opened with applies.
+
+The Web App renders the compaction row like a running work group and expands exactly one of its two layers:
-The new context is **assembled from the Agent State as it is at that moment**, exactly as a new Session's first context is: `system_config.yaml` in full (the prompt template with its section prompts and toggles, the builtin tool entries and MCP Servers, the compaction settings, `max_turns`, the model defaults), `AGENTS.md`, the vault, the installed Skills' metadata, the Memory indexes, the schedule roster and the Environment's date. So an edit made during the old context — by the model working on its own configuration, or by hand in the Agent settings — takes effect at the next compaction rather than the next Session. Runtime parameters fall into three tiers. **Strict** — the system prompt, the toolset (MCP included) and the model reference never change inside a running context: they shape the request prefix, and a context's prefix is fixed from open to close, so the provider's prompt cache stays valid across the whole Trace file (the vault, a tool's `r`/`rw` permission and the Project's command policy never reach the model, but are read once per context on the same rotation schedule). **Soft** — the thinking level: a purely per-request parameter — every LLM request takes the Session's pinned level (the Web App's in-chat picker, the CLI's `--thinking` / `/thinking`) or, unpinned, the Agent config default read when the context opened; changeable mid-context and never recorded in the Trace, at the cost of the provider's cached messages, which is why the pickers advise compacting first. **Unrestricted** — the approval mode, re-read from the database per decision, never touching the request, so an edit applies immediately; and the `compaction` section (`max_context_length`, `max_session_turns`, `mode`, `prompt`), which the engine re-reads from `system_config.yaml` at every compaction checkpoint — after each request reports its token usage, and on a manual `/compact` — caching it by the file's mtime, so lowering an Agent's threshold applies to conversations already running instead of waiting for a rotation. Compaction settings never belonged to the request prefix: they decide when a context ends, not what it looks like. A read that fails keeps the settings already in force rather than failing the run. The Environment is re-equipped: the vault's values go straight into the command environment of every command spawned from then on (processes already running keep the environment they were started with); MCP Servers are cached by config — an entry that did not change keeps its live connection and discovered tools, a removed or changed one is closed, and only new, changed or previously failed ones connect, the wait streaming as the same `mcp_connect_begin` / `mcp_connect_end` pair the first run brackets it with — followed by the new `tool_list_ready`. The rotated Trace file opens with the `session_meta` recording the prompt this context runs with, then the connect pair (if any) and the toolset record. What stays fixed for the Session's lifetime is the Session itself: its id, Workspace, model entry (credentials, window and per-model annotations included) and origin. An Agent State that cannot be assembled (a config that no longer parses) fails the run with that error and the engine stays on the old context — the same error a new Session would hit. The same rule opens a context that resume finds closed by a completed compaction (see [Sessions & Traces](/sessions-and-traces)).
+- The header's title doubles as its status: **Compacting** (or **Clearing**) while it runs, **Compacted** (or **Cleared**) once done — the work-group header's own **Running**/**Done** idiom. The header also carries the wall time, ticking while it runs and settled once done.
+- While the compaction runs, the row is open and its sections are not: **Thinking** (present only when the request produced any) and **Result**, each a closed row carrying its own label and its own wall time. The reader can see that they are there and how long each is taking, without the request's raw workings landing in the transcript.
-The compaction request keeps the session's toolset **unchanged** — the request prefix (tool list included) stays byte-identical to ordinary turns, so the provider's prompt cache remains valid at the moment the context is largest. Compaction still succeeds only with a valid summary: a response that calls a tool or whose extracted summary is empty counts as one more failed attempt — any tool calls are answered with synthesized failed outputs (keeping `tool_use`/`tool_result` pairing intact), and the resent request carries a corrective note ahead of the compaction Prompt (committed history can only be appended to; rewriting it would invalidate the prompt cache). Every failure — unusable summaries and the `failed`/`timeout`/`malformed` transport statuses alike — draws on the one reconnect budget and backoff ladder described under "Automatic reconnect" above; only `auth` stops the compaction at once. Once the budget is exhausted the compaction ends `failed`, keeping the original context and Trace file until the next trigger; `compaction_end` reuses the unified retry detail block — `attempt` (the final attempt's ordinal, failed attempts included) and, on failure, the last `error_message` detail (shown on the chat banner and the CLI line) — and a failed compaction also lands in the cost center as a `compaction_failed` error record. The first **committed** attempt — adopted or rejected — also absorbs whatever turn input was folded into the compaction request (mid-Task tool results, or the carry-over a manual `/compact` folds in) into the old context's history: retries resend only the repairs and the Prompt, and nothing resends the absorbed input afterwards.
+Once the compaction settles, the row closes itself again, leaving the one-line summary. The chevron is there from the start of a summarize compaction, so the reader can open either section to watch the request work, or read the outcome afterwards.
-An abandoned compaction is **made up later**, never patched over. Mid-Task the run ends the way any interruption does: the turn's still-pending state is held as carry-over under the same committed/not-committed rule, an `abort` event closes the run, and the next message resends that carry-over merged with the user's input — where the still-standing threshold triggers the compaction again. At a Task boundary the run simply ends with the original context kept. Either way nothing synthetic is invented to keep the loop running on a context that was supposed to shrink.
+A history rebuild reads the same content back from the compaction span's recorded thinking and output, so a reload shows exactly what the live viewer saw. Consumers that render a transcript already treat model messages inside the span as compaction-internal, so nothing leaks into the conversation, and the CLI prints none of it.
-Compaction triggered **mid-Task** never preempts the tools: `runTurn` returns only once every tool call of the turn has completed, so the results are ready and paired before the checkpoint is even reached. They then ride the compaction request itself, ahead of the compaction Prompt, in their original call order — whatever a tool produced (a normal result, a `[tool error]`, a denial) is what the summary is written from. A tool that waits on approval or runs for minutes simply delays the compaction; no clock is running on it, because the compaction request has not been issued yet. Nothing synthetic is inserted to close the exchange.
+### An unfinished compaction span
-While the compaction request runs, its thinking and the summary it writes ride the output stream as ordinary `partial_thinking` and `partial_text` (or the complete `thinking` / `text`, for LLM implementations that stream nothing), positioned between the paired compaction events — no separate event type, and the compaction request's other raw messages stay Trace-only as before. The request carries the Session's pinned thinking level, exactly as every other LLM request does; with no pin, the level the model context was opened with applies. The Web App renders the compaction row like a running work group, and expands exactly one of its two layers: the header's title doubles as its status — Compacting (or Clearing) while it runs, Compacted (or Cleared) once done, the work-group header's own Running/Done idiom — and carries the wall time (ticking while it runs, settled once done); **while the compaction runs the row is open and its sections are not** — **Thinking** (present only when the request produced any) and **Result**, each a closed row carrying its own label and its own wall time, so the reader can see that they are there and how long each is taking without the request's raw workings landing in the transcript. Once the compaction settles the row closes itself again, leaving the one-line summary. The chevron is there from the start of a summarize compaction, so the reader can open either section to watch the request work, or read the outcome afterwards. A history rebuild reads the same content back from the compaction span's recorded thinking and output, so a reload shows exactly what the live viewer saw. Consumers that render a transcript already treat model messages inside the span as compaction-internal, so nothing leaks into the conversation, and the CLI prints none of it.
+A compaction the user quit out of — the process died mid-request, leaving a `compaction_begin` with no matching end — is an **abandoned compaction**. When the Session next loads, resume closes the span with a `retryable` `compaction_end` before appending anything else, and **discards the half-written summary**. Nothing is reconstructed from it, the original context stands, and the standing threshold makes the compaction up at the next trigger.
-A compaction the user quit out of — the process died mid-request, leaving a `compaction_begin` with no matching end — is simply a **failed compaction**. When the session next loads, resume closes the span with a `failed` `compaction_end` before appending anything else and **discards the half-written summary**: nothing is reconstructed from it, the original context stands, and the standing threshold makes the compaction up at the next trigger. Closing the span is what keeps the conversation that follows visible — every reader treats messages between the paired events as compaction-internal — and the Web App drops the partial draft from the row rather than showing a truncated summary as if it had been adopted.
+Closing the span is what keeps the conversation that follows visible: every reader treats messages between the paired events as compaction-internal. The Web App drops the partial draft from the row rather than showing a truncated summary as if it had been adopted.
## Concurrency model
-- Within a turn: approvals are sequential, execution is concurrent, and the next turn's input keeps the original order;
-- within a Session: only one Task or one compaction runs at a time (the Server rejects concurrent requests with 409);
-- a [Subagent](/tools) is an independent Session with its own Trace and loop; its messages are forwarded to the parent tagged with `origin`.
+- Within a turn: approvals are sequential, execution is concurrent, and the next turn's input keeps the original order.
+- Within a Session: only one Task or one compaction runs at a time. The Server answers a new Task with `409` while one is running or compacting, unless the request sets `queueIfBusy`, which queues it as a follow-up.
+- A [Subagent](/tools) is an independent Session with its own Trace and loop. Its messages are forwarded to the parent tagged with `origin`.
## Side channels
-- **Session titles**: `session.generateTitle()` is a one-shot out-of-band LLM call (no tools, no system Prompt) that never enters history or Trace;
-- **Usage accounting**: each turn's `token_usage` events are persisted row by row by the Server — the raw data behind the cost statistics.
+- **Session titles**: `session.generateTitle()` is a one-shot out-of-band LLM call — no tools, no system Prompt, thinking off. It never enters history or Trace.
+- **Usage accounting**: each turn's `token_usage` events are persisted row by row by the Server. This is the raw data behind the cost statistics.
diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.md
index 90274da6..f923eb3a 100644
--- a/packages/docs/content/agent-loop.zh.md
+++ b/packages/docs/content/agent-loop.zh.md
@@ -1,42 +1,53 @@
---
title: Agent 运行循环
-description: context_engine 的总体流程图与逐环节拆解——审批、并发工具执行、中断补发、自动重连与上下文压缩。
+description: session.run 如何驱动 Task 与轮次:审批、工具并发执行、钩子、运行中插话、自动重连与上下文压缩。
---
-SDK 的唯一执行入口是 `session.run(newMessages, opts?)`:输入本次新增的 OmniMessage 列表(Prompt),返回一个异步生成器,流式产出 [OmniMessage](/omni-message)。一次 `run` 自动跑完一个完整的 Task,直到模型给出不含工具调用的最终答复——若有 [stop hook](#stop-hook) 要求继续,则接连跑多个 Task。
+SDK 唯一的执行入口是 `session.run(newMessages, opts?)`:输入是本次新增的 OmniMessage 列表(Prompt),返回值是一个异步生成器,流式产出 [OmniMessage](/omni-message)。一次 `run` 驱动一个完整的 Task,直到模型给出不含工具调用的最终答复;若 [Stop hook](#stop-hook) 要求继续,同一次 `run` 会接连驱动多个 Task。
-本页先给出 context_engine 的总体流程,再逐环节拆解;逐条消息级的可见时序与顺序保证见[消息流转与时序](/message-flow)。源码:`packages/core/src/engine/context-engine.ts`。
+本页先给出 `context_engine` 的总体流程,再逐个环节拆解;逐条消息的可见时序与顺序保证见[消息流转与时序](/message-flow)。源码:`packages/core/src/engine/context-engine.ts`。
## 总体流程
+下图追踪一次 `run` 调用从进入到返回的全过程。
+
```text
session.run(newMessages, { approve, signal })
- │ 存在上次中断的补发内容?→ 前置到本轮输入
+ │ carry-over from a previous interrupt? → prepend to this run's input
▼
-┌── 轮循环(≤ max_turns,默认 -1 不限制)────────────────────────┐
+┌── turn loop (≤ max_turns; default -1 = no cap) ───────────────┐
│ │
│ request_begin │
│ LLM.streamGenerate(newMessages) │
-│ ├─ 流式产出 partial_* 分片 + 完整消息(thinking/text/…) │
-│ ├─ 每个完整 tool_call: │
-│ │ approve(toolCall) ──deny──► 合成 aborted 输出 │
-│ │ │allow (审批逐个;写审计事件) │
-│ │ ▼ │
-│ │ Environment.executeTool ──► 并发执行,输出流式回传 │
+│ ├─ streams partial_* fragments + complete msgs │
+│ ├─ for each complete tool_call: │
+│ │ pre_tool_use hooks (if installed), then │
+│ │ approve(toolCall) ──deny──► synthetic aborted output │
+│ │ │allow (approvals sequential; │
+│ │ ▼ decision audited) │
+│ │ Environment.executeTool ──► runs concurrently, │
+│ │ output streams back │
│ └─ LLMOutcome: │
-│ failed/timeout/malformed ──► 同轮自动重连(≤5 次连续无进展, │
-│ 附 [turn_retried],工具不重跑) │
-│ token_usage + request_end(LLM 流结束即产出,不等工具) │
+│ retryable ──► reconnect within the turn │
+│ (≤5 fruitless, with [turn_retried]; tools not rerun) │
+│ fatal ──► keep carry-over, run returns (no abort) │
+│ token_usage + request_end (at LLM-stream end; not waiting │
+│ for tools) │
│ │
-│ 工具输出按原始调用顺序重排 ──► 作为下一轮输入 │
-│ 本轮无 tool_call?──► Task 结束,run 返回 │
-│ 压缩触发(context/turns)?──► summarize/discard + Trace 轮转 │
+│ tool outputs reordered to original call order ──► next turn │
+│ no tool_call this turn? ──► Task ends │
+│ compaction trigger (context/turns)? ──► summarize/discard │
+│ + Trace rotation │
└───────────────────────────────────────────────────────────────┘
+ │
+ ▼
+stop hooks (each answer → a `hook` event; the first `continue` ──► its input
+becomes the next Task's user message, same run) ── no continue? ──► run returns
-signal 中断(任意时刻)──► 产出 abort 事件 + 构造补发内容 ──► run 返回
+signal fires (any point) ──► emit abort + build carry-over ──► run returns
```
-全程的每条消息与事件同时流向两个去处:实时输出给 Human,以及写入 [Trace](/sessions-and-traces)。
+全程的每条消息与事件同时流向两个去处:实时推给 Human,同时写入 [Trace](/sessions-and-traces)。
## 输入与输出
@@ -44,164 +55,409 @@ signal 中断(任意时刻)──► 产出 abort 事件 + 构造补发内容
const agent = await createAgent({ agentId: "default_agent" });
const session = await agent.createSession({ workspaceDir: process.cwd() });
-for await (const output of session.run([userText("整理 data/ 下的 CSV 文件")], {
+for await (const output of session.run([userText("Clean up the CSV files under data/")], {
approve: async (toolCall) => "allow",
signal: abortController.signal,
})) {
- // output: partial_* 分片、完整 model_msg、event_msg
+ // output: partial_* fragments, complete model_msg, event_msg
}
```
```ts
interface RunOptions {
- signal?: AbortSignal; // 中断信号(如 Ctrl-C)
- approve?: ApproveFn; // 逐工具审批;未注入时默认全部拒绝(保守策略)
+ signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
+ approve?: ApproveFn; // per-tool approval; denies everything when omitted (conservative default)
+ preToolUse?: PreToolUseFn; // pre-tool-use hook consult, called before approve for each complete tool_call
}
```
-## 一轮(Turn)的生命周期
+`preToolUse` 由 Session 根据 Agent 已安装的钩子包自行填入(见 [Pre-tool-use hook](#pre-tool-use-hook))。
+
+生成器的返回值说明本次运行如何结束:正常跑完为 `null`,否则是一个 `RunCutoff`:
+
+```ts
+interface RunCutoff {
+ kind: "abort" | "llm_failure" | "compaction_failure" | "max_turns";
+ errorCode?: ErrorCode;
+ errorMessage?: string;
+}
+```
+
+## 一轮的生命周期
+
+Task 由若干连续的 Request(轮)组成。每一轮:
+
+1. 引擎产出 `request_begin`。
+2. LLM 流式返回 `partial_*` 分片,随后是完整消息。
+3. 每个完整的 `tool_call` 先交给已安装的 `pre_tool_use` 钩子,再恰好触发一次 `approve` 回调(钩子已作出决定时除外);决策记为一条 `approval_decision` 事件。
+4. 通过审批的调用在 Environment 中并发执行,审批本身则逐个进行;工具输出按完成顺序流出。
+5. LLM 流结束时,正常完成的请求先产出最后一条 `token_usage`,随即产出 `request_end(status)`。这一步**不等待工具**:仍在执行的工具输出可以出现在 `request_end` 之后。未完成的请求不产出 `token_usage`。
+6. 整批工具调用全部到达终态后,工具结果**按原始调用顺序重排**,作为下一轮的输入;在此之前不会发起下一次 Request。
+
+某一轮不再产生 `tool_call` 时,Task 结束。
+
+拒绝会生成一条合成的 `aborted` 工具输出,供模型据此继续。输出文本取决于拒绝方:
+
+| 拒绝方 | 模型收到的工具输出 |
+| --- | --- |
+| 审批回调 | `Tool call denied by user.` |
+| [命令策略](/configuration#命令策略)的 `forbidden` 决策(见 [ApproveFn](/interfaces#approvefn)) | `Tool call denied by policy.` |
+| `pre_tool_use` 钩子 | `Tool call denied by the <name> hook: <reason>.` |
+
+## 中断与补发
-Task 由若干连续的 Request(轮)组成,每轮:
+`signal` 触发后,引擎产出 `abort` 事件并立即返回,同时为下一次 `run` 构造补发内容。以 `fatal` 收场的请求会构造同样的补发内容,但不产出 `abort` 事件(见[自动重连](#自动重连))。
-1. 产出 `request_begin`;
-2. LLM 流式返回:`partial_*` 分片与完整消息依次产出;
-3. 每个完整的 `tool_call` 恰好触发一次 `approve` 回调,决策以 `approval_decision` 事件记录;
-4. 通过审批的工具交给 Environment **并发执行**(审批本身逐个进行),输出按完成顺序流出;
-5. LLM 流结束时,先产出其最后一条 `token_usage`,随即产出 `request_end(status)`——**不等待工具**,仍在执行的工具输出可出现在 `request_end` 之后;
-6. 整批工具全部到达终态后,工具结果**按原始调用顺序**重排,作为下一轮输入——在此之前不会发起下一次 Request。
+补发什么,取决于这一轮进行到了哪一步:
-某轮不再产生 `tool_call` 时,Task 结束。拒绝会生成一条合成的 `aborted` 工具输出供模型据此继续——`Tool call denied by user.`,决定为[命令策略](/configuration#沙箱安全策略)的 `forbidden` 时则为 `Tool call denied by policy.`(见 [ApproveFn](/interfaces#approvefn))。
+| 场景 | 条件 | 补发内容 |
+| --- | --- | --- |
+| A | 模型输出已完成:该轮的 `tool_call` 已提交 | 已完成的工具结果按结构化 `tool_call_output` 补发;未执行完的调用补上 `[interrupted: tool aborted by user]` 占位,保证 `tool_call` 与输出严格配对。 |
+| B | 模型输出未完成 | 整轮压平为一段 `[turn_aborted]` 用户文本,携带已产生的部分输出。 |
-## 中断与补发(carry-over)
+中断若发生在 Request 发出之前,输入原样保留为补发内容,不压平,多模态输入因此不会丢失。
-`signal` 触发中断后,引擎产出 `abort` 事件并立即返回,同时为下一次 `run` 构造补发内容:
+补发内容只进入模型上下文,不写入 Trace:Trace 永远只记录真实发生的消息。
-- **场景 A:模型输出已完成**(该轮 `tool_call` 已提交)——已完成的工具结果按结构化 `tool_call_output` 补发;未执行完的调用补上 `[interrupted: tool aborted by user]` 占位,保证 `tool_call` 与输出严格配对;
-- **场景 B:模型输出未完成**——整轮压平为一段 `[turn_aborted]` 用户文本,携带已产生的部分输出。
+## 钩子
-补发内容只进入模型上下文,不写入 Trace——Trace 永远只记录真实发生的消息。
+**钩子**是 Session 在循环的固定点上执行的函数。目前有三个钩子点:
-## Stop hook
+| 钩子点 | 触发时机 | 小节 |
+| --- | --- | --- |
+| `stop` | 一个 Task 结束的那一刻:模型给出不含工具调用的最终答复,或被掐断(用户中断、LLM 失败、达到 `max_turns` 上限) | [Stop hook](#stop-hook) |
+| `pre_tool_use` | 每个工具调用审批之前 | [Pre-tool-use hook](#pre-tool-use-hook) |
+| `user_prompt` | 用户提交 Prompt 时 | [User-prompt hook](#user-prompt-hook) |
-hook 是 Session 在循环固定点上执行的函数。目前有三个点:**stop**——一个 Task 结束的那一刻(模型给出不含工具调用的最终答复,或被掐断:用户中断、LLM 故障、`max_turns` 上限)——**`pre_tool_use`**,每次工具调用审批之前,以及 **`user_prompt`**,用户提交 Prompt 之时(均见下方小节)。Session 咨询的 hook 就是**安装在 Agent `agent_state/hooks/` 里的钩子包**——[插件](/skills#钩子包)携带的那些——像 Skill 一样每个 Session 都新鲜读取;SDK 嵌入方也可以经 `SessionConfig.hooks.stop` / `.preToolUse` 注册进程内函数。
+Session 咨询的钩子,就是安装在 Agent 的 `agent_state/hooks/` 目录里的钩子包,由[插件](/skills#钩子包)携带,像 Skill 一样每个 Session 都重新读取。SDK 嵌入方也可以经 `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt` 注册进程内函数。
-已安装的 hook 是纯 Node 脚本,像 Claude Code 运行 command hook 那样以子进程运行:只告诉它去哪里看,其余一切——token 用量、轮次、Task 的结束方式、它自己的状态文件——都由它从 Trace 推导。
+已安装的钩子是纯 Node 脚本,像 Claude Code 运行 command hook 那样以子进程运行。它只被告知去哪里看,其余一切都由它从 Trace 推导:Token 用量、轮数、Task 的结束方式,以及它自己的状态文件。退出码非零即为失败,stderr 的末尾成为 reason;超时的脚本会被终止,超时时长取清单里的 `timeout`,缺省 60 秒。
+
+### Stop hook
```text
stdin { "hook": "stop", "session_id": "…", "trace_path": "/abs/…/<session>_001.jsonl" }
-stdout 空 = 无意见;否则
- { "decision": "continue" | "stop", // continue:`input` 作为下一个 Task 的 user 消息
+stdout nothing = no opinion; otherwise
+ { "decision": "continue" | "stop", // continue: `input` becomes the next Task's user message
"input": "…",
- "reason": "一行给人看的说明",
- "output": { "…": 标量 }, // hook 自己的记录
- "subagent": { "prompt": "…", "agent_id": "…" } } // 请求一个游离的后台子会话
-exit 非零 = 失败(stderr 末尾成为 reason);超时(缺省 60 秒)即被杀
+ "reason": "one line for people",
+ "output": { "…": scalars }, // the hook's own record
+ "subagent": { "prompt": "…", "agent_id": "…" } } // ask for a detached background subagent
+exit non-zero = failure (stderr's tail becomes the reason); a timeout (default 60 s) kills it
```
-`trace_path` 是正在写入的 Trace 文件——当前上下文分段;压缩会换新文件——无 Trace 的 Session 缺省。规则:
+`trace_path` 是正在写入的 Trace 文件,即当前的上下文分段;压缩会换到新文件。没有 Trace 的 Session 不带这个字段。
+
+规则如下:
+
+- 每个 Task 结束后,钩子按注册顺序逐个执行。
+- 每条非空回答都会记录为一条 [`hook` 事件](/omni-message#eventmsg),字段包括 `hook`、`name`(包名)、`decision`、`reason` 和 `output`。事件推到流上并写入 Trace。注入的输入不在事件里,它是紧随其后的那条 user 消息。
+- 第一个 `continue` 生效。它的输入带上 [`sender: "harness"`](/omni-message#modelmsg完整消息) 标记先推到流上,再在同一次 `run` 调用内驱动下一个 Task。普通运行从不产出自己的输入,宿主据流渲染这条注入的输入;说明它来自 harness 的是这一标记,而不是文本内容。无人 `continue` 时调用返回。
+- Task 被掐断之后,或 signal 已中止时,`continue` 只记录、不执行:用户的中断压过一切钩子。
+- `subagent` 回答让 Session 派生一个游离的后台子 Session(同一 Agent,或 `agent_id` 指定的 Agent),以该 prompt 为第一条 user 消息。它继承本次运行的审批回调,输出流被丢弃(它自己的 Trace 才是记录),其 Session id 以 `output.session_id` 记在事件上。
+- 钩子失败(崩溃、打印的不是 JSON,或超时)时,以错误信息为 `reason` 记录,按无意见处理,永远不会拖垮运行。
-- 每个 Task 结束后按注册顺序逐个执行;每个非空回答都记为一条 [`hook` 事件](/omni-message#event_msg)——`hook`、`name`(钩子包名)、`decision`、`reason`、`output`——推到流上并写入 Trace;注入的输入不在事件里,它是紧随其后的那条 user 消息;
-- 第一个 `continue` 生效:其输入带上 [`sender: "harness"`](/omni-message#model_msg) 标记先 yield 到流上(普通运行从不 yield 自己的输入,宿主据此渲染注入的那条——说明消息来自 harness 的是这一标记,而不是文本内容),再在同一次 `run` 调用内驱动下一个 Task;无人 `continue` 则调用返回;
-- 被掐断之后、或 signal 已中止时,`continue` 只记录、不执行——用户的中断压过一切 hook;
-- `subagent` 回答让 Session 派生一个游离的后台子 Session(同一 Agent,或 `agent_id` 指定的那个),以该 prompt 为第一条 user 消息;它继承本次运行的审批回调,输出流被丢弃(它自己的 Trace 才是记录),其 Session id 以 `output.session_id` 记在事件上;
-- hook 失败——崩溃、打印的不是 JSON、或超时——以错误信息为 `reason` 记录、按无意见处理,永远不会拖垮运行。
+插件库内置两个钩子包:
-插件库内置两个钩子包。[目标模式](/goal-mode)是其一:它的 stop hook 读目标文件、判定、交回下一轮的协议消息。**`continual-learning`** 插件是另一个(不预装):刚结束的 Task 跑了超过 30 个完成的轮次时,它把该 Task 浓缩成摘录——user 与 assistant 文本、工具调用与参数、工具输出,各自截断,不含思考与图片——并以 `subagent` 请求作答,prompt 里给出 Skill 目录与该任务调用过的 Skill 名,请子会话把值得沉淀的发现写进相关 `SKILL.md`,或什么都不改。窗口就是 Task 本身(Trace 里自它的输入消息起的记录;压缩在任务中途换文件时,窗口即新文件所含),因此一个 Task 至多触发一次——在它结束时——短任务从不触发。没有安装任何 Skill 的 Agent 不会触发。
+- [目标模式](/goal-mode):它的 stop 钩子读取目标文件、作出判定,并交回下一轮的协议消息。
+- **`continual-learning`** 插件(不预装):刚结束的 Task 跑了超过 30 个完成的轮次、且 Agent 至少装有一个 Skill 时触发。它把该 Task 浓缩成摘录(user 与 assistant 文本、工具调用与参数、工具输出,各自截断,不含思考与图片),并以 `subagent` 请求作答:prompt 里给出 Skill 目录与该 Task 调用过的 Skill,请子会话把值得沉淀的发现写进相关 `SKILL.md`,或者什么都不改。
+
+continual-learning 的窗口就是 Task 本身:Trace 里自它的输入消息起的记录;压缩在 Task 中途换了文件时,窗口即新文件所含的内容。因此一个 Task 至多在结束时触发一次,短 Task 从不触发。
### Pre-tool-use hook
-钩子包还可以声明 `pre_tool_use` 命令(`hooks.json`,来自插件的 `hooks.pre_tool_use`)。引擎在每个完整的工具调用上、**审批回调之前**咨询它们——同一套子进程契约,调用本身随 stdin 给出:
+钩子包还可以声明 `pre_tool_use` 命令,写在它的 `hooks.json` 里(由插件的 `hooks.pre_tool_use` 生成)。引擎在每个完整的工具调用上、审批回调**之前**咨询一次,沿用同一套子进程契约,调用本身随 stdin 给出:
```text
stdin { "hook": "pre_tool_use", "session_id", "trace_path",
- "tool_name": "exec_command", "tool_call_id": "…", "arguments": "<原始参数 JSON>" }
-stdout 空 = 无意见;否则
- { "decision": "allow" | "deny", // deny:拒绝该调用;allow:不询问直接放行
- "reason": "给人看的一行说明",
- "output": { "…": 标量 } } // 钩子自己的记录
+ "tool_name": "exec_command", "tool_call_id": "…", "arguments": "<raw argument JSON>" }
+stdout nothing = no opinion; otherwise
+ { "decision": "allow" | "deny", // deny: refuse the call; allow: approve it without asking
+ "reason": "one line for people",
+ "output": { "…": scalars } } // the hook's own record
```
-规则与 stop 点一致——每个非空回答记一条 `hook` 事件、第一个决定生效、崩溃 / 非 JSON / 超时按无意见记录——另有三条自己的:
+规则与 stop 点一致:每个非空回答记一条 `hook` 事件,第一个决定生效,崩溃、非 JSON 输出或超时都记录下来并按无意见处理。另有三条自己的规则:
-- **deny** 不咨询审批回调直接拒绝;模型在工具输出里读到拒绝原因,含钩子名与 `reason`;
-- **allow** 不询问宿主直接放行——但[命令策略](/configuration#沙箱安全策略)仍然压过它:钩子包在 Agent 可写的状态里,策略是 Project 持有的安全配置,被策略否决的调用无论钩子怎么答都保持 `forbidden`。deny 只会收窄、永远不会放宽;
-- 脚本跑在**热路径**上——每个工具调用执行前咨询一次——保持脚本轻快,并在清单里给出较小的 `timeout`。
+- **deny** 不咨询审批回调,直接拒绝调用;模型在工具输出里读到拒绝,其中含钩子名与 `reason`。
+- **allow** 不询问宿主,直接放行。但[命令策略](/configuration#命令策略)仍然压过它:钩子包在 Agent 可写的状态里,策略是 Project 持有的安全配置,被策略否决的调用无论钩子怎么答都保持 `forbidden`。deny 只会收窄原本会执行的范围。
+- 脚本跑在**热路径**上:每个工具调用执行前都要咨询一次。脚本要轻快,并在清单里设置较小的 `timeout`。
-没有内置插件带这个点;它留给自定义守卫——项目专属的沙箱规则、审计日志、为已知安全的调用跳过审批弹窗的放行清单。
+没有内置插件使用这个钩子点,它留给自定义守卫:项目专属的沙箱规则、审计日志,或为已知安全的调用跳过审批弹窗的放行清单。
### User-prompt hook
-第三个点 `user_prompt` 用来扩展提交的 Prompt。钩子只在 core 里运行:宿主在接受某个流程的用户 Prompt 时经 `Session.runUserPromptHook(name, prompt, extras)` 触发它——Session 自己补上 id 与 scratchpad 目录——回答里的 `context` 紧随用户自己的消息之后、以 harness 标记发出(渲染为紧凑的折叠卡片)。[目标模式的启动](/goal-mode)是唯一的内置用途:goal 插件的 `start.mjs` 就是它的 `user_prompt` 命令——服务端对 `goal: { budget }` 请 Session 运行它,它写下 `GOAL.json` 并以第一轮协议消息作答。
+第三个钩子点 `user_prompt` 用来扩展提交的 Prompt。钩子只在 core 里运行:宿主接受某个包所负责流程的用户 Prompt 时,经 `Session.runUserPromptHook(name, prompt, extras)` 触发它,Session 自己补上 id 与 scratchpad 目录。
```text
-stdin { "hook": "user_prompt", "session_id", "scratchpad_dir", "prompt", …宿主附加字段(goal 为 "budget") }
-stdout { "context": "<追加在用户消息之后的文本>" }
+stdin { "hook": "user_prompt", "session_id", "scratchpad_dir", "prompt", …host extras (goal: "budget") }
+stdout { "context": "<text appended after the user's message>" }
```
-## 运行中插话(Steering)
+回答里的 `context` 紧随用户自己的消息之后、以 harness 标记发出,渲染为紧凑的折叠卡片。包未安装、或没有声明 `user_prompt` 命令时,调用返回 `null`。这个钩子点不记 `hook` 事件,扩展出的那条消息本身就是记录。
+
+[目标模式](/goal-mode)的启动是唯一的内置用途:goal 插件的 `start.mjs` 就是它的 `user_prompt` 命令。服务端收到 `goal: { budget }` 时请 Session 运行它,它写下 `GOAL.json`,并以第 1 轮的协议消息作答。
+
+## 运行中插话
+
+Task 运行期间,宿主可以用 `session.steer(input)` 排队一条用户消息(`input` 是 OmniMessage 列表,与 `run` 接收 Prompt 的形状一致),而不打断循环。到下一次组装输入时,引擎把它随那一轮送出。
+
+### 插话消息如何送达
+
+- 引擎把它作为一条**独立的用户文本消息**送出,内容包裹在 `[user_steering]…[/user_steering]` 中。
+- 它与该轮的工具输出一起发送;该轮没有工具调用时,它单独作为继续输入发送,Task 不会就此结束。
-Task 运行期间,宿主可通过 `session.steer(input)` 排队一条用户消息而不打断循环(`input` 是 OmniMessage 列表,与 `run` 接收 Prompt 的形状一致):引擎在下一次输入组装时把它作为**独立的用户文本消息**送出,内容包裹在 `[user_steering]…[/user_steering]` 中,与该轮工具输出一起进入下一次请求(该轮没有工具调用时则单独作为继续输入,Task 不会就此结束)。输入中的用户文本成为标记块的正文,图片紧跟其后,作为普通用户图片消息送出,因此一张没有配文的图片本身就是一条完整的插话;模型不支持视觉时,图片改为折叠成 `[attached image: <path>]` 路径行写在标记块**内部**,与 Prompt 的图片走同一条路(标记块必须仍是整条文本,否则这条消息会丢掉插话身份、被当成新 Task)。插话是真实的用户输入:像 Prompt 一样写入 Trace、推送到输出流,恢复重放时按普通轮次输入处理;工具输出本身从不被改写。队列在**每次**输入组装时排空——包括运行中压缩完成后的那次,压缩请求期间到达的插话不会被吞掉。没有 Task 运行时 `steer` 返回 `false`(宿主转为发起普通 Task);仅在运行退出(含中断)时丢弃队列。
+### 插话消息中的文本与图片
+
+- 输入中的用户文本成为标记块的正文。
+- 图片紧跟其后,作为普通的用户图片消息送出,因此一张没有配文的图片本身就是一条完整的插话。
+- 模型不支持视觉时,图片折叠成 `[attached image: <path>]` 行,写在标记块**内部**,与 Prompt 的图片走同一条路。标记块必须仍是整条文本,否则这条消息会丢掉插话身份,被当成新 Task。
+
+### 送达保证
+
+- 插话是真实的用户输入:像 Prompt 一样写入 Trace、推送到输出流,恢复重放时按普通轮次输入处理;工具输出本身从不被改写。
+- 队列在**每次**组装输入时排空,包括运行中压缩完成后的那一次;压缩请求期间到达的插话照样送达,不会被吞掉。
+- 排队中的后台任务完成回报在同样的组装点送达,排在插话之前,用户自己的话总在最后。
+- 队列只在运行退出(含中断)时丢弃。
+
+### 插话 API
+
+| 调用 | 效果 | 返回值 |
+| --- | --- | --- |
+| `session.steer(input)` | Task 运行期间把输入排入队列 | 没有 Task 在运行时返回 `false`,宿主此时改为提交普通 Task |
+| `session.unsteer(input)` | 在送达之前撤回已排队的输入 | 输入已送达或运行已退出时返回 `false` |
## 输入图片
-一张输入图片要么以图片消息的形态跟着请求走,要么变成一行 `[attached image: <路径>]`,指向会话 scratchpad 里的文件——模型再用 `read_file` 去看,Web 则从路径还原出缩略图。这个转换是每个 Session 绑定一次的同一个函数(Session 是唯一同时知道 scratchpad 目录和模型能力的层),而**是否折叠由各输入路径自己决定**:
+一张输入图片要么以图片消息随请求发送,要么变成一行 `[attached image: <path>]`,指向会话 scratchpad 里的文件;模型再用 `read_file` 查看,Web App 则从路径还原缩略图。这个转换是每个 Session 绑定一次的同一个函数(Session 是唯一同时知道 scratchpad 和模型能力的层),各输入路径自行决定是否应用它:
-| 输入 | 何时折叠 | 折叠时机 |
+| 输入 | 折叠条件 | 应用时机 |
| --- | --- | --- |
-| Prompt(`run`) | 模型不支持图片 | `run` 入口,早于写 Trace 和取标题素材 |
-| 插话(`steer`) | 模型不支持图片 | 投递时,即 turn 边界——入队必须保持同步,而中断时被丢弃的队列若已折叠会留下没人读的孤儿文件 |
-| 目标(goal) | **总是** | 抽取 objective 之前,这样路径行才能活过每一轮的重新注入 |
+| Prompt(`run`) | 模型没有视觉能力 | `run` 入口,早于写 Trace 和取标题素材 |
+| 插话(`steer`) | 模型没有视觉能力 | 投递时,即轮次边界:入队必须保持同步,而且若入队时就折叠,中止时被丢弃的队列会留下孤儿文件 |
-目标模式是唯一的例外,因为它的目标每轮都作为文本重新注入:见[目标模式](/goal-mode)。
+目标模式没有自己的规则:随目标附带的图片在第 1 轮随用户消息发出,像 Prompt 的图片一样折叠;之后的轮次只重新注入目标文本。见[目标模式](/goal-mode)。
## 自动重连
-除 `auth` 外,LLM 侧的所有失败都会触发引擎内自动重连——`timeout`(传输形态的错误:网络超时、传输层断连、限流、5xx)、`malformed`(流截断、JSON 解析失败),**以及 `failed`**——凡不是明确凭据错误的供应商拒绝都在此列,普通 403 与配额/订阅错误也一样重试。终态只是分类而非策略:分类器只挑标签,用自己说法描述瞬时故障的网关(例如 `Upstream HTTP/2 stream failed`)或阶梯中途恢复的配额,都与断网一样走满同一阶梯。重试一个真正的永久错误,代价是走完退避梯度后以同样的方式收场;而把瞬时错误直接中断,则毁掉这一轮。注意改的是**策略**而非**分类**:`failed` 请求在 `request_end` 与成本中心里仍然记为 `failed`,不会被改标成超时。重连时同一次 `run` 内重发原始输入,并附加 `[turn_retried]` 块携带上一次的部分输出,避免工具重复执行。默认最多 5 次**连续无进展**的重连,指数退避并设上限(基数 2s、上限 30s:2s、4s、8s、16s、30s,总耐心约 60s——所有可重试类别共用一张时间表,按较慢的类别定基数:供应商重启、限流这类瞬时故障需要以秒计的恢复时间,旧的 250ms 基数约 7.75s 就烧完整个阶梯;每次计划等待也都达到 Web App 2s 的倒计时下限,重试始终可见);超限后该轮以 `failed` 收场。**收到过内容的尝试不计入**:一次尝试若已经吐出内容才断开(例如响应中途的 `terminated: other side closed (UND_ERR_SOCKET)`),说明连接已建立、模型已在产出,阶梯归零、从 2s 重新起步——同一轮里断两次 socket,不该被累加成放弃的理由,何况 `[turn_retried]` 会把已产出的内容一路带进每次重试。归零的兜底是另一条绝对上限:单轮总尝试 20 次,只有「每次吐几个字就断」的端点才够得着它。`attempt` 始终计的是总尝试序号,不随阶梯归零回退。每次失败的 `request_end` 会以 `retry_in_ms` 宣告计划中的等待(与实际休眠同一公式)、以 `attempt` 标注这是本轮第几次尝试(权威序号,CLI 与 Web 的重试行直接显示它),Web App 据此实时倒计时,并提供「立即重试」(经 `Session.skipReconnectWait` 跳过剩余等待——重试计数不变)与「放弃」(普通中断;引擎的退避中中断路径结束本轮)两个内联按钮,CLI 则打印自己的 `[重试]` 行。三种可重试终态的渲染完全一致——用户看不见的重试,等于一次没有任何解释、也无从退出的卡顿。压缩请求是一次普通的 LLM 请求,默认沿用同一重连上限与退避阶梯(无效摘要也计入同一预算,见「上下文压缩」一节);压缩放弃后保留原上下文、等下一次触发再试。鉴权错误在任何重试启发式之前判定、从不重试:请求以专属终态 `auth` 收场(Session 锁定的只是模型引用,凭据在会话装载时取自当前 Project 配置),Web App 据此禁用该 Session 的输入框,直到该模型的凭据被更新(更新后自动解锁)或用户点击「重试」。工具错误从不重试——它们作为 `tool_call_output` 反馈给模型,由模型决定下一步。
+只有 `retryable` 的 LLM 失败会触发同一次运行内的重连;`fatal` 失败立即结束运行。
+
+### 可重试失败与致命失败
+
+`retryable` 这一类有意划得很宽,包括:
+
+- 传输中断与空闲超时;
+- `408`、`429` 和 `5xx` 响应;
+- 解析失败或被截断的响应,例如响应 JSON 解析失败、流被干净地截断;
+- 分类器无法归类的一切错误。
+
+fatal 判定是一份确定性的白名单,所以用自己的说法描述瞬时故障的网关(例如 `Upstream HTTP/2 stream failed`)照样能重试。可重试失败的具体原因记在请求的 `error_code`(`timeout`、`network` 或 `malformed`)与 `error_message` 上。
+
+`fatal` 失败立即停止运行、不重试,包括:
+
+- 供应商确定性的 `4xx` 拒绝,例如参数无效或配额耗尽(`408` 与 `429` 除外);
+- 凭据失败(`auth`);
+- 客户端确定性的拒绝,例如在没有 fast 档位的模型上开启 fast 模式(`unsupported`);
+- 无法组装成请求的输入(`invalid_input`)。
+
+同样的请求只会以同样的方式失败,走退避阶梯只会推迟用户本可据以处理的错误信息。
+
+### 一轮如何重试
+
+重连时,引擎重发原始输入,并附加 `[turn_retried]` 块携带上一次的部分输出;这个块把累积的输出带进每一次重试,因此工具不会重复执行。
+
+### 退避阶梯
+
+默认的上限与等待时间:
+
+| 属性 | 值 |
+| --- | --- |
+| 连续无进展重连的上限 | 5 |
+| 退避基数 | 2 秒 |
+| 退避上限 | 30 秒 |
+| 等待序列 | 2 秒、4 秒、8 秒、16 秒、30 秒 |
+| 总耐心 | ≈ 60 秒 |
+| 每轮绝对上限 | 20 次尝试 |
+
+所有可重试失败共用这一张时间表。这样定是为了让供应商重启、限流这类瞬时故障有真正的恢复时间,同时每次计划等待都不低于 Web App 2 秒的倒计时下限,重试始终可见。
+
+断开前**收到过内容**的尝试(例如响应中途的 `terminated: other side closed (UND_ERR_SOCKET)`)说明连接已建立、模型正在产出,所以它的失败让阶梯从 2 秒重新起步,而不是继续攀升:同一轮里断两次 socket,不该累加成放弃的理由。给这种归零兜底的是另一条绝对上限,单轮总尝试 20 次,只有「每次吐几个字就断」的端点才够得着。`attempt` 始终累计每一次尝试,不随阶梯归零回退。
+
+### 运行何时放弃
+
+运行在两种情况下放弃:`fatal` 失败,以及重试耗尽的 `retryable` 失败。两种情况都不产出 `abort` 事件,因为 `abort` 只标记用户中断:`request_end` 即终局记录,本轮尚未了结的状态保留为下一次运行的补发内容。
+
+- `fatal` 失败的终局 `request_end` 状态为 `fatal`,并带 `error_code` 与 `error_message`。
+- 重试耗尽时,终局 `request_end` 状态为 `retryable`,带 `attempt` 与错误字段,但没有 `retry_in_ms`;重试输入(原始输入加上它的 `[turn_retried]` 块)保留为补发内容。
+
+Session 创建时锁定的只有模型引用,凭据在 Session 装载时取自当前 Project 配置,因此凭据失败后,用户更新该模型的 API key 再发送即可。
-## 上下文压缩(Compaction)
+### 重试状态与用户控制
-压缩不只是缩短历史:**每次压缩都会轮换出一个全新的模型上下文**。压缩完成后,Agent 的全部运行配置按此刻的 Agent State 重新装配——与新建 Session 的首个上下文完全相同——Trace 随之开启新文件(一个 Trace 文件恒等于一个模型上下文)。因此你(或模型自己)在对话进行中对 Agent 配置的修改,会在下一次压缩后生效——只有 `compaction` 一节例外,引擎在每个压缩检查点重读它,修改立即对进行中的对话生效。
+每个将要重试的失败都在 `request_end` 上以 `retry_in_ms` 宣告计划等待(与实际休眠同一公式),每个失败都标注 `attempt`:本次重试序列内的权威序号,从 1 开始,CLI 与 Web App 直接显示它。等待刻意做成可见的:用户看不见的重试,等于一次没有任何解释、也无从退出的卡顿。
-压缩配置由组装层从 `system_config.yaml` 填充默认值:
+Web App 把等待渲染成实时倒计时,并提供两个按钮:
+
+| 按钮 | 效果 |
+| --- | --- |
+| **立即重试** | 经 `Session.skipReconnectWait` 跳过剩余等待,尝试计数不变 |
+| **放弃** | 普通中断;引擎的退避中中断路径会结束本轮 |
+
+CLI 则打印自己的 `[retry]` 行。
+
+### 压缩请求的重试
+
+压缩请求是一次普通的 LLM 请求,默认沿用同一重连上限与退避阶梯,无效摘要也计入同一预算(见[上下文压缩](#上下文压缩));唯一的区别是收到过内容不会让压缩的阶梯归零。放弃的压缩保留原上下文,等下一次触发再试。
+
+工具错误从不重试:它们作为 `tool_call_output` 反馈给模型,由模型决定下一步。
+
+## 上下文压缩
+
+压缩不只是缩短历史:**每次压缩都会轮换出一个全新的模型上下文**。压缩完成后,Agent 的全部运行配置按此刻的 Agent State 重新装配,与新建 Session 的首个上下文完全相同,Trace 随之开启新文件。一个 Trace 文件恒等于一个模型上下文。
+
+因此,对话进行中对 Agent 配置的修改会在下一次压缩后生效。唯一的例外是 `compaction` 一节本身:引擎在每个压缩检查点重读它,修改立即对进行中的对话生效。
+
+### 设置、触发条件与模式
+
+压缩配置由组装层从 `system_config.yaml` 填充:
```ts
interface CompactionSettings {
- maxContextLength: number; // 上下文 Token 阈值(取最近一次 token_usage 的 request.total);<=0 关闭
- maxSessionTurns: number; // Session 累计轮数阈值(跨 Task 计数);<=0 不限制
+ maxContextLength: number; // context-token threshold (last token_usage's request.total); <=0 disables
+ maxSessionTurns: number; // cumulative Session turn threshold (counted across Tasks); <=0 = unlimited
mode: "summarize" | "discard";
- prompt: string; // summarize 模式使用的压缩 Prompt
+ prompt: string; // the Prompt used by summarize compaction
}
```
-三种触发方式(`compaction_begin.reason`):
+三种触发方式(记在 `compaction_begin.reason`):
+
+| reason | 条件 |
+| --- | --- |
+| `context` | 上一轮的 `token_usage.request.total` ≥ 生效的上下文阈值 |
+| `turns` | Session 轮数 ≥ `maxSessionTurns`(默认 -1,即不限) |
+| `manual` | 用户运行 `/compact` 或调用 `session.compact()` |
+
+`context` 触发的生效阈值取 `maxContextLength`(默认 256000)与模型 `context_window` − 2048 中的较小者:32k 的本地 vLLM 因此在约 30.7k 处压缩,而不是先撞上窗口上限;1M 窗口的模型则在配置的 256000 处触发。条目没有可用的 `context_window`(未配置或小于 4096)时,按 128000 的假定窗口推导,即约 126k。
+
+两种模式:
-| reason | 触发条件 |
+| 模式 | 行为 |
| --- | --- |
-| `context` | 上一轮 `token_usage.request.total` ≥ `maxContextLength`(默认 256000;生效阈值取它与模型 `context_window` − 2048 中的较小者,故 32k 的本地 vLLM 约在 30.7k 处压缩、而不是先撞上窗口硬限制,1M 窗口的模型则在配置的 256000 处触发;条目未配置 `context_window` 时按 128000 的假定窗口推导,即约 126k) |
-| `turns` | Session 轮数 ≥ `maxSessionTurns`(默认 -1,即不限) |
-| `manual` | 用户执行 `/compact` 或调用 `session.compact()` |
+| `summarize`(默认) | 向旧上下文追加压缩 Prompt,提取 `[summary]` 后包装为 `[context_summary]` 用户文本,在全新的模型上下文中继续 |
+| `discard` | 直接丢弃旧上下文。Task 进行中会等到 Task 结束再丢弃,否则这个 Task 就无法继续 |
+
+系统标记统一写作 `[tag]…[/tag]`;读取旧 Trace 与旧的持久化压缩 Prompt 时,仍识别早期的尖括号形式(`<summary>`、`<context_summary>` 等)。
+
+摘要提取自带容忍阶梯:
+
+1. 优先取第一个非空的 `[summary]` 标签对。
+2. 标签对全为空时,改取剥离标签后剩余的文本,兼容把正文写在闭合标签之后的模型。
+3. 完全没有标签时,整段输出原样使用。
+
+压缩时 [Trace 文件](/sessions-and-traces)随之轮转(`_002`、`_003`……),一个 Trace 文件恒等于一个完整的模型上下文。调用 `session.compact()` 之前,可以用 `compactability()` 探询可行性(`ok | unsupported | empty | just_compacted`)。
+
+### 组装新上下文
+
+新上下文**按此刻的 Agent State 整体装配**,与新建 Session 的首个上下文完全相同,包括:
+
+- 整份 `system_config.yaml`:提示词模板及各节提示词与开关、内置工具条目与 MCP Server、压缩配置、`max_turns`、模型默认参数;
+- `AGENTS.md`;
+- vault;
+- 已装 Skill 的元数据;
+- Memory 索引;
+- 定时任务名单;
+- 环境字段中的日期。
+
+因此旧上下文期间的修改,无论是模型改自己的配置,还是用户在 Agent 设置里手改,都在下一次压缩时生效,不必等下一个 Session。
+
+### 运行时参数分层
+
+运行参数分三层:
+
+| 层级 | 参数 | 规则 |
+| --- | --- | --- |
+| 严格层 | 系统提示词、工具集(含 MCP)、模型引用 | 在运行中的上下文内绝不改变。它们构成请求前缀,上下文的前缀自开启固定到关闭,因此整个 Trace 文件内供应商的提示词缓存始终有效。 |
+| 软限制层 | 思考等级 | 纯粹的逐请求参数,允许在上下文中途更换,不记入 Trace,代价是供应商的消息缓存失效。 |
+| 不限制层 | 审批模式;`compaction` 一节(`max_context_length`、`max_session_turns`、`mode`、`prompt`) | 逐次决策或在每个压缩检查点重读,修改立即生效,且不触及请求。 |
+
+- 每次 LLM 请求取 Session 钉住的思考等级(Web App 对话内的选择器,或 CLI 的 `--thinking` / `/thinking`),未钉住时取上下文开启时读到的 Agent 配置缺省值。选择器会提醒先压缩,因为中途更换会让供应商的消息缓存失效。
+- 审批模式逐次决策时从数据库重读,因此修改即刻生效。
+- 引擎在每个压缩检查点(每次请求回报 Token 用量之后,以及手动 `/compact` 时)从 `system_config.yaml` 重读 `compaction` 一节,并按文件 mtime 缓存,因此调低 Agent 的阈值对已在运行的对话立即生效,不必等轮换。读盘失败时沿用已生效的配置,不会让运行失败。
+- 压缩配置本就不属于请求前缀:它决定上下文何时结束,而不是上下文长什么样。
+- vault、工具的 `r`/`rw` 权限和 Project 的命令策略都不进入模型请求,但随同一轮换节奏,在每个上下文开启时读取一次。
+
+### 重新装备 Environment
+
+轮换时,Environment 随之重新装备:
+
+- vault 的值直接进入此后每条命令的子进程环境;已在运行的进程保留启动时的环境。
+- MCP Server 按配置缓存:条目未变的保持连接与已发现的工具,被删除或改动的关闭,只有新增、改动或上次连接失败的才去连接,等待期间流式发出与首次运行相同的 `mcp_connect_begin` / `mcp_connect_end` 事件对,随后是新的 `tool_list_ready`。
+
+轮转出的新 Trace 文件以记录本上下文所用提示词的 `session_meta` 开头,随后是连接事件对(如有)与工具集记录。
+
+整个 Session 生命周期内固定的只有 Session 自身:id、Workspace、模型条目(含凭据、窗口与逐模型标注)与来源。
+
+Agent State 无法装配(例如配置文件已无法解析)时,本次运行以该错误结束,引擎保持旧上下文,与新建 Session 遇到的是同一个错误。恢复时发现上下文已被完成的压缩关闭,同样按此规则开启新上下文(见 [Session 与 Trace](/sessions-and-traces))。
+
+### 压缩请求
+
+压缩请求**保持 Session 的工具集不变**:请求前缀(含工具列表)与普通轮次逐字节一致,确保上下文最大的时刻供应商的提示词缓存依然有效。
+
+只有得到有效摘要,压缩才算成功。响应里调用了工具、或提取出的摘要为空,都算一次失败的尝试:
+
+- 其中的工具调用先以合成的失败输出逐一应答,保持 `tool_use`/`tool_result` 配对完整。
+- 重发的请求在压缩 Prompt 前附加一条纠正说明:已提交的历史只能追加,改写会使提示词缓存失效。
+
+无效摘要与 `retryable` 失败共用上文[自动重连](#自动重连)中的同一重连预算与退避阶梯。
+
+首个**已提交**的尝试(无论被采纳还是被判无效)还会把折进压缩请求的本轮输入(Task 中途的工具结果,或手动 `/compact` 折入的补发内容)吸收进旧上下文的历史:重试只重发修复输出与压缩 Prompt,此后也不再重发已吸收的输入。
+
+### 压缩何时放弃
+
+预算耗尽后,压缩以 `retryable` 结束(即本次放弃),保留原上下文与 Trace 文件,等待下次触发。`fatal` 失败让压缩立即以 `fatal` 结束:配置或凭据改变之前,下次触发也会撞上同一堵墙。用户中断则以 `aborted` 结束。
+
+`compaction_end` 复用统一的重试详情块:`attempt`(最终尝试序号,失败尝试也计入),失败时还有最后一次的 `error_code` 与 `error_message`(聊天横幅与 CLI 行直接展示)。以 `retryable` 或 `fatal` 结束的压缩,还会作为一条 `compaction_failed` 错误记录进入成本中心。
+
+被放弃的压缩**留待补做**,而不是就地凑合:
+
+- Task 中途:运行结束。本轮尚未了结的状态按同一条「是否已提交」规则保留为补发内容,下一条消息把补发内容与用户输入合并重发,阈值依然超标,压缩在那里再次触发。这类运行的终局记录是 `compaction_end`,只有用户中断了压缩时才会跟着 `abort` 事件。
+- Task 边界上:直接结束本次运行,保留原上下文。
+
+两种情形都不会合成任何东西,让循环在本该缩小的上下文上硬跑下去。
+
+### 工具与 Task 中途压缩
+
+**Task 中途**触发的压缩绝不抢在工具前面:`runTurn` 要等本轮全部工具调用执行完毕才返回,因此到达检查点时结果已经就绪,也已与 `tool_call` 配对。
+
+这些结果随后随压缩请求本身发出,排在压缩 Prompt 之前,保持原始调用顺序:工具产出什么(正常结果、`[tool error]`、拒绝回执),摘要就据此写成。需要审批或要跑几分钟的工具只会让压缩延后,由于压缩请求尚未发出,没有任何计时在跑。全程不插入任何合成消息去闭合这次交换。
+
+### 观察压缩过程
+
+压缩请求运行期间,每次尝试的 `token_usage`,以及它写出的思考与摘要,都会上行到输出流,位于成对的压缩事件之间:思考与摘要以普通的 `partial_thinking` 与 `partial_text` 出现(不产出流式消息的 LLM 实现则为完整的 `thinking` / `text`)。不新增事件类型,压缩请求的其他原始消息一如既往只写 Trace。压缩请求与其他每次 LLM 请求一样携带 Session 钉住的思考等级;未钉住时取该模型上下文开启时的等级。
-两种模式:`summarize`(默认)向旧上下文追加压缩 Prompt,提取 `[summary]` 后包装为 `[context_summary]` 用户文本,在**全新的模型上下文**中继续;`discard` 直接丢弃旧上下文。系统标记统一写作 `[tag]…[/tag]`;读取旧 Trace 与旧压缩 Prompt 时仍识别早期的尖括号形式(`<summary>`、`<context_summary>` 等)。摘要提取自带容忍阶梯:优先取第一个非空的 `[summary]` 标签对;标签对全为空时,改取剥离标签后剩余的全部文本(兼容把正文写在闭合标签之后的模型);完全没有标签则整段输出照用。压缩时 [Trace 文件随之轮转](/sessions-and-traces)(`_002`、`_003`……),一个 Trace 文件恒等于一个完整模型上下文。`session.compact()` 前可用 `compactability()` 探询可行性(`ok | unsupported | empty | just_compacted`)。
+Web App 把压缩行呈现为一个运行中的工作分组,两层里只展开一层:
-新上下文**按此刻的 Agent State 整体装配**,与新建 Session 的首个上下文完全相同:整份 `system_config.yaml`(提示词模板及各节提示词与开关、内置工具条目与 MCP Server、压缩配置、`max_turns`、模型默认参数)、`AGENTS.md`、vault、已装 Skill 的元数据、Memory 索引、定时任务名单与环境字段中的日期。因此旧上下文期间的修改——模型改自己的配置,或用户在 Agent 设置里手改——在下一次压缩即生效,不必等下一个 Session。运行参数分三层。**严格层**:系统提示词、工具集(含 MCP)与模型引用在运行中的上下文内绝不改变——它们构成请求前缀,上下文的前缀自开启固定到关闭,整个 Trace 文件内提供商的提示词缓存始终有效(vault、工具的 `r`/`rw` 权限与 Project 的命令策略虽不进模型请求,也随同一轮换节奏在上下文开启时读取一次)。**软限制层**:思考等级——纯粹的每请求参数:每次 LLM 请求取 Session 钉住的等级(Web 对话内选择器、CLI 的 `--thinking` / `/thinking`),未钉住则取上下文开启时读到的 Agent 配置缺省;允许中途更换、不落 Trace,代价是提供商的消息缓存失效,因此选择器会提醒建议先压缩。**不限制层**:审批模式——逐次决策从数据库重读、从不进入请求,修改即刻生效;`compaction` 一节(`max_context_length`、`max_session_turns`、`mode`、`prompt`)同属此层——引擎在每个压缩检查点(每次请求回报 token 用量之后,以及手动 `/compact`)从 `system_config.yaml` 重读该节并按文件 mtime 缓存,因此调低阈值对已在运行的对话立即生效,不必等轮换;压缩配置本就不属于请求前缀——它决定上下文何时结束,而非上下文长什么样。读盘失败时沿用上一次读到的值,绝不让本次运行失败。Environment 随之重新装备:vault 的值直接进入此后每条命令的子进程环境(已在运行的进程保留启动时的环境);MCP Server 按配置缓存——条目未变的保持连接与已发现的工具,被删除或改动的关闭,只有新增、改动或上次失败的才连接,等待期间流式发出与首次运行相同的 `mcp_connect_begin` / `mcp_connect_end` 事件对——随后是新的 `tool_list_ready`。轮转出的新 Trace 文件以记录本上下文实际所用提示词的 `session_meta` 开头,随后是连接事件对(如有)与工具集记录。整个 Session 生命周期内固定的只有 Session 自身:id、Workspace、模型条目(含凭据、窗口与逐模型标注)与来源。Agent State 装配失败(例如配置文件已无法解析)时本次运行以该错误结束、引擎保持旧上下文——与新建 Session 遇到的是同一个错误。恢复时发现上下文已被完成的压缩关闭,同样按此规则开启(见 [Session 与 Trace](/sessions-and-traces))。
+- 组头的标题兼作状态:进行中为**压缩中**(或**清空中**),结束后为**压缩完毕**(或**清空完毕**),与工作分组组头的**运行中**/**运行完毕**同一写法;标题还带 wall time,进行中实时计时,结束后定格。
+- 压缩运行期间,该行展开,其中两节不展开:**思考**(请求产出了思考时才有)与**压缩结果**各是一条折叠的行,各自带标签与自己的 wall time。读者能看到它们存在、各花了多久,而压缩请求的原始过程不会落进正文。
-压缩请求**保持会话工具集不变**——请求前缀(含工具列表)与普通轮次逐字节一致,确保上下文最大的时刻提供商的提示词缓存依然有效。只有得到有效摘要,压缩才算成功:若响应中出现工具调用、或提取出的摘要为空,视同一次普通的失败尝试——工具调用先以合成的失败输出逐一应答(保持 `tool_use`/`tool_result` 配对完整),重发的请求在压缩 Prompt 前附加一条纠正说明(已提交的历史只能追加、不能改写,改写会使提示词缓存失效)。所有失败——无效摘要与 `failed`/`timeout`/`malformed` 传输失败——共用上文「自动重连」一节的同一重连预算与退避阶梯;只有 `auth` 会让压缩当场停止。预算耗尽后压缩以 `failed` 结束,保留原上下文与 Trace 文件,等待下次触发;`compaction_end` 复用统一的重试详情块——`attempt`(最终尝试序号,失败尝试也计入)与失败时的 `error_message` 详情(聊天横幅与 CLI 直接展示),压缩失败还会作为一条 `compaction_failed` 错误记录进入成本中心。首个**已提交**的尝试(无论被采纳还是被判无效)同时会把折叠进压缩请求的本轮输入(任务中途的工具结果、手动 `/compact` 折叠的补发内容)吸收进旧上下文:重试只重发修复输出与压缩 Prompt,此后也不再重发已吸收的输入。
+压缩结束后,该行自行收起,只留下一行摘要。summarize 压缩一开始就带上折叠箭头,读者展开任一节即可实时观看请求的过程,或事后阅读结果。
-被放弃的压缩**留待补做**,而不是就地兜底。任务中途按打断的同一套流程收场:本轮尚未了结的状态按同一条「是否已提交」规则转入 carry-over,以 `abort` 事件结束本次运行,下一条消息把 carry-over 与用户输入合并重发——阈值依然超标,压缩在那里再次触发。Task 边界上则直接结束本次运行、保留原上下文。两种情形都不合成任何东西去让循环在本该缩小的上下文上硬跑下去。
+历史重建从压缩区间已记录的思考与输出读回同一段内容,刷新后与实时视图一致。渲染对话的消费方本就把区间内的模型消息视为压缩内部消息,所以不会漏进正文,CLI 也不打印其中任何内容。
-任务中途触发的压缩绝不抢在工具前面:`runTurn` 要等本轮**全部**工具调用执行完毕才返回,因此到达压缩检查点时结果已经就绪、也已与 `tool_call` 配对。这些结果随后**随压缩请求本身**发出,排在压缩 Prompt 之前、保持原始调用顺序——工具产出什么(正常结果、`[tool error]`、被拒绝的回执),摘要就据此写成。需要审批或耗时数分钟的工具只是让压缩延后:压缩请求尚未发出,也就没有任何计时在跑。全程不插入任何合成消息去闭合该交换。
+### 未完成的压缩区间
-压缩请求运行期间,它的思考与它写出的摘要以普通的 `partial_thinking` 与 `partial_text`(不产出流式消息的 LLM 实现则为完整 `thinking` / `text`)在成对压缩事件之间上行——不新增事件类型,压缩请求的其他原始消息一如既往只写 Trace。压缩请求与其他每一次 LLM 请求一样携带 Session 钉住的思考等级;未钉住时取该模型上下文开启时的等级。Web App 的压缩行按运行中的工作分组呈现,且两层里只展开一层:组头的标题兼作状态——进行中为「压缩中」/「清空中」、结束后为「压缩完毕」/「清空完毕」,与工作分组组头的「运行中」/「运行完毕」同一写法——并带 wall time(进行中实时计时、结束后定格);**压缩运行期间该行展开、其中两节不展开**——「思考」(请求产出了思考时才有)与「压缩结果」各是一条折叠的行,各自带标签与自己的 wall time,读者能看到它们存在、各花了多久,而压缩请求的原始过程不会落进正文。压缩结束后该行自行收起,只留下一行摘要。summarize 压缩一开始就带上折叠箭头,读者展开任一节即可实时观看或事后阅读。历史重建从压缩区间已记录的思考与输出读回同一段内容,刷新后与实时视图一致。渲染对话的消费方本就把压缩区间内的模型消息视为压缩内部消息,因此不会漏进正文,CLI 也不打印其中任何内容。
+用户中途退出程序导致没写完的压缩(进程死在请求中途,留下没有配对 end 的 `compaction_begin`),就是一次**被放弃的压缩**。Session 下次加载时,恢复流程在续写任何内容之前先以 `retryable` 的 `compaction_end` 收束该区间,并**丢弃写了一半的摘要**:不做任何重建,原上下文照旧,阈值依然超标,压缩留待下次触发时补做。
-用户中途退出程序导致没写完的压缩(留下没有配对 end 的 `compaction_begin`),就是一次**压缩失败**。会话下次加载时,恢复流程在续写任何内容之前先以 `failed` 收束该区间,并**直接丢弃写了一半的摘要**:不做任何重建,原上下文照旧,阈值依然超标、压缩留待下次触发时补做。收束区间正是让其后对话保持可见的关键——所有读取方都把成对事件之间的消息当作压缩内部消息;Web 端同时丢掉那段半成品草稿,不把截断的摘要摆成像是已被采纳的样子。
+收束区间正是让其后对话保持可见的关键:所有读取方都把成对事件之间的消息当作压缩内部消息。Web App 同时从压缩行里丢掉那段半成品草稿,不把截断的摘要摆成已被采纳的样子。
## 并发模型
-- 同一轮内:审批逐个、执行并发、下一轮输入按原始顺序;
-- 同一 Session:同时只有一个 Task 或一次压缩在运行(Server 侧以 409 拒绝并发请求);
-- [Subagent](/tools) 是独立 Session,拥有自己的 Trace 与运行循环,消息以 `origin` 标记转发给父级。
+- 一轮之内:审批逐个进行,执行并发,下一轮输入保持原始顺序。
+- 同一 Session 内:同时只有一个 Task 或一次压缩在运行。Task 运行中或压缩进行中时,Server 对新 Task 返回 `409`;请求设置了 `queueIfBusy` 时,则把它作为后续任务排队。
+- [子 Agent](/tools) 是独立的 Session,拥有自己的 Trace 与运行循环,消息以 `origin` 标记转发给父级。
-## 相关旁路
+## 旁路通道
-- **Session 标题**:`session.generateTitle()` 走独立的一次性 LLM 调用(无工具、无系统 Prompt),不进入历史与 Trace;
-- **用量落账**:每轮的 `token_usage` 事件被 Server 逐条入库,构成成本统计的原始数据。
+- **Session 标题**:`session.generateTitle()` 是一次性的旁路 LLM 调用(无工具、无系统提示词、不开思考),不进入历史与 Trace。
+- **用量落账**:每轮的 `token_usage` 事件由 Server 逐条入库,构成成本统计的原始数据。
diff --git a/packages/docs/content/agents.en.md b/packages/docs/content/agents.en.md
new file mode 100644
index 00000000..f1f75af3
--- /dev/null
+++ b/packages/docs/content/agents.en.md
@@ -0,0 +1,382 @@
+---
+title: Agents
+description: Create agents, and configure their prompts, tools, Skills, hooks, memory, vault and scheduled tasks.
+---
+
+An agent is a configured assistant in a Project. Each agent has its own instructions, runtime settings, tools, Skills, hook packages, memory, vault variables and scheduled tasks, stored together as its Agent State. You create agents and change their settings on the **Agents** page.
+
+- To see the agents in a Project, see [The Agents page](#the-agents-page).
+- To add an agent, see [Create an agent with AI](#create-an-agent-with-ai) or [Create an agent manually](#create-an-agent-manually).
+- To change an agent, see [Agent settings](#agent-settings) and the section for each tab.
+- To back up, move or reset an agent, see [Overview tab](#overview-tab).
+- To delete an agent, see [Delete an agent](#delete-an-agent).
+
+## The Agents page
+
+In the sidebar, select **Agents**. The page lists every agent in the current Project. Use the search box (**Search agents: id / name / description**) to filter the list.
+
+Every Project starts with the built-in agent `default_agent`. While it is the only agent, a card below it offers to create your first one: "No agent of your own yet".
+
+Each agent card shows:
+
+- the agent's name, its id, its Agent State version (for example `v3`) and its description;
+- a row of counts: Sessions, tools, Skills, hook packages, memories, vault variables and scheduled tasks, plus when the agent was last modified. Select a count to open the matching settings tab;
+- the agent's Session activity over the last 30 days;
+- **New chat**, which starts a conversation with the agent; **Settings**, which opens its settings; an icon that opens its costs in **Cost Center**; and a delete button.
+
+When a newer kernel is available for some agents, their cards show **Kernel update needed**, and a notice at the top of the page offers **Update now** and **Dismiss**. See [Update the kernel](#update-the-kernel).
+
+You can also reach an agent from the sidebar. When conversations are grouped by agent, each agent's group header has a **New chat** button and an **Agent settings** button, and the sidebar has a **Create agent** button that opens the **Create agent** dialog.
+
+## Create an agent with AI
+
+Describe the agent you want, and an existing agent sets it up for you.
+
+1. On the **Agents** page, select **Create with AI**. The **Create an agent with AI** dialog opens.
+2. Describe what the agent does, for whom, and what it produces. To start from an example, select one under **Try an example**: **Jotting agent**, **Financial Copilot**, **Document RAG agent**, **Deep research report agent** or **Report-writing agent**.
+3. Optional: expand **Full prompt** to read the instructions that travel with your description, or select **Copy prompt**.
+4. Select **Edit in a new conversation**. A new conversation opens with the prompt filled in. Nothing is sent yet.
+5. Review the prompt and send it.
+
+The dialog shows which agent does the work: "Done by *agent* in a new conversation". It is the Project's `default_agent`, or the first agent when there is no `default_agent`.
+
+The fixed instructions tell that agent to use the `agent-initialization` Skill and to:
+
+- use the agent id you gave, or pick a short id that describes the agent, and stop instead of overwriting when that agent already exists;
+- start from `default_agent`'s configuration, set the name and description, and write the agent's role and rules into its `AGENTS.md`;
+- copy only the Skills the new agent needs from the plugin library, and leave every other agent untouched;
+- report the new agent's id, the Skills it installed, and how to start a conversation with it.
+
+The **Report-writing agent** example creates an agent with the id `report-writer`. The [Evaluation Center](/evaluation-center) has a matching Benchmark example, so you can go on to evaluate and optimize it.
+
+## Create an agent manually
+
+1. On the **Agents** page, select **Create manually**. The **Create agent** dialog opens.
+2. Optional: in **Name**, enter a name. An empty name uses the agent id.
+3. In **Agent id**, enter an id, or select **Generate with AI** beside the field to have the Project's default model derive one from the name, or from the description while the name is empty. An id is 2–64 characters long, starts with a lowercase letter, and uses only lowercase letters, digits and underscores. A proposal replaces what is in the box and stays editable. You cannot change the id later.
+4. Optional: fill in **Description**.
+5. Optional: in **Plugins**, select plugins from the plugin library to install on the new agent. Their Skills and hook packages are installed when the agent is created.
+6. Optional: in **Import Skills from a project directory**, select a directory. PenguinHarness reads the Skills under its `.agents/skills` and `.claude/skills` folders; select the ones to install. If a Skill from the directory has the same name as a Skill from a selected plugin, the directory's Skill is installed.
+7. Select **Create**. The new agent's settings open.
+
+Any Project member can create an agent.
+
+### Start from a snapshot
+
+A snapshot package is an exported Agent State. You can create an agent from one, for example to copy an agent to another Project or another machine.
+
+**Before you begin**
+
+- A snapshot package (`.tar.gz`) of the agent you want to copy. A package can be up to 14 MB. To create one, see [Export and import a snapshot](#export-and-import-a-snapshot).
+
+1. In the **Create agent** dialog, under **Initialize from a snapshot**, select **Choose a snapshot package** and pick the package. If **Agent id** is empty, it is filled in from the file name.
+2. Leave **Name** and **Description** empty to keep the values in the package, or fill them in to replace them.
+3. Select **Create**.
+
+> [!NOTE]
+> A snapshot package carries its own Skills and hooks. While a package is selected, **Plugins** and **Import Skills from a project directory** are hidden.
+
+## Delete an agent
+
+Only the Project owner can delete an agent. The built-in `default_agent` cannot be deleted.
+
+1. On the agent's card, select the delete button (**Delete agent**).
+2. Confirm.
+
+> [!WARNING]
+> Deleting an agent deletes its directory on the server, including all of its Traces. You cannot recover it.
+
+## Agent settings
+
+To open an agent's settings, select **Settings** on its card, select one of its counts, or select **Agent settings** on its group in the sidebar. The settings are organized into tabs:
+
+| Tab | What you configure |
+| --- | --- |
+| **Overview** | Name and description, Agent State snapshots, kernel updates, and restoring the default configuration |
+| **System Prompt** | `AGENTS.md` and the system prompt template |
+| **Runtime** | Turn limit, output tokens, thinking level, timeout and context compaction |
+| **Tools** | Built-in tool settings and MCP servers |
+| **Skills** | Installed Skills and the Skills prompt |
+| **Hooks** | Installed hook packages and the switch for running them |
+| **Memory** | The agent's memories and the memory prompts |
+| **Vault** | Environment variables for the agent's commands |
+| **Schedules** | Scheduled tasks |
+
+Each tab has its own address, `/agents/<agentId>?tab=<tab>`, where `<tab>` is `overview`, `prompt`, `runtime`, `tools`, `skills`, `hooks`, `memory`, `vault` or `schedules`.
+
+### Save changes
+
+On the Overview, System Prompt, Runtime and Tools tabs, and in each prompt section, select **Save** and confirm. The confirmation reads "Save these changes? They will be written to the configuration files on the server."
+
+- Most changes apply to new conversations right away, and to running conversations after their next compaction.
+- A Runtime change that touches only the context compaction fields takes effect immediately, including in running conversations.
+- Switches such as **Enable skills** save as soon as you flip them, without the **Save** button.
+
+For the file format behind these settings, see [Agent config](/configuration#agent-config).
+
+### Who can change what
+
+Any Project member can change most settings. These actions are for the Project owner only:
+
+- deleting the agent and importing a snapshot;
+- turning **Enable hooks** on or off;
+- editing vault variables, the **Enable vault** switch and the **Vault prompt**;
+- creating, editing, enabling, disabling and deleting scheduled tasks, and editing the **Enable schedules** switch and the **Schedules prompt** (members can still use **Create with AI**);
+- importing memories.
+
+## Overview tab
+
+### Edit the name and description
+
+Change **Name** or **Description**, then select **Save**.
+
+### Export and import a snapshot
+
+The **Agent State** section shows the agent's **Agent State version** and its **State path**, the folder that holds the Agent State on the server. Select the copy button to copy the path.
+
+- **Export snapshot** downloads the Agent State as a `.tar.gz` package. The package leaves out the vault, so secrets never travel in a snapshot.
+- **Import snapshot** replaces the whole Agent State with a package and adopts the version inside it, but keeps the agent's current vault. A snapshot of the current version is taken first. Only the Project owner can import. If the package's version is not newer than the current one, a **Version conflict** dialog asks you to confirm the overwrite.
+
+For how versions and snapshots work, see [Self-Improvement](/self-improvement#snapshots-and-versions).
+
+### Update the kernel
+
+An agent's kernel version records which generation of the built-in default settings its configuration is based on. An existing agent never picks up newer defaults on its own. When PenguinHarness ships newer defaults, the **Kernel** section shows the current and the latest kernel version, and the Overview tab shows a red dot.
+
+1. In the **Kernel** section, select **Update kernel**.
+2. Confirm.
+
+Tabs you have not customized are updated to the current built-in defaults. A tab you have edited stays unchanged in full and is listed in the result. The name, description, Agent State version and MCP servers are not affected. For the details, see [Kernel updates](/configuration#kernel-updates).
+
+> [!TIP]
+> To update several agents at once, select **Update now** in the notice at the top of the **Agents** page.
+
+### Restore the default configuration
+
+1. In the **Kernel** section, select **Restore default configuration**.
+2. Confirm.
+
+> [!WARNING]
+> Restoring the default configuration cannot be undone.
+
+The agent's configuration is overwritten with the current defaults: the custom system prompt, tool list, model and compaction settings, and MCP servers are all replaced. Only the name, the description and the Agent State version are kept.
+
+## System Prompt tab
+
+- **AGENTS.md** holds the agent's role, rules and working instructions.
+- **system_prompt template** is the template the system prompt is built from.
+
+Under **Available placeholders (click to insert)**, select a placeholder to insert it at the cursor in the template:
+
+| Placeholder | Inserts |
+| --- | --- |
+| `{{AGENTS_MD}}` | The `AGENTS.md` content |
+| `{{VAULT}}` | The vault section: the **Vault prompt** with the list of vault variable names; empty when **Enable vault** is off |
+| `{{SKILLS}}` | The Skills section: the **Skills prompt** with the installed Skills' metadata; empty when **Enable skills** is off |
+| `{{MEMORY}}` | The memory section: the main memory prompt, plus the workspace addendum in persistent workspaces; empty when memory is off |
+| `{{SCHEDULES}}` | The scheduled tasks section: the **Schedules prompt** with the task names; empty when **Enable schedules** is off |
+| `{{PLATFORM}}` | The runtime platform |
+| `{{OS_VERSION}}` | The operating system version |
+| `{{SHELL}}` | The shell used to run commands |
+| `{{DATE}}` | The current date |
+| `{{PROJECT_DIR}}` | The PenguinHarness app data root, which holds all agents' data and Project data; not the task's working directory |
+| `{{AGENT_ID}}` | The agent's id |
+| `{{CWD}}` | The absolute Workspace path |
+| `{{PROVIDER}}` | The model's provider group |
+| `{{MODEL_ID}}` | The upstream model id |
+| `{{SESSION_ID}}` | The Session id |
+
+The switches and prompts for the vault, Skills, memory and scheduled tasks sections are on their own tabs. See also [System prompt placeholders](/configuration#system-prompt-placeholders).
+
+## Runtime tab
+
+| Field | Meaning |
+| --- | --- |
+| `max_turns` | The most turns one Task may take; `-1` means unlimited |
+| `model.max_tokens` | The output token limit per request |
+| `model.thinking_level` | `low`, `medium`, `high`, `xhigh` or `max`. A new agent uses `medium`. `xhigh` and `max` behave like the tier below them on some models. An agent that stored the old `none` tier keeps it, but it is no longer offered |
+| `model.timeoutMs` | How long to wait between events from the model provider, in milliseconds; not a limit on the whole request |
+| `max_context_length` | The context size that triggers compaction |
+| `max_session_turns` | The number of turns that triggers compaction |
+| `mode` | `summarize` (the default) has the model summarize the old context and continues from the summary in a fresh window; `discard` drops the old context without a summary |
+| `prompt` | The prompt used to summarize the context |
+
+`max_turns` and `model.timeoutMs` accept a number greater than 0, or `-1`. For how the thinking level works on each model, see [Thinking levels](/models#thinking-levels). For compaction, see [Compaction](/agent-loop#compaction).
+
+## Tools tab
+
+### Built-in tools
+
+The table lists the built-in tools. For each tool you can set:
+
+| Column | Meaning |
+| --- | --- |
+| `permission` | **Read-only** (`r`): the tool only reads, and the read-only approval mode approves it automatically. **Read & write** (`rw`): the tool can change things, and the read-only approval mode asks you first |
+| `timeoutMs` | The tool's time limit, in milliseconds |
+| `maxOutputLength` | The most output the tool may return |
+| `call_description` | Whether the model writes a one-sentence description of each call, which is shown to you while the call runs. On by default; only tools that accept a description can be switched |
+
+Leave a field empty to use the default. Select **Save** to save the table. For the approval modes, see [Approval](/tools#approval).
+
+### Add an MCP server
+
+MCP servers add external tools to the agent. Their tools are named `mcp__<name>__<tool>`. Changes in the **MCP Servers** section save immediately.
+
+1. On the **Tools** tab, select **Add MCP Server**.
+2. Choose the transport:
+ - `http`, the default: Streamable HTTP, the current remote transport.
+ - `stdio`: a local process that PenguinHarness starts and talks to over stdin and stdout.
+ - `sse`: the legacy HTTP+SSE transport, for servers that have not migrated.
+3. In **name**, enter the tool-name prefix. Use letters, digits, `_` and `-`, starting with a letter or digit.
+4. Fill in the connection fields:
+ - For `stdio`: **command**; **args**, one argument per line; **env**, one `KEY=value` per line; and **cwd**, which defaults to the Session's Workspace. The agent's vault variables are not passed to MCP server processes.
+ - For `http` and `sse`: **url**, and **headers**, one `Header-Name: value` per line, for example an `Authorization` header.
+5. Choose **permission**:
+ - **Auto (readOnlyHint)**: each tool is read-only if it declares the `readOnlyHint` annotation, and read & write otherwise.
+ - **Read-only**: every tool of the server is treated as read-only.
+ - **Read & write**: every tool of the server is treated as read & write.
+6. Optional: adjust **connectTimeoutMs** (connecting and discovering tools, 10000 by default), **timeoutMs** and **maxOutputLength**, which apply to every tool of the server.
+7. Optional: select **Test connection** to try the settings before you save. It reports the number of tools found and how long it took.
+8. Select **Save**.
+
+> [!NOTE]
+> The permission level matters only in the read-only approval mode; the other approval modes ignore it. It does not restrict what the server can do: marking a server read-only only skips the confirmation that mode would ask for.
+
+To change a server, select **Edit** on its row. To remove it, select **Remove** and confirm; its tools stop being available from the next Session. For more about MCP servers, see [MCP Servers](/tools#mcp-servers).
+
+### Test MCP servers
+
+1. In the **MCP Servers** section, select **Test connection**.
+2. Select **Start test**.
+
+PenguinHarness connects to each server in turn and discovers its tools. Nothing is saved. Each row shows the number of tools and the time taken, or **Connection failed** with the reason.
+
+## Skills tab
+
+The **Skills** tab lists the Skills installed on the agent. You can export or uninstall a Skill, import one with **Import skill**, turn the Skills section of the system prompt on or off with **Enable skills**, and edit the **Skills prompt**. See [Manage an agent's Skills](/skills#manage-an-agents-skills).
+
+## Hooks tab
+
+The **Hooks** tab lists the hook packages installed on the agent. You can export and uninstall hook packages, import one with **Import hook**, and turn hooks on or off for the agent with **Enable hooks**. Installing from the library happens on the **Plugins** page. See [Hook packages](/skills#hook-packages).
+
+## Memory tab
+
+Memory lets an agent keep what it learns across Sessions. The agent saves what is worth keeping as it works, and you can ask it to remember something. **User memory** applies to all of the agent's Sessions; Workspace memory is kept separately for each Workspace.
+
+- **Enable memory** turns memory on or off. It saves immediately. Turning it off only stops memory from entering the agent's context and from being prepared for new Sessions; it deletes nothing.
+- If the system prompt template has no `{{MEMORY}}` placeholder, the tab says so. Select **Insert the {{MEMORY}} placeholder** to add it. This happens with agents created before memory existed.
+
+The memories are grouped by scope: **User memory** first, then one group per Workspace. Select a group's header to collapse or expand it; the browser remembers the choice for each user, Project and agent.
+
+### View, edit and delete memories
+
+Each memory row has three buttons:
+
+- **View** shows the memory's title, date, description and content in a side panel, or on narrow screens in a sheet from the bottom that opens at half or full height.
+- **Edit** opens the **Edit memory** dialog. Describe the change in **What to change** (optional), then select **Open a new chat**. A new conversation with this agent opens with the prompt filled in; for a Workspace memory, it also uses that Workspace. Send the message, and the agent updates the memory file and its `MEMORY.md` index together.
+- **Delete** deletes the memory after you confirm, and removes its line from `MEMORY.md`.
+
+Memory content is changed through the agent in a chat, not edited in place.
+
+### Add a memory
+
+1. On a group's header, select **Add**. The **Add memory** dialog opens.
+2. In **Content or source to remember**, paste the content, or a file path or URL.
+3. Select **Open a new chat**, then send the message. The agent organizes the content into memories in that group.
+
+### Export and import memories
+
+- **Export** on a group's header downloads every memory in the group, with the group's `MEMORY.md`, as one JSON file. The file name includes the export date and time, so repeated exports do not overwrite each other.
+- **Import** on a group's header reads such a file back into the group. Only the Project owner can import.
+
+When you import, choose what happens when the group already has a memory with the same name:
+
+| Option | Result |
+| --- | --- |
+| **Keep the one that is here** (default) | Adds only what the group does not have. Nothing is lost |
+| **Take the file's version** | Replaces same-named memories. Memories the file does not carry are left alone |
+| **Replace the whole group** | Deletes every memory the file does not carry |
+
+If the import would overwrite or delete memories, or replace the group's `MEMORY.md`, a **Confirm the import** dialog lists what changes first.
+
+### Memory prompts
+
+Under **Memory prompt**, edit the text that the `{{MEMORY}}` placeholder expands to:
+
+- **Main prompt** (`memory.prompt`) is injected into every Session.
+- **Workspace addendum** (`memory.workspace_prompt`) is injected only into Sessions with a persistent Workspace.
+
+The prompts can use `{{USER_MEMORY_INDEX}}` (the user `MEMORY.md` index), `{{WORKSPACE_MEMORY_INDEX}}` (the Workspace `MEMORY.md` index) and `{{WORKSPACE_MEMORY_DIR}}` (the current Workspace's memory folder). The last two work only in the workspace addendum. Each index is cut at 200 lines and 25,000 characters.
+
+The memory count on the agent's card opens this tab.
+
+## Vault tab
+
+The vault holds environment variables for the agent, such as API keys. PenguinHarness passes them to the agent's shell commands. The model sees the variable names, never their values. Subagents use their own vaults and do not inherit this one. Changes take effect from the next Task; a Task that is already running is not affected.
+
+Only the Project owner can change the vault. Members see the variable names with masked values.
+
+### Add a variable
+
+1. On the **Vault** tab, select **Create manually**. The **Add variable** dialog opens.
+2. In **Name**, enter the variable name, for example `OPENAI_API_KEY`. Use letters, digits and underscores, not starting with a digit.
+3. In **Value**, enter the value.
+4. Select **Add**. If the variable already exists, confirm to overwrite its value.
+
+To delete a variable, select **Remove** on its row and confirm. The value cannot be recovered.
+
+### Add variables with AI
+
+**Create with AI** opens **Add secrets with AI**. Describe the variables you need, or pick an example: **Find the keys this agent needs**, **Reset an expired token** or **Connect an internal service**. Then select **Edit in a new conversation** and send the prompt. The Project's default agent writes the variables with `penguin config vault set`.
+
+> [!WARNING]
+> A secret value you type into this dialog is sent to the model provider, recorded in the conversation's Trace, and shown again in the command the agent runs. The safer way is to let AI create only the variable names and explain what each is for, then fill in the values on the **Vault** tab yourself.
+
+### Vault prompt
+
+- **Enable vault** controls whether the vault section enters the system prompt. With it off, the variables still reach the agent's commands.
+- **Vault prompt** is the text that the `{{VAULT}}` placeholder expands to. Its `{{VAULT_KEYS}}` placeholder lists the variable names, one per line.
+
+## Schedules tab
+
+A scheduled task sends a prompt to the agent on a schedule: once, or every period. Changes made on this tab take effect immediately.
+
+> [!NOTE]
+> Scheduled tasks fire only while the PenguinHarness service is running.
+
+You can also create and manage scheduled tasks from a conversation; see [Scheduled tasks](/schedules).
+
+### Create a scheduled task
+
+Only the Project owner can create a task manually.
+
+1. On the **Schedules** tab, select **Create manually**. The **New scheduled task** dialog opens.
+2. In **Name**, enter the task's file name, without `.toml`. You cannot change it later.
+3. In **Period**, enter how often the task runs, such as `30m`, `12h` or `7d`. Leave it empty for a one-off task. The shortest period is 5 minutes.
+4. Set **Start at**, and optionally **End at**.
+5. Under **Target**, choose where the prompt goes:
+ - **New session each time**: every run starts a new Session. Optionally choose a **Model** (the Project default if you choose none) and a **Workspace** (a temporary Workspace if you leave it empty).
+ - **Bound Session**: every run goes to one existing Session. Choose it in **Session**.
+6. In **Prompt**, enter what to send.
+7. Leave **Enabled** selected to activate the task, then select **Create**.
+
+To create a task by describing it instead, select **Create with AI**, or pick one of the **Suggestions** shown when the list is empty: **Daily brief**, **Weekly review**, **Follow-up reminder** or **Monitor for updates**. Then select **Edit in a new conversation** and send the prompt. The Project's default agent creates the task for this agent. Any member can use **Create with AI**.
+
+### Manage scheduled tasks
+
+The table shows each task's **Name**, **Status**, **Period**, **Target**, **Next / last fired** and **Queue**. The status is **Active**, **Disabled**, **Expired**, **Done**, **Missed** or **Invalid**; point at **Invalid** to see why.
+
+On each row, the owner can select **Disable** or **Enable**, **Edit**, or **Delete**. Files that cannot be parsed are listed under **Files that failed to parse (skipped by the scheduler)**.
+
+### Schedules prompt
+
+- **Enable schedules** controls whether the scheduled tasks section enters the system prompt. With it off, tasks still run.
+- **Schedules prompt** is the text that the `{{SCHEDULES}}` placeholder expands to. It teaches the model to manage scheduled tasks with its file tools, and its `{{SCHEDULE_LIST}}` placeholder lists the task names.
+
+## How it works
+
+An agent's configuration and data live in its Agent State, the `agent_state/` folder that the Overview tab shows as **State path**. It holds `system_config.yaml`, `AGENTS.md`, the vault, tools, Skills, hook packages, scheduled tasks and memories. The agent's Traces are stored next to it, in the agent's own folder; see [Data layout](/sessions-and-traces#data-layout).
+
+- Memories are files under `agent_state/memory/`, with a `MEMORY.md` index for each group. For how memory is stored, see [Memory](/configuration#memory).
+- Vault variables are stored in `agent_state/.vault.toml`. For the file format, see [Vault](/configuration#vault).
+- Scheduled tasks are stored as TOML files under `agent_state/schedule/`, which you can also edit by hand. For the file format, see [Schedules](/configuration#schedules).
diff --git a/packages/docs/content/agents.zh.md b/packages/docs/content/agents.zh.md
new file mode 100644
index 00000000..e84ce981
--- /dev/null
+++ b/packages/docs/content/agents.zh.md
@@ -0,0 +1,382 @@
+---
+title: 智能体
+description: 创建 Agent,配置它的提示词、工具、Skill、钩子、记忆、密钥保险柜和定时任务。
+---
+
+Agent 是 Project 里配置好的助手。每个 Agent 都有自己的指令、运行参数、工具、Skill、钩子包、记忆、密钥保险柜变量和定时任务,这些内容存放在一起,构成它的 Agent State。创建 Agent、修改设置,都在**智能体**页面上完成。
+
+- 要查看 Project 里的 Agent,见[智能体页面](#智能体页面)。
+- 要添加 Agent,见[用 AI 创建 Agent](#用-ai-创建-agent) 或[手动创建 Agent](#手动创建-agent)。
+- 要修改 Agent,见 [Agent 设置](#agent-设置)和各标签页对应的章节。
+- 要备份、迁移或重置 Agent,见[概览标签页](#概览标签页)。
+- 要删除 Agent,见[删除 Agent](#删除-agent)。
+
+## 智能体页面
+
+在侧边栏选择**智能体**。页面列出当前 Project 里的所有 Agent。可以用搜索框(**搜索 Agent:id / 名称 / 描述**)过滤列表。
+
+每个 Project 都自带内置 Agent `default_agent`。当它还是唯一的 Agent 时,它下方会出现一张卡片,提示你创建第一个自己的 Agent:「还没有自己的智能体」。
+
+每个 Agent 卡片显示:
+
+- Agent 的名称、id、Agent State 版本(例如 `v3`)和描述;
+- 一排数字:Session、工具、Skill、钩子包、记忆、密钥保险柜变量、定时任务的数量,以及最近一次修改的时间。点击任一数字即可打开对应的设置标签页;
+- 这个 Agent 最近 30 天的 Session 活动;
+- **新建对话**:和这个 Agent 开始对话;**设置**:打开它的设置;一个图标:在**成本中心**查看成本;以及一个删除按钮。
+
+部分 Agent 有新内核可用时,卡片上会显示**内核需要更新**,页面顶部的通知会提供**现在升级**和**忽略**。见[更新内核](#更新内核)。
+
+也可以从侧边栏进入某个 Agent。对话按 Agent 分组显示时,每个分组标题上有**新建对话**和 **Agent 设置**按钮;侧边栏还有**创建 Agent** 按钮,点击打开**创建 Agent** 对话框。
+
+## 用 AI 创建 Agent
+
+描述你想要的 Agent,一个现有的 Agent 会替你把它创建出来。
+
+1. 在**智能体**页面选择**用 AI 创建**,打开**用 AI 创建 Agent** 对话框。
+2. 描述这个 Agent 做什么、为谁服务、产出什么。想从示例开始,就在**试试这些示例**下选一个:**随记智能体**、**金融 Copilot**、**文档 RAG 智能体**、**深度研究报告智能体**或**报告写作智能体**。
+3. 可选:展开**完整提示词**,查看会随描述一起发送的指令;也可以选择**复制提示词**。
+4. 选择**在新对话中编辑**。会打开一个新对话,提示词已填好,此时还没有发送。
+5. 检查提示词并发送。
+
+对话框会写明由哪个 Agent 执行:「将由『*Agent*』在新对话中完成」。执行者是 Project 的 `default_agent`;没有 `default_agent` 时,用第一个 Agent。
+
+固定指令要求执行 Agent 使用 `agent-initialization` Skill,并且:
+
+- 使用你给定的 Agent id,或者起一个简短、能体现用途的 id;如果这个 Agent 已经存在,就停下来,不要覆盖;
+- 以 `default_agent` 的配置为基础,设置名称和描述,把新 Agent 的角色和规则写进它的 `AGENTS.md`;
+- 只从插件库复制新 Agent 需要的 Skill,其他 Agent 一概不动;
+- 报告新 Agent 的 id、安装了哪些 Skill,以及怎样和它开始对话。
+
+**报告写作智能体**示例会创建 id 为 `report-writer` 的 Agent。[评估中心](/evaluation-center)里有配套的 Benchmark 示例,创建后可以继续对这个 Agent 做评估和优化。
+
+## 手动创建 Agent
+
+1. 在**智能体**页面选择**手动创建**,打开**创建 Agent** 对话框。
+2. 可选:在**名称**中填写名称。名称留空时用 Agent id。
+3. 在 **Agent id** 中输入 id,也可以点击输入框旁边的**用 AI 生成**,由 Project 的默认模型根据名称生成一个;名称为空时则根据描述生成。id 长度为 2–64 个字符,以小写字母开头,只能用小写字母、数字和下划线。生成的 id 会覆盖框里原有的内容,之后仍可以手动修改。创建后 id 不能再改。
+4. 可选:填写**描述**。
+5. 可选:在**插件**中从插件库选择要装到新 Agent 上的插件。Agent 创建时会一并装上这些插件的 Skill 和钩子包。
+6. 可选:在**从项目目录导入技能**中选择一个目录。PenguinHarness 会读取这个目录下 `.agents/skills` 和 `.claude/skills` 文件夹里的 Skill,从中勾选要安装的。目录里的 Skill 与所选插件里的 Skill 同名时,装的是目录里的那个。
+7. 选择**创建**,打开新 Agent 的设置。
+
+任何 Project 成员都能创建 Agent。
+
+### 从快照创建
+
+快照包是导出的 Agent State。可以基于它创建 Agent,例如把 Agent 复制到另一个 Project 或另一台机器。
+
+**开始之前**
+
+- 要复制的 Agent 的快照包(`.tar.gz`)。单个包最大 14 MB。制作方法见[导出和导入快照](#导出和导入快照)。
+
+1. 在**创建 Agent** 对话框中,在**从快照初始化**下点击**选择快照包**,选定包文件。**Agent id** 为空时,会按文件名自动填入。
+2. **名称**和**描述**留空则沿用包里的值,填写则覆盖。
+3. 选择**创建**。
+
+> [!NOTE]
+> 快照包自带 Skill 和钩子。选定快照包后,**插件**和**从项目目录导入技能**会隐藏。
+
+## 删除 Agent
+
+只有 Project owner 能删除 Agent。内置的 `default_agent` 不能删除。
+
+1. 在 Agent 卡片上选择删除按钮(**删除 Agent**)。
+2. 确认。
+
+> [!WARNING]
+> 删除 Agent 会删除它在服务端的目录,包括全部 Trace,删除后无法恢复。
+
+## Agent 设置
+
+要打开某个 Agent 的设置,可以在卡片上选择**设置**,可以点击卡片上的某个数字,也可以在侧边栏对应分组上选择 **Agent 设置**。设置分为几个标签页:
+
+| 标签页 | 配置内容 |
+| --- | --- |
+| **概览** | 名称和描述、Agent State 快照、内核更新、还原为默认配置 |
+| **系统提示词** | `AGENTS.md` 和系统提示词模板 |
+| **运行参数** | 轮次上限、输出 Token、思考等级、超时和上下文压缩 |
+| **工具** | 内置工具设置和 MCP Server |
+| **技能** | 已安装的 Skill 和技能提示词 |
+| **钩子** | 已安装的钩子包和运行开关 |
+| **记忆** | Agent 的记忆和记忆提示词 |
+| **密钥保险柜** | Agent 命令用的环境变量 |
+| **定时任务** | 定时任务 |
+
+每个标签页都有自己的地址:`/agents/<agentId>?tab=<tab>`,其中 `<tab>` 是 `overview`、`prompt`、`runtime`、`tools`、`skills`、`hooks`、`memory`、`vault` 或 `schedules`。
+
+### 保存修改
+
+在概览、系统提示词、运行参数和工具四个标签页,以及各个提示词区块,选择**保存**并确认。确认框写着:「确定保存这些修改吗?修改将写入服务器上的配置文件。」
+
+- 大多数修改立即对新对话生效;正在运行的对话要在下一次压缩后才生效。
+- 运行参数的修改如果只涉及上下文压缩字段,则立即生效,正在运行的对话也不例外。
+- **启用技能**这类开关一拨动就保存,不需要按**保存**。
+
+这些设置对应的文件格式见 [Agent 配置](/configuration#agent-配置)。
+
+### 权限
+
+大多数设置,任何 Project 成员都能修改。以下操作只有 Project owner 能做:
+
+- 删除 Agent、导入快照;
+- 打开或关闭**启用钩子**;
+- 编辑密钥保险柜变量、**启用密钥保险柜**开关和**保险柜提示词**;
+- 创建、编辑、启用、停用和删除定时任务,编辑**启用定时任务**开关和**定时任务提示词**(成员仍可使用**用 AI 创建**);
+- 导入记忆。
+
+## 概览标签页
+
+### 修改名称和描述
+
+修改**名称**或**描述**,然后选择**保存**。
+
+### 导出和导入快照
+
+**Agent State** 区块显示 **Agent State 版本**和 **State 路径**(Agent State 在服务端所在的文件夹),点击复制按钮可以复制路径。
+
+- **导出快照**:把 Agent State 下载为 `.tar.gz` 包。包里不含密钥保险柜,密钥不会随快照流出。
+- **导入快照**:用包整体替换 Agent State,并采用包内的版本,但保留 Agent 当前的密钥保险柜。导入前会先对当前版本做一次快照。只有 Project owner 能导入。如果包内版本不比当前版本新,会弹出**版本冲突**对话框,要求确认覆盖。
+
+版本和快照的工作机制见[自我进化](/self-improvement#快照与版本)。
+
+### 更新内核
+
+Agent 的内核版本记录它的配置基于哪一代内置默认设置。已有的 Agent 永远不会自动采用更新的默认值。PenguinHarness 发布新默认值后,**内核**区块会显示当前内核版本和最新内核版本,概览标签页上出现红点。
+
+1. 在**内核**区块选择**更新内核**。
+2. 确认。
+
+没有自定义过的标签页会更新为当前的内置默认值。编辑过的标签页整个保持不变,并在结果中列出。名称、描述、Agent State 版本和 MCP Server 不受影响。详情见[内核更新](/configuration#内核更新)。
+
+> [!TIP]
+> 要一次更新多个 Agent,可以在**智能体**页面顶部的通知里选择**现在升级**。
+
+### 还原为默认配置
+
+1. 在**内核**区块选择**还原为默认配置**。
+2. 确认。
+
+> [!WARNING]
+> 还原为默认配置的操作无法撤销。
+
+还原时用当前默认值覆盖 Agent 的配置:自定义系统提示词、工具列表、模型和压缩设置、MCP Server 全部替换,只保留名称、描述和 Agent State 版本。
+
+## 系统提示词标签页
+
+- **AGENTS.md** 保存 Agent 的角色、规则和工作指令。
+- **system_prompt 模板**:系统提示词由这个模板生成。
+
+在「可用占位符(点击插入)」下选择一个占位符,即可插入到模板中光标所在位置:
+
+| 占位符 | 插入内容 |
+| --- | --- |
+| `{{AGENTS_MD}}` | `AGENTS.md` 的内容 |
+| `{{VAULT}}` | 密钥保险柜区块:**保险柜提示词**加变量名列表;**启用密钥保险柜**关闭时为空 |
+| `{{SKILLS}}` | Skill 区块:**技能提示词**加已安装 Skill 的元数据;**启用技能**关闭时为空 |
+| `{{MEMORY}}` | 记忆区块:主记忆提示词,持久 Workspace 中还包括工作区附加段;记忆关闭时为空 |
+| `{{SCHEDULES}}` | 定时任务区块:**定时任务提示词**加任务名列表;**启用定时任务**关闭时为空 |
+| `{{PLATFORM}}` | 运行平台 |
+| `{{OS_VERSION}}` | 操作系统版本 |
+| `{{SHELL}}` | 执行命令所用的 shell |
+| `{{DATE}}` | 当前日期 |
+| `{{PROJECT_DIR}}` | PenguinHarness 应用数据根目录,存放所有 Agent 数据和 Project 数据;不是 Task 的工作目录 |
+| `{{AGENT_ID}}` | Agent 的 id |
+| `{{CWD}}` | Workspace 的绝对路径 |
+| `{{PROVIDER}}` | 模型的供应商分组 |
+| `{{MODEL_ID}}` | 上游模型 id |
+| `{{SESSION_ID}}` | Session id |
+
+密钥保险柜、Skill、记忆和定时任务区块的开关和提示词,分别在各自的标签页里。另见[系统提示词占位符](/configuration#系统提示词占位符)。
+
+## 运行参数标签页
+
+| 字段 | 含义 |
+| --- | --- |
+| `max_turns` | 一个 Task 允许的最大轮次;`-1` 表示不限 |
+| `model.max_tokens` | 每次请求的输出 Token 上限 |
+| `model.thinking_level` | `low`、`medium`、`high`、`xhigh` 或 `max`。新建 Agent 默认 `medium`。在部分模型上,`xhigh` 和 `max` 的实际表现与低一档相同。保存过旧档位 `none` 的 Agent 会继续保留,但选项中不再提供 |
+| `model.timeoutMs` | 等待模型供应商事件的时间上限,单位毫秒;不限制整个请求的时长 |
+| `max_context_length` | 触发压缩的上下文大小 |
+| `max_session_turns` | 触发压缩的轮数 |
+| `mode` | `summarize`(默认):让模型总结旧上下文,然后在新的窗口里从总结继续;`discard`:直接丢弃旧上下文,不做总结 |
+| `prompt` | 总结上下文时使用的提示词 |
+
+`max_turns` 和 `model.timeoutMs` 接受大于 0 的数字或 `-1`。思考等级在各模型上的表现见[思考等级](/models#思考等级)。压缩的工作方式见[压缩](/agent-loop#上下文压缩)。
+
+## 工具标签页
+
+### 内置工具
+
+表格列出全部内置工具,每个工具可以设置:
+
+| 列 | 含义 |
+| --- | --- |
+| `permission` | **Read-only**(`r`):工具只读取,「放行只读」审批模式会自动放行。**Read & write**(`rw`):工具可能修改内容,「放行只读」审批模式会先询问你 |
+| `timeoutMs` | 工具的时限,单位毫秒 |
+| `maxOutputLength` | 工具最多可返回的输出量 |
+| `call_description` | 模型是否为每次调用写一句话描述,调用运行时会显示给你。默认开启;只有支持描述的工具才能切换 |
+
+字段留空即使用默认值。点击**保存**即可保存表格。审批模式见[审批](/tools#审批)。
+
+### 添加 MCP Server
+
+MCP Server 给 Agent 增加外部工具,工具名形如 `mcp__<name>__<tool>`。**MCP Server** 区块里的改动立即保存。
+
+1. 在**工具**标签页选择**添加 MCP Server**。
+2. 选择传输方式:
+ - `http`(默认):Streamable HTTP,当前的远程传输方式。
+ - `stdio`:本地进程,由 PenguinHarness 启动,通过 stdin 和 stdout 通信。
+ - `sse`:旧的 HTTP+SSE 传输方式,供尚未迁移的 Server 使用。
+3. 在 **name** 中输入工具名前缀,可以用字母、数字、`_` 和 `-`,以字母或数字开头。
+4. 填写连接字段:
+ - `stdio`:**command**;**args**,每行一个参数;**env**,每行一个 `KEY=value`;**cwd**,默认是 Session 的 Workspace。Agent 的密钥保险柜变量不会传给 MCP Server 进程。
+ - `http` 和 `sse`:**url**;**headers**,每行一个 `Header-Name: value`,例如 `Authorization` 请求头。
+5. 选择 **permission**:
+ - **Auto(readOnlyHint)**:工具声明了 `readOnlyHint` 注解就按只读处理,否则按 Read & write 处理。
+ - **Read-only**:Server 的所有工具都按只读处理。
+ - **Read & write**:Server 的所有工具都按 Read & write 处理。
+6. 可选:调整 **connectTimeoutMs**(连接和发现工具,默认 10000)、**timeoutMs** 和 **maxOutputLength**,这些设置对 Server 的所有工具生效。
+7. 可选:保存前选择**测试连接**验证配置,它会报告发现的工具数量和耗时。
+8. 选择**保存**。
+
+> [!NOTE]
+> permission 级别只在「放行只读」审批模式下起作用,其他审批模式都会忽略它。它也不限制 Server 能做什么:把 Server 标为只读,只是让这个审批模式跳过本该弹出的确认。
+
+要修改某个 Server,在它的行上选择**编辑**。要移除,选择**删除**并确认;从下一个 Session 开始,它的工具不再可用。更多关于 MCP Server 的内容见 [MCP Server](/tools#mcp-server)。
+
+### 测试 MCP Server
+
+1. 在 **MCP Server** 区块选择**测试连接**。
+2. 选择**开始测试**。
+
+PenguinHarness 依次连接每个 Server 并发现它的工具,不会保存任何内容。每行显示工具数量和耗时;失败则显示**连接失败**和原因。
+
+## 技能标签页
+
+**技能**标签页列出 Agent 已安装的 Skill。可以导出或卸载 Skill,用**导入技能**导入新的 Skill,用**启用技能**控制系统提示词里的 Skill 区块,还可以编辑**技能提示词**。见[管理 Agent 的 Skill](/skills#管理-agent-的-skill)。
+
+## 钩子标签页
+
+**钩子**标签页列出 Agent 已安装的钩子包。可以导出、卸载钩子包,用**导入钩子**导入新的钩子包,用**启用钩子**为这个 Agent 开关钩子。从插件库安装,要到**插件市场**页面操作。见[钩子包](/skills#钩子包)。
+
+## 记忆标签页
+
+记忆让 Agent 跨 Session 保留学到的东西。Agent 在工作过程中会自己保存值得记住的内容,你也可以让它记住指定内容。**用户记忆**对这个 Agent 的所有 Session 生效;Workspace 记忆按 Workspace 分别保存。
+
+- **启用记忆**开关控制记忆的开与关,切换后立即保存。关闭后只是阻止记忆进入 Agent 的上下文、不再为新 Session 准备记忆,不会删除任何内容。
+- 系统提示词模板里没有 `{{MEMORY}}` 占位符时,标签页会给出提示,选择**插入 {{MEMORY}} 占位符**即可补上。记忆功能出现之前创建的 Agent 会有这种情况。
+
+记忆按范围分组:**用户记忆**排在最前,之后每个 Workspace 一组。点击分组标题可以折叠或展开;浏览器会为每个用户、Project 和 Agent 记住折叠状态。
+
+### 查看、编辑和删除记忆
+
+每条记忆一行,行上有三个按钮:
+
+- **查看**:在侧边面板显示这条记忆的标题、日期、描述和内容;窄屏下则从底部弹出面板,可以半屏或全屏高度打开。
+- **编辑**:打开**编辑记忆**对话框。在**修改要求**里描述要改什么(可选),然后选择**打开新对话**。会打开和这个 Agent 的新对话,提示词已填好;如果编辑的是 Workspace 记忆,还会使用对应的 Workspace。发送消息后,Agent 会同时更新记忆文件和 `MEMORY.md` 索引。
+- **删除**:确认后删除这条记忆,并从 `MEMORY.md` 里移除对应的行。
+
+记忆内容要通过对话交给 Agent 修改,不能就地编辑。
+
+### 添加记忆
+
+1. 在分组标题上选择**添加**,打开**添加记忆**对话框。
+2. 在**要记住的内容或来源**里粘贴内容、文件路径或 URL。
+3. 选择**打开新对话**,然后发送消息。Agent 会把内容整理成这个分组里的记忆。
+
+### 导出和导入记忆
+
+- 分组标题上的**导出**:把分组里的全部记忆连同 `MEMORY.md` 下载为一个 JSON 文件。文件名包含导出日期和时间,多次导出不会互相覆盖。
+- 分组标题上的**导入**:把这类文件读回分组。只有 Project owner 能导入。
+
+导入时,如果分组里已有同名记忆,需要选择处理方式:
+
+| 选项 | 结果 |
+| --- | --- |
+| **保留现有的这条**(默认) | 只添加分组里没有的记忆。不丢失任何内容 |
+| **改用文件里的版本** | 替换同名记忆。文件里没有的记忆保持不变 |
+| **整组替换** | 删除文件里没有的全部记忆 |
+
+如果导入会覆盖或删除记忆,或者替换分组的 `MEMORY.md`,会先弹出**确认导入**对话框,列出将要发生的变化。
+
+### 记忆提示词
+
+在**记忆提示词**下编辑 `{{MEMORY}}` 占位符展开后的文本:
+
+- **主提示词**(`memory.prompt`):注入每个 Session。
+- **工作区附加段**(`memory.workspace_prompt`):只注入带持久 Workspace 的 Session。
+
+这些提示词可以用 `{{USER_MEMORY_INDEX}}`(用户 `MEMORY.md` 索引)、`{{WORKSPACE_MEMORY_INDEX}}`(Workspace 的 `MEMORY.md` 索引)和 `{{WORKSPACE_MEMORY_DIR}}`(当前 Workspace 的记忆文件夹)。后两个只在工作区附加段里生效。每个索引最多 200 行、25,000 字符。
+
+点击 Agent 卡片上的记忆数字即可打开这个标签页。
+
+## 密钥保险柜标签页
+
+密钥保险柜存放 Agent 用的环境变量,比如 API key。PenguinHarness 把它们传给 Agent 的 shell 命令。模型只能看到变量名,永远看不到值。子 Agent 用各自的密钥保险柜,不继承这里的变量。修改从下一个 Task 起生效;正在运行的 Task 不受影响。
+
+只有 Project owner 能修改密钥保险柜。成员能看到变量名,值以掩码显示。
+
+### 添加变量
+
+1. 在**密钥保险柜**标签页选择**手动创建**,打开**添加环境变量**对话框。
+2. 在**键名**中输入变量名,例如 `OPENAI_API_KEY`。可以用字母、数字和下划线,不能以数字开头。
+3. 在**值**中输入变量值。
+4. 选择**添加**。变量已存在时,确认后覆盖原值。
+
+要删除变量,在它的行上选择**删除**并确认。值无法恢复。
+
+### 用 AI 添加变量
+
+选择**用 AI 创建**会打开**让 AI 添加密钥**。描述需要的变量,或选一个示例:**盘点这个智能体需要的 key**、**重置一个过期 token** 或 **接入一个内部服务**。然后选择**在新对话中编辑**并发送提示词。Project 的默认 Agent 会用 `penguin config vault set` 写入变量。
+
+> [!WARNING]
+> 在这个对话框里输入的密钥值会发送给模型供应商,记录进对话的 Trace,还会在 Agent 运行的命令里再次出现。更安全的做法是让 AI 只创建变量名并说明各自用途,然后你在**密钥保险柜**标签页自己填入值。
+
+### 保险柜提示词
+
+- **启用密钥保险柜**控制密钥保险柜区块是否进入系统提示词。关闭时,变量仍然会传给 Agent 的命令。
+- **保险柜提示词**:`{{VAULT}}` 占位符展开后的文本。其中的 `{{VAULT_KEYS}}` 占位符列出变量名,每行一个。
+
+## 定时任务标签页
+
+定时任务按计划给 Agent 发送提示词:发一次,或按周期反复发。这个标签页上的修改立即生效。
+
+> [!NOTE]
+> 定时任务只在 PenguinHarness 服务运行时触发。
+
+也可以在对话里创建和管理定时任务,见[定时任务](/schedules)。
+
+### 创建定时任务
+
+只有 Project owner 能手动创建定时任务。
+
+1. 在**定时任务**标签页选择**手动创建**,打开**新建定时任务**对话框。
+2. 在**名称**中输入任务的文件名,不带 `.toml`。创建后不能修改。
+3. 在**周期**中输入任务运行频率,例如 `30m`、`12h` 或 `7d`。一次性任务留空。最短周期为 5 分钟。
+4. 设置**开始时间**,也可以设置**结束时间**。
+5. 在**目标**下选择提示词发到哪里:
+ - **每次新建会话**:每次运行都新建一个 Session。可以再选 **Model**(不选就用 Project 默认值)和 **Workspace**(留空就用临时 Workspace)。
+ - **绑定 Session**:每次运行都发给同一个已有的 Session。在 **Session** 中选择。
+6. 在 **Prompt** 中输入要发送的内容。
+7. 保持勾选**启用**以激活任务,然后选择**创建**。
+
+也可以用描述的方式创建:选择**用 AI 创建**,或从列表为空时显示的**建议**中选一个:**每日简报**、**每周回顾**、**跟进提醒**或**监控更新**。然后选择**在新对话中编辑**并发送提示词。Project 的默认 Agent 会为这个 Agent 创建任务。任何成员都能使用**用 AI 创建**。
+
+### 管理定时任务
+
+表格显示每个任务的**名称**、**状态**、**周期**、**目标**、**下次 / 最近触发**和**排队**。状态可能是**生效**、**停用**、**已过期**、**已完成**、**已错过**或**无效**;指向**无效**可查看原因。
+
+owner 可以在每一行选择**停用**或**启用**、**编辑**、**删除**。无法解析的文件列在「解析失败的文件(已跳过调度)」下。
+
+### 定时任务提示词
+
+- **启用定时任务**控制定时任务区块是否进入系统提示词。关闭时,任务照常运行。
+- **定时任务提示词**:`{{SCHEDULES}}` 占位符展开后的文本。它教模型用文件工具管理定时任务,其中的 `{{SCHEDULE_LIST}}` 占位符列出任务名。
+
+## 工作原理
+
+Agent 的配置和数据存放在它的 Agent State 里,也就是概览标签页上 **State 路径**显示的 `agent_state/` 文件夹。里面有 `system_config.yaml`、`AGENTS.md`、密钥保险柜、工具、Skill、钩子包、定时任务和记忆。Agent 的 Trace 不在其中,而是存放在它旁边、这个 Agent 自己的文件夹里,见[数据目录](/sessions-and-traces#数据目录)。
+
+- 记忆是 `agent_state/memory/` 下的文件,每个分组有一个 `MEMORY.md` 索引。存储方式见[记忆](/configuration#记忆)。
+- 密钥保险柜变量保存在 `agent_state/.vault.toml`。文件格式见[密钥保险柜](/configuration#vault)。
+- 定时任务以 TOML 文件保存在 `agent_state/schedule/` 下,也可以手动编辑。文件格式见[定时任务](/configuration#定时任务)。
diff --git a/packages/docs/content/architecture.en.md b/packages/docs/content/architecture.en.md
index 92e0fd7b..3476040a 100644
--- a/packages/docs/content/architecture.en.md
+++ b/packages/docs/content/architecture.en.md
@@ -1,20 +1,27 @@
---
title: Architecture
-description: How the three-interface boundary, the context_engine and OmniMessage organize the SDK, CLI, Server and Web App into one system.
+description: How the SDK, Server, CLI and Web App divide responsibilities, and how the three-interface boundary and OmniMessage organize the system.
---
-PenguinHarness is a pnpm monorepo whose center is the execution engine in `@prismshadow/penguin-core`; the CLI, the Server and the Web App are just different "Human implementations" of that same engine.
+PenguinHarness is a pnpm monorepo. Its center is the execution engine in `@prismshadow/penguin-core`. The Server ships with the product as the Human implementation of that engine: it runs every Task. SDK embedders can also drive the engine directly.
+
+The Web App and the CLI are clients of the Server over HTTP and SSE, and the desktop app wraps the Server and the Web App in one window. This page covers the layers, the engine's three-interface boundary, the [data flow of one Task](#data-flow-of-one-task), where each responsibility lives, and the source layout.
## Layers
+The stack, top to bottom:
+
```text
┌─────────────┐ ┌─────────────────────────────┐
│ CLI │ │ Web App (React SPA) │
-│ (penguin) │ │ ↑ OmniMessage over SSE │
-│ │ │ Server (Hono + SQLite) │
+│ (penguin) │ │ │
└──────┬──────┘ └──────────────┬──────────────┘
- │ session.run(...) │ ← Human boundary
+ │ │ HTTP · OmniMessage over SSE
┌──────┴────────────────────────┴──────────────┐
+│ Server (Hono + SQLite) │
+└──────────────────────┬───────────────────────┘
+ │ session.run(...) ← Human boundary
+┌──────────────────────┴───────────────────────┐
│ core: context_engine (ReAct loop) │
│ ├── LLMInterface ──→ AgentHub ──→ models │
│ ├── EnvironmentInterface ──→ builtin tools│
@@ -23,42 +30,66 @@ PenguinHarness is a pnpm monorepo whose center is the execution engine in `@pris
└──────────────────────────────────────────────┘
```
+The CLI and the Web App talk to the Server over HTTP and SSE. Among the shipped apps, only the Server calls `session.run`.
+
| Package | Role |
| --- | --- |
-| `packages/core` | SDK and engine: context_engine, OmniMessage, LLM/Environment interfaces, State and Trace |
-| `packages/cli` | Terminal Human implementation: REPL and one-shot runs, embeds core in-process |
-| `packages/server` | Web Human implementation: HTTP for input and approvals, SSE for the output stream |
-| `packages/web` | Rendering SPA: streams by the OmniMessage protocol, contains no engine logic |
-| `plugins/*` | The built-in plugin library, one package per plugin: skills (`SKILL.md` directories) and session hooks (script packages), loaded by core |
+| `packages/core` | SDK and engine: `context_engine`, OmniMessage, the LLM and Environment interfaces, hooks, state and Trace |
+| `packages/server` | The Human implementation: runs Tasks through core, takes input and approvals over HTTP, streams output over SSE |
+| `packages/cli` | Terminal client of the Server: REPL and one-shot runs over HTTP and SSE. It starts a local Server when none is running. Only `penguin config` reads and writes configuration files directly through the SDK |
+| `packages/web` | Rendering SPA: renders the OmniMessage stream and contains no engine logic |
+| `packages/desktop` | Desktop app: an Electron shell that runs the Server as a `utilityProcess` and opens its window on the local HTTP address |
+| `packages/hmr` | The hot-update mechanism: the version store, the atomic commit, the resource registry, and park → boot → swap |
+| `plugins/*` | The built-in plugin library, one package per plugin: Skills (`SKILL.md` directories) and Session hooks (script packages), loaded by core |
+
+## The three-interface boundary
+
+The `context_engine` is the heart of the system. It does exactly two things: it maintains the linear message history, and it orchestrates the event flow between three interfaces. It speaks only [OmniMessage](/omni-message) and performs no protocol conversion.
+
+- **Human**: the user-side boundary. It is deliberately not an interface class: the SDK's single entry point, `session.run(newMessages, { approve, signal })`, *is* the Human boundary. Input is a list of new OmniMessages plus an approval callback; output is a stream of OmniMessages. The Server is the shipped implementation. The CLI and the Web App reach it over HTTP and SSE, and SDK embedders call `session.run` themselves.
+- **LLM**: the model-side interface, `LLMInterface`. It translates OmniMessage into requests against the AgentHub model gateway, and streamed events back into OmniMessage. All provider protocol adaptation happens inside AgentHub, so core never imports a vendor SDK.
+- **Environment**: the tool-execution interface, `EnvironmentInterface`. It runs approved tool calls and streams the results back.
+
+The kernel contains no provider, tool or UI specifics, so each side swaps by configuration without touching core: a local shell today, another sandbox tomorrow; the CLI, the Web App or a programmatic caller. See [Core Interfaces](/interfaces) for the signatures.
+
+## Data flow of one Task
+
+1. The Human hands a Prompt (a list of OmniMessages) to `session.run`.
+2. The engine issues a Request. The `LLMInterface` streams `partial_*` fragments and complete messages.
+3. Every complete `tool_call` triggers one `approve` decision. Approved calls run concurrently in the Environment.
+4. Tool outputs are re-fed in their original order as the next Request's input.
+5. The Task ends when a turn produces no `tool_call`: that turn is the final answer.
+
+Every message and event flows to two destinations at once: it streams live to the Human, and it is appended to the [Trace](/sessions-and-traces). Loop details such as interruption, reconnect and compaction are on [The Agent Loop](/agent-loop).
## Division of responsibilities
-To place a design in a layer, ask where its **source of truth** lives. The four layers split as:
+To place a design in a layer, ask where its **source of truth** lives. One rule decides: what is editable or recorded lives in files; what makes messages flow lives in the SDK; what needs a resident process and multiple users lives in the Server; the rest is rendering.
| Layer | Owns | Does not own |
| --- | --- | --- |
-| SDK (`core`) | Protocol and execution — everything that makes messages flow | persisted user state, multi-user, any rendering |
-| Server | The resident process and the multi-user runtime | engine logic (fully delegated to the SDK) |
+| SDK (`core`) | Protocol and execution: everything that makes messages flow | persisted user state, multi-user, any rendering |
+| Server | The resident process and the multi-user runtime | engine logic, fully delegated to the SDK |
| File layer (`~/.penguin/data`) | Everything editable and everything recorded | any computation |
| CLI / Web | Rendering and interaction | business state |
-Item by item (design → owner → carrying file or module):
+Item by item, each design maps to an owner and to the file or module that carries it:
| Design | Owner | Carried by |
| --- | --- | --- |
| The OmniMessage protocol, message parsing and partial aggregation | SDK | `core/src/omnimessage/` — see [The OmniMessage Protocol](/omni-message) |
| The ReAct loop, carry-over, reconnect, compaction | SDK | `core/src/engine/context-engine.ts` — see [The Agent Loop](/agent-loop) |
-| The approval mechanism (one decision per tool_call) | SDK | `ApproveFn` (`core/src/interfaces/shared.ts`); the concrete mode is injected by CLI/Server |
+| The approval mechanism (one decision per `tool_call`) | SDK | `ApproveFn` (`core/src/interfaces/shared.ts`); the concrete mode is injected by the Server or an SDK host |
| Tool execution and centralized close-out | SDK | `core/src/environment/` — see [Tools & Approval](/tools) |
| Model access (provider protocol adaptation) | SDK → AgentHub | `core/src/llm/` + `@prismshadow/agenthub` — see [Models & Providers](/models) |
| Trace writing and Session-recovery logic | SDK | `core/src/trace/` (the records themselves live in the file layer) |
| Subagent spawning and message forwarding | SDK | the `run_subagent` tool + the injected `SubagentRunner` |
| Multi-user auth and Project authorization | Server | `server/src/auth/`, `server/src/services/project-service.ts` |
| Session indexing, per-Session mutex, SSE forwarding | Server | `server/src/runtime/` — see [Server API](/server-api) |
-| Scheduled tasks (execution) | Server | `server/src/runtime/scheduler.ts`; the task definitions live in the file layer at `agent_state/schedule/*.toml` |
+| Scheduled task execution | Server | `server/src/runtime/scheduler.ts`; the task definitions live in the file layer at `agent_state/schedule/*.toml` |
| Approval-mode persistence and manual decisions | Server | `server/src/runtime/approvals.ts` + SQLite |
| Usage persistence and cost statistics | Server | `server/src/runtime/usage-recorder.ts`, `services/usage-service.ts` |
-| Agent behavior definition (prompts, runtime params) | File layer | `agent_state/system_config.yaml`, `AGENTS.md` — see the [Configuration Reference](/configuration) |
+| Agent behavior definition (prompts, runtime parameters) | File layer | `agent_state/system_config.yaml`, `AGENTS.md` — see the [Configuration Reference](/configuration) |
| Skills, hooks | File layer | `agent_state/skills/<name>/SKILL.md`, `agent_state/hooks/<name>/hooks.json` — see [Skills & Plugins](/skills) |
| Secrets | File layer | Vault: `agent_state/.vault.toml`; model credentials: `.project_config.toml` (both 0600) |
| The model table and the default model | File layer | `<project>/.project_config.toml` |
@@ -67,68 +98,83 @@ Item by item (design → owner → carrying file or module):
| Snapshots | File layer | `snapshots/v<version>.tar.gz`; the export/import service lives in the Server |
| Streaming rendering, approval UI, charts | CLI / Web | `cli/src`, `web/src` (pure rendering, no engine logic) |
-The one-line rule: **what is editable or recorded lives in files; what makes messages flow lives in the SDK; what needs a resident process and multiple users lives in the Server; the rest is rendering.** The Server's SQLite stores only indexes and aggregates — it never competes with the file layer as a source of truth.
+> [!NOTE]
+> The Server's SQLite stores only indexes and aggregates. It never competes with the file layer as a source of truth.
+
+## The state layer
+
+Below the engine sits a purely file-based state layer. Its root is `~/.penguin/data` (override it with `PENGUIN_HOME`), organized as `<project>/agents/<agent>/`:
+
+| Component | Location | Contents |
+| --- | --- | --- |
+| Agent State | `agent_state/` | `system_config.yaml`, `AGENTS.md`, Skills, Vault. An agent's entire behavior is editable files. |
+| Project config | `.project_config.toml` | The model table and credentials. Model identity is always the `(provider, model_id)` pair. |
+| Trace | `traces/` | Append-only JSONL: the single source of truth for Session recovery. |
+
+The Server keeps an additional SQLite index (users, authorization, usage stats) but never duplicates the file layer's facts. The CLI, the SDK and the Web App share one data directory and can be mixed freely.
## Source layout
-How each package is organized (single-purpose files, split by layer; every file's header comment is its design note):
+Each package is organized into single-purpose files, split by layer. Every file's header comment is its design note.
```text
packages/
├── core/src
│ ├── agent.ts / session.ts # the createAgent composition layer and Session (run / compact / generateTitle)
-│ ├── session-title.ts # one-shot title generation (out-of-band LLM call, never in Trace)
│ ├── engine/context-engine.ts # ReAct loop orchestration: turn lifecycle, approvals, carry-over, reconnect, compaction
-│ ├── omnimessage/ # types.ts protocol types · builders.ts constructors · aggregate.ts partial aggregation
-│ ├── llm/ # generative-model.ts AgentHub adapter · tool-call-ids.ts id uniqueness
-│ ├── environment/ # environment.ts execution close-out · tools/ registry, 9 builtin tools, background sessions
-│ ├── state/ # paths · default-config · project-config · model-catalog
+│ ├── omnimessage/ # types.ts protocol types · builders.ts constructors · aggregate.ts partial aggregation · markers/
+│ ├── interfaces/ # llm.ts · environment.ts · shared.ts (ApproveFn and the vocabulary both sides share)
+│ ├── llm/ # generative-model.ts AgentHub adapter · tool-call-ids.ts id uniqueness · context-limits.ts
+│ ├── environment/ # environment.ts execution close-out · tools/ registry, 7 builtin tools, background sessions · mcp/
+│ ├── hooks/ # the stop / pre_tool_use / user_prompt hook points and the hook-script runner
+│ ├── plugins/ # the built-in plugin library and its loader
+│ ├── plugin/ · kernel/ # the plugin contract a server plugin compiles against · the hot-update module kernel
+│ ├── state/ # paths · default-config · project-config · model-catalog · memory
│ │ # agent-state (Skill install, prompt assembly) · agent-vault · builtin-agents
│ ├── trace/ # writer.ts append-only JSONL · resume.ts replay-based recovery
-│ └── internal/ # date and Session helpers
-├── cli/src # commander entry + run / chat / config / serve commands and approval prompts
-├── server/src # app assembly · db (node:sqlite) · auth · http/routes · runtime · services
-├── web/src # api client · state · lib/omni stream rendering · components · feature pages
+│ └── internal/ # shared helpers: dates, Session support, merge queue, session-title.ts (one-shot title generation, never in Trace)
+├── server/src # index.ts boot sequence · app assembly · db (node:sqlite) · auth · http/routes · runtime · services · hmr · plugin · terminal
+├── cli/src # commander entry · commands/ (run / chat / input / logs / ls / agent / project / schedule / config / serve …) · server client and approval prompts
+├── web/src # api client · state · lib/omni stream rendering · components · feature pages (layout below)
+├── desktop/ # the Electron shell
+├── hmr/ # the hot-update mechanism
├── landing/ # the product landing page (with the blog)
└── docs/ # this documentation site
```
-The internals of server and web are detailed on [Server API](/server-api) and the [Web App Guide](/web-app).
-
-## The three-interface boundary
-
-The context_engine is the heart of the system and does exactly two things: it maintains the linear message history, and it orchestrates the event flow between three interfaces. It speaks only [OmniMessage](/omni-message) and performs no protocol conversion:
-
-- **Human** — the user-side boundary. It is deliberately not an interface class: the SDK's single entry point `session.run(newMessages, { approve, signal })` *is* the Human boundary. Input is a list of new OmniMessages plus an approval callback; output is streamed OmniMessages. The CLI and the Server are its two shipped implementations.
-- **LLM** — the model-side interface (`LLMInterface`). Translates OmniMessage to requests against the AgentHub model gateway and streamed events back into OmniMessage. All provider protocol adaptation happens inside AgentHub; core never imports a vendor SDK.
-- **Environment** — the tool-execution interface (`EnvironmentInterface`). Runs approved tool calls and streams results back.
+### Web App source
-Why this boundary matters: the kernel contains no provider, tool or UI specifics, so each side swaps by configuration (local shell today, other sandboxes tomorrow; CLI, Web, or programmatic callers) without touching the core. See [Core Interfaces](/interfaces) for the signatures.
+```text
+packages/web/src
+├── api/ # fetch wrapper · one function per API (DTOs type-only from @prismshadow/penguin-server/api) · SSE wrapper
+├── state/ # auth / project / sessions / company / theme / locale contexts
+├── lib/omni/ # OmniMessage stream → view-model reducer; connect-first + dedup stream controller
+├── components/ # ui primitives (modal / drawer / select …) and the app layout
+├── pages/ # the login pages
+└── features/ # chat / agents / skills / plugins / models / usage / traces / benchmark / schedules / company / settings / admin … pages
+```
-## Data flow of one Task
+The Server's routes and delivery guarantees are detailed on [Server API](/server-api), and how the Server process assembles its subsystems on [Server Boot and Subsystems](/server-boot).
-1. Human hands a Prompt (a list of OmniMessages) to `session.run`;
-2. the engine issues a Request: the LLMInterface streams `partial_*` fragments and complete messages;
-3. every complete `tool_call` triggers one `approve` decision; approved calls run concurrently in the Environment;
-4. tool outputs are re-fed in their original order as the next Request's input;
-5. the Task ends when a turn produces no `tool_call` (the final answer).
+## Key design decisions
-Every message and event flows to two destinations at once: streamed live to the Human, and appended to the [Trace](/sessions-and-traces). Loop details (interruption, reconnect, compaction) are on [The Agent Loop](/agent-loop).
+### One protocol, three jobs
-## The state layer
+OmniMessage is at once the SDK's external interface, the Trace's on-disk format and the engine's internal currency. What streams, what is stored and what the model sees are the same thing.
-Below the engine sits a purely file-based state layer rooted at `~/.penguin/data` (override with `PENGUIN_HOME`), organized as `<project>/agents/<agent>/`:
+### Errors converge into messages
-- **Agent State** — the `agent_state/` directory: `system_config.yaml`, `AGENTS.md`, Skills, Vault. An Agent's entire behavior is editable files.
-- **Project config** — `.project_config.toml`: the model table and credentials; model identity is always the `(provider, model_id)` pair.
-- **Trace** — the `traces/` directory: append-only JSONL, the single source of truth for Session recovery.
+The LLM and the Environment never throw into the engine. Their results carry a four-value `stop_reason`, and the concrete cause rides on `error_code` and `error_message`:
-The Server keeps an additional SQLite index (users, authorization, usage stats) but never duplicates the file layer's facts — the CLI, SDK and Web share one data directory and can be mixed freely.
+| `stop_reason` | Meaning and engine behavior |
+| --- | --- |
+| `completed` | Finished normally; the loop continues or the Task ends |
+| `retryable` | An LLM failure worth retrying: the engine reconnects within the run, up to 5 consecutive fruitless retries, on an exponential backoff with a ceiling |
+| `fatal` | A definitive failure, such as a rejected credential: the run stops at once, because no retry can make it work |
+| `aborted` | A user interruption |
-## Key design decisions
+### A thin model layer
-- **One protocol, three jobs**: OmniMessage is simultaneously the SDK's external interface, the Trace on-disk format and the engine's internal currency — what streams, what is stored and what the model sees are the same thing.
-- **Errors converge into messages**: the LLM and Environment never throw into the engine; results carry a six-value `stop_reason` (`completed | failed | aborted | timeout | malformed | auth`), and every LLM-side status except `auth` triggers an in-run reconnect (`failed / timeout / malformed`, up to 5 times with an exponential-with-ceiling backoff). `auth` is the one terminal class: a rejected credential cannot be retried into working. Retrying `failed` is a policy choice — the status itself is still reported as `failed`.
-- **A thin model layer**: core defines only `LLMInterface`; provider adaptation lives entirely in AgentHub (`@prismshadow/agenthub`), which is what makes any OpenAI-compatible endpoint reachable. See [Models & Providers](/models).
+Core defines only `LLMInterface`. Provider adaptation lives entirely in AgentHub (`@prismshadow/agenthub`), which is what makes any OpenAI-compatible endpoint reachable. See [Models & Providers](/models).
Source entry points: `packages/core/src/engine/context-engine.ts`, `packages/core/src/interfaces/`.
diff --git a/packages/docs/content/architecture.zh.md b/packages/docs/content/architecture.zh.md
index f9277cb5..c2e9e4fa 100644
--- a/packages/docs/content/architecture.zh.md
+++ b/packages/docs/content/architecture.zh.md
@@ -1,134 +1,180 @@
---
title: 架构总览
-description: 三接口边界、context_engine 与 OmniMessage 如何把 SDK、CLI、Server、Web 组织成一个系统。
+description: SDK、Server、CLI 和 Web App 如何分工,以及三接口边界与 OmniMessage 如何组织整个系统。
---
-PenguinHarness 是一个 pnpm monorepo,核心是 `@prismshadow/penguin-core` 中的执行引擎;CLI、Server 与 Web App 都只是这同一个引擎的不同「Human 实现」。
+PenguinHarness 是一个 pnpm monorepo,核心是 `@prismshadow/penguin-core` 里的执行引擎。Server 是随产品交付的 Human 实现,所有 Task 都由它运行;SDK 嵌入方也可以直接驱动引擎。
+
+Web App 和 CLI 经 HTTP 与 SSE 访问 Server,桌面应用则把 Server 和 Web App 装进同一个窗口。本页依次介绍分层结构、引擎的三接口边界、[一个 Task 的数据流](#一个-task-的数据流)、各项职责的归属和源码结构。
## 分层结构
+自上而下:
+
```text
┌─────────────┐ ┌─────────────────────────────┐
│ CLI │ │ Web App (React SPA) │
-│ (penguin) │ │ ↑ OmniMessage over SSE │
-│ │ │ Server (Hono + SQLite) │
+│ (penguin) │ │ │
└──────┬──────┘ └──────────────┬──────────────┘
- │ session.run(...) │ ← Human 边界
+ │ │ HTTP · OmniMessage over SSE
┌──────┴────────────────────────┴──────────────┐
-│ core: context_engine(ReAct 循环) │
-│ ├── LLMInterface ──→ AgentHub ──→ 各模型 │
-│ ├── EnvironmentInterface ──→ 内置工具 │
-│ ├── Agent State(可编辑文件) │
-│ └── Trace(追加式 JSONL) │
+│ Server (Hono + SQLite) │
+└──────────────────────┬───────────────────────┘
+ │ session.run(...) ← Human boundary
+┌──────────────────────┴───────────────────────┐
+│ core: context_engine (ReAct loop) │
+│ ├── LLMInterface ──→ AgentHub ──→ models │
+│ ├── EnvironmentInterface ──→ builtin tools│
+│ ├── Agent State (editable files) │
+│ └── Trace (append-only JSONL) │
└──────────────────────────────────────────────┘
```
+CLI 和 Web App 经 HTTP 与 SSE 同 Server 通信。随产品交付的各个应用里,只有 Server 调用 `session.run`。
+
| 包 | 角色 |
| --- | --- |
-| `packages/core` | SDK 与执行引擎:context_engine、OmniMessage、LLM/Environment 接口、State 与 Trace |
-| `packages/cli` | 终端 Human 实现:REPL 与单次运行,直接内嵌 core |
-| `packages/server` | Web Human 实现:HTTP 承接输入与审批,SSE 推送输出流 |
-| `packages/web` | 渲染层 SPA:按 OmniMessage 协议流式渲染,不含业务引擎 |
-| `plugins/*` | 内置插件库,一插件一包:Skill(`SKILL.md` 目录)与会话钩子(脚本包),由 core 加载 |
+| `packages/core` | SDK 与引擎:`context_engine`、OmniMessage、LLM 与 Environment 接口、钩子、状态和 Trace |
+| `packages/server` | Human 实现:通过 core 运行 Task,经 HTTP 接收输入和审批,用 SSE 流式输出结果 |
+| `packages/cli` | Server 的终端客户端:REPL 与单次运行都经 HTTP 和 SSE 完成;本地没有运行中的 Server 时会自动启动一个。只有 `penguin config` 直接经 SDK 读写配置文件 |
+| `packages/web` | 纯渲染的 SPA:渲染 OmniMessage 流,不含任何引擎逻辑 |
+| `packages/desktop` | 桌面应用:一个 Electron 外壳,把 Server 作为 `utilityProcess` 运行,并在本地 HTTP 地址上打开窗口 |
+| `packages/hmr` | 热更新机制:版本存储、原子提交、资源注册表,以及 park → boot → swap |
+| `plugins/*` | 内置插件库,每个插件一个包:Skill(`SKILL.md` 目录)和会话钩子(脚本包),由 core 加载 |
+
+## 三接口边界
+
+`context_engine` 是整个系统的核心,只做两件事:维护线性消息历史,以及在三个接口之间编排事件流。它只认识 [OmniMessage](/omni-message),不做任何协议转换。
+
+- **Human**:用户侧边界。它刻意不是一个接口类:SDK 的唯一入口 `session.run(newMessages, { approve, signal })` *就是* Human 边界。输入是一组新增的 OmniMessage 和一个审批回调,输出是 OmniMessage 流。Server 是随产品交付的实现;CLI 和 Web App 经 HTTP 与 SSE 访问它,SDK 嵌入方则自己调用 `session.run`。
+- **LLM**:模型侧接口 `LLMInterface`。它把 OmniMessage 转成发往 AgentHub 模型网关的请求,再把流式事件转回 OmniMessage。供应商协议适配全部在 AgentHub 内完成,core 不引入任何厂商 SDK。
+- **Environment**:工具执行接口 `EnvironmentInterface`。它执行通过审批的工具调用,并把结果流式送回。
+
+内核不含任何供应商、工具或 UI 的细节,三侧都能按配置替换而不必改动 core:今天是本地 shell,明天可以换成别的沙箱;调用方可以是 CLI、Web App,也可以是程序化调用。接口签名见[核心接口](/interfaces)。
+
+## 一个 Task 的数据流
+
+1. Human 把一段 Prompt(一组 OmniMessage)交给 `session.run`。
+2. 引擎发起一次 Request,`LLMInterface` 流式产出 `partial_*` 分片和完整消息。
+3. 每个完整的 `tool_call` 触发一次 `approve` 决策,通过审批的调用在 Environment 中并发执行。
+4. 工具输出按原始顺序回填,作为下一次 Request 的输入。
+5. 某一轮不再产生 `tool_call` 时,Task 结束:这一轮就是最终答复。
+
+每条消息和事件都同时流向两个去处:实时推给 Human,同时追加写入 [Trace](/sessions-and-traces)。中断、重连、压缩等循环细节见 [Agent 运行循环](/agent-loop)。
## 职责划分
-判断一个设计归属哪一层,只看它的**事实来源**在哪里。四层的分工:
+判断一个设计归属哪一层,只看它的**事实来源**在哪里。判定规则只有一条:能编辑的与被记录的在文件层;让消息流动起来的在 SDK;需要常驻进程与多用户的在 Server;其余是渲染。
-| 层 | 承担 | 不承担 |
+| 层 | 负责 | 不负责 |
| --- | --- | --- |
-| SDK(`core`) | 协议与执行:让消息流动起来的一切 | 持久化用户态、多用户、任何渲染 |
-| Server | 常驻进程与多用户运行时 | 引擎逻辑(全部委托给 SDK) |
-| 文件层(`~/.penguin/data`) | 一切可编辑的定义与一切被记录的历史 | 任何计算 |
+| SDK(`core`) | 协议与执行:让消息流动的一切 | 持久化用户状态、多用户、任何渲染 |
+| Server | 常驻进程与多用户运行时 | 引擎逻辑,完全委托给 SDK |
+| 文件层(`~/.penguin/data`) | 一切可编辑的定义与一切被记录的历史 | 任何计算 |
| CLI / Web | 渲染与交互 | 业务状态 |
-逐项对应(设计 → 归属 → 承载文件或模块):
+逐项对应(设计 → 归属 → 承载文件或模块):
-| 设计 | 归属 | 承载 |
+| 设计 | 归属 | 承载位置 |
| --- | --- | --- |
| OmniMessage 协议、消息解析与分片聚合 | SDK | `core/src/omnimessage/`,见 [OmniMessage 协议](/omni-message) |
| ReAct 循环、补发、重连、压缩 | SDK | `core/src/engine/context-engine.ts`,见 [Agent 运行循环](/agent-loop) |
-| 审批机制(每个 tool_call 一次决策) | SDK | `ApproveFn`(`core/src/interfaces/shared.ts`);具体模式由 CLI/Server 注入 |
-| 工具执行与统一收尾 | SDK | `core/src/environment/`,见[工具与审批](/tools) |
-| 模型接入(Provider 协议适配) | SDK → AgentHub | `core/src/llm/` + `@prismshadow/agenthub`,见[模型与 Provider](/models) |
-| Trace 写入与 Session 恢复逻辑 | SDK | `core/src/trace/`(记录本体在文件层) |
-| Subagent 派生与消息回流 | SDK | `run_subagent` 工具 + `SubagentRunner` 注入 |
+| 审批机制(每个 `tool_call` 一次决策) | SDK | `ApproveFn`(`core/src/interfaces/shared.ts`);具体模式由 Server 或 SDK 宿主注入 |
+| 工具执行与集中收尾 | SDK | `core/src/environment/`,见[工具与审批](/tools) |
+| 模型访问(供应商协议适配) | SDK → AgentHub | `core/src/llm/` + `@prismshadow/agenthub`,见[模型与 Provider](/models) |
+| Trace 写入与 Session 恢复逻辑 | SDK | `core/src/trace/`(记录本身存放在文件层) |
+| 子 Agent 派生与消息回流 | SDK | `run_subagent` 工具 + 注入的 `SubagentRunner` |
| 多用户认证与 Project 授权 | Server | `server/src/auth/`、`server/src/services/project-service.ts` |
-| Session 索引、并发互斥、SSE 转发 | Server | `server/src/runtime/`,见 [Server API](/server-api) |
-| 定时任务(Schedule 执行) | Server | `server/src/runtime/scheduler.ts`;任务定义在文件层 `agent_state/schedule/*.toml` |
-| 审批模式持久化与人工决策 | Server | `server/src/runtime/approvals.ts` + SQLite |
-| 用量落库与成本统计 | Server | `server/src/runtime/usage-recorder.ts`、`services/usage-service.ts` |
-| Agent 行为定义(Prompt、运行参数) | 文件层 | `agent_state/system_config.yaml`、`AGENTS.md`,见[配置参考](/configuration) |
-| Skill、钩子 | 文件层 | `agent_state/skills/<name>/SKILL.md`、`agent_state/hooks/<name>/hooks.json`,见[技能与插件](/skills) |
-| 密钥 | 文件层 | Vault:`agent_state/.vault.toml`;模型凭据:`.project_config.toml`(均 0600) |
+| Session 索引、Session 级互斥、SSE 转发 | Server | `server/src/runtime/`,见 [Server API](/server-api) |
+| 定时任务执行 | Server | `server/src/runtime/scheduler.ts`;任务定义放在文件层的 `agent_state/schedule/*.toml` |
+| 审批模式持久化与手动决策 | Server | `server/src/runtime/approvals.ts` + SQLite |
+| 用量持久化与成本统计 | Server | `server/src/runtime/usage-recorder.ts`、`services/usage-service.ts` |
+| Agent 行为定义(Prompt 与运行时参数) | 文件层 | `agent_state/system_config.yaml`、`AGENTS.md`,见[配置参考](/configuration) |
+| Skill 与钩子 | 文件层 | `agent_state/skills/<name>/SKILL.md`、`agent_state/hooks/<name>/hooks.json`,见[技能与插件](/skills) |
+| 密钥 | 文件层 | Vault:`agent_state/.vault.toml`;模型凭据:`.project_config.toml`(两者权限均为 0600) |
| 模型表与默认模型 | 文件层 | `<project>/.project_config.toml` |
-| 运行历史(恢复的唯一事实来源) | 文件层 | `traces/<date>/<session>_<index>.jsonl`,见 [Session 与 Trace](/sessions-and-traces) |
-| Benchmark 题库与评分 | 文件层 | `<project>/benchmarks/<id>/`,见[自我进化](/self-improvement) |
-| 快照 | 文件层 | `snapshots/v<version>.tar.gz`;导入导出服务在 Server |
-| 流式渲染、审批 UI、统计图表 | CLI / Web | `cli/src`、`web/src`(纯渲染,不含引擎逻辑) |
+| 运行历史(恢复的唯一事实来源) | 文件层 | `traces/<date>/<session>_<index>.jsonl`,见 [Session 与 Trace](/sessions-and-traces) |
+| Benchmark 题目与分数 | 文件层 | `<project>/benchmarks/<id>/`,见[自我进化](/self-improvement) |
+| 快照 | 文件层 | `snapshots/v<version>.tar.gz`;导出/导入服务由 Server 提供 |
+| 流式渲染、审批 UI、图表 | CLI / Web | `cli/src`、`web/src`(纯渲染,不含引擎逻辑) |
+
+> [!NOTE]
+> Server 的 SQLite 只存索引与聚合数据,从不与文件层争当事实来源。
+
+## 状态层
-一句话判定:**能编辑的与被记录的在文件层;让消息流动起来的在 SDK;需要常驻进程与多用户的在 Server;其余是渲染。**Server 的 SQLite 只存索引与聚合,从不与文件层争当事实来源。
+引擎之下是纯文件的状态层。数据根目录为 `~/.penguin/data`(可用 `PENGUIN_HOME` 修改),按 `<project>/agents/<agent>/` 组织:
+
+| 组件 | 位置 | 内容 |
+| --- | --- | --- |
+| Agent State | `agent_state/` | `system_config.yaml`、`AGENTS.md`、Skill、Vault。一个 Agent 的全部行为都是可编辑的文件。 |
+| Project 配置 | `.project_config.toml` | 模型表与凭据。模型身份恒为 `(provider, model_id)` 二元组。 |
+| Trace | `traces/` | 追加式 JSONL:恢复 Session 的唯一事实来源。 |
+
+Server 额外维护一个 SQLite 索引库(用户、授权、用量统计),但从不复制文件层的事实。CLI、SDK 与 Web App 共用同一份数据目录,可以混用。
## 源码结构
-各包的目录设计(职责单一、按层拆分;文件头注释即该文件的设计说明):
+各包按层拆分,文件职责单一;每个文件的头注释就是它的设计说明。
```text
packages/
├── core/src
-│ ├── agent.ts / session.ts # createAgent 组装层与 Session(run / compact / generateTitle)
-│ ├── session-title.ts # 一次性标题生成(旁路 LLM 调用,不入 Trace)
-│ ├── engine/context-engine.ts # ReAct 循环编排:轮生命周期、审批、补发、重连、压缩
-│ ├── omnimessage/ # types.ts 协议类型 · builders.ts 构造函数 · aggregate.ts 分片聚合
-│ ├── llm/ # generative-model.ts AgentHub 适配 · tool-call-ids.ts id 唯一化
-│ ├── environment/ # environment.ts 执行与收尾 · tools/ 注册表、9 个内置工具、后台会话
-│ ├── state/ # paths · default-config · project-config · model-catalog
-│ │ # agent-state(Skill 安装、提示词装配)· agent-vault · builtin-agents
-│ ├── trace/ # writer.ts 追加式 JSONL · resume.ts 回放恢复
-│ └── internal/ # 日期与 Session 辅助
-├── cli/src # commander 入口 + run / chat / config / serve 命令与审批交互
-├── server/src # app 组装 · db(node:sqlite)· auth · http/routes · runtime · services
-├── web/src # api 客户端 · state · lib/omni 流渲染 · components · features 各页面
-├── landing/ # 产品落地页(含博客)
-└── docs/ # 本文档站
+│ ├── agent.ts / session.ts # the createAgent composition layer and Session (run / compact / generateTitle)
+│ ├── engine/context-engine.ts # ReAct loop orchestration: turn lifecycle, approvals, carry-over, reconnect, compaction
+│ ├── omnimessage/ # types.ts protocol types · builders.ts constructors · aggregate.ts partial aggregation · markers/
+│ ├── interfaces/ # llm.ts · environment.ts · shared.ts (ApproveFn and the vocabulary both sides share)
+│ ├── llm/ # generative-model.ts AgentHub adapter · tool-call-ids.ts id uniqueness · context-limits.ts
+│ ├── environment/ # environment.ts execution close-out · tools/ registry, 7 builtin tools, background sessions · mcp/
+│ ├── hooks/ # the stop / pre_tool_use / user_prompt hook points and the hook-script runner
+│ ├── plugins/ # the built-in plugin library and its loader
+│ ├── plugin/ · kernel/ # the plugin contract a server plugin compiles against · the hot-update module kernel
+│ ├── state/ # paths · default-config · project-config · model-catalog · memory
+│ │ # agent-state (Skill install, prompt assembly) · agent-vault · builtin-agents
+│ ├── trace/ # writer.ts append-only JSONL · resume.ts replay-based recovery
+│ └── internal/ # shared helpers: dates, Session support, merge queue, session-title.ts (one-shot title generation, never in Trace)
+├── server/src # index.ts boot sequence · app assembly · db (node:sqlite) · auth · http/routes · runtime · services · hmr · plugin · terminal
+├── cli/src # commander entry · commands/ (run / chat / input / logs / ls / agent / project / schedule / config / serve …) · server client and approval prompts
+├── web/src # api client · state · lib/omni stream rendering · components · feature pages (layout below)
+├── desktop/ # the Electron shell
+├── hmr/ # the hot-update mechanism
+├── landing/ # the product landing page (with the blog)
+└── docs/ # this documentation site
```
-server 与 web 的内部结构分别见 [Server API](/server-api) 与 [Web App 指南](/web-app)。
-
-## 三接口边界
-
-context_engine 是整个系统的核心,它只做两件事:维护线性消息历史,以及在三个接口之间编排事件流。它只认识 [OmniMessage](/omni-message),不做任何协议转换:
-
-- **Human**——用户侧边界。它不是一个接口类:SDK 的唯一入口 `session.run(newMessages, { approve, signal })` 就是 Human 边界本身。输入是新增的 OmniMessage 列表与审批回调,输出是流式 OmniMessage。CLI 与 Server 是它的两种实现形态。
-- **LLM**——模型侧接口(`LLMInterface`)。把 OmniMessage 翻译为模型网关 AgentHub 的请求,把流式事件翻译回 OmniMessage。所有 Provider 协议适配都在 AgentHub 内完成,core 不直接依赖任何模型厂商 SDK。
-- **Environment**——工具执行接口(`EnvironmentInterface`)。执行通过审批的工具调用,把结果以流式 OmniMessage 送回。
+### Web App 源码
-这一边界设计的意义:引擎内核不含任何 Provider、工具或 UI 细节,三侧实现均可按配置替换(本地 shell、其他执行沙箱;CLI、Web、程序化调用),而互不影响。接口签名详见[接口契约](/interfaces)。
+```text
+packages/web/src
+├── api/ # fetch wrapper · one function per API (DTOs type-only from @prismshadow/penguin-server/api) · SSE wrapper
+├── state/ # auth / project / sessions / company / theme / locale contexts
+├── lib/omni/ # OmniMessage stream → view-model reducer; connect-first + dedup stream controller
+├── components/ # ui primitives (modal / drawer / select …) and the app layout
+├── pages/ # the login pages
+└── features/ # chat / agents / skills / plugins / models / usage / traces / benchmark / schedules / company / settings / admin … pages
+```
-## 一个 Task 的数据流
+Server 的路由与投递保证见 [Server API](/server-api),Server 进程如何组装各个子系统见 [Server 启动与子系统](/server-boot)。
-1. Human 把 Prompt(OmniMessage 列表)交给 `session.run`;
-2. 引擎发起一次 Request:经 LLMInterface 流式产出 `partial_*` 与完整消息;
-3. 每个完整的 `tool_call` 触发一次 `approve` 审批;通过后交 Environment 并发执行;
-4. 工具输出按原始顺序回填,进入下一轮 Request;
-5. 某轮不再产生 `tool_call`(最终答复)时 Task 结束。
+## 关键设计决策
-全程的每条消息与事件同时流向两个去处:实时输出给 Human,以及追加写入 [Trace](/sessions-and-traces)。运行循环的细节(中断、重连、压缩)见 [Agent 运行循环](/agent-loop)。
+### 一个协议,三种职责
-## 状态层
+OmniMessage 同时是 SDK 的对外接口、Trace 的落盘格式和引擎内部的通货:「流出去的」「存下来的」「模型看到的」是同一种东西。
-引擎之下是纯文件的状态层,数据根目录为 `~/.penguin/data`(`PENGUIN_HOME` 可改),按 `<project>/agents/<agent>/` 组织:
+### 错误收敛为消息
-- **Agent State**——`agent_state/` 目录:`system_config.yaml`、`AGENTS.md`、Skills、Vault。Agent 的全部行为定义都是可编辑文件。
-- **Project 配置**——`.project_config.toml`:模型表与凭据,模型身份恒为 `(provider, model_id)` 二元组。
-- **Trace**——`traces/` 目录:追加式 JSONL,恢复 Session 的唯一事实来源。
+LLM 与 Environment 从不向引擎抛异常。它们的结果携带四值 `stop_reason`,具体原因由 `error_code` 和 `error_message` 承载:
-Server 额外维护一个 SQLite 索引库(用户、授权、用量统计),但从不复制文件层的事实——CLI、SDK 与 Web 共用同一份数据目录,可以混用。
+| `stop_reason` | 含义与引擎行为 |
+| --- | --- |
+| `completed` | 正常完成;循环继续或 Task 结束 |
+| `retryable` | 值得重试的 LLM 失败:引擎在同一次运行内自动重连,最多连续 5 次无进展的重试,指数退避并设上限 |
+| `fatal` | 确定性的失败,例如凭据被拒:运行立即停止,因为重试也不可能成功 |
+| `aborted` | 用户中断 |
-## 关键设计决策
+### 薄模型层
-- **一个协议,三种职责**:OmniMessage 同时是 SDK 对外接口、Trace 落盘格式与引擎内部通货——「流出去的」「存下来的」「模型看到的」是同一种东西。
-- **错误收敛为消息**:LLM 与 Environment 从不向引擎抛异常;结果携带六值 `stop_reason`(`completed | failed | aborted | timeout | malformed | auth`),除 `auth` 外的所有 LLM 侧状态都会触发引擎内重连(`failed / timeout / malformed`,至多 5 次、指数退避设上限)。`auth` 是唯一的终态类别:凭据被拒绝,重试不可能让它变对。重试 `failed` 是策略选择——该状态本身仍如实上报为 `failed`。
-- **薄模型层**:core 只定义 `LLMInterface`,Provider 适配全部下沉到 AgentHub(`@prismshadow/agenthub`),因此支持任意 OpenAI 兼容端点,见[模型与 Provider](/models)。
+core 只定义 `LLMInterface`,供应商适配全部下沉到 AgentHub(`@prismshadow/agenthub`),因此任意 OpenAI 兼容端点都能接入。见[模型与 Provider](/models)。
源码入口:`packages/core/src/engine/context-engine.ts`、`packages/core/src/interfaces/`。
diff --git a/packages/docs/content/chat.en.md b/packages/docs/content/chat.en.md
new file mode 100644
index 00000000..a9bee60e
--- /dev/null
+++ b/packages/docs/content/chat.en.md
@@ -0,0 +1,376 @@
+---
+title: Chat
+description: Start a conversation with an agent, follow its work as it runs, and steer it while a Task is in progress.
+---
+
+The chat page is where you work with an agent. You start a conversation, follow the agent's work as it streams in, and steer it while a Task runs. Side panels beside the conversation show its files, its Trace, its scheduled tasks and more.
+
+- New here? Start with [Start a conversation](#start-a-conversation) and [Send a message](#send-a-message).
+- While the agent works, see [While a Task runs](#while-a-task-runs).
+- To change how a conversation runs, see [Change the thinking level](#change-the-thinking-level), [Switch the model](#switch-the-model), [Hand off to another agent](#hand-off-to-another-agent) and [Fork a conversation](#fork-a-conversation).
+- To keep an eye on the agent, see [Follow the agent's work](#follow-the-agents-work), [Check Session stats](#check-session-stats) and [Manage the context](#manage-the-context).
+- To find your way around, see [Use side panels](#use-side-panels) and [Organize the conversation list](#organize-the-conversation-list).
+- For quick reference, see [Keyboard shortcuts](#keyboard-shortcuts) and [Limits](#limits).
+
+## Start a conversation
+
+A new conversation starts as a draft. The Session is created when you send the first message.
+
+1. In the sidebar, select **New chat**. The draft opens on the agent in the Project's **New chat defaults**, as long as that agent still exists in the Project; otherwise on `default_agent`, and otherwise on the first agent.
+2. Above the composer, pick the **Agent**, the **Workspace** (a directory on the server, chosen in a directory browser), the **Approval mode**, the **Model** and the **Thinking level**.
+3. Type your message and press Enter.
+
+Once the Session exists, its model and Workspace are locked. To move to another model later, see [Switch the model](#switch-the-model).
+
+Good to know:
+
+- The Project's **New chat defaults** (in **Project settings**, see [Web App](/web-app#projects-and-members)) prefill a new draft's agent, Workspace and approval mode, and the model starts as the Project's default model. The thinking level shows the agent's own level, else the Project default, else medium.
+- Switching the thinking level or the model in a draft makes it the new default: the level is written back to the selected agent's `model.thinking_level` immediately, and the model carries over to your next conversation.
+- A draft keeps its selections, text and Skills per user and Project. If you select **New chat** while a draft holds typed text, that draft moves to a **Drafts** group in the sidebar.
+
+There are four approval modes. See [Tools and Approvals](/tools).
+
+| In the picker | Mode | Tool calls |
+| --- | --- | --- |
+| **Approve everything** | `allow-all` | Every call runs without asking |
+| **Deny everything** | `deny-all` | Every call is denied |
+| **Approve read-only** | `read-only` | Read-only tools run; every other call waits for your approval |
+| **Ask every time** | `always-ask` | Every call waits for your approval |
+
+### Start from an example prompt
+
+Below the composer, the draft page files example prompts into folders, with one folder open at a time. Select a row to fill the composer with that prompt. Nothing is sent, so you can read and edit it before you send it. A built-in example also selects the Skills it needs.
+
+### Save your own shortcuts
+
+The last folder, **My shortcuts**, holds up to 3 prompts of your own.
+
+1. Type the prompt into the composer.
+2. In **My shortcuts**, select **New shortcut**. The editor opens with the composer's text, and suggests its first line as the **Name**.
+3. Save.
+
+A shortcut is a name (at most 40 characters) and a prompt (at most 4000 characters). It pins no Skills. Shortcuts are stored per user on the server, so they follow you to another browser or machine. Each row has edit and delete actions, and deleting asks first. The folder header counts them, such as `2/3`, and the **New shortcut** row disappears once 3 are saved; the cap keeps this folder the same height as a built-in one.
+
+## Send a message
+
+Press Enter to send, and Shift+Enter for a new line. In an empty composer, the up and down arrows recall the messages you typed earlier in this Session.
+
+### Attach images and files
+
+- Paste an image into the composer. Pasting accepts images only.
+- In the + menu (**More input options**), select **Upload image** or **Upload file**.
+
+An attachment can be any type. Selected files show as removable chips above the text, in the order you picked them, and a message with attachments and no text can be sent.
+
+Limits apply at two moments:
+
+- When you pick or drop a file: a file over the per-file size (100MB by default) or an image over 20MB is refused before anything is read, and the message names the limit in force.
+- When you send: a message carries at most 20 files and 120MB in total by default. Over that, the send fails with "Too many files attached to one message." or "The request is too large."
+
+An admin can change both sizes under [System settings › Upload limits](/settings#upload-limits). The 20MB cap for images placed inline does not follow them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every Session resume.
+
+On send, attached files are written into the Session's scratchpad, which is deleted with the Session. The conversation shows an "Attached files" notice; the file contents never enter the conversation, and the model opens each file by path with its file tools. On a model without image input, images are saved to the scratchpad the same way and passed as file paths, and a hint above the composer says so.
+
+### Drag files onto the chat
+
+Drag files onto the conversation or the composer, on the chat page or the draft page.
+
+- While the drag is over that area, a "Drop files to attach" overlay covers it. Dragging text, or anything that is not a file, is ignored.
+- Release to attach the whole batch. Images go the same way as pasted images and everything else becomes an attachment, with the same checks and messages as the + menu.
+- Dropping works while a Task runs; the attachments then follow the [mid-run send mode](#steer-or-queue-a-message).
+- In goal mode, dropped images are attached and files are refused with a notice.
+
+Only the chat area attaches. Dropping a file on the sidebar, the top bar, another panel or a page without a composer does nothing, and the browser does not navigate away to the file. The Files panel is the other drop target, and it uploads into the Workspace instead; see [Files panel](/files). The Files panel can also add a file, a directory or a selected passage to your message as a chip.
+
+### Use slash commands
+
+Type `/` to open the slash menu. Press Enter or Tab to run the highlighted entry. The menu does not open while a Task runs or compacts.
+
+| Command | What it does |
+| --- | --- |
+| `/compact` | Compacts the context |
+| `/agent` | Hands the conversation to another agent; see [Hand off to another agent](#hand-off-to-another-agent) |
+| `/model` | Continues the conversation on another model; see [Switch the model](#switch-the-model) |
+| `/goal` | Turns on goal mode; see [Set a goal](#set-a-goal) |
+| A Skill's name | Selects or clears an installed Skill; selected Skills are sent with the message |
+
+`/compact`, `/agent` and `/model` appear only in a started conversation: a draft has no context to compact, and it picks its agent and model up front.
+
+### Set a goal
+
+**Goal mode**, in the + menu or through `/goal`, turns your message into an objective. The harness then keeps running Tasks until the goal is complete, blocked or out of its **Token budget**, which you can set on the goal chip.
+
+- The agent needs the `goal` plugin.
+- The objective must be text. Images can come along, and file attachments are refused.
+- Goal mode cannot be turned on while a Task runs.
+
+See [Goal mode](/goal-mode).
+
+## While a Task runs
+
+While a Task runs, the composer stays live and the toolbar keeps a single action button. With an empty composer it is **Stop**, which ends the Task; it also stops a running compaction.
+
+### Steer or queue a message
+
+When you type while a Task runs, the button sends according to the **Mid-run send mode** at the bottom of the + menu. The choice is remembered in this browser.
+
+- **Steer** (the default): the button reads **Send to the running agent**. Your text, images and files reach the agent with its next turn, and the message shows as **User steering**.
+- **Queue**: the button reads **Queue as the next message**. The server holds the message and sends it as an ordinary new message when the run finishes. Until then, a line above the composer shows each queued message ("Follow-up queued — sent when this run finishes: …"). The queue survives a page reload.
+
+Some drafts cannot be steered:
+
+- Selected Skills with no text, image or file go to the queue.
+- With a staged `/agent` pick, sending opens the new conversation right away.
+- With a staged `/model` pick, sending waits until the turn finishes. The button stays **Stop**, and a line above the composer explains the wait.
+
+### Recall a message
+
+A steering message that has not reached the agent yet ("Steering queued — delivered with the next turn: …") and each queued follow-up end in a **Recall** button, a curved arrow. It puts the message back into the composer, in front of what you have typed, attachments included, so you can edit and send it again.
+
+- A steering message that already reached the agent cannot be recalled, and neither can a follow-up that has started.
+- When the run ends before a steering message is delivered, for example because you pressed **Stop** while a tool was running, the message returns to the composer by itself, attachments and all.
+
+### Approve tool calls
+
+When a tool call needs your approval, it shows allow and deny buttons in the conversation, and its step group opens. A subagent's pending approval shows as an amber dot on its row. You can change the approval mode during a Session. See [Tools and Approvals](/tools).
+
+### Send a tool call to the background
+
+When an `exec_command` or `run_subagent` call has been running for 10 seconds, its row offers **Send to background**. The call returns at once with a handle to the work, nothing is stopped, and the turn continues instead of waiting. The result arrives later as a background-task notice. The row then shows **[Background]**, and a moved command appears under [Processes](#processes).
+
+### Retry or give up
+
+When a model request fails and the harness waits at least 2s before retrying, the retry line counts down to the next attempt. Select **Retry now** to skip the wait, or **Give up** to stop the Task.
+
+A request the model provider rejects, for example because of an invalid API key, ends the run with an error line ("[Error]: llm request error: …"). Fix the problem, such as updating the key on the [Models](/models) page, and send again.
+
+## Change the thinking level
+
+The composer's thinking level picker offers low, medium, high, xhigh and max.
+
+In a started conversation, the picker shows the agent's configured level (or "—" when the agent sets none) and follows it until you pick one yourself. Until then, your sends carry no level, so changes to the agent's settings keep taking effect. A level you pick is stored on the Session:
+
+- It survives a page reload.
+- It applies to every later run of the conversation, whatever you later change in the agent's settings.
+- It is never written back to the agent's settings.
+
+Changing the level mid-conversation lowers the prompt-cache hit rate and raises cost, so a dialog asks first:
+
+- **Compact, then switch** (recommended): compacts the context like `/compact`, then applies the level. If the compaction fails, is aborted or cannot start, the level is still applied, and a notice or error says so.
+- **Switch anyway**: applies the level at once.
+- **Cancel**: keeps the current level.
+
+A compaction can only start on an idle conversation, so while a Task runs the first choice is disabled with a note, and the other two stay available. The dialog is skipped when the conversation has no messages yet, when you pick the level already shown, and right after a successful compaction.
+
+## Switch the model
+
+A Session's model is locked; selecting the model name says "Type /model to switch models". Switching continues the conversation in a new Session.
+
+1. In the composer, type `/model` and pick a model. It appears as a chip above the text, and nothing is sent yet.
+2. Type a message if you want. With an empty composer, "Continue this conversation on the new model" is sent.
+3. Press Enter.
+
+The new Session keeps the agent, the Workspace and the approval mode. It opens with a "Switched model (was …) — continued from the earlier conversation" banner that links back, and the model reads the earlier conversation's Trace file when it needs the history.
+
+- The switch waits until the Session is idle, because it continues from the Session's Trace, which a running turn or a compaction is still writing. A line above the composer says so while it waits.
+- To cancel, select × on the chip, or press Backspace at the start of the text.
+- The chip is saved with the draft, so it survives a reload or a visit to another conversation.
+
+## Hand off to another agent
+
+1. In the composer, type `/agent` and pick an agent. It appears as a chip above the text, and nothing is sent yet.
+2. Type the message to carry over.
+3. Press Enter.
+
+A new conversation opens with that agent and your text, showing where it was handed off from. With an empty composer, only the handoff itself is sent. As with `/model`, × or Backspace cancels, and the chip is saved with the draft.
+
+## Fork a conversation
+
+Under each finished reply, a stats line shows input and output Tokens, TPS, elapsed time and cost, then the reply time, copy and **Fork**. On a wide window the line appears when you point at the reply; on a phone it is always shown, without TPS. Fork is offered on replies that contain text.
+
+1. Select **Fork** (**Fork chat from here**).
+2. Confirm. The conversation up to this reply is copied into a new chat; the original stays unchanged.
+
+The fork is a new Session with the same agent, model, Workspace and approval mode. Its Trace and scratchpad are independent copies, so images and files keep rendering even after the source chat is deleted. Forks of one chat are titled `Source title (1)`, `Source title (2)` and so on, in any interface language, and a number is never reused.
+
+## Follow the agent's work
+
+- **Text** renders as it streams, and thinking blocks can be collapsed.
+- **Steps**, meaning thinking and tool calls, are grouped under a **Running** or **Done** header with the step count and time. The group is open while it runs, closes when it is done, and opens again when a call in it needs approval.
+- **Tool cards** expand to show arguments and output, with a live timer while running. A card is headed by the description the model wrote or a shortened file path. Built-in tools go by short names (`read_file` reads as "read", with the full name in the tooltip); turn this off with **Tool short names** under [System settings › Appearance](/settings#appearance). Other tools, MCP tools included, always use their own names.
+- **Compaction** leaves a row whose title is its status: **Compacting** while it runs and **Compacted** when it ends (**Clearing** and **Cleared** for a context clear), with its time. While it runs, the row opens a thinking section once the request's thinking arrives, and a result section when the summary starts; both are collapsed by default, each with its own time. The row folds back to one line when the compaction ends. A failed compaction keeps the title **Compaction** (or **Clear**) over a one-line reason.
+- **MCP connect**, the first connection to the agent's MCP servers, leaves a row with the number of tools found and the names of unavailable servers. It expands into one group per server, with its status, tool count and connect time, and each group opens to its tool list or the error.
+- **Subagents** each leave a row with their avatar, name, short Session id, a spinner while running, and an amber dot while one of their tool calls awaits approval. Selecting the row opens the **Agents panel**: a call graph of that Task at the top, with each node's elapsed time, and the selected subagent's live conversation below. Nested tool cards and approvals work as in the main chat, the subagent has a composer of its own, and **Jump to this session** opens it as a full conversation. When the current Task starts a subagent, the Agents panel opens by itself, once per Task.
+
+### Older messages
+
+A conversation opens on its latest 50 turns. Scroll near the top to load 50 more; your reading position stays in place. If loading fails, select "Failed to load earlier messages — click to retry". Once nothing older remains, "Beginning of conversation" marks the start. Turn numbers and header statistics count from the start of the conversation, so they match a full load.
+
+To return to the newest message, select **Jump to latest**. In a longer conversation, ticks in the left margin mark each exchange: point at a tick to preview it, and select it to jump there. Where the margin has no room, such as on a phone, an **Outline** button in the toolbar lists the same exchanges.
+
+## Use side panels
+
+The chat page has two docks for panels: the right sidebar and the bottom panel. The **Right sidebar** and **Bottom panel** buttons at the top right of the chat toolbar show and hide them. An empty dock offers a list of panels to open; **Add panel** adds another, and a panel can move to the other dock. Panels become available once the conversation has started.
+
+| Panel | What it shows |
+| --- | --- |
+| **Agents panel** | The Task's subagents: the call graph and each subagent's live conversation |
+| **Files** | The Workspace's files, with preview, editing and upload; see [Files panel](/files) |
+| **Memory** | The agent's memory |
+| **Trajectories** | The conversation's Trace files: a summary, per-turn statistics, an execution timeline and each event, with **Export** |
+| **Remote control** | Binding the conversation to a messaging app; see [Remote control](/remote-control) |
+| **Scheduled tasks** | Tasks that send prompts to this conversation on a schedule; see [Scheduled tasks](/schedules) |
+| Terminal | A shell; see [Use a terminal](#use-a-terminal) |
+
+Each conversation remembers its own panel layout in this browser, and switching conversations restores it. Hiding a dock keeps its panels as they were, including unsaved edits. While a subagent waits for approval, an amber dot marks the button of the dock that holds the Agents panel, or the **Right sidebar** button when the panel is closed.
+
+### Open panels with the shortcuts launcher
+
+When the right sidebar is closed on a desktop-width window, or no panel is open on a narrow one, a round **Shortcuts** button floats 32px inside the right edge of the conversation. It is not shown on the draft page or while the conversation's history is loading or failed to load.
+
+1. Select the button, or focus it and press Enter or Space. A fan of round entries opens to its left: **Agents panel**, **Files**, **Memory**, **Trajectories**, **Remote control**, **Scheduled tasks** and **Terminal**, then **Hide launcher**.
+2. Point at an entry, or focus it, to see its name under the button.
+3. Select the entry. The panel opens in the right sidebar on a desktop-width window, or in the bottom sheet on a narrow one, and the button disappears.
+
+Good to know:
+
+- The entries show icons only, with no tooltips: the name appears under the button. While the button itself is pointed at or focused, its caption says what a click does: **Open** or **Close**.
+- Up and down arrows move through the button and its entries, and Home and End jump to either end. Esc, a click elsewhere, scrolling, or tabbing away folds the fan.
+- Near the top or bottom of the conversation, the fan shortens to what fits.
+- Drag the button up or down along the edge; a short press is still a click. It springs back to the edge, never rests over the toolbar or the composer, and keeps its position in this browser for every conversation.
+- While the right sidebar is closed and a subagent awaits approval, the button and its Agents panel entry show the amber dot.
+- **Hide launcher** puts the button away for good, and a message says where to turn it back on: the **Shortcuts launcher** switch under [System settings › Appearance](/settings#appearance).
+
+### Use a terminal
+
+Terminals open as tabs in the docks, or on the standalone `/terminal` page.
+
+- Ctrl+` shows or hides the terminal tabs. With no terminal open, it takes over a running shell no conversation holds, or starts a new one.
+- Ctrl+W, with a terminal focused, closes that terminal after a confirmation, like the × on its tab. The keystroke never reaches the shell. Browsers reserve Ctrl+W for closing the browser tab and may act on it first; the desktop app passes it to the terminal.
+
+## Check Session stats
+
+The right side of the chat toolbar shows the Session's totals: Tokens, cost and elapsed time. While the conversation has background tasks, an icon with their count sits beside them. On a narrow screen, a single **Session info** icon stands in for all of them. While a Task runs, an hourglass and **Running** show next to the title.
+
+Select the totals to open the details card:
+
+- **Agent**, **Model**, the Session id (with a copy button), the **Workspace** path and when the Session was **Created**.
+- **Total Tokens**, including the cache hit rate and subagents' usage.
+- **Cost**, shown only for priced models; an asterisk means some usage has no price.
+- **Elapsed**, with two parts in parentheses, such as `Elapsed 10.3s (API 5s, tools 5.3s)`. API is the time spent in model requests, minus time waiting for your approval. Tools is the wall time covered by tool calls, so tools running in parallel count once. The two are separate measurements, not a split of the total: a background tool overlaps the model's decoding, and approval waits and harness overhead belong to neither, so they can add up to more or less than the total.
+
+Copy buttons across the app confirm in place: the icon turns into a check mark for a moment. **Copy Session ID** in a conversation's row menu shows a "Copied" message instead.
+
+### Processes
+
+Under **Processes**, the details card lists the background processes the conversation started: commands that ran past their wait time, commands started with `run_in_background`, and commands moved with **Send to background**. Each row shows the command, the start time and the pid. A running row links to the service the process serves, when one is detected (the last local URL its output printed, or a port its process group listens on).
+
+- **Stop** ends the whole process group and removes the row. The conversation is told the process was stopped, not that it failed, so the model knows the server is gone without treating it as a crash to restart.
+- An exited row is labeled "exited" and has **Remove**, which deletes the entry from the list.
+
+> [!WARNING]
+> Removing a process is immediate and final. Its captured output goes with it, and the model can no longer be asked to read that output. Keep the row until you are done with it.
+
+## Manage the context
+
+The context ring at the right of the toolbar shows how full the context is, measured against the point where compaction starts: the agent's `compaction.max_context_length`, capped by what the model's window allows. It turns amber past 80% and red past 95%. Right after a compaction, the ring is empty until the next request reports the usage.
+
+Select the ring to open the context panel:
+
+- The used and threshold figures.
+- A bar as long as the model's full window ("Max context N"), split into **System prompt**, **Tool definitions**, **User messages**, **Model messages**, **Tool requests** and **Tool results**. Select a segment or a legend row to keep it highlighted, and select it again to release it.
+- **Top 5 tools** or **Top 5 files**, switched by the **Tools** and **Files** buttons. Files are listed by name, with the full path on hover.
+
+The dashed marker on the bar is the compaction threshold. The hatched stretch past it is room the model has but the Session cannot use yet, because compaction starts first.
+
+### Change the compaction threshold
+
+1. Drag the dashed marker, or focus it and press the left and right arrow keys: each press moves 1,000 Tokens, or 10,000 with Shift.
+2. Release, or press Enter. The **Change the compaction threshold** dialog opens, and you can still edit the number. Esc cancels.
+3. Confirm. The threshold is saved to the agent and applies to this conversation at once, even mid-run.
+
+A value above the model's window is accepted, with a note that the window's size is what takes effect. When the model's window is already smaller than the agent's threshold, a notice above the composer says so, with **Open agent settings** and **Dismiss**.
+
+## Organize the conversation list
+
+The sidebar lists the Project's conversations. **Search chats** filters the titles of the conversations already loaded.
+
+In **List options** (the sliders icon at the top of the list):
+
+- **Group by**: **Group by workspace** (the default), **Group by agent** or **Group by time** (**Past day**, **Past month** and **Earlier**).
+- **Sort by**: **Most recent** or **Manual order**, where you drag rows. Manual order is offered only with a mouse or trackpad.
+
+The button beside it follows the grouping: **New workspace**, **Create agent** or **New chat**. Groups can be pinned, reordered by dragging, and have a + button that starts a new chat in them.
+
+When grouped by Workspace, the directories the system creates for itself fold into one **Temporary workspaces** group: the Workspace a conversation gets when you choose none, and the Test Workspace an evaluation creates for each case and run. Both live directly under the agent's `workspaces/` directory, and every directory there joins this group.
+
+### Row actions
+
+- Point at a row to swap its last-active time for two buttons: **Archive** and **More** (…). Tabbing to either one shows it too.
+- Right-click the row, long-press it on a touch screen, press Shift+F10, or select **More** to open its menu: **Pin**, **Rename chat**, **Remote control** (see [Remote control](/remote-control)), **Archive**, **Copy Session ID** and **Delete chat**. Esc, a click elsewhere or scrolling the list closes it.
+- **Delete chat** asks for confirmation. Deleting removes the conversation's messages and Trace for good.
+
+The right-click menu replaces the browser's own menu only on conversation rows and in the Files panel. A pinned conversation sorts to the top of its group. Pinning is offered only in the active list, and pins are remembered per Project in the browser.
+
+### Row marks
+
+| Mark | Meaning |
+| --- | --- |
+| Turning hourglass | The Session is running |
+| Squeezing bar | The Session is compacting |
+| Green dot | A run finished that you have not looked at yet |
+| Small green activity trace | The Session still has background tasks: commands running past their wait time, or background subagents mid-round. The tooltip counts them, such as "2 background tasks" |
+| Amber count | Tool calls waiting for approval |
+| Pin | The conversation is pinned |
+| Remote control icon | A messaging connection is enabled for the conversation |
+| Alarm clock | A scheduled task bound to the conversation will still fire; see [Scheduled tasks](/schedules) |
+
+The background-task mark does not depend on the others: an idle conversation whose dev server is still running keeps it, and it disappears as soon as the last task ends, without a refresh.
+
+### Folders
+
+Below each group's active conversations are its folders: **Subagents**, **Scheduled**, **Evaluations** and **Archived**, each loading its rows only when opened. When grouped by time, one set of folders covers the whole Project, and **Load more chats** fetches older conversations.
+
+- **Evaluations** holds the conversations opened by **Use** in the [Evaluation Center](/evaluation-center), and the Test Sessions an evaluation starts for every case and run, so they do not crowd the tested agent's list.
+- Opening a subagent, scheduled or evaluation conversation opens its folder.
+- A group with nothing but folder rows, such as an agent that has only run evaluations, starts collapsed and sorts after the other groups (pinned groups excepted), with a dimmed header counting the folded rows. Once you open it, it stays open for that Project.
+
+A group's active conversations, and each open folder, show ten conversations at a time. **Show N more chats** reveals ten more; rows already loaded come first, and more are fetched from the server only when they run out. Once more than ten show, **Show less** folds back to the first ten. With more than ten groups, the list shows ten groups per page, with a pager below it.
+
+## Keyboard shortcuts
+
+| Keys | Action |
+| --- | --- |
+| Enter | Send the message, or run the highlighted slash command |
+| Shift+Enter | New line |
+| Up / Down | In an empty composer, recall earlier messages of this Session |
+| Tab | Run the highlighted slash command |
+| Backspace | At the start of the text, remove a staged `/agent` or `/model` chip |
+| Shift+F10 | Open the menu of the focused conversation row, or of the Files panel |
+| Esc | Close a menu; fold the shortcuts launcher; cancel a pending threshold change |
+| Left / Right | Move the focused compaction threshold marker by 1,000 Tokens (10,000 with Shift) |
+| Ctrl+` | Show or hide the terminal tabs |
+| Ctrl+W | Close the focused terminal, after confirmation |
+
+## Limits
+
+| Item | Limit |
+| --- | --- |
+| Inline image | 20MB, separate from the attachment limits |
+| Attachments per message | 20 files |
+| Attachment size | 100MB per file and 120MB per message by default; set by an admin under [Upload limits](/settings#upload-limits) |
+| Shortcuts | 3 per user; name up to 40 characters, prompt up to 4000 |
+| History | The latest 50 turns on opening, then 50 more per load |
+| Conversation list | 10 conversations at a time per group or folder; 10 groups per page |
+| Send to background | Offered after a call has run for 10 seconds |
+| Retry countdown | Shown for waits of 2s or more |
+| Context ring | Amber past 80%, red past 95% |
+
+## How it works
+
+Some of what you do in the chat travels as structured text in the conversation, which you may notice in the Trace:
+
+- A model switch starts the new Session with a `[model_switch_from]` block naming the source Session, its title, its Trace file, its Workspace and the previous provider and model, followed by your message. The new conversation shows the block as the "Switched model" banner.
+- A steering message is sent as a `[user_steering]` user message with the agent's next turn.
+- Selected Skills travel with the message in a `[use_skills]` block.
+- Each attached file adds an `[attached file: <path>]` line to the message.
diff --git a/packages/docs/content/chat.zh.md b/packages/docs/content/chat.zh.md
new file mode 100644
index 00000000..1fff501a
--- /dev/null
+++ b/packages/docs/content/chat.zh.md
@@ -0,0 +1,376 @@
+---
+title: 对话
+description: 与 Agent 开始对话,实时跟进它的工作,并在 Task 运行期间插话。
+---
+
+对话页是你和 Agent 一起工作的地方:在这里开始对话,看 Agent 的工作过程流式呈现,并在 Task 运行时随时插话。对话旁边的侧边面板还能查看它的文件、Trace、定时任务等。
+
+- 刚开始用,先看[开始对话](#开始对话)和[发送消息](#发送消息)。
+- Agent 工作期间能做什么,见 [Task 运行期间](#task-运行期间)。
+- 想改变对话的运行方式,见[切换思考等级](#切换思考等级)、[切换模型](#切换模型)、[交接给其他 Agent](#交接给其他-agent) 和[分叉对话](#分叉对话)。
+- 想随时掌握 Agent 的状态,见[查看 Agent 的工作过程](#查看-agent-的工作过程)、[查看 Session 统计](#查看-session-统计)和[管理上下文](#管理上下文)。
+- 熟悉界面布局,见[使用侧边面板](#使用侧边面板)和[整理对话列表](#整理对话列表)。
+- 速查,见[快捷键](#快捷键)和[限制](#限制)。
+
+## 开始对话
+
+新对话从草稿开始,发送第一条消息时才创建 Session。
+
+1. 在侧边栏选择**新建对话**。草稿默认使用 Project **新对话默认值**里的那个 Agent,前提是它还在这个 Project 里;否则用 `default_agent`,再没有就用第一个 Agent。
+2. 在输入框上方选择 **Agent**、**Workspace**(服务器上的一个目录,在目录浏览器中选取)、**审批模式**、**Model** 和**思考等级**。
+3. 输入消息,按 Enter 发送。
+
+Session 创建后,模型和 Workspace 就锁定了。之后想换模型,见[切换模型](#切换模型)。
+
+几点说明:
+
+- Project 的**新对话默认值**(在 **Project 设置**中,见 [Web App](/web-app#project-与成员))会预填新草稿的 Agent、Workspace 和审批模式,模型则默认为 Project 的默认模型。思考等级优先显示 Agent 自己的等级,没有时用 Project 的默认值,再没有就是 medium(中)。
+- 在草稿里切换思考等级或模型,切换后的值就成为新的默认值:思考等级立即写回所选 Agent 的 `model.thinking_level`,模型则沿用到你的下一个对话。
+- 草稿按用户和 Project 保存所选项、正文和选中的 Skill。草稿里有已输入的文字时再点**新建对话**,这份草稿会移到侧边栏的**草稿**分组。
+
+审批模式共四种,见[工具与审批](/tools)。
+
+| 选择器中的名称 | 模式 | 工具调用 |
+| --- | --- | --- |
+| **全部放行** | `allow-all` | 全部直接执行,不询问 |
+| **全部拒绝** | `deny-all` | 全部拒绝 |
+| **放行只读** | `read-only` | 只读工具直接执行,其余调用等你审批 |
+| **总是询问** | `always-ask` | 每次调用都等你审批 |
+
+### 从示例 Prompt 开始
+
+草稿页在输入框下方把示例 Prompt 分放在几个折叠夹里,同一时间只展开一个。点击某一行,这条 Prompt 会填入输入框,但不会发送,你可以先读一读、改一改再发。内置示例还会顺带选中它需要的 Skill。
+
+### 保存自己的快捷指令
+
+最后一个折叠夹**我的快捷指令**用来存放你自己的 Prompt,最多 3 条。
+
+1. 在输入框里写好 Prompt。
+2. 在**我的快捷指令**中选择**新建快捷指令**。编辑框会带上输入框里的内容,并把第一行建议为**名称**。
+3. 保存。
+
+一条快捷指令由名称(最多 40 个字符)和 Prompt(最多 4000 个字符)组成,不绑定 Skill。快捷指令按用户保存在服务器上,换浏览器、换机器都还在。每行都有编辑和删除操作,删除前会确认。折叠夹标题会显示用量,例如 `2/3`;存满 3 条后,**新建快捷指令**这一行不再出现。设这个上限,是为了让它和内置折叠夹一样高。
+
+## 发送消息
+
+按 Enter 发送,Shift+Enter 换行。输入框为空时,按上、下方向键可以调出你在本 Session 里输入过的消息。
+
+### 附加图片和文件
+
+- 直接把图片粘贴到输入框。粘贴只接受图片。
+- 在 + 菜单(**更多输入方式**)中选择**上传图片**或**上传文件**。
+
+附件不限类型。选中的文件按选择顺序以小卡片的形式显示在正文上方,可以逐个移除;只有附件、没有文字的消息也能发送。
+
+大小和数量限制分两个时刻检查:
+
+- 选择或拖入文件时:超过单个文件大小上限(默认 100MB)的文件,或超过 20MB 的图片,会在读取之前被拒绝,提示中写明当前生效的上限。
+- 发送时:一条消息默认最多 20 个文件、合计 120MB,超出时发送失败,提示「一条消息附加的文件过多。」或「请求体过大。」
+
+管理员可以在[系统设置 › 上传限制](/settings#上传限制)中修改这两个大小。嵌入对话的图片另有 20MB 上限,不随它们变化:这类图片会进入对话和 Trace,此后每次翻阅历史、每次恢复 Session,都要再付出一次它的体积。
+
+发送时,附件写入 Session 的 scratchpad,随 Session 一起删除。对话中显示一条「附加文件」提示;文件内容本身不进入对话,模型用文件工具按路径逐个读取。如果模型不支持图片输入,图片也会这样存进 scratchpad、以文件路径传给模型,输入框上方会给出提示。
+
+### 把文件拖到对话区
+
+在对话页或草稿页,都可以把文件拖到对话内容或输入框上。
+
+- 拖动经过这个区域时,会出现覆盖整个区域的「松开以添加附件」浮层。拖动文字等非文件内容时不触发。
+- 松开即把整批文件加入附件。图片按粘贴图片的方式处理,其余文件成为附件,校验和报错与 + 菜单一致。
+- Task 运行期间也可以拖入,这时附件按[运行中发送方式](#插话或排队)发送。
+- 目标模式下,拖入的图片照常添加,文件会被拒绝并给出提示。
+
+只有对话区会接收附件。把文件拖到侧边栏、顶栏、其他面板或没有输入框的页面上,什么都不会发生,浏览器也不会跳转去打开这个文件。另一个拖放目标是文件浏览面板,它会把文件上传到 Workspace,见[文件面板](/files)。文件浏览面板还能把文件、目录或选中的一段内容作为小卡片加进你的消息。
+
+### 使用斜杠命令
+
+输入 `/` 打开斜杠菜单,按 Enter 或 Tab 执行高亮的条目。Task 运行或压缩期间,菜单不会弹出。
+
+| 命令 | 作用 |
+| --- | --- |
+| `/compact` | 压缩上下文 |
+| `/agent` | 把对话交接给另一个 Agent,见[交接给其他 Agent](#交接给其他-agent) |
+| `/model` | 换一个模型继续对话,见[切换模型](#切换模型) |
+| `/goal` | 开启目标模式,见[设定目标](#设定目标) |
+| Skill 名称 | 选中或取消一个已安装的 Skill;选中的 Skill 随消息一起发送 |
+
+`/compact`、`/agent` 和 `/model` 只在已经开始的对话里出现:草稿没有可压缩的上下文,Agent 和模型也在一开始就选定了。
+
+### 设定目标
+
+**目标模式**(在 + 菜单中,或输入 `/goal`)把你的消息变成一个目标。之后 harness 会一轮接一轮地运行 Task,直到目标完成、受阻或用完 **Token 预算**;预算可以在目标小卡片上设置。
+
+- Agent 需要安装 `goal` 插件。
+- 目标必须是文字。图片可以一起带上,文件附件会被拒绝。
+- Task 运行期间不能开启目标模式。
+
+见[目标模式](/goal-mode)。
+
+## Task 运行期间
+
+Task 运行时,输入框仍可使用,工具栏上只保留一个操作按钮。输入框为空时它是**停止**,点击结束 Task;正在进行的压缩也能用它停止。
+
+### 插话或排队
+
+Task 运行时输入了内容,发送按钮的行为取决于 + 菜单底部的**运行中发送方式**,这个选择记在当前浏览器里。
+
+- **插话**(默认):按钮显示为**发送给运行中的 Agent**。文字、图片和文件随 Agent 的下一轮送达,消息显示为**用户插话**。
+- **排队**:按钮显示为**排队为下一条消息**。消息先存在服务端,本轮运行结束后作为一条普通的新消息自动发出。在此之前,输入框上方逐条列出排队中的消息(「跟进消息已排队,本轮结束后自动发送:…」)。刷新页面后队列仍在。
+
+有几种草稿不能插话:
+
+- 只选了 Skill,没有文字、图片或文件时,改为排队。
+- 已暂存 `/agent` 的选择时,发送会立即打开新对话。
+- 已暂存 `/model` 的选择时,发送要等本轮结束:按钮保持为**停止**,输入框上方有一行说明。
+
+### 撤回消息
+
+还没送达 Agent 的插话(「插话已排队,将随下一轮送达:…」)和每条排队中的跟进消息,行尾都有一个**撤回**按钮(弯回的箭头)。点击后,消息连同附件回到输入框,排在你已输入的文字前面,可以修改后重新发送。
+
+- 已经送达 Agent 的插话不能撤回,已经开始发送的跟进消息也不能。
+- 如果插话送达之前运行就结束了(常见的情形是工具还在运行时你按了**停止**),这条消息会连同附件自动回到输入框。
+
+### 审批工具调用
+
+工具调用需要你审批时,对话里会出现允许和拒绝按钮,它所在的步骤组也会展开。子 Agent 有待审批的调用时,它那一行会显示琥珀色圆点。Session 进行中可以随时更改审批模式,见[工具与审批](/tools)。
+
+### 把工具调用转入后台
+
+`exec_command` 或 `run_subagent` 调用运行满 10 秒后,这一行会出现**转入后台执行**。点击后调用立即返回一个任务句柄,不会中止任何工作,本轮也不再等它,直接往下进行。结果之后以后台任务通知的形式送达。这一行随后标为 **[后台任务]**,转入后台的命令会出现在[会话进程](#会话进程)中。
+
+### 重试或放弃
+
+模型请求失败、harness 要等待 2 秒及以上再重试时,重试提示行会倒计时到下一次尝试。选择**立即重试**跳过剩余等待,选择**放弃**结束 Task。
+
+模型供应商拒绝的请求(例如 API key 无效)会以一行错误结束本次运行(「[错误]:模型请求错误:…」)。解决问题后重新发送即可,比如到[模型库](/models)页更新 key。
+
+## 切换思考等级
+
+输入框的思考等级选择器提供 low(低)、medium(中)、high(高)、xhigh(极高)和 max(最高)几档。
+
+在已经开始的对话里,选择器显示 Agent 配置的等级(Agent 没有设置时显示「—」),并一直跟随它,直到你自己选一档。在此之前发送消息不带等级,所以对 Agent 设置的修改会持续生效。你选定的等级保存在 Session 上:
+
+- 刷新页面后不变。
+- 这段对话之后的每次运行都用它,之后再改 Agent 设置也不影响。
+- 不会写回 Agent 设置。
+
+对话中途切换等级会降低提示词缓存命中率、增加成本,所以会先弹出确认框:
+
+- **压缩后切换**(推荐):先像 `/compact` 一样压缩上下文,压缩结束后再应用新等级。压缩失败、被中断或无法启动时,等级照样切换,并以提示或报错说明。
+- **仍要切换**:立即应用。
+- **取消**:保持当前等级。
+
+压缩只能在对话空闲时启动,所以 Task 运行期间第一项不可用,旁边有说明,另外两项照常可用。对话还没有消息、重选当前显示的等级,或者刚成功压缩完,切换时都不弹确认框。
+
+## 切换模型
+
+Session 的模型是锁定的,点击模型名称会提示「输入 /model 切换模型」。切换模型会在一个新的 Session 中继续对话。
+
+1. 在输入框输入 `/model`,选择一个模型。它以小卡片的形式出现在正文上方,此时还不会发送。
+2. 可以接着输入要说的话。输入框为空时,会发送「换用新模型继续这段对话」。
+3. 按 Enter。
+
+新 Session 沿用原来的 Agent、Workspace 和审批模式,开头有一条「已切换模型(原为 …),延续原会话」横幅,可以点回原对话;模型需要早先的历史时,会自己读取原对话的 Trace 文件。
+
+- 切换要等 Session 空闲,因为新 Session 要从原 Session 的 Trace 接续,而运行中的一轮或压缩还在写这个文件。等待期间,输入框上方有一行说明。
+- 要取消,点小卡片上的 ×,或在正文开头按 Backspace。
+- 小卡片随草稿一起保存,刷新页面或去别的对话再回来都还在。
+
+## 交接给其他 Agent
+
+1. 在输入框输入 `/agent`,选择一个 Agent。它以小卡片的形式出现在正文上方,此时还不会发送。
+2. 输入要一并带过去的消息。
+3. 按 Enter。
+
+系统会为这个 Agent 打开一个新对话,带上你的文字,并注明是从哪段对话交接来的。输入框为空时,只发送交接本身。和 `/model` 一样,× 或 Backspace 可以取消,小卡片也随草稿保存。
+
+## 分叉对话
+
+每条完成的回复下方有一行统计:输入和输出 Token、TPS、用时和成本,然后是回复时间、复制和**分叉**。宽屏上,鼠标指向回复时才显示这一行;手机上一直显示,但不显示 TPS。只有含文字的回复才提供分叉。
+
+1. 选择**分叉**(**从这里分叉对话**)。
+2. 确认。截至这条回复的对话会复制成一个新对话,原对话保持不变。
+
+分叉得到的是一个新 Session,沿用相同的 Agent、模型、Workspace 和审批模式。它的 Trace 和 scratchpad 都是独立的副本,所以即使删除了原对话,图片和文件仍能正常显示。同一对话的多个分叉依次命名为 `原标题 (1)`、`原标题 (2)` 等,不随界面语言变化,编号也不会复用。
+
+## 查看 Agent 的工作过程
+
+- **文字**随生成逐步显示,思考块可以折叠。
+- **步骤**,即思考和工具调用,归在一个标着**运行中**或**运行完毕**的分组下,显示步数和用时。分组运行时展开、结束后收起,组内有调用需要审批时会再次展开。
+- **工具卡片**可以展开查看参数和输出,运行时有实时计时。卡片标题是模型写的说明,或缩短后的文件路径。内置工具用短名显示(`read_file` 显示为「读取」,完整名称在悬停提示里),可以在[系统设置 › 外观](/settings#外观)中关闭**工具短名**。其他工具(含 MCP 工具)始终显示原名。
+- **压缩**会留下一行,标题就是状态:进行中为**压缩中**,结束后为**压缩完毕**(清空上下文时为**清空中**、**清空完毕**),并带用时。进行期间,这一行在请求的思考内容到达后出现思考部分,摘要开始生成时出现结果部分,两部分默认折叠,各有自己的用时。压缩结束后这一行收回成一行。压缩失败时,标题保持为**压缩**(或**清空**),下面一行写明原因。
+- **MCP 连接**,即首次连接 MCP 服务器,会留下一行,显示发现的工具数,并列出不可用的服务器。展开后每个服务器一组,显示状态、工具数和连接用时;再展开可以看到工具列表或失败原因。
+- **子 Agent** 各自留下一行,显示头像、名称、短 Session id,运行中带转圈动画,有工具调用待审批时带琥珀色圆点。点击这一行会打开**智能体面板**:上方是该 Task 的调用图,每个节点显示运行时长;下方是所选子 Agent 的实时对话。嵌套的工具卡片和审批与主对话完全一致,子 Agent 还有自己的输入框,**跳转到该会话**可以把它作为完整对话打开。当前 Task 派生子 Agent 时,智能体面板会自动打开,每个 Task 只自动打开一次。
+
+### 更早的消息
+
+打开对话时只加载最近 50 轮。滚动到顶部附近会再加载 50 轮,阅读位置保持不动;加载失败时,点击「更早的对话加载失败,点击重试」。没有更早的内容时,顶部显示「已是对话开头」。轮次编号和顶部统计都从对话开头算起,与一次加载全部的结果一致。
+
+要回到最新消息,选择**回到最新消息**。对话较长时,左侧留白处有一列刻度,每个刻度对应一轮问答:指向刻度可以预览,点击即跳转。留白放不下时(例如在手机上),工具栏会出现**对话索引**按钮,列出同样的内容。
+
+## 使用侧边面板
+
+对话页有两个放面板的侧栏:右侧栏和下侧栏,用对话工具栏右上角的**右侧栏**和**下侧栏**按钮显示或隐藏。空的侧栏会列出可以打开的面板;用**添加面板**可以再加一个,面板也可以移到另一侧。对话开始后才能使用这些面板。
+
+| 面板 | 内容 |
+| --- | --- |
+| **智能体面板** | 本 Task 的子 Agent:调用图和每个子 Agent 的实时对话 |
+| **文件浏览** | Workspace 中的文件,可预览、编辑和上传,见[文件面板](/files) |
+| **记忆** | Agent 的记忆 |
+| **轨迹观测** | 对话的 Trace 文件:汇总、每轮统计、执行时间线和逐条事件,可以**导出** |
+| **远程控制** | 把对话绑定到聊天软件,见[远程控制](/remote-control) |
+| **定时任务** | 按计划向这段对话发送 Prompt 的任务,见[定时任务](/schedules) |
+| 终端 | 一个 Shell,见[使用终端](#使用终端) |
+
+每段对话会在当前浏览器里记住自己的面板布局,切换对话时恢复。隐藏侧栏不会改变其中的面板,未保存的编辑也会保留。子 Agent 等待审批时,放着智能体面板的那个侧栏按钮上会出现琥珀色圆点;智能体面板没有打开时,圆点在**右侧栏**按钮上。
+
+### 用快捷方式悬浮球打开面板
+
+桌面宽度下右侧栏关闭时,或窄屏下没有打开任何面板时,对话区右缘内侧 32px 处会浮着一个圆形的**快捷方式**按钮。草稿页不显示它;对话历史正在加载或加载失败时也不显示。
+
+1. 点击按钮,或聚焦后按 Enter 或空格键。按钮左侧会展开一圈圆形入口:**智能体面板**、**文件浏览**、**记忆**、**轨迹观测**、**远程控制**、**定时任务**和**终端**,最后是**隐藏悬浮球**。
+2. 指向或聚焦某个入口,按钮下方会显示它的名称。
+3. 选择入口。桌面宽度下面板在右侧栏打开,窄屏下在底部弹层中打开,按钮随即消失。
+
+几点说明:
+
+- 入口只有图标,没有悬停提示,名称显示在按钮下方。指向或聚焦按钮本身时,下方文字说明点击后的效果:**打开**或**关闭**。
+- 上、下方向键在按钮和各入口之间移动,Home 和 End 跳到两端。按 Esc、点击别处、滚动或用 Tab 移走焦点,都会收起这圈入口。
+- 靠近对话区顶部或底部时,这圈入口会缩短,只显示放得下的部分。
+- 按钮可以沿右缘上下拖动,短按仍是点击。松手后按钮贴回边缘,不会停在工具栏或输入框上;它的位置记在当前浏览器里,所有对话共用。
+- 右侧栏关闭时,如果有子 Agent 在等待审批,按钮和其中的智能体面板入口上都会出现琥珀色圆点。
+- **隐藏悬浮球**会让按钮不再出现,同时提示在哪里重新打开:[系统设置 › 外观](/settings#外观)中的**快捷方式悬浮球**开关。
+
+### 使用终端
+
+终端以标签页的形式出现在侧栏里,也可以在独立的 `/terminal` 页面中打开。
+
+- Ctrl+` 显示或隐藏终端标签页。没有打开的终端时,会接管一个没有被任何对话占用、仍在运行的 Shell,或者新建一个。
+- 终端获得焦点时按 Ctrl+W,确认后关闭这个终端,与点击标签页上的 × 效果相同。这个按键不会传给 Shell。浏览器把 Ctrl+W 留给关闭浏览器标签页,可能会先响应;桌面应用会把它交给终端。
+
+## 查看 Session 统计
+
+对话工具栏右侧显示 Session 的累计数据:Token、成本和用时。对话还有后台任务时,旁边会多一个图标,并显示任务数量。窄屏上,这些统计合并为一个 **Session 信息**图标。Task 运行期间,标题旁显示沙漏和**运行中**。
+
+点击这组统计会打开详情卡片:
+
+- **Agent**、**Model**、Session id(旁边有复制按钮)、**Workspace** 路径,以及 Session 的**创建时间**。
+- **总 Token**,含缓存命中率和子 Agent 的用量。
+- **成本**,只在模型配置了价格时显示;带星号表示部分用量没有价格。
+- **用时**,括号里有两项,形如 `用时 10.3s(API 5s,工具 5.3s)`。API 是花在模型请求里的时间,已扣除等待你审批的时间;工具是各次工具执行覆盖的实际时间,并行的工具只算一次。两项是各自独立的测量,并不是对总用时的拆分:后台工具会和模型解码同时进行,审批等待和 harness 开销又不属于任何一项,所以两项之和可能大于、也可能小于总用时。
+
+应用里的复制按钮都在按钮本身给出反馈:图标短暂变成对勾。对话行菜单中的**复制 Session ID** 则改为弹出「已复制」提示。
+
+### 会话进程
+
+详情卡片的**会话进程**列出对话启动的后台进程:超过等待时间仍在运行的命令、用 `run_in_background` 启动的命令,以及通过**转入后台执行**转入后台的命令。每行显示命令、启动时间和 pid。检测到进程所服务的地址时,运行中的行会附上链接(取其输出中最后打印的本机 URL,否则取其进程组监听的端口)。
+
+- **停止**会结束整个进程组,并把这一行从列表移除。对话会得知这个进程是被停止的,而不是运行失败,模型因此知道服务已经关掉,不会把它当作崩溃去重启。
+- 已退出的行标注「已退出」,带**移除**按钮,可以把这一条从列表中删除。
+
+> [!WARNING]
+> 移除进程立即生效,且不可撤销。它捕获的输出会一并删除,之后无法再让模型读取这些输出。输出还有用的话,请先保留这一行。
+
+## 管理上下文
+
+工具栏右侧的上下文圆环显示上下文的占用程度,标尺是压缩触发的位置:Agent 的 `compaction.max_context_length`,但不超过模型窗口允许的大小。占用超过 80% 时变成琥珀色,超过 95% 时变成红色。刚压缩完时圆环是空的,要等下一次请求回报用量。
+
+点击圆环打开上下文面板:
+
+- 已用量与阈值。
+- 一条与模型完整窗口等长的横条(下方标着「最大上下文 N」),按**系统提示词**、**工具定义**、**用户消息**、**模型消息**、**工具请求**和**工具结果**分段。点击某一段或某个图例行会保持高亮,再点一次取消。
+- **工具用量 Top 5** 或**文件用量 Top 5**,用**工具**和**文件**按钮切换。文件只列文件名,悬停可以看到完整路径。
+
+横条上的虚线标记就是压缩阈值。虚线右侧的斜纹部分是模型还有、但 Session 暂时用不到的空间,因为压缩会先触发。
+
+### 修改压缩阈值
+
+1. 拖动虚线标记,或者聚焦后按左、右方向键:每按一次移动 1,000 Token,按住 Shift 时移动 10,000。
+2. 松开鼠标或按 Enter,弹出**修改压缩阈值**对话框,数值仍可修改。按 Esc 取消。
+3. 确认。新阈值写入 Agent,并立即对这段对话生效,运行中也不例外。
+
+填入超过模型窗口的值也会被接受,同时提示实际生效的是窗口大小。如果模型窗口本来就小于 Agent 的阈值,输入框上方会出现提示,并提供**打开 Agent 设置**和**忽略**两个按钮。
+
+## 整理对话列表
+
+侧边栏列出当前 Project 的对话。**搜索会话**按标题筛选已经加载的对话。
+
+在**列表选项**(列表顶部的滑块图标)中:
+
+- **分组方式**:**按工作区分组**(默认)、**按智能体分组**或**按时间分组**(分为**近一天**、**近一月**和**更早**)。
+- **排序方式**:**最近更新**或**手动排序**(拖动行来排序)。手动排序只在使用鼠标或触控板时提供。
+
+旁边的按钮随分组方式变化:**新建工作区**、**创建 Agent** 或**新建对话**。分组可以置顶,也可以拖动调整顺序;分组上的 + 按钮用来在该分组里新建对话。
+
+按工作区分组时,系统自己创建的目录会并入同一个**临时工作区**分组:一种是没有选择 Workspace 时对话自动得到的目录,另一种是评估为每道题目、每次运行创建的测试 Workspace。两者都直接位于 Agent 的 `workspaces/` 目录下,这个目录下的所有目录都归入该分组。
+
+### 行操作
+
+- 鼠标指向某一行时,行尾的最近活跃时间换成两个按钮:**归档**和**更多**(…)。用 Tab 移到这两个按钮上时也会显示。
+- 右键点击这一行、在触屏上长按、按 Shift+F10,或者选择**更多**,都能打开行菜单:**置顶**、**重命名对话**、**远程控制**(见[远程控制](/remote-control))、**归档**、**复制 Session ID** 和**删除对话**。按 Esc、点击别处或滚动列表会关闭菜单。
+- **删除对话**需要确认,删除后对话的消息和 Trace 会被永久移除。
+
+只有在对话行和文件浏览面板里,右键菜单才会替代浏览器自带的菜单。置顶的对话排在所属分组的最前面。置顶只在活跃列表中提供,置顶状态按 Project 记在浏览器里。
+
+### 行标记
+
+| 标记 | 含义 |
+| --- | --- |
+| 翻转的沙漏 | Session 正在运行 |
+| 向中线合拢的横条 | Session 正在压缩 |
+| 绿点 | 有一次运行已经结束,你还没有查看 |
+| 绿色小活动波形 | Session 仍有后台任务:超过等待时间仍在运行的命令,或正在跑一轮的后台子 Agent。悬停提示会显示数量,例如「2 个后台任务」 |
+| 琥珀色数字 | 有工具调用等待审批 |
+| 置顶标记 | 对话已置顶 |
+| 远程控制图标 | 这段对话已启用消息软件连接 |
+| 闹钟 | 绑定到这段对话的定时任务还会触发,见[定时任务](/schedules) |
+
+后台任务标记与其他标记互不影响:对话已经空闲、但 dev server 还开着时,标记仍在;最后一个后台任务结束的那一刻标记就会消失,无需刷新。
+
+### 折叠夹
+
+每个分组的活跃对话下方是它的折叠夹:**子智能体**、**定时任务**、**评估任务**和**已归档**,各自在展开时才加载其中的对话。按时间分组时,整个 Project 共用一组折叠夹,**加载更多会话**用来加载更早的对话。
+
+- **评估任务**收纳在[评估中心](/evaluation-center)点击**使用**打开的对话,以及评估为每道题目、每次运行启动的测试 Session,这样它们就不会挤满被测 Agent 的列表。
+- 打开子 Agent、定时任务或评估的对话时,它所在的折叠夹会自动展开。
+- 只有折叠夹、没有活跃对话的分组(例如只跑过评估的 Agent)默认折叠,排在其他分组之后(置顶的分组除外),分组标题变浅,并显示折叠的对话数。展开过一次后,在这个 Project 中会一直保持展开。
+
+分组里的活跃对话和每个展开的折叠夹,一次都显示 10 条。**展开其余 N 个对话**每次再显示 10 条:先显示已经加载的,不够时才向服务器取。显示超过 10 条后,**收起**可以折回前 10 条。分组超过 10 个时,列表每页显示 10 个分组,下方有翻页控件。
+
+## 快捷键
+
+| 按键 | 作用 |
+| --- | --- |
+| Enter | 发送消息,或执行高亮的斜杠命令 |
+| Shift+Enter | 换行 |
+| 上 / 下方向键 | 输入框为空时,调出本 Session 输入过的消息 |
+| Tab | 执行高亮的斜杠命令 |
+| Backspace | 在正文开头按下时,移除暂存的 `/agent` 或 `/model` 小卡片 |
+| Shift+F10 | 打开当前聚焦的对话行或文件浏览面板的右键菜单 |
+| Esc | 关闭菜单;收起快捷方式悬浮球;取消待确认的阈值修改 |
+| 左 / 右方向键 | 聚焦压缩阈值标记时,每次移动 1,000 Token(按住 Shift 为 10,000) |
+| Ctrl+` | 显示或隐藏终端标签页 |
+| Ctrl+W | 确认后关闭当前聚焦的终端 |
+
+## 限制
+
+| 项目 | 限制 |
+| --- | --- |
+| 嵌入对话的图片 | 20MB,与附件上限分开 |
+| 每条消息的附件数 | 20 个文件 |
+| 附件大小 | 默认单个文件 100MB、单条消息合计 120MB;管理员可在[上传限制](/settings#上传限制)中修改 |
+| 快捷指令 | 每个用户 3 条;名称最多 40 个字符,Prompt 最多 4000 个字符 |
+| 历史消息 | 打开时加载最近 50 轮,之后每次加载 50 轮 |
+| 对话列表 | 每个分组或折叠夹一次显示 10 条对话;每页 10 个分组 |
+| 转入后台执行 | 调用运行满 10 秒后提供 |
+| 重试倒计时 | 等待 2 秒及以上时显示 |
+| 上下文圆环 | 超过 80% 为琥珀色,超过 95% 为红色 |
+
+## 工作原理
+
+你在对话中的一些操作会以结构化文本的形式写进对话,查看 Trace 时可能会注意到:
+
+- 切换模型时,新 Session 的第一条消息以 `[model_switch_from]` 块开头,写明原 Session、它的标题、Trace 文件、Workspace,以及原来的供应商和模型,后面跟着你的消息。新对话把这个块显示为「已切换模型」横幅。
+- 插话以 `[user_steering]` 用户消息的形式,随 Agent 的下一轮送达。
+- 选中的 Skill 放在 `[use_skills]` 块里随消息发送。
+- 每个附件会在消息里加一行 `[attached file: <path>]`。
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 7b16379f..42396c4a 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -1,38 +1,67 @@
---
title: CLI Reference
-description: Complete reference for the penguin command, its subcommands, and options.
+description: Every penguin command and subcommand, with its options, defaults, output shapes and examples.
---
-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.
+This page documents every `penguin` command. It opens with how the CLI reaches a server and the conventions all commands share, then gives each command a summary, its usage, an options table and examples.
-The CLI is a thin client of the server: every session-facing command (`run`, `chat`, `ls`, `input`, `logs`, `agent`, `project`, `cost`, `schedule`, `org`) 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.
+The CLI ships as the npm package `@prismshadow/penguin-cli`, and the command is `penguin`. Bare `penguin` prints help. `-v, --version` prints the running build's one-line identity, and `penguin version --json` prints all of it. On startup the CLI loads a `.env` file from the working directory.
+
+The CLI is a thin client of the server. Every session-facing command (`run`, `chat`, `ls`, `input`, `logs`, `agent`, `project`, `cost`, `schedule`, `org`) sends HTTP requests to a PenguinHarness server and renders the replies. Tasks run on the server, Sessions live in its index, and the Web App sees everything the CLI creates, and the other way round. 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:
+A CLI that talks to the server on the local machine needs no login. The CLI picks its server in this order, and the first match 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.
+1. `--server <url>`: an explicit target.
+2. `PENGUIN_API_URL`: the same, from the environment. Server-driven sessions inject it into every tool subprocess, together with `PENGUIN_API_TOKEN`, `PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID`, 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`): the CLI attaches to the running local server.
+4. Auto-start: the CLI spawns a detached local server on an ephemeral port, waits for it and attaches. The server's output goes to `<root>/logs/server-auto-<date>.log`. If two CLIs race, the losing 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).
+The CLI authenticates with the local API token. The server writes a fresh token to `<root>/api-token` on every boot (owner-only), and the CLI sends it as `Authorization: Bearer`. `PENGUIN_API_TOKEN` overrides the file. The CLI reads the file only for loopback targets, so a remote `--server` needs `PENGUIN_API_TOKEN` set explicitly. Holding the file grants admin authority by design, because local filesystem access to the data root already does. `penguin server reset-admin-password` relies on the same rule.
## 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.
-- 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`.
+- 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 CLI never infers, guesses or defaults the provider. On `run` and `chat` the pair as a whole is optional: pass both to pick a model, or neither to use the Project's default model. Passing only one is an error.
+- 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 variables name the session's own Project and agent.
+- 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 that `penguin ls` prints is the intended shorthand. An ambiguous fragment is an error that lists the candidates.
+- 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, and `--agent-id` picks the agent. `input` and `logs` name the Session they picked in a dim `[latest]` line on stderr, so the target is always clear and `--json` output 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 output: `--json` prints raw JSON instead of rendered or tabular output.
+- Target server: `--server <url>` targets a specific server. See [Server connection](#server-connection).
+- Caller-context defaults: inside a harness agent (`PENGUIN_SESSION_ID` is set), a Session created by `run` or `chat` takes each unspecified field from the calling Session's live values: the Workspace, the model pair, the approval mode and the thinking level. `run_subagent` applies the same inheritance to the children it spawns, so both surfaces follow one convention. For each field, an explicit flag wins over the caller's value, which wins over the plain fallback. A failed lookup prints a dim warning and uses the plain fallback. Outside an agent nothing changes, and `--project-id` / `--agent-id` keep their environment-variable defaults.
+- Timeouts: `--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. At expiry the command detaches cleanly and exits 0. The Task keeps running on the server, and a later `penguin input` or `penguin logs` can pick it up. Accepted values are `30s`, `5m`, `2h`, or a bare integer meaning seconds; anything else is rejected. `--timeout 0` returns immediately after delivery (`{sessionId, status: "running"}` under `--json`), so the same option also covers "don't wait". Without the option, the command waits indefinitely. For new Tasks, `run --background` remains the usual fire-and-forget: it prints the bare session id for scripts and detaches as soon as the Task is created.
+- Argument errors: a missing argument, a missing required option, an unknown option or a mistyped command prints one line in the interface language, the command's own usage and a pointer to its `--help`, then exits non-zero.
+- Data root: `--root <dir>` sets the data root for the commands that read it directly: `config`, `auth`, `version`, `server status` and `server stop`. A relative path resolves against the working directory. Priority: `--root`, then the `PENGUIN_HOME` environment variable, then `~/.penguin/data`.
## penguin run
-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`.
+Creates a Session on the server (or reuses one), sends one message, streams and renders the Task until it ends, prints the stats line and exits. The exit code is 0 when the Task completes and 1 when it is aborted. A goal run exits 0 only when the goal outcome is `complete`.
+
+```bash
+penguin run -m <message> [options]
+```
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `-m, --message <message>` | The message to send. Required. | — |
+| `--project-id <id>` | Project to use. | `PENGUIN_PROJECT_ID`, else `default_project` |
+| `--agent-id <id>` | Agent to use. | `PENGUIN_AGENT_ID`, else `default_agent` |
+| `--workspace <path>` | Workspace directory. A relative path resolves against the CLI's working directory. The directory must exist on the server's machine, which in the default local setup is this machine. | The working directory |
+| `--model-id <id>` | Upstream id of the model to use. Requires `--provider`. | The Project's default model |
+| `--provider <group>` | Provider group of the model. Required with `--model-id`. | — |
+| `--approve <mode>` | Approval mode; see [Approval modes (--approve)](#approval-modes---approve). With `--session`, it PATCHes the Session's sticky mode. | `allow-all` |
+| `--thinking <level>` | Pins the Session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`) before the Task. It applies from the Session's next LLM request. | The Session's pinned level, else the agent config |
+| `--session <sessionId>` | Reuses an existing Session (full id or unique fragment) instead of creating one. Cannot be combined with `--workspace` or the model pair. | — |
+| `--source <source>` | Marks the new Session as created by a Benchmark evaluation. The only value is `benchmark`, and the Web App files such Sessions under the Evaluations folder of the session list. Cannot be combined with `--session`. | — |
+| `--background` | POSTs the Task and exits 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](#global-conventions). Cannot be combined with `--background`. | Wait indefinitely |
+| `--goal [budget]` | Goal mode: the message is the objective, and the server loops until the goal reaches a terminal state. The optional value is a token budget, such as `500k`. | — |
+| `--json` | Prints 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](#server-connection). | — |
+
+When `--timeout` expires, `run` prints what has rendered so far and a dim still-running line with the session id, then exits 0 without aborting the Task. Under `--json` it prints `{sessionId, status: "running", text}`. `--timeout 0` returns right after the POST, and under `--json` prints `{sessionId, status: "running"}` with no `text`. For a goal run, the `status` in the final JSON object is the goal outcome.
+
+Ctrl-C at an approval prompt denies that tool call. At any other time it aborts the Task on the server.
```bash
penguin run -m "Summarize the code structure of this directory"
@@ -40,62 +69,73 @@ penguin run -m "keep going" --session 402a2e24 # reuse a session by fragm
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 |
-| `--approve <mode>` | Approval mode, see below (default `allow-all`). With `--session` it PATCHes the session's sticky mode |
-| `--thinking <level>` | Pins the session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`) before the task; it applies from the session's next LLM 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 |
-| `--source <source>` | Marks the new session as created by a Benchmark evaluation; the only value is `benchmark`, and the Web App files such sessions under the Evaluations folder of the session list. Excludes `--session` |
-| `--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
-Interactive REPL; each input line starts a Task. Takes the same options as `run` (minus `-m, --message`), plus:
+Starts an interactive REPL, where each input line starts a Task.
-| Option | Description |
-| --- | --- |
-| `--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) |
+```bash
+penguin chat [options]
+```
-With `--resume`, the Workspace and model are locked by the original Session and cannot be overridden via `--workspace` / `--model-id` / `--provider`. `--thinking` is still accepted: it re-pins the existing Session, effective from its next LLM request (mid-context changes cost the provider's cached context — compacting first is recommended). On exit, a copy-pastable `penguin chat --resume <sessionId>` command is printed.
+| Option | Description | Default |
+| --- | --- | --- |
+| `--project-id <id>` / `--agent-id <id>` | Project and agent to use, as on `run`. | See [Global conventions](#global-conventions) |
+| `--workspace <path>` | Workspace directory, as on `run`. | The working directory |
+| `--model-id <id>` / `--provider <group>` | Model pair, as on `run`. | The Project's default model |
+| `--approve <mode>` | Approval mode; see [Approval modes (--approve)](#approval-modes---approve). | `allow-all` |
+| `--thinking <level>` | Pins the Session's thinking level, as on `run`. | The Session's pinned level, else the agent config |
+| `--resume [sessionId]` | Resumes a Session (full id or unique fragment). Without an id, resumes the agent's latest Session. | — |
+| `--verbose` | Shows full tool output instead of collapsing long outputs; see [Tool output collapsing](#tool-output-collapsing). | Long outputs collapsed |
+| `--server <url>` | Target server; see [Server connection](#server-connection). | — |
-In-REPL commands:
+With `--resume`, the original Session fixes the Workspace and model, so `--workspace`, `--model-id` and `--provider` cannot override them. `--thinking` is still accepted: it re-pins the existing Session from its next LLM request. Changing the level mid-context costs the provider's cached context, so compact first. On exit, if the Session has any history, the REPL prints a copy-pastable `penguin chat --resume <sessionId>` command.
+
+### In-REPL commands
| Input | Behavior |
| --- | --- |
-| any text while a Task runs | Mid-run steering: queued and delivered to the model between turns as a `[user_steering]` user message (a `»` acknowledgment echoes the text); rendering is held while you type so streamed output doesn't scribble over the line. If the Task finishes first, the line is sent as the next normal prompt |
-| `/compact` | Proactively compact the current context |
-| `/clear` | Start a fresh blank Session in place; the old Session stays on disk and can be resumed with `--resume` |
-| `/thinking` | Show this Session's thinking level: the level it is pinned to (by `--thinking` or `/thinking`), else the Agent's configured level |
-| `/thinking <level>` | Pin the Session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`); never written back to the Agent config. Soft-limited: it applies from the next request, mid-context included — the reply advises `/compact` first, since the change invalidates the provider's cached context; subagent sessions spawned from then on inherit the pinned level |
-| `/verbose` | Toggle between collapsed and full tool output |
-| `/exit`, `/quit` | Quit |
+| Any text while a Task runs | Mid-run steering. The line is queued and reaches the model between turns as a `[user_steering]` user message, and a `»` acknowledgment echoes the text. Rendering pauses while you type, so streamed output does not overwrite the line. If the Task finishes first, the line is sent as the next normal prompt. |
+| `/goal[:<budget>] <objective>` | Runs goal mode on the objective. The optional budget is a token budget, such as `/goal:500k`. Ctrl-C aborts the whole goal. See [Goal mode](/goal-mode). |
+| `/compact` | Compacts the current context now. |
+| `/clear` | Starts a fresh blank Session in place, on the same Workspace and model. The old Session stays on the server and can be resumed with `--resume`. |
+| `/thinking` | Shows this Session's thinking level: the level pinned by `--thinking` or `/thinking`, else the agent's configured level. |
+| `/thinking <level>` | Pins the Session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`). The level is never written back to the agent config. |
+| `/verbose` | Switches between collapsed and full tool output. |
+| `/exit`, `/quit` | Quits. |
+
+A pinned thinking level is soft-limited: it applies from the next request, even mid-context. The reply advises running `/compact` first, because the change invalidates the provider's cached context. Subagent Sessions spawned after the change inherit the pinned level.
+
+### Tool output collapsing
+
+Long tool outputs, such as an `exec_command` result or a whole file from `read_file`, are collapsed by default so they do not flood the screen. The first 4 lines stream live. When the output finishes, the REPL prints an elision marker (`… (+N lines, /verbose for full output)`) and the last 4 lines. Outputs of up to 9 lines appear in full.
+
+Collapsing only affects the display: the model, the Trace and the Web App always receive the complete output. `/verbose`, or starting with `--verbose`, turns collapsing off for later outputs. History shown by `--resume` is collapsed the same way. `penguin run` never collapses output, because its output feeds pipes and nested CLIs.
-Long tool outputs (an `exec_command` result, a whole file from `read_file`) are collapsed by default so they don't flood the screen: the first 4 lines stream live, and when the output finishes an elision marker (`… (+N lines, /verbose for full output)`) plus the last 4 lines are printed; outputs of up to 9 lines are shown in full. This is display-only — the model, the Trace, and the Web App always receive the complete output. `/verbose` (or starting with `--verbose`) turns collapsing off for subsequent outputs; resumed history (`--resume`) is collapsed the same way. `penguin run` never collapses: its output feeds pipes and nested CLIs.
+### Ctrl-C
-Ctrl-C is state-dependent:
+What Ctrl-C does depends on the REPL's state:
| State | Behavior |
| --- | --- |
-| Awaiting tool approval | Deny that tool call |
-| Task running | Abort the current Task and return to input |
-| Input buffer non-empty | Clear the current input |
-| Idle with empty buffer | Show an exit confirmation (y/N) |
+| Awaiting tool approval | Denies that tool call. |
+| Task running | Aborts the current Task and returns to input. |
+| Input buffer not empty | Clears the current input. |
+| Idle with an empty buffer | Shows 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`.
+Lists the Project's Sessions, for all agents or for one with `--agent-id`. Columns: short id (the 8-hex tail other commands accept as a fragment), agent, title, running/idle, last active and the end of the Workspace path. Archived Sessions appear only with `-a`.
+
+```bash
+penguin ls [options]
+```
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `--project-id <id>` / `--agent-id <id>` | Scope. Without `--agent-id`, every agent of the Project is listed. | See [Global conventions](#global-conventions) |
+| `-a, --all` | Includes archived Sessions. | — |
+| `--days <n>` | Lists only Sessions whose last activity falls within the last n calendar days. Today counts as day 1, so `--days 2` covers yesterday and today, as `cost --days` does. Combines with `-a` and `--json`. | — |
+| `--json` / `--server <url>` | See [Global conventions](#global-conventions). | — |
```bash
penguin ls
@@ -103,18 +143,30 @@ 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).
+Sends a message into a Session or, without `-m`, polls its last answer. The session id is optional. When you omit it, the command uses the agent's most recent Session (see [Global conventions](#global-conventions)), so bare `penguin input` answers "what did my agent last say".
+
+```bash
+penguin input [session_id] [options]
+```
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `-m, --message <text>` | The message text. Omit it to poll the last assistant reply instead. | — |
+| `--timeout <duration>` | Soft-yield wait budget. With `-m`, the command detaches at expiry as `run` does, and `--timeout 0` returns right after delivery. Without `-m`, the command takes the snapshot at expiry (`0` means immediately) and notes that the Session is still running. | Wait indefinitely |
+| `--project-id <id>` | Scope of the fragment search. A full session id needs none. | `PENGUIN_PROJECT_ID`, else `default_project` |
+| `--agent-id <id>` | The agent whose most recent Session an omitted session id means. | `PENGUIN_AGENT_ID`, else `default_agent` |
+| `--json` / `--server <url>` | See [Global conventions](#global-conventions) and the JSON shapes below. | — |
+
+With `-m`, a running Session receives the text as steering, delivered between turns, and an idle Session starts a new Task. By default the command waits and renders until the turn completes.
-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).
+Without `-m`, the command is a poll that mirrors `input_subagent`'s empty-prompt semantics. It prints the Session's most recent complete assistant text, an idempotent snapshot of the last answer taken from the end of the history. Thinking and tool output are skipped, and nothing is queued or steered. If the Session is running, the command first waits silently, up to `--timeout` when given (`--timeout 0` takes the snapshot immediately). If the Session is still running at expiry, the command prints the latest text with the still-running note and exits 0.
+
+Under `--json`:
+
+- With `-m`, the command prints `{sessionId, status, text}`, where `status` is `completed`, `aborted` or `running`. The `--timeout 0` shape has no `text`.
+- The poll form prints `{sessionId, status, text}`, where `status` is `idle` or `running`, and `text` is `""` when there is no reply yet.
```bash
penguin input 402a2e24 -m "also check the tests"
@@ -124,17 +176,22 @@ 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.
+Renders a Session's history with the same renderer the REPL uses. The session id is optional. When you omit it, the command uses the agent's most recent Session (see [Global conventions](#global-conventions)), so bare `penguin logs` shows what just happened.
+
+```bash
+penguin logs [session_id] [options]
+```
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `--tail <n>` | Shows only the last n entries. | All entries |
+| `-f, --follow` | Keeps following the live stream after the history. Read-only: Ctrl-C detaches without touching the Session. | — |
+| `--timeout <duration>` | Stops following after this long (soft yield, exit 0). Only meaningful with `-f`. | — |
+| `--project-id <id>` | Scope of the fragment search. | `PENGUIN_PROJECT_ID`, else `default_project` |
+| `--agent-id <id>` | The agent whose most recent Session an omitted session id means. | `PENGUIN_AGENT_ID`, else `default_agent` |
+| `--json` / `--server <url>` | `--json` prints the raw message array, and with `-f` one JSON message per line as messages arrive. | — |
```bash
penguin logs # the agent's most recent session
@@ -142,38 +199,54 @@ 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
+`agent ls` lists the Project's agents with their id, name, session count and description. `agent create` creates an agent.
+
```bash
-penguin agent ls
-penguin agent create --agent-id helper --name "Helper" --plugins software-development,goal
+penguin agent ls [--project-id <id>] [--json] [--server <url>]
+penguin agent create --agent-id <id> [options]
```
-`agent ls` lists the project's agents (id, name, session count, description). `agent create` creates one:
+Options of `agent create`:
-| Option | Description |
-| --- | --- |
-| `--agent-id <id>` | Required; the agent id (directory name) |
-| `--name <s>` / `--description <s>` | Display name and description |
-| `--plugins <a,b>` | Comma-separated library plugin names to preinstall (each one's skills and hook package); unknown names are rejected before anything is created |
-| `--project-id <id>` / `--json` / `--server <url>` | As everywhere |
+| Option | Description | Default |
+| --- | --- | --- |
+| `--agent-id <id>` | The agent id, which is also its directory name. Required. | — |
+| `--name <name>` / `--description <text>` | Display name and description. | — |
+| `--plugins <names>` | Comma-separated library plugin names to preinstall, each with its Skills and hook package. Unknown names are rejected before anything is created. | — |
+| `--project-id <id>` / `--json` / `--server <url>` | See [Global conventions](#global-conventions). | — |
+
+```bash
+penguin agent ls
+penguin agent create --agent-id helper --name "Helper" --plugins software-development,goal
+```
## 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 project ls` lists the Projects this account can reach, its own and shared ones, with their id, display name and role. It takes `--json` and `--server`.
+
+```bash
+penguin project ls
+```
## 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.
+Shows Token usage and cost from the server's usage aggregates. By default the command prints a summary card with today, the last 7 days and the total, which ignore any range options. `--by` prints a grouped table instead.
+
+```bash
+penguin cost [options]
+```
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `--days <n>` | Covers the last n days by setting the from and to dates. | — |
+| `--from <date>` / `--to <date>` | Explicit range in `yyyy-mm-dd`, always given as a pair. | — |
+| `--by <dimension>` | Groups by `date`, `agent`, `model` or `session`. | Summary card |
+| `--project-id <id>` / `--agent-id <id>` | Scope. `--agent-id` filters, and there is no default agent: costs cover the whole Project unless you narrow them. | Project: see [Global conventions](#global-conventions) |
+| `--json` / `--server <url>` | See [Global conventions](#global-conventions). | — |
+
+A `+` after a cost marks a partial sum: some model in that bucket has no pricing configured. `-` means there is no priced usage at all.
```bash
penguin cost
@@ -181,21 +254,38 @@ 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 |
+## penguin schedule
-A `+` after a cost marks a partial sum (some model in the bucket has no pricing configured); `-` means no priced usage at all.
+Lists and manages the Project's scheduled tasks.
-## penguin schedule
+```bash
+penguin schedule ls [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+penguin schedule add <name> --prompt <text> --start-at <ISO|now> [options]
+penguin schedule update <name> [options]
+penguin schedule rm <name> [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+```
-`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.
+`penguin schedule ls` lists the scheduled tasks of all agents, or of 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 state other than active (`expired`, `done`, `missed` or `invalid`). Schedule files that cannot be parsed are listed too, marked `invalid`.
-`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.
+`add`, `update` and `rm` go through the API, which writes the schedule's TOML file. The file stays the single source of truth, and the CLI acts as a validated writer, the same pattern model config and the vault follow: updates go through the system interface, validation happens at the interface layer, and hand edits stay possible. API errors are printed verbatim, so an agent gets validation right away instead of waiting for the reconcile pass that a hand edit goes through.
+
+Options of `add` and `update`:
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `--prompt <text>` | The text each firing sends. Required on `add`. | — |
+| `--start-at <ISO\|now>` | First fire time, in ISO 8601 or the literal `now` for the current instant. Required on `add`. | — |
+| `--period <duration>` | Fixed interval, at least `5m` (for example `30m`, `12h`, `1d`, `7d`). | One-shot |
+| `--end-at <ISO>` | Stops firing after this instant. | — |
+| `--session-id <id>` | Binds firings to one Session. Use either this or the new-session options, not both. | — |
+| `--workspace <path>` / `--model-id <id> --provider <group>` | New-session mode: each firing creates a Session on this Workspace and model. The model pair is both-or-neither. | A temporary Workspace; the Project's default model |
+| `--disabled` (`add`) | Creates the task disabled. | Enabled |
+| `--enable` / `--disable` (`update`) | Turns the task on or off. | — |
+| `--project-id <id>` / `--agent-id <id>` / `--json` / `--server <url>` | See [Global conventions](#global-conventions). | — |
+
+- `add` creates the task enabled, because adding a task means you want it to run; `--disabled` opts out. This is a deliberate difference from the raw file, whose `enabled = false` default stays for hand edits.
+- `update` reads the stored task, changes it and writes it back, so fields you do not specify keep their values. Switching between the bound-Session and new-session targets clears the other target's fields.
+- `rm` deletes without asking. The server still requires the Project owner.
```bash
penguin schedule add daily-report --prompt "summarize the day" --start-at 2026-09-01T09:00:00Z --period 1d
@@ -204,21 +294,9 @@ 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) |
-
## penguin org
-Company mode's command family — a thin client over the organization API. An organization's files under the Project directory (the employee tree, the desks ledger, calendar, tickets, channels) stay the single source of truth; every subcommand reads a projection of them or writes through the route that edits them, with the same validated-writer contract `schedule` has: API errors surface verbatim, so an agent gets synchronous validation instead of the reconcile lag a hand edit hits. Generated ids carry a prefix by convention — `co_` for an organization, `ch_` for a channel — which the server proposes but never enforces, so an id passed here is created exactly as typed.
+Company mode's command family, a thin client over the organization API. An organization's files under the Project directory (the employee tree, the desks ledger, the calendar, tickets and channels) stay the single source of truth. Every subcommand either reads a projection of those files or writes through the route that edits them, under the same validated-writer contract `schedule` follows: API errors are printed verbatim, so an agent gets validation right away instead of waiting for the reconcile pass a hand edit goes through. By convention, generated ids carry a prefix, `co_` for an organization and `ch_` for a channel. The server proposes these prefixes but never enforces them, so an id passed here is created exactly as typed.
```bash
penguin org ls [--project-id <id>] [--json]
@@ -261,65 +339,135 @@ penguin org handbook rm <path>
penguin org finance [--period <YYYY-MM>] [--json]
```
-Every subcommand takes `--org-id <id>`, `--project-id`, `--json` and `--server`. **`--org-id` defaults to `PENGUIN_ORG_ID`**, the one variable company mode adds to the control environment described under "Server connection": the server injects it into every tool subprocess of a desk or ticket session, so an employee's own `penguin org` calls address its organization without naming it, while a person in a shell passes the flag. There is no default organization — with neither, the command fails before contacting any server. `create` is the exception: its `--org-id` is the id to create and never comes from the environment. `--json` prints the response as one line of JSON; the write commands otherwise print a one-line confirmation.
+### Common options
+
+Every subcommand takes `--org-id <id>`, `--project-id`, `--json` and `--server`.
+
+`--org-id` defaults to `PENGUIN_ORG_ID`, the one variable company mode adds to the environment described under [Server connection](#server-connection). The server injects it into every tool subprocess of a desk or ticket session, so an employee's own `penguin org` calls reach its organization without naming it, while a person in a shell passes the flag. There is no default organization: with neither the flag nor the variable, the command fails before contacting any server. `create` is the exception, because its `--org-id` is the id to create and never comes from the environment.
+
+`--json` prints the response as one line of JSON. Without it, the write commands print a one-line confirmation.
+
+### Caller identity in a session
+
+Inside a session, the same environment identifies the caller:
+
+- `--agent-id` on the `calendar` commands and the `<agent_id>` argument of `desk` default to `PENGUIN_AGENT_ID`, so an employee schedules its own events and renews its own desk. `calendar ls` without the flag lists every employee's events.
+- `ticket start` runs the ticket session as `--agent-id` when given, else as `PENGUIN_AGENT_ID` when it is set, else as the ticket's owner, whom the server picks. The command also sends `PENGUIN_SESSION_ID`, which lets the server enforce its rule: only the ticket's owner, or a person, starts the ticket's sessions. An employee that asks for someone else's ticket, or for a ticket with no employee owner, gets `403 not_ticket_owner`, printed verbatim. The error tells it to assign the ticket instead (`penguin org ticket assign <id> --owner agent:<employee>`) and let that employee's desk pick it up in its next sweep. The owner uses `--agent-id` to bring a colleague onto its own ticket.
+- The ticket writes (`create`, `assign`, `move`, `block`, `unblock`, `progress`) and the channel writes (`create`, `invite`, `join`, `archive`, `unarchive`, `send`) send `PENGUIN_SESSION_ID` in their request body, so the file records the session's employee rather than the token's user. `ticket attach` attaches that session when `--session` is omitted; `--session` takes a full id or a unique fragment, as everywhere.
+- The channel reads (`ls`, `show`, `tail`) and the member DELETE behind `leave` and `remove` have no request body, so they send the same session as `?sessionId=`. Without it, the server would answer an employee as the signed-in person, and `channel ls` would list every channel instead of the employee's own.
+
+### ls, show and chart
+
+- `ls` lists the Project's organizations with their employee, ticket and spend counts.
+- `show` prints one organization's overview: name, mission, status and working language, employees by state, tickets per column, and the period's spend against the CEO's budget. It also lists what waits for you: mentions, tickets to review, and tickets blocked on you.
+- `chart` prints the reporting tree, indented by level, with each employee's title, live state, own and cumulative spend, and budget.
+
+An organization or employee that fails validation is listed with `invalid: <reason>` rather than hidden.
+
+### create
+
+`--ceo-budget` is the CEO's monthly budget in USD and defaults to 100. Budgets are compared along the cumulative line, the employee plus every subordinate, so the CEO's budget covers the whole company. A new organization is therefore capped rather than unbounded, and the trigger block of the initialization run names the number so the CEO can size its hiring proposal to it. `0` is a real budget of zero. To remove the cap again, send `PATCH .../employees/<org_id>_ceo` with `budget: null`, as the Web App's employee editor does.
+
+`--language zh|en` sets the organization's working language. Without it, the mission decides: one Han character anywhere in it makes the language `zh`. Everything the organization writes follows this language: its handbook, the employee briefs, the CEO's initialization run and the desk session titles.
+
+### hire
+
+`hire` takes exactly one of `--agent-id`, which hires an existing agent, and `--new-agent`, which creates one. For a new agent, `--name`, `--description` and `--skills` describe it; `--skills` lists extra library plugins, added on top of `agent-company,agent-development`, which every employee needs.
+
+`--workspace` is a subdirectory of the organization's shared workspace (`.` for all of it) or an absolute path. It is never resolved against the CLI's working directory. It defaults to a subdirectory named after the employee, because the shared root holds the shared inputs and is nobody's desk.
+
+- A relative subdirectory is normalized, so `./hr`, `hr/` and `hr` are the same partition. The server creates it when it records the hire, so `--workspace hr` is enough and nothing has to exist first.
+- An absolute path names one of the user's own directories and must already exist.
+- A path that climbs out of the shared workspace with `..` is refused with 400 `invalid_workspace`.
+
+A desk or ticket session also creates its directory when it opens. `--budget` is the monthly budget in USD for the employee plus everyone below it.
+
+### employee set
+
+`employee set` changes only the fields you give. `--workspace` works as it does for `hire` but has no default: the partition changes only when you pass the flag. `--budget` is the monthly budget in USD for the employee plus everyone below it. The model pair is both-or-neither, as everywhere.
+
+### calendar
+
+`calendar` uses the same writer as `penguin schedule`: `add` creates an enabled event unless you pass `--disabled`, `--start-at now` means the current instant, `update` reads the stored event, changes it and writes it back, and `rm` deletes without asking. Events fire into the employee's desk session, and only while both the organization and the employee are active; otherwise the status column shows `paused`.
+
+`add` and `update` answer with the event plus any rota advice the write triggered: another employee's recurring event on the same start minute, a second recurring event for the same employee with the same period, or a recurring event that starts at `now`. The CLI prints each piece of advice on its own line as `Rota notice: …`. The advice never blocks the write, and the lines stay in the server's English.
+
+### ticket
+
+- `ls` fetches the whole board and filters it locally. `--status` takes a column: `proposed`, `in_progress`, `review`, `done` or `rejected`. Under `--json`, `ls` prints the filtered list as `{ tickets, invalidFiles }`.
+- `show` prints the derived figures first (column, running state, cost and rolled-up cost, contributing sessions, child tickets), then the ticket's own fields, its prose sections, and its operation history under `History:`.
+- `create` takes either `--goal` (with `--criteria`) or the whole Markdown body from `--body-file`. The frontmatter is generated either way.
+- `start` prints the bare session id, as `run --background` does, for `penguin logs` and `penguin input` to pick up.
+- `--owner <principal>` names the one principal responsible: an employee (an agent id or `agent:<id>`) or a Project member (`user:<id>`). It defaults to the caller. When no `--notify` is given, the owner becomes the whole `notify` list, but only if the owner is an employee: a person is not notified about a ticket they own, and adds themselves with `--notify` to be told.
+- Who filed a ticket is not a flag. It is the `created` entry of the ticket's history, taken from the environment the command ran in.
+- A ticket id is `<yyyy-mm-dd>-<slug>`, where the slug is lowercase English words joined by hyphens. `--slug <words>` sets it. A title with too little English in it needs this flag when the server cannot have the Project's model name it (400 `slug_required`).
+- A write that claims work also records the calling session as one of the ticket's contributing sessions, so its cost is added to the ticket. These writes are `progress`, an edit of the body, and `move --to review`. Moving into any other column, `block` and `unblock` record nothing.
+- `progress -m` takes one plain sentence saying what was done and where; the server records who wrote it and when.
+- `--goal`, `--criteria` and `progress -m` ask for every input, deliverable and file to be named by its full path.
-The same environment identifies the caller inside a session:
+### channel
-- `--agent-id` on the `calendar` commands and the positional of `desk` default to `PENGUIN_AGENT_ID` — an employee schedules its own events and renews its own desk. `calendar ls` without the flag lists every employee's events.
-- `ticket start` runs the ticket session as `--agent-id` when given, else `PENGUIN_AGENT_ID` when set, else the ticket's owner as the server picks it. It also carries `PENGUIN_SESSION_ID`, which is what lets the server apply the rule: **only the ticket's owner, or a person, starts its sessions** — an employee asking for anyone else's ticket (or for one with no employee owner) gets `403 not_ticket_owner`, printed verbatim, telling it to assign the ticket instead (`penguin org ticket assign <id> --owner agent:<employee>`) and let that desk pick it up in its next sweep. `--agent-id` is how the owner enlists a colleague on its own ticket.
-- The ticket writes (`create`, `assign`, `move`, `block`, `unblock`, `progress`) and the channel writes (`create`, `invite`, `join`, `archive`, `unarchive`, `send`) carry `PENGUIN_SESSION_ID` in their body, so the file records the session's employee rather than the token's user; `ticket attach` attaches that session when `--session` is omitted (a full id or a unique fragment, as everywhere).
-- The channel reads (`ls`, `show`, `tail`) and the member DELETE behind `leave` and `remove` have no body, so they carry the same session as `?sessionId=`. Without it the server answers an employee as the signed-in person, and `channel ls` would list every channel instead of the employee's own.
+`--channel` defaults to `default_channel`, the all-hands channel that every employee and Project member is in. `ls` lists it first, under its localized label rather than its stored name.
-`--channel` defaults to `default_channel`, the all-hands channel every employee and Project member is in; `ls` prints it first, under its localized label rather than its stored name. A new channel holds only its creator: an employee gets in when a member invites it, a person may `join` any channel and read every one of them. `join` and `leave` name the caller's own principal — the session's employee inside a desk or ticket session, the signed-in person outside one — so joining can never add somebody else. `join`, `remove`, `archive` and `unarchive` are people's actions, so inside a session the server answers them `403 not_a_member` — like every other API error, printed verbatim.
+A new channel holds only its creator. An employee gets in when a member invites it; a person may `join` any channel and can read all of them. `join` and `leave` always act on the caller's own principal (the session's employee inside a desk or ticket session, the signed-in person outside one), so joining can never add someone else. `join`, `remove`, `archive` and `unarchive` are actions for people: inside a session the server answers them with `403 not_a_member`, which is printed verbatim like every other API error.
-Per group:
+`tail` prints the day's last 20 messages as `time sender text`; `-n` changes the count and `--date` picks another day. Under `--json` it prints the day's response with those messages. `send` posts one message, and `@agent:<id>` and `@all` mentions trigger the mentioned employees' desks. A `system` line carries a structured `notice` beside its English text, so `tail` renders it in the CLI's own language; a notice kind this build does not know keeps the English text.
-- `ls` / `show` / `chart`: the project's organizations with employee, ticket and spend counts; one organization's overview — name, mission, status and working language, employees by state, tickets per column, the period's spend against the CEO's budget, and what waits for you (mentions, tickets to review, tickets blocked on you); and the reporting tree, indented by level, with each employee's title, live state, own and cumulative spend and budget. An organization or employee that fails validation is listed with `invalid: <reason>` rather than hidden.
-- `create`: `--ceo-budget` is the CEO's monthly budget in USD and defaults to **100**. Budgets are compared on the cumulative line — the employee plus every subordinate — so the CEO's is the whole company's: a new organization is capped rather than unbounded, and the initialization run's trigger block names the number so the CEO can size its hiring proposal to it. `0` is a real (zero) budget; clearing it again — back to unbounded — is `PATCH .../employees/<org_id>_ceo` with `budget: null`, which the Web App's employee editor sends. `--language zh|en` is the organization's working language; without it the mission decides it (one Han character anywhere makes it `zh`), and everything the organization writes — its handbook, the employee briefs, the CEO's initialization run, the desk session titles — follows.
-- `hire`: exactly one of `--agent-id` (an existing Agent) and `--new-agent` (creates it; `--name`, `--description` and `--skills` — extra library plugins, added on top of the `agent-company,agent-development` every employee needs — describe it). `--workspace` is a sub-directory of the organization's shared workspace (`.` for all of it) or an absolute path, never resolved against the CLI's cwd, and defaults to a sub-directory named after the employee — the shared root holds the shared inputs and is nobody's desk. A relative sub-directory is normalized — `./hr`, `hr/` and `hr` are one partition — and created by the server as the hire is written, so `--workspace hr` is enough and nothing has to exist first; an absolute path names a directory of the user's and must already exist; a spec that climbs out of the shared workspace with `..` is refused with 400 `invalid_workspace`. `employee set --workspace` does the same but has no default: it changes the partition only when it is given. A desk or ticket session creates the directory too when it opens. `--budget` is USD per month for the employee plus everyone below it. `employee set` changes only the given fields; the model pair is both-or-neither, as everywhere.
-- `calendar`: the same writer as `penguin schedule` — `add` is enabled by default with `--disabled` opting out, `--start-at now` is the current instant, `update` is read-modify-write, `rm` deletes without prompting. Events fire into the employee's desk session, and only while the organization and the employee are active; the status column says `paused` otherwise. `add` and `update` answer with the event plus the rota advice the write earned — another employee's recurring event on the same start minute, a second recurring event for the same employee on the same period, a recurring event started at `now` — printed one per line as `Rota notice: …`. They are advisory: the write always succeeds, and the lines stay in the server's English.
-- `ticket`: `ls` fetches the whole board and filters locally (`--status` is a column: `proposed`, `in_progress`, `review`, `done`, `rejected`); `show` prints the derived figures — column, running state, cost and rolled-up cost, contributing sessions, child tickets — then the ticket's own fields, its prose sections and its operation history under `History:`. `create` takes either `--goal` (with `--criteria`) or the whole Markdown body from `--body-file`; the frontmatter is generated either way. Under `--json`, `ls` prints the filtered list as `{ tickets, invalidFiles }`. `start` prints the bare session id, like `run --background`, for `penguin logs` / `penguin input` to pick up. `--owner <principal>` names the ONE principal responsible — an employee (an Agent id or `agent:<id>`) or a Project member (`user:<id>`), the caller by default; when no `--notify` is given it becomes the whole `notify` list, but only when it is an employee: a person is not notified about a ticket they own, and lists themselves in `--notify` to be told. Who filed a ticket is not a flag — it is the `created` entry of its history, taken from the environment the command ran in. A ticket id is `<yyyy-mm-dd>-<slug>` with the slug in lowercase English words joined by hyphens; `--slug <words>` names it, and a title with too little English in it needs that flag when the server cannot have the Project's model name it (400 `slug_required`). A write that claims work — `progress`, an edit of the body, `move --to review` — also books the calling session as one of the ticket's contributing sessions, so its cost is split onto the ticket; moving into any other column, `block` and `unblock` book nothing. `progress -m` takes one plain sentence — what was done and where — since the server records who wrote it and when. `--goal`, `--criteria` and `progress -m` ask for every input, deliverable and file to be named by its full path.
-- `channel tail` prints the day's last 20 messages (`-n` changes the count, `--date` picks another day) as `time sender text` — under `--json`, the day's response with those messages; `channel send` posts one — `@agent:<id>` and `@all` mentions trigger the mentioned employees' desks. A `system` line carries a structured `notice` beside its English text, so `tail` renders it in the CLI's own language; a kind this build does not know keeps the English.
-- `finance`: the period's spend per employee (own and cumulative along the reporting line, against the budget, with `warned` / `paused` marks) and per ticket, then the total; when some usage ran on a model without pricing, a note on stderr says the figures are a lower bound.
+### handbook
+
+- `list` lists the handbook's files with their path, size and last update, the index first.
+- `show` prints one document, or the index (`README.md`) when no path is given.
+- `write` stores a document from exactly one of `-m <text>` and `--file <file>`.
+- `rm` deletes a document. The index cannot be deleted.
+
+Paths that contain `..` segments are refused.
+
+### finance
+
+`finance` prints the period's spend per employee (own and cumulative along the reporting line, against the budget, with `warned` and `paused` marks) and per ticket, then the total. When some usage ran on a model without pricing, a note on stderr says the figures are a lower bound.
## Approval modes (--approve)
| Mode | Behavior |
| --- | --- |
-| `allow-all` | Auto-approve every tool call (default) |
-| `deny-all` | Auto-reject every tool call |
-| `read-only` | Auto-approve read-only tools; prompt for the rest |
-| `always-ask` | Prompt for every tool call |
+| `allow-all` | Approves every tool call automatically (the default) |
+| `deny-all` | Rejects every tool call automatically |
+| `read-only` | Approves read-only tools automatically and asks about the rest |
+| `always-ask` | Asks about every tool call |
-At an interactive prompt, `y` / `yes` approves and `n` / `no` denies; a bare Enter defaults to approve.
+At an approval prompt, `n` or `no` denies the call. `y`, `yes` or any other answer, including a bare Enter, approves it.
## penguin config
-Manages a Project's model configuration, per-Agent vault environment variables, and the UI language. Except for `lang`, all subcommands below accept `--project-id <id>` (defaults to the default Project) and `--root <dir>`.
+Manages a Project's model configuration, per-agent vault environment variables and the UI language. Every subcommand except `lang` takes `--project-id <id>` (default: the default Project) and `--root <dir>`.
### model add
-Add or update a model entry:
+Adds or updates a model entry.
```bash
penguin config model add --provider deepseek --model-id deepseek-v4-pro --api-key sk-... --set-default
```
-| Option | Description |
-| --- | --- |
-| `--model-id <id>` | Required; the upstream model id |
-| `--provider <group>` | Required; the provider group the entry belongs to. It is never derived from the model id: gateways resell vendor models under their upstream ids, so a guessed group would write the credential onto another vendor's endpoint. Use `custom` for any endpoint outside the built-in groups. |
-| `--api-key <key>` | API key, stored inline in the Project's hidden `.project_config.toml` |
-| `--base-url <url>` | Custom endpoint base URL |
-| `--context-window <n>` | Context window size |
-| `--max-tokens <n>` | Per-model max output tokens (positive integer). Overrides the Agent's `model.max_tokens` when set; omit to inherit — lower it for small-context models |
-| `--client-type <type>` | Client protocol type |
-| `--vision` / `--no-vision` | Mark vision input as supported / unsupported |
-| `--fast-mode` / `--no-fast-mode` | Enable / disable fast mode (faster output at premium pricing; off by default). Enabling it on a model whose AgentHub client rejects the parameter still writes the entry but warns on stderr. Omit both to keep the current value |
-| `--price-cache-read <n>` | Cache-read price |
-| `--price-cache-write <n>` | Cache-write price |
-| `--price-output <n>` | Output price |
-| `--set-default` | Also set as the default model |
+| Option | Description | Default |
+| --- | --- | --- |
+| `--model-id <id>` | The upstream model id. Required. | — |
+| `--provider <group>` | The provider group the entry belongs to. Required. | — |
+| `--api-key <key>` | API key, stored inline in the Project's hidden `.project_config.toml`. | — |
+| `--base-url <url>` | Custom endpoint base URL. | See below |
+| `--context-window <n>` | Context window size, in tokens. | — |
+| `--max-tokens <n>` | Maximum output tokens for this model, a positive integer. When set, it overrides the agent's `model.max_tokens`; lower it for small-context models. | The agent's `model.max_tokens` |
+| `--client-type <type>` | AgentHub client protocol type, such as `openai-chat`. | See below |
+| `--vision` / `--no-vision` | Marks image input as supported or unsupported. | Keeps the current value |
+| `--fast-mode` / `--no-fast-mode` | Turns fast mode (faster output at premium pricing) on or off. | Off; omitting both keeps the current value |
+| `--price-cache-read <n>` | Cache-read price, in USD per million tokens. | — |
+| `--price-cache-write <n>` | Cache-write price, in USD per million tokens. | — |
+| `--price-output <n>` | Output price, in USD per million tokens. | — |
+| `--set-default` | Also sets the entry as the Project's default model. | — |
+
+- The CLI never derives `--provider` from the model id. Gateways resell vendor models under their upstream ids, so a guessed group could write the credential onto another vendor's endpoint. Use `custom` for any endpoint outside the built-in groups.
+- For a new entry, `--client-type` and `--base-url` default to what the built-in catalog sets for that exact `(provider, model_id)` pair. Without a catalog row, the group decides: a group that pins a protocol uses it; `custom`, user-defined and gateway groups get `openai-chat`, with a gateway's endpoint filled in as the base URL; and first-party vendor groups leave both unset. Updating an existing entry changes them only when you pass the flags.
+- Turning on `--fast-mode` for a model whose AgentHub client rejects the parameter still writes the entry, but prints a warning on stderr.
### model default / model vision / model list / model remove
@@ -330,13 +478,13 @@ penguin config model list
penguin config model remove --model-id <id> --provider <group>
```
-- `model default` sets the Project's default model; `model vision` sets the vision proxy model. Both require `--model-id` and `--provider`, and the reference must already exist in the model list.
-- `model list` lists configured models; the default model is marked with `*`.
-- `model remove` deletes a model entry along with the credential stored inline on it. It requires `--model-id` and `--provider` — the pair is matched exactly, so the same upstream id under another group is left alone — and exits non-zero if the pair is not in the config. When the removed entry was the default model or the vision model, that setting is cleared: a pointer left naming a model that is no longer configured would fail the next session outright.
+- `model default` sets the Project's default model, and `model vision` sets the vision proxy model. Both require `--model-id` and `--provider`, and the pair must already be in the model list.
+- `model list` lists the configured models and marks the default model with `*`.
+- `model remove` deletes a model entry together with the credential stored inline on it. It requires `--model-id` and `--provider` and matches the pair exactly, so the same upstream id under another group is left alone. It exits non-zero when the pair is not in the config. If the removed entry was the default model or the vision model, that setting is cleared, because a setting that names a model no longer configured would make the next session fail outright.
### vault
-Per-Agent environment variable store, written to `agent_state/.vault.toml`. Values are injected into tool subprocess environments only — never into the model context.
+A per-agent store of environment variables, written to `agent_state/.vault.toml`. The values are injected only into the environments of tool subprocesses, never into the model context.
```bash
penguin config vault set --key GITHUB_TOKEN --value ghp_xxx
@@ -350,71 +498,82 @@ penguin config vault remove --key GITHUB_TOKEN
| `vault list` | `[--agent-id <id>]` |
| `vault remove` | `--key <name>` (required), `[--agent-id <id>]` |
+`--agent-id` defaults to `default_agent`.
+
### lang
```bash
penguin config lang en
```
-Sets the CLI UI language (`en` or `zh`) by writing `PENGUIN_LANG` into the shell startup file.
+Sets the CLI's interface language (`en` or `zh`) by writing `PENGUIN_LANG` into your shell's startup file. In an interactive terminal the command then offers to open a new shell so the setting takes effect; otherwise it prints how to apply it. On Windows the command is refused, because there is no POSIX shell startup file to write.
## penguin server / penguin web
-Two entry points into the same service process: `server` runs headless; `web` additionally waits for readiness, prints the URL, and opens the browser.
+Two entry points into the same service process. `server` runs it headless. `web` also waits until the service is ready, prints its URL and opens the browser.
```bash
-penguin web
+penguin server [--port <port>] [--host <host>]
+penguin web [--port <port>] [--host <host>] [--no-open]
```
-| Option | Description |
-| --- | --- |
-| `--port <port>` | Listen port, default 7364 |
-| `--host <host>` | Listen host, default 127.0.0.1 |
-| `--no-open` | `web` only: do not open the browser |
+| Option | Description | Default |
+| --- | --- | --- |
+| `--port <port>` | Listen port. | `7364` |
+| `--host <host>` | Listen host. | `127.0.0.1` |
+| `--no-open` | `web` only: does not open the browser. | — |
-Port / host priority: command-line option > the `PORT` / `HOST` env vars (including `.env`) > defaults.
+Port and host are resolved in this order: the command-line option, then the `PORT` / `HOST` environment variables (including those from `.env`), then the defaults.
-Both run the service as a child process and stay behind as its supervisor: the terminal's Ctrl+C reaches the service, the command exits with the service's exit code, and when the service asks to be restarted — the Web App's **Restart and update** after `penguin update` has replaced the install — the supervisor relaunches it on the new release, printing a line as it does. A dev run through `tsx` cannot be relaunched by plain node and runs the service in-process instead; the Web App then tells the admin to restart by hand.
+If a server is already running on this data root, `penguin server` says so and exits 1, while `penguin web` prints the running instance's URL and opens it (unless `--no-open`) instead of starting a second one.
+
+Both commands run the service as a child process and stay in front of it as its supervisor. Ctrl+C in the terminal reaches the service, and the command exits with the service's exit code. When the service asks to be restarted, as the Web App's **Restart and update** does after `penguin update` has replaced the install, the supervisor starts it again on the new release and prints a line saying so. A development run through `tsx` cannot be relaunched by plain Node, so it runs the service in-process instead, and the Web App then tells the admin to restart by hand.
+
+```bash
+penguin web
+```
### penguin server status
-Prints this data root's server state and the machine's own id, as one line of JSON. It answers whether or not a server is running — the data root is the source, not a live process:
+Prints the server state of this data root and the machine's own id, as one line of JSON. It answers whether or not a server is running, because it reads the data root rather than asking a live process.
```bash
-penguin server status
+penguin server status [--root <dir>]
# {"running":true,"port":7364,"pid":41233,"machineId":"LNrJdHAZJ91G58i0"}
```
-`running` requires both that the recorded pid is alive and that its port accepts a connection, so a recycled pid does not read as a live server. `machineId` is `null` until a server has started here at least once — the id is minted on first boot and never changes afterwards. The data root is selected by `PENGUIN_HOME` as usual.
+`running` is true only when the recorded pid is alive and its port accepts a connection, so a recycled pid does not look like a live server. `port` and `pid` are `null` when no server is running. `machineId` is `null` until a server has started on this machine at least once: the id is minted on first boot and never changes afterwards. The data root comes from `--root` or `PENGUIN_HOME` as usual.
-This is what the Machines page runs over ssh to ask a machine what it is doing, which is why the output is JSON rather than prose.
+The **Machines** page runs this command over ssh to ask a machine what it is doing, which is why the output is JSON rather than prose.
### penguin server reset-admin-password
-Offline rescue when the Web admin password is forgotten. Run it with the server stopped — it refuses while one is running on the data root:
+An offline rescue for a forgotten Web admin password. Run it with the server stopped; it refuses while a server is running on the data root.
```bash
penguin server reset-admin-password
```
-The built-in `admin` is returned to the unclaimed state — a random password nobody ever sees, and every one of admin's sessions revoked. Start the server again and open the first-login link it prints to set a new password; nothing is written down in the meantime. Other accounts are reset by the admin on the user-management page; this command only touches `admin`. The data root is selected by `PENGUIN_HOME` as usual.
+The built-in `admin` returns to the unclaimed state: its password becomes a random one nobody has seen, and all of its sessions are revoked. Start the server again and open the first-login link it prints to set a new password; nothing needs to be written down in between. The admin resets other accounts on the **Users** page, and this command only touches `admin`. The data root comes from `PENGUIN_HOME` as usual.
### penguin server stop
-Stops the server on this data root and reports the outcome as one line of JSON:
+Stops the server on this data root and reports the outcome as one line of JSON.
```bash
-penguin server stop
+penguin server stop [--root <dir>]
# {"ok":true,"pid":41233}
```
-A `SIGTERM` and a wait, never a `SIGKILL`: the server holds a database and may be finishing a task, and a caller deciding to destroy that on a timeout is not its call to make. A root with nothing serving it answers `{"ok":true}` — that is the outcome asked for, not a failure.
+The command sends `SIGTERM` and waits up to 15 seconds for the server to let go of the data root. It never sends `SIGKILL`: the server holds a database and may be finishing a task, and destroying that on a timeout is not a caller's decision to make. A root with no server running answers `{"ok":true}`, because nothing serving the root is the outcome the caller asked for.
+
+When the server cannot be stopped, the command prints `{"ok":false,"pid":…,"detail":"…"}` and exits 1. That happens when the signal cannot be delivered, when the server still holds the data root 15 seconds after `SIGTERM`, and on Windows, where a graceful stop cannot be signalled; stop the server from its own console there.
-The Machines page runs this over ssh when it restarts a machine. It is a command rather than a request to the server itself because the machine that needs stopping is usually the one whose platform is behind, and a platform route only exists once the machine already runs the build that has it.
+The **Machines** page runs this command over ssh when it restarts a machine. It is a command rather than a request to the server because the machine that needs stopping is usually the one whose platform is out of date, and a platform route exists only once the machine already runs the build that has it.
## penguin version
-Reports which build is running. The version number alone cannot answer that — every build made from a checkout between two releases also calls itself `0.2.3` — so a release and a source build identify themselves differently.
+Reports which build is running. The version number alone cannot answer that, because every build made from a checkout between two releases also calls itself `0.2.3`, so a release and a source build identify themselves differently.
```bash
penguin version # v0.2.3 (a release)
@@ -422,20 +581,24 @@ penguin version # v0.2.3-14-g9e8f7d6-dirty (built from a checkout)
penguin version --json # the full build info
```
-| Option | Description |
-| --- | --- |
-| `--json` | Print the full version report instead of the one line: `{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}` |
-| `--root <dir>` | Data root whose HMR store to report as `harness`. Priority: `--root` > `PENGUIN_HOME` > `~/.penguin/data` |
+| Option | Description | Default |
+| --- | --- | --- |
+| `--json` | Prints the full version report instead of one line: `{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}`. | — |
+| `--root <dir>` | The data root whose HMR store is reported as `harness`. Only used with `--json`. | `PENGUIN_HOME`, else `~/.penguin/data` |
-The bare form prints one line, which for a source build is `git describe --tags --dirty` output — `v0.2.3-14-g9e8f7d6-dirty` reads as fourteen commits past `v0.2.3`, at `9e8f7d6`, with uncommitted changes. `-v, --version` prints that same line.
+The bare form prints one line. For a source build, that line is the output of `git describe --tags --dirty`: `v0.2.3-14-g9e8f7d6-dirty` means fourteen commits after `v0.2.3`, at commit `9e8f7d6`, with uncommitted changes. `-v, --version` prints the same line.
-`describe` names the nearest reachable git tag, which is not always `v` + `version`: release preparation bumps `version` in its own commit and creates the tag afterwards, so a build from that window reports `v0.2.3-14-g9e8f7d6` while `version` already reads `0.2.4`. Read `version` for the release number and `describe` for the position in history.
+`describe` names the nearest reachable git tag, which is not always `v` followed by `version`. Release preparation bumps `version` in its own commit and creates the tag afterwards, so a build from that window reports `v0.2.3-14-g9e8f7d6` while `version` already reads `0.2.4`. Read `version` for the release number and `describe` for the position in history.
-The JSON is the same record `GET /api/version` returns, so a bug report can be gathered from either side of the HTTP boundary. In it, `channel` is `release` or `source`; `buildDate` and `commit` are stamped into the build by the release workflow and are null for a source build; `branch` and `dirty` describe a source build's git position and are null for a release, where the question does not apply — the workflow stamps its constants into the tree before building.
+The JSON is the same record that `GET /api/version` returns, so a bug report can collect it from either side of the HTTP boundary. In it:
+
+- `channel` is `release` or `source`.
+- `buildDate` and `commit` are stamped into the build by the release workflow, and are null for a source build.
+- `branch` and `dirty` describe a source build's git position, and are null for a release, where they do not apply: the release workflow stamps its constants into the tree before building.
### harness: what was hot-pushed here
-`harness` describes the data root's HMR store — the harness code a hot update committed, which a restart resumes. It is null when nothing was ever pushed to that root.
+`harness` describes the data root's HMR store: the harness code a hot update committed, which a restart resumes. It is null when nothing was ever pushed to that root.
```json
"harness": {
@@ -445,16 +608,15 @@ The JSON is the same record `GET /api/version` returns, so a bug report can be g
}
```
-This is the one thing the version line cannot report. A pushed bundle lands outside any checkout, so it identifies itself by the version it was compiled from and nothing more; `source.revision` — recorded by the pusher, spelled the same way as `describe` — is the only thing that names the revision behind it. `bundles` holds the committed artifacts' content-addressed pointers, which identify the pushed code itself regardless of what the pusher claimed about it.
+This is the one thing the version line cannot report. A pushed bundle lands outside any checkout, so it can only identify itself by the version it was compiled from. `source.revision`, recorded by the pusher and written the same way as `describe`, is the only field that names the revision behind it. `bundles` holds the content-addressed pointers of the committed artifacts, which identify the pushed code itself whatever the pusher claimed about it.
-It describes the store, not the process: `penguin` runs the packaged CLI while `penguin-hmr` runs the store's, so a non-null `harness` does not by itself mean the command printing it is the pushed code. `source` is null for a version pushed by a client that recorded no provenance, including anything pushed before it was recorded at all.
+`harness` describes the store, not the running process. `penguin` runs the packaged CLI while `penguin-hmr` runs the store's, so a non-null `harness` does not mean the command that printed it is the pushed code. `source` is null for a version pushed by a client that recorded no provenance, including anything pushed before provenance was recorded at all.
-An installed penguin never shells out to git: it reads constants stamped into the build. A release gets them from the release workflow; every other build gets its git position inlined by the bundler that produced it, so an artifact still identifies itself after it has left the checkout it came from — a hot-pushed bundle under `<root>/hmr/store/` reports the revision it was built at, on a machine with no checkout and no git installed. Asking git at run time is only the fallback, for an un-bundled `tsx` run; even then it asks about its own checkout, so `penguin version` inside an unrelated repository reports the harness's revision and not that repository's.
-## penguin auth
+An installed `penguin` never runs git: it reads constants stamped into the build. A release gets them from the release workflow. Every other build gets its git position inlined by the bundler that produced it, so an artifact still identifies itself after it leaves its checkout: a hot-pushed bundle under `<root>/hmr/store/` reports the revision it was built at, even on a machine with no checkout and no git installed. Asking git at run time is only the fallback for an unbundled `tsx` run, and even then it asks about its own checkout, so `penguin version` run inside an unrelated repository reports the harness's revision, not that repository's.
-Signs in to a running PenguinHarness server from the terminal. This is the only part of the CLI that talks to a server as a client — `config`, `run` and `chat` all work on the data root directly.
+## penguin auth
-Two ways in, and which is right depends on where you are standing.
+Signs in to a running PenguinHarness server from the terminal. There are two ways in, and the right one depends on where you are.
```bash
penguin auth login # password, against the server on this data root
@@ -464,54 +626,74 @@ penguin auth logout
penguin auth token # no password: minted from this data root
```
-`login` takes a password and asks a running server for a session, exactly as the browser's login page does. The target defaults to the server running on this data root (read from its lock file), so signing in to your own needs no URL.
+Every `auth` subcommand takes `--root <dir>` to pick the data root; see [Global conventions](#global-conventions).
-Run interactively it asks for the account first, then the password — and the password prompt names the account, so one account's password is never typed at another's. Supply the password non-interactively (`--password` or `PENGUIN_PASSWORD`) and neither question is asked: that is a script, and a script cannot answer one.
+### penguin auth login
-| Option | Description |
-| --- | --- |
-| `--server <url>` | Server to sign in to; default the one running on this data root |
-| `--user-id <id>` | Account; asked for when omitted, defaulting to `admin` on a bare Enter |
-| `--password <pw>` | Password; also read from `PENGUIN_PASSWORD`, otherwise prompted without echo |
-| `--print` | Also print the session token to stdout, for piping |
+`login` takes a password and asks a running server for a session, exactly as the browser's login page does. The target defaults to the server running on this data root, read from its lock file, so signing in to your own server needs no URL.
-Prefer `PENGUIN_PASSWORD` or the prompt over `--password`: a command line is world-readable through `ps`.
+When run interactively, `login` asks for the account first and then the password, and the password prompt names the account, so you never type one account's password for another. If you supply the password non-interactively (`--password` or `PENGUIN_PASSWORD`), neither question is asked, because a script cannot answer them.
-`token` takes no password at all. It writes a session row straight into the data root's `web.db`, and what authorizes it is that you can read and write that root — which already holds every credential the token could reach. That makes it the **data root owner's** tool: on a multi-user deployment the root belongs to the OS account running the server, and everyone else signs in with `auth login` instead. Use it where there is no password to give: a machine whose admin password somebody set by hand, a script that must not hold one, or a controller reaching a managed machine over ssh.
+| Option | Description | Default |
+| --- | --- | --- |
+| `--server <url>` | The server to sign in to. | The server running on this data root |
+| `--user-id <id>` | The account. Asked for when omitted; a bare Enter means `admin`. | `admin` |
+| `--password <pw>` | The password. Also read from `PENGUIN_PASSWORD`; otherwise prompted for without echo. | — |
+| `--print` | Also prints the session token to stdout, for piping. | — |
-| Option | Description |
-| --- | --- |
-| `--user-id <id>` | Account, default `admin` |
-| `--ttl-seconds <n>` | Lifetime, default 3600 |
-| `--mark` | Print a fixed marker line before the token — for a caller parsing it out of a shell whose login profile may print a banner |
+> [!WARNING]
+> Prefer `PENGUIN_PASSWORD` or the prompt over `--password`: anyone on the machine can read a command line through `ps`.
+
+### penguin auth token
+
+`token` takes no password at all. It writes a session row straight into the data root's `web.db`, and what authorizes it is that you can read and write that root, which already holds every credential the token could reach. That makes `token` the tool of the **data root owner**: on a multi-user deployment the root belongs to the OS account that runs the server, and everyone else signs in with `auth login`. It fails when no server has ever run on the data root, since there is no `web.db` to write to yet. Use it where there is no password to give:
-The session is written to `<root>/cli-session.json` at mode 0600, which is what `status` reads and `logout` revokes and deletes. `logout` tells the server first, so the session dies there rather than merely being forgotten here; if the server cannot be reached it says so, and the local file goes anyway.
+- A machine whose admin password someone set by hand.
+- A script that must not hold a password.
+- A controller reaching a managed machine over ssh.
+
+| Option | Description | Default |
+| --- | --- | --- |
+| `--user-id <id>` | The account. | `admin` |
+| `--ttl-seconds <n>` | The session's lifetime in seconds: a positive integer, capped at 30 days. | `3600` |
+| `--mark` | Prints a fixed marker line before the token, for a caller that parses the token out of a shell whose login profile may print a banner. | — |
+
+### penguin auth status / penguin auth logout
+
+The session is stored in `<root>/cli-session.json` with mode 0600. `login` writes it, and so does `token` when a server is running on the data root. `status` reads it. `logout` revokes the session and deletes the file: it tells the server first, so the session ends on the server rather than merely being forgotten locally. If the server cannot be reached, `logout` says so and deletes the local file anyway.
## penguin update
-Upgrades this install in place, using the mechanism it was installed with. The install kind is detected from the real path of the running CLI, never guessed.
+Upgrades this install in place, using the mechanism it was installed with. The command detects the install kind from the real path of the running CLI and never guesses.
```bash
penguin update --check # report versions only
penguin update # upgrade to the latest release, after confirming
```
-| Option | Description |
-| --- | --- |
-| `--check` | Only report the installed and latest versions; change nothing. Exit code is 0 either way |
-| `--release <tag>` | Target a specific release instead of the latest (`v0.1.2` or `0.1.2`); older tags are allowed and reported as a downgrade |
-| `-y, --yes` | Skip the confirmation prompt |
+| Option | Description | Default |
+| --- | --- | --- |
+| `--check` | Only reports the installed and latest versions, and changes nothing. Exits 0 either way. | — |
+| `--release <tag>` | Targets a specific release instead of the latest (`v0.1.2` or `0.1.2`). Older tags are allowed and reported as a downgrade. | The latest release |
+| `-y, --yes` | Skips the confirmation prompt. | — |
-The target flag is `--release`, not `--version`, because `-v, --version` is the CLI's own version flag and would take precedence.
-
-Release discovery and tarball downloads honor `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`, using the same policy as the stable installer entry point. The default `auto` mode reads the OSS `latest.json`, prefers that immutable release, and falls back to the matching GitHub tag; the package itself is then served by whichever source the installer's speed probe picks. Forced `oss` and `github` modes are strict; `--release <tag>` skips latest-version discovery while retaining the selected source policy. An explicit HTTPS `PENGUIN_DOWNLOAD_BASE_URL` has highest priority for installer and payload downloads, with an optional `PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` for the payload.
+The flag is `--release`, not `--version`, because `-v, --version` is the CLI's own version flag and would take precedence.
| Install kind | How it upgrades |
| --- | --- |
-| Tarball (`install.sh`, default `~/.penguin`) | Re-runs the official installer, preserving the install dir and whether the package bundles a Node runtime |
-| Global npm/pnpm/yarn/bun install | Runs that manager's global install of `@prismshadow/penguin-cli@<target>`; if the manager cannot be identified, prints the command instead of guessing |
-| Source checkout | Refused — update it with `git pull` and a rebuild |
+| Tarball (`install.sh`, default `~/.penguin`) | Re-runs the official installer, keeping the install directory and whether the package bundles a Node runtime |
+| Global npm, pnpm, yarn or bun install | Runs that package manager's global install of `@prismshadow/penguin-cli@<target>`. If the manager cannot be identified, prints the command instead of guessing |
+| Source checkout | Refused: update it with `git pull` and a rebuild |
+| The desktop app's bundled CLI | Refused: it is replaced when the app updates, so check for updates from the app menu |
+| Unrecognized layout | Refused: reinstall with the official installer, or upgrade with the package manager you used |
+
+Without `-y`, the command prints exactly what it will do (the mechanism, the target version and the install directory) and asks for confirmation. When stdin is not a terminal, it requires `--yes` instead of waiting on a prompt nobody can answer. **The data root is never touched**: an upgrade replaces only `bin`, `lib`, `web` and `node`. On Windows neither upgrade path runs in place. The installer is a POSIX shell script, and a global install cannot be driven from here because Node does not execute an `npm` or `pnpm` `.cmd` shim without a shell, so the command prints the exact command for you to run yourself.
+
+Release discovery and downloads follow `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`, the same policy as the stable installer entry point:
-Without `-y` the command prints exactly what it will do — mechanism, target version and install dir — and asks for confirmation; when stdin is not a terminal it requires `--yes` rather than waiting on a prompt nobody can answer. **The data root is never touched**: an upgrade only replaces `bin`, `lib`, `web` and `node`. Neither path upgrades in place on Windows: the installer is a POSIX shell script, and a global install cannot be driven from here because Node will not execute an `npm`/`pnpm` `.cmd` shim without a shell — so the command prints the exact command to run yourself instead.
+- `auto`, the default, reads the OSS `latest.json`, prefers that immutable release, and falls back to the matching GitHub tag. The package itself then comes from whichever source the installer's speed probe picks.
+- `oss` and `github` are strict: the command uses only that source.
+- `--release <tag>` skips latest-version discovery but still follows the selected source policy.
+- An explicit HTTPS `PENGUIN_DOWNLOAD_BASE_URL` takes precedence over everything for the installer and package downloads, and `PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` optionally adds a fallback for the package.
See also: [Configuration Reference](/configuration), [Models & Providers](/models).
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 77a751f6..c76c7442 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -1,101 +1,141 @@
---
title: CLI 参考
-description: penguin 命令的子命令与选项完整参考。
+description: 所有 penguin 命令和子命令的选项、默认值、输出结构与示例。
---
-CLI 由 npm 包 `@prismshadow/penguin-cli` 提供,命令为 `penguin`。不带子命令执行 `penguin` 时打印帮助;`-v, --version` 打印当前构建的单行身份,`penguin version --json` 打印其完整信息。启动时自动加载工作目录下的 `.env`。
+本页收录所有 `penguin` 命令。开头先说明 CLI 如何连接服务器,以及所有命令共享的约定;随后逐条介绍每个命令,各配一段概述、用法、选项表和示例。
-CLI 是服务端的瘦客户端:所有会话相关命令(`run`、`chat`、`ls`、`input`、`logs`、`agent`、`project`、`cost`、`schedule`、`org`)都向 PenguinHarness 服务端发 HTTP 请求并渲染回复——Task 在服务端执行,Session 记录在服务端索引里,Web App 能看到 CLI 创建的一切(反之亦然)。只有 `config` 仍直接编辑 Project 配置文件,`server` / `web` 则负责启动服务本身。
+CLI 以 npm 包 `@prismshadow/penguin-cli` 发布,命令名为 `penguin`。直接运行 `penguin` 会打印帮助。`-v, --version` 打印当前构建的一行标识信息,`penguin version --json` 则打印完整信息。启动时,CLI 会从工作目录加载 `.env` 文件。
+
+CLI 是服务器的瘦客户端。所有面向会话的命令(`run`、`chat`、`ls`、`input`、`logs`、`agent`、`project`、`cost`、`schedule`、`org`)都向 PenguinHarness 服务器发送 HTTP 请求,并渲染返回结果。Task 在服务器上运行,Session 存放在服务器的索引里;CLI 创建的一切 Web App 都能看到,反过来也一样。只有 `config` 仍直接编辑 Project 的文件,`server` / `web` 则负责启动服务本身。
## 服务器连接
-连接本机服务器的 CLI 无需登录。连接按以下顺序解析,先命中先用:
+与本机服务器通信的 CLI 无需登录。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 竞争拉起时,输家的子进程自行退出,双方都附着到赢家。
+1. `--server <url>`:显式指定的目标。
+2. `PENGUIN_API_URL`:同样指定目标,但取自环境变量。服务器驱动的会话会把它注入每个工具子进程,同时注入的还有 `PENGUIN_API_TOKEN`、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID` 和 `PENGUIN_SESSION_ID`,这样 Agent 自己调用 `penguin` 时,请求就能到达运行它的那台服务器。
+3. 数据根目录下存在活跃的 `server.lock`(数据根目录取 `PENGUIN_HOME`,否则为 `~/.penguin/data`):CLI 接入正在运行的本地服务器。
+4. 自动启动:CLI 在临时端口上拉起一个独立运行的本地服务器,等它就绪后接入。服务器输出写入 `<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` 同一条规则)。
+CLI 使用本地 API token 认证。服务器每次启动都会把一个新 token 写入 `<root>/api-token`(仅所有者可读),CLI 以 `Authorization: Bearer` 的形式发送它。`PENGUIN_API_TOKEN` 优先于这个文件。CLI 只对回环地址目标读取这个文件,因此远程 `--server` 需要显式设置 `PENGUIN_API_TOKEN`。按设计,持有这个文件就等于持有管理员权限——能直接访问数据根目录的本地文件系统,本来就拥有同样的权限。`penguin server reset-admin-password` 依据的也是同一条规则。
## 全局约定
-- 模型引用:模型身份始终是 `(provider, model_id)` 二元组。`--model-id` 填上游模型 id,`--provider` 填其所属分组;provider 绝不推断、绝不猜测、也没有缺省值。`run` / `chat` 上这对参数整体可选——两个都给即指定模型,两个都不给则使用 Project 默认模型——但只给其中一个是错误。
-- 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`。
+- 模型引用:模型的标识始终是 `(provider, model_id)` 这一对。`--model-id` 接收上游模型 id,`--provider` 接收模型所属的分组。CLI 从不推断、猜测或默认指定供应商。在 `run` 和 `chat` 上,这一对参数整体可选:两个都传即可选择模型,两个都不传则使用 Project 的默认模型;只传一个是错误。
+- Project 与 Agent 默认值:`--project-id` 依次回退到 `PENGUIN_PROJECT_ID`,再回退到 `default_project`;`--agent-id` 依次回退到 `PENGUIN_AGENT_ID`,再回退到 `default_agent`。在服务器驱动的会话里,这些环境变量指向会话所属的 Project 和 Agent。
+- Session 引用:凡是接受 session id 的命令(`input`、`logs`、`run --session`、`chat --resume`),完整 id 或任何唯一的片段都有效。`penguin ls` 打印的 8 位十六进制尾部就是为此准备的简写。片段有歧义时报错,并列出所有候选。
+- 默认使用最近的 Session:session id 可选的命令(`input [session_id]`、`logs [session_id]`、`chat --resume`)在省略 id 时,指向 Agent 最近的一个 Session,由 `--agent-id` 指定是哪个 Agent。`input` 和 `logs` 会在 stderr 上用一行暗色的 `[latest]` 标注选中的 Session,目标始终明确,stdout 上的 `--json` 输出也保持可解析。如果这个 Agent 一个 Session 都没有,命令会打印一行提示指向 `penguin run` / `penguin chat`,然后以非零码退出。
+- JSON 输出:`--json` 打印原始 JSON,取代渲染后的或表格形式的输出。
+- 目标服务器:`--server <url>` 指定要连接的服务器。参见[服务器连接](#服务器连接)。
+- 调用方上下文默认值:在 harness Agent 内部(`PENGUIN_SESSION_ID` 已设置)时,`run` 或 `chat` 创建的 Session 会从调用方 Session 的实时取值继承每一个未指定的字段:Workspace、模型对、审批模式和思考等级。`run_subagent` 对它派生的子 Agent 采用同样的继承,两个入口遵循同一条约定。对每个字段,显式传入的选项优先于调用方的值,调用方的值又优先于普通回退值。查找失败时打印一条暗色警告,并改用普通回退值。在 Agent 之外,行为不变:`--project-id` / `--agent-id` 仍按环境变量取默认值。
+- 超时:`run`、`input` 和 `logs -f` 上的 `--timeout <duration>` 限制等待时长,语义为软让出——相当于把 `exec_command` 的让出窗口模型搬到 CLI 上。到时后命令干净地脱离并退出,退出码为 0。Task 在服务器上继续运行,之后可以用 `penguin input` 或 `penguin logs` 接上。可接受的值有 `30s`、`5m`、`2h`,或一个表示秒数的纯整数;其他值一律拒绝。`--timeout 0` 在消息送达后立即返回(`--json` 下为 `{sessionId, status: "running"}`),所以这个选项也覆盖「不等」的场景。不带此选项时,命令无限等待。对新建 Task 而言,惯常做法仍是 `run --background`:提交后不再等待,打印裸 session id 供脚本使用,Task 一创建就脱离。
+- 参数错误:缺少参数、缺少必填选项、选项未知或命令拼错时,CLI 用界面语言打印一行错误、命令自身的用法,并提示查看 `--help`,然后以非零码退出。
+- 数据根目录:`--root <dir>` 为直接读取数据根目录的命令指定根目录,涉及 `config`、`auth`、`version`、`server status` 和 `server stop`。相对路径相对工作目录解析。优先级:`--root`,然后是 `PENGUIN_HOME` 环境变量,最后是 `~/.penguin/data`。
## penguin run
-在服务端创建(或复用)一个 Session,发送单条消息,流式渲染直至 Task 结束,打印统计行后退出。完成时退出码为 0;goal 模式仅目标 `complete` 时退出 0。
+在服务器上创建一个 Session(或复用已有的),发送一条消息,流式渲染 Task 直到结束,打印统计行后退出。Task 完成时退出码为 0,中途中止时为 1。目标模式运行只有在目标结果为 `complete` 时才以 0 退出。
```bash
-penguin run -m "总结当前目录的代码结构"
-penguin run -m "继续" --session 402a2e24 # 用片段复用既有会话
-penguin run -m "长任务" --background # 立即返回 session id
+penguin run -m <message> [options]
```
-| 选项 | 说明 |
-| --- | --- |
-| `-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` 时必填 |
-| `--approve <mode>` | 审批模式,见下文(缺省 `allow-all`)。与 `--session` 同用时 PATCH 该会话的粘性模式 |
-| `--thinking <level>` | 发起任务前把会话的思考等级钉为 `low` / `medium` / `high` / `xhigh` / `max`,自会话的下一次 LLM 请求起生效。省略时按会话钉定值(否则 Agent 配置)生效 |
-| `--session <sessionId>` | 复用既有 Session(完整 id 或唯一片段),不再新建;不能与 `--workspace` 及模型对同用 |
-| `--source <source>` | 把新建会话标记为 Benchmark 评估创建;唯一取值为 `benchmark`,Web App 会把这类会话归入会话列表的「评估任务」子夹。不能与 `--session` 同用 |
-| `--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>` | 目标服务器(见「服务器连接」) |
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `-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>` | 模型所属的供应商分组。与 `--model-id` 搭配时必填。 | — |
+| `--approve <mode>` | 审批模式;见[审批模式(--approve)](#审批模式--approve)。配合 `--session` 时,以 PATCH 请求更新 Session 固定的审批模式。 | `allow-all` |
+| `--thinking <level>` | 在 Task 开始前固定 Session 的思考等级(`low` / `medium` / `high` / `xhigh` / `max`)。从 Session 的下一次 LLM 请求起生效。 | Session 已固定的等级,否则用 Agent 配置 |
+| `--session <sessionId>` | 复用已有的 Session(完整 id 或唯一片段),而不是新建。不能与 `--workspace` 或模型对同时使用。 | — |
+| `--source <source>` | 把新建的 Session 标记为由 Benchmark 评估创建。取值仅限 `benchmark`,Web App 会把这类 Session 归入会话列表的「评估任务」文件夹。不能与 `--session` 同时使用。 | — |
+| `--background` | 以 POST 提交 Task 后立即退出,打印 session id(`--json` 下为 `{"sessionId"}`)。Task 在服务器上继续运行;可用 `penguin logs -f` 跟踪。 | — |
+| `--timeout <duration>` | 软让出的等待预算;见[全局约定](#全局约定)。不能与 `--background` 同时使用。 | 无限等待 |
+| `--goal [budget]` | 目标模式:消息就是目标,服务器循环执行,直到目标达到终态。可选值是 Token 预算,例如 `500k`。 | — |
+| `--json` | 打印最终的 `{sessionId, status, text}` 对象,取代渲染后的流。`text` 拼接主 Session 的 助手文本消息。 | — |
+| `--server <url>` | 目标服务器;见[服务器连接](#服务器连接)。 | — |
+
+`--timeout` 到时后,`run` 打印目前已渲染的内容和一行暗色的仍在运行提示(附 session id),然后退出 0,不中止 Task。`--json` 下则打印 `{sessionId, status: "running", text}`。`--timeout 0` 在 POST 完成后立即返回,`--json` 下打印 `{sessionId, status: "running"}`,不含 `text`。对目标模式运行,最终 JSON 对象里的 `status` 就是目标结果。
+
+在审批提示处按 Ctrl-C 会拒绝这一次工具调用;其他任何时候按 Ctrl-C 都会在服务器上中止 Task。
+
+```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
+```
## penguin chat
-交互式 REPL,每输入一行发起一个 Task。选项与 `run` 相同(除 `-m, --message` 外),另加:
+启动交互式 REPL,每行输入都会启动一个 Task。
-| 选项 | 说明 |
-| --- | --- |
-| `--resume [sessionId]` | 恢复指定 Session(完整 id 或唯一片段);省略 id 时恢复该 Agent 最近的 Session |
-| `--verbose` | 显示完整工具输出;缺省折叠过长的工具输出(见下文) |
-| `--server <url>` | 目标服务器(见「服务器连接」) |
+```bash
+penguin chat [options]
+```
-使用 `--resume` 时,Workspace 与模型由原 Session 锁定,不可再用 `--workspace` / `--model-id` / `--provider` 覆盖。`--resume` 下仍接受 `--thinking`:它重新钉住该 Session,自下一次 LLM 请求起生效(中途更换会使提供商缓存失效,建议先压缩)。退出时会打印可直接复制的 `penguin chat --resume <sessionId>` 命令。
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--project-id <id>` / `--agent-id <id>` | 要使用的 Project 和 Agent,同 `run`。 | 见[全局约定](#全局约定) |
+| `--workspace <path>` | Workspace 目录,同 `run`。 | 工作目录 |
+| `--model-id <id>` / `--provider <group>` | 模型对,同 `run`。 | Project 的默认模型 |
+| `--approve <mode>` | 审批模式;见[审批模式(--approve)](#审批模式--approve)。 | `allow-all` |
+| `--thinking <level>` | 固定 Session 的思考等级,同 `run`。 | Session 已固定的等级,否则用 Agent 配置 |
+| `--resume [sessionId]` | 恢复一个 Session(完整 id 或唯一片段)。不带 id 时,恢复 Agent 最近的 Session。 | — |
+| `--verbose` | 显示完整工具输出,而不是折叠长输出;见[工具输出折叠](#工具输出折叠)。 | 长输出折叠 |
+| `--server <url>` | 目标服务器;见[服务器连接](#服务器连接)。 | — |
-REPL 内命令:
+使用 `--resume` 时,原 Session 已固定 Workspace 和模型,`--workspace`、`--model-id` 和 `--provider` 无法覆盖它们。`--thinking` 仍然有效:它重新固定现有 Session,从下一次 LLM 请求起生效。在上下文中途更改等级会使供应商的上下文缓存失效,所以请先压缩。退出时,如果 Session 已有历史,REPL 会打印一条可直接复制运行的 `penguin chat --resume <sessionId>` 命令。
+
+### REPL 内命令
| 输入 | 行为 |
| --- | --- |
-| 运行中输入任意文字 | 运行中插话:排队后以 `[user_steering]` 用户消息随下一轮送达模型(`»` 确认行会回显文字);输入期间渲染暂挂,流式输出不会打断正在输入的行。若 Task 恰好已结束,该行作为下一条普通消息发送 |
-| `/compact` | 主动压缩当前上下文 |
-| `/clear` | 原地开启全新空白 Session;原会话保留在磁盘上,仍可用 `--resume` 恢复 |
-| `/thinking` | 显示本 Session 的思考等级:被 `--thinking` 或 `/thinking` 钉住的等级,否则为 Agent 配置的等级 |
-| `/thinking <level>` | 钉住本 Session 的思考等级(`low` / `medium` / `high` / `xhigh` / `max`);不会写回 Agent 配置。软限制:自下一次请求起生效、允许中途更换——回执会建议先 `/compact` 压缩,因为更换会使提供商的提示词缓存失效;此后派生的子会话继承钉住的等级 |
-| `/verbose` | 在折叠与完整工具输出之间切换 |
-| `/exit`、`/quit` | 退出 |
+| Task 运行期间输入的任意文本 | 运行中插话。这一行会排队,在两轮之间以 `[user_steering]` 用户消息的形式送达模型,同时一个 `»` 确认符会回显这段文本。你输入时渲染暂停,流式输出不会覆盖这一行。如果 Task 先结束,这一行会变成下一条普通 Prompt 发送出去。 |
+| `/goal[:<budget>] <objective>` | 对给出的目标运行目标模式。可选的预算是 Token 预算,例如 `/goal:500k`。Ctrl-C 会中止整个目标。见[目标模式](/goal-mode)。 |
+| `/compact` | 立即压缩当前上下文。 |
+| `/clear` | 原地开启一个全新的空白 Session,仍用同一个 Workspace 和模型。旧 Session 保留在服务器上,之后可用 `--resume` 恢复。 |
+| `/thinking` | 显示这个 Session 的思考等级:`--thinking` 或 `/thinking` 固定的等级,否则是 Agent 配置的等级。 |
+| `/thinking <level>` | 固定 Session 的思考等级(`low` / `medium` / `high` / `xhigh` / `max`)。等级不会写回 Agent 配置。 |
+| `/verbose` | 在折叠和完整工具输出之间切换。 |
+| `/exit`、`/quit` | 退出。 |
+
+固定的思考等级属于软限制:从下一次请求起生效,即使处在上下文中途。回复会建议先运行 `/compact`,因为更改会使供应商的上下文缓存失效。更改之后派生的子 Agent Session 继承固定的等级。
+
+### 工具输出折叠
+
+长工具输出——比如 `exec_command` 的结果或 `read_file` 读出的整个文件——默认折叠,以免刷满屏幕。前 4 行实时流式显示。输出结束后,REPL 打印一个省略标记(`… (+N lines, /verbose for full output)`)和最后 4 行。不超过 9 行的输出会完整显示。
-过长的工具输出(`exec_command` 的结果、`read_file` 读回的整个文件)缺省折叠显示,避免刷屏:前 4 行照常流式打印,输出结束时打印省略标记(`……(另有 N 行,/verbose 显示完整输出)`)与最后 4 行;不超过 9 行的输出完整显示。这只是显示层截断——模型、Trace 与 Web App 收到的始终是完整输出。`/verbose`(或启动时加 `--verbose`)可关闭折叠、对后续输出生效;`--resume` 恢复的历史按同一规则折叠。`penguin run` 从不折叠:它的输出供管道与嵌套 CLI 消费。
+折叠只影响显示:模型、Trace 和 Web App 收到的始终是完整输出。输入 `/verbose` 或以 `--verbose` 启动,即可为后续输出关闭折叠。`--resume` 展示的历史同样按此折叠。`penguin run` 从不折叠输出,因为它的输出要供管道和嵌套 CLI 使用。
-Ctrl-C 的行为依状态而定:
+### Ctrl-C
+
+Ctrl-C 的行为取决于 REPL 当时的状态:
| 状态 | 行为 |
| --- | --- |
-| 等待工具审批 | 拒绝该次工具调用 |
-| Task 运行中 | 中断当前 Task,返回输入 |
-| 输入缓冲非空 | 清空当前输入 |
-| 空闲且缓冲为空 | 显示退出确认(y/N) |
+| 等待工具审批 | 拒绝这一次工具调用。 |
+| Task 运行中 | 中止当前 Task,回到输入。 |
+| 输入缓冲区非空 | 清空当前输入。 |
+| 空闲且缓冲区为空 | 显示退出确认(y/N)。 |
## penguin ls
-列出 Project 的会话——覆盖全部 Agent,或用 `--agent-id` 限定一个。列依次为:短 id(其余命令可作片段使用的末尾 8 位十六进制)、Agent、标题、运行中 / 空闲、最近活动、Workspace 尾段。已归档会话仅在 `-a` 下出现。
+列出 Project 的 Session,默认覆盖所有 Agent,用 `--agent-id` 可只看一个。各列依次为:短 id(即 8 位十六进制尾部,其他命令可以把它当作片段使用)、Agent、标题、运行中/空闲、最近活跃时间和 Workspace 路径的末段。已归档的 Session 只有加 `-a` 才显示。
+
+```bash
+penguin ls [options]
+```
+
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--project-id <id>` / `--agent-id <id>` | 范围。不带 `--agent-id` 时列出 Project 的所有 Agent。 | 见[全局约定](#全局约定) |
+| `-a, --all` | 包含已归档的 Session。 | — |
+| `--days <n>` | 只列出最近 n 个自然日内有活动的 Session。今天算第 1 天,所以 `--days 2` 覆盖昨天和今天,与 `cost --days` 一致。可与 `-a` 和 `--json` 组合。 | — |
+| `--json` / `--server <url>` | 见[全局约定](#全局约定)。 | — |
```bash
penguin ls
@@ -103,77 +143,110 @@ 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)。
+向一个 Session 发送消息;不带 `-m` 时,则轮询它最后一次的回答。session id 可省略:省略时命令使用 Agent 最近的 Session(见[全局约定](#全局约定)),所以直接运行 `penguin input` 就能回答「我的 Agent 最后说了什么」。
```bash
-penguin input 402a2e24 -m "顺便检查一下测试"
-penguin input 402a2e24 -m "排个队" --timeout 0 # 送达后立即返回
-penguin input 402a2e24 # 轮询:打印最近一条助手回复
-penguin input # 轮询当前 Agent 最近一次会话
-penguin input 402a2e24 --timeout 5m # 轮询,最多等运行中的一轮 5 分钟
+penguin input [session_id] [options]
```
-| 选项 | 说明 |
-| --- | --- |
-| `-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 为 `""`) |
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `-m, --message <text>` | 消息文本。省略它则改为轮询最后一次 助手回复。 | — |
+| `--timeout <duration>` | 软让出的等待预算。带 `-m` 时,到时后命令像 `run` 一样脱离,`--timeout 0` 在送达后立即返回。不带 `-m` 时,命令在到时点拍快照(`0` 表示立即拍),并注明 Session 仍在运行。 | 无限等待 |
+| `--project-id <id>` | 片段搜索的范围。完整 session id 无需此选项。 | `PENGUIN_PROJECT_ID`,否则 `default_project` |
+| `--agent-id <id>` | 省略 session id 时,取这个 Agent 最近的 Session。 | `PENGUIN_AGENT_ID`,否则 `default_agent` |
+| `--json` / `--server <url>` | 见[全局约定](#全局约定)和下文的 JSON 结构。 | — |
+
+带 `-m` 时,运行中的 Session 收到的文本会作为插话处理,在两轮之间送达;空闲的 Session 则启动一个新 Task。默认情况下,命令会等待并渲染,直到这一轮完成。
+
+不带 `-m` 时,命令是一次轮询,语义与 `input_subagent` 的空 Prompt 一致。它打印 Session 最近一次完整的 助手文本——从历史末尾取得的最后一次回答的幂等快照。思考与工具输出一概跳过,也不会排队或插话。如果 Session 正在运行,命令会先静默等待,给了 `--timeout` 就最多等这么久(`--timeout 0` 表示立即拍快照)。到时如果 Session 仍在运行,命令打印最新文本并注明仍在运行,退出 0。
+
+`--json` 下:
+
+- 带 `-m` 时,命令打印 `{sessionId, status, text}`,`status` 取 `completed`、`aborted` 或 `running`。`--timeout 0` 的结构没有 `text`。
+- 轮询形式打印 `{sessionId, status, text}`,`status` 取 `idle` 或 `running`,还没有回复时 `text` 为 `""`。
+
+```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
+```
## penguin logs
-用与 REPL 相同的渲染器渲染会话历史。session id 可以省略:省略即取当前 Agent 最近一次会话(见「全局约定」),裸 `penguin logs` 因此就是「刚才发生了什么」。
+用与 REPL 相同的渲染器渲染一个 Session 的历史。session id 可省略:省略时命令使用 Agent 最近的 Session(见[全局约定](#全局约定)),所以直接运行 `penguin logs` 就能看到刚才发生的事。
```bash
-penguin logs # 当前 Agent 最近一次会话
+penguin logs [session_id] [options]
+```
+
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--tail <n>` | 只显示最后 n 条记录。 | 全部记录 |
+| `-f, --follow` | 历史播完后继续跟踪实时流。只读:Ctrl-C 脱离,不改动 Session。 | — |
+| `--timeout <duration>` | 跟踪这么长时间后停止(软让出,退出 0)。只在配合 `-f` 时有意义。 | — |
+| `--project-id <id>` | 片段搜索的范围。 | `PENGUIN_PROJECT_ID`,否则 `default_project` |
+| `--agent-id <id>` | 省略 session id 时,取这个 Agent 最近的 Session。 | `PENGUIN_AGENT_ID`,否则 `default_agent` |
+| `--json` / `--server <url>` | `--json` 打印原始消息数组;配合 `-f` 时,消息一到就以每行一条 JSON 打印。 | — |
+
+```bash
+penguin logs # the agent's most recent session
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
+`agent ls` 列出 Project 的 Agent,包括 id、名称、会话数和描述。`agent create` 创建 Agent。
+
```bash
-penguin agent ls
-penguin agent create --agent-id helper --name "Helper" --plugins software-development,goal
+penguin agent ls [--project-id <id>] [--json] [--server <url>]
+penguin agent create --agent-id <id> [options]
```
-`agent ls` 列出 Project 的 Agent(id、名称、会话数、描述)。`agent create` 创建一个:
+`agent create` 的选项:
-| 选项 | 说明 |
-| --- | --- |
-| `--agent-id <id>` | 必填,Agent id(即目录名) |
-| `--name <s>` / `--description <s>` | 显示名与描述 |
-| `--plugins <a,b>` | 逗号分隔的插件库插件名,预装进新 Agent(各自的 Skill 与钩子包);未知名称在创建任何东西之前即被拒绝 |
-| `--project-id <id>` / `--json` / `--server <url>` | 同各处约定 |
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--agent-id <id>` | Agent id,同时也是它的目录名。必填。 | — |
+| `--name <name>` / `--description <text>` | 显示名称和描述。 | — |
+| `--plugins <names>` | 要预装的插件库插件名,逗号分隔,每个插件连同各自的 Skill 和钩子包一起安装。名称未知时直接拒绝,此时还没有创建任何东西。 | — |
+| `--project-id <id>` / `--json` / `--server <url>` | 见[全局约定](#全局约定)。 | — |
+
+```bash
+penguin agent ls
+penguin agent create --agent-id helper --name "Helper" --plugins software-development,goal
+```
## penguin project
-`penguin project ls` 列出当前账号可用的 Project(自有与被授权),含 id、显示名与角色。`--json` / `--server` 同各处约定。
+`penguin project ls` 列出这个账号能访问的 Project——自己的和共享的——包括 id、显示名称和角色。支持 `--json` 和 `--server`。
+
+```bash
+penguin project ls
+```
## penguin cost
-来自服务端用量聚合的 Token 用量与成本。缺省打印汇总卡片——今日 / 近 7 天 / 累计(与任何范围参数无关,恒计算);`--by` 改为打印分组表格。
+展示来自服务器用量聚合的 Token 用量与成本。默认打印一张摘要卡片,包含今天、最近 7 天和总计,忽略任何范围选项。`--by` 则打印分组表格。
+
+```bash
+penguin cost [options]
+```
+
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--days <n>` | 设置起止日期,覆盖最近 n 天。 | — |
+| `--from <date>` / `--to <date>` | 显式范围,`yyyy-mm-dd` 格式,必须成对给出。 | — |
+| `--by <dimension>` | 按 `date`、`agent`、`model` 或 `session` 分组。 | 摘要卡片 |
+| `--project-id <id>` / `--agent-id <id>` | 范围。`--agent-id` 用于过滤,且没有默认 Agent:不主动缩小范围时,成本覆盖整个 Project。 | Project:见[全局约定](#全局约定) |
+| `--json` / `--server <url>` | 见[全局约定](#全局约定)。 | — |
+
+成本后面的 `+` 表示部分求和:这个分组里有模型没有配置价格。`-` 表示完全没有可计价的用量。
```bash
penguin cost
@@ -181,77 +254,82 @@ 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
-成本后缀 `+` 表示部分和(该桶里有模型未配置价格);`-` 表示完全没有计价用量。
+列出并管理 Project 的定时任务。
-## penguin schedule
+```bash
+penguin schedule ls [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+penguin schedule add <name> --prompt <text> --start-at <ISO|now> [options]
+penguin schedule update <name> [options]
+penguin schedule rm <name> [--project-id <id>] [--agent-id <id>] [--json] [--server <url>]
+```
+
+`penguin schedule ls` 列出所有 Agent 的定时任务,用 `--agent-id` 可只看一个。各列为:Agent、名称、是否启用、开始时间、周期(一次性任务显示 `once`)、目标(绑定的 Session 短 id,或 `new session`)、上次触发时间,以及每个非 active 状态的标记(`expired`、`done`、`missed` 或 `invalid`)。无法解析的定时任务文件也会列出,并标记 `invalid`。
-`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 立即得到校验结果,不必像手工编辑那样等下一轮对账。
-`add` / `update` / `rm` 经 API 管理定时任务,由 API 写入任务的 TOML 文件——**文件仍是唯一真相源**,CLI 是带校验的写入器(与模型配置、vault 同一模式:一律经系统接口更新、校验收敛在接口层,手编依然可行)。API 错误原样透出,Agent 因此获得同步校验,而非手编 TOML 时要等对账周期的滞后。
+`add` 和 `update` 的选项:
+
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--prompt <text>` | 每次触发发送的文本。`add` 必填。 | — |
+| `--start-at <ISO\|now>` | 首次触发时间,ISO 8601 格式,或用字面量 `now` 表示当前时刻。`add` 必填。 | — |
+| `--period <duration>` | 固定间隔,至少 `5m`(例如 `30m`、`12h`、`1d`、`7d`)。 | 一次性 |
+| `--end-at <ISO>` | 这个时刻之后不再触发。 | — |
+| `--session-id <id>` | 把每次触发绑定到一个 Session。只能在它和新建 Session 选项之间二选一。 | — |
+| `--workspace <path>` / `--model-id <id> --provider <group>` | 新建 Session 模式:每次触发都在这个 Workspace 和模型上创建一个 Session。模型对要么都给,要么都不给。 | 临时 Workspace;Project 的默认模型 |
+| `--disabled`(`add`) | 创建时即处于禁用状态。 | 启用 |
+| `--enable` / `--disable`(`update`) | 开启或关闭任务。 | — |
+| `--project-id <id>` / `--agent-id <id>` / `--json` / `--server <url>` | 见[全局约定](#全局约定)。 | — |
+
+- `add` 创建的任务默认启用,因为添加任务就是想让它跑起来;不想启用就用 `--disabled`。这是与原始文件的刻意差异:原始文件的 `enabled = false` 默认值保留不变,供手工编辑使用。
+- `update` 读取已存储的任务,修改后写回,未指定的字段保持原值。在绑定 Session 和新建 Session 两种目标之间切换时,会清空另一种目标的字段。
+- `rm` 不询问直接删除。服务器仍要求调用者是 Project 所有者。
```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 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
```
-| 选项 | 说明 |
-| --- | --- |
-| `--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 授权照旧生效) |
-
## penguin org
-公司模式的命令族——组织 API 的瘦客户端。组织在 Project 目录下的文件(员工树、工位台账、日程、工单、频道)仍是唯一真相源;每个子命令要么读取它们的投影,要么经编辑它们的接口写入,契约与 `schedule` 的带校验写入器相同:API 错误原样透出,Agent 因此获得同步校验,而非手编文件时要等对账周期的滞后。自动生成的 id 按约定带前缀——组织 `co_`、频道 `ch_`——服务端只提议、不强制,因此这里传入的 id 一律按原样创建。
+公司模式的命令族,是组织 API 之上的瘦客户端。组织在 Project 目录下的文件(员工树、工位台账、日历、工单和频道)始终是唯一事实来源。每个子命令要么读取这些文件的投影,要么通过编辑这些文件的路由写入;契约与 `schedule` 一致——CLI 是经过校验的写入方,API 错误原样打印,Agent 立即得到校验结果,不必像手工编辑那样等下一轮对账。按约定,生成的 id 带前缀:组织用 `co_`,频道用 `ch_`。服务器建议这些前缀但从不强制,这里传入的 id 会严格按输入原样创建。
```bash
penguin org ls [--project-id <id>] [--json]
-penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>] [--project-id <id>] # 按约定取 `co_<slug>`
-penguin org show [--org-id <id>] [--json] # 概览:工作语言、员工与状态、看板计数、预算占用、待处理事项
-penguin org chart [--org-id <id>] [--json] # 员工树
+penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>] [--project-id <id>] # by convention `co_<slug>`
+penguin org show [--org-id <id>] [--json] # overview: working language, employees and states, board counts, spend against budget, pending items
+penguin org chart [--org-id <id>] [--json] # the employee tree
penguin org hire (--agent-id <id> | --new-agent <id> [--name <s>] [--description <s>] [--skills <a,b>]) --title <s> --reports-to <agent_id> [--workspace <path>] [--budget <usd>] [--duties <s>]
penguin org employee set <agent_id> [--title <s>] [--reports-to <agent_id>] [--workspace <path>] [--budget <usd>] [--duties <s>] [--model-id <id> --provider <p>]
-penguin org leave <agent_id> # 移出组织(CEO 不可),不删 Agent
-penguin org desk show [<agent_id>] [--json] # 工位会话 id 与 Workspace(尚无工位时开一个)
-penguin org desk renew [<agent_id>] # 换新的工位会话(重置上下文)
+penguin org leave <agent_id> # out of the organization (not the CEO); the Agent itself stays
+penguin org desk show [<agent_id>] [--json] # the desk session id and Workspace (opens the desk if there is none)
+penguin org desk renew [<agent_id>] # a fresh desk session (resets the context)
penguin org calendar ls [--agent-id <id>] [--json]
penguin org calendar add <name> [--agent-id <id>] --prompt <s> --start-at <ISO|now> [--period <dur>] [--end-at <ISO>] [--title <s>] [--disabled]
-penguin org calendar update <name> [--agent-id <id>] [<同上字段>] [--enable|--disable]
+penguin org calendar update <name> [--agent-id <id>] [same fields] [--enable|--disable]
penguin org calendar rm <name> [--agent-id <id>]
penguin org ticket ls [--status <col>] [--owner <principal>] [--blocked] [--json]
penguin org ticket show <ticket_id> [--json]
penguin org ticket create --title <s> (--goal <s> [--criteria <s>] | --body-file <path>) [--owner <principal>] [--slug <words>] [--parent <ticket_id>] [--notify <p,p>] [--priority P0|P1|P2] [--due <date>]
-penguin org ticket move <ticket_id> --to <col> [--reason <s>] # 移入 rejected 须给 reason
+penguin org ticket move <ticket_id> --to <col> [--reason <s>] # moving into rejected needs a reason
penguin org ticket assign <ticket_id> --owner <principal>
-penguin org ticket block <ticket_id> --reason <s> [--by <principal|ticket_id>] # 工单留在所在列
+penguin org ticket block <ticket_id> --reason <s> [--by <principal|ticket_id>] # the ticket stays in its column
penguin org ticket unblock <ticket_id>
-penguin org ticket progress <ticket_id> -m <text> # 追加一条进展,记为当前会话所写
-penguin org ticket start <ticket_id> [-m <附言>] [--workspace <path>] [--agent-id <id>] [--json] # 新开一个后台处理该工单的工单会话,打印会话 id
-penguin org ticket attach <ticket_id> [--session <session_id>] # 把既有会话挂为贡献会话(缺省当前会话)
-penguin org channel ls [--json] # 人看到全部频道,员工只看到自己所在的
-penguin org channel create <channel_id> [--name <s>] [--purpose <s>] # 新频道只有创建者一人;按约定取 `ch_<slug>`
-penguin org channel show <channel_id> [--json] # 用途、成员数与成员清单
-penguin org channel invite <channel_id> <principal>... # 任一成员可邀请;每个 principal 一次 POST
-penguin org channel join <channel_id> # 仅限人;员工只能等成员邀请
-penguin org channel leave <channel_id> # 移出自己
-penguin org channel remove <channel_id> <principal> # 仅限人
-penguin org channel archive <channel_id> | unarchive <channel_id> # 仅限人;归档期间只读
+penguin org ticket progress <ticket_id> -m <text> # a progress entry, attributed to the calling session
+penguin org ticket start <ticket_id> [-m <note>] [--workspace <path>] [--agent-id <id>] [--json] # a ticket session working on the ticket in the background; prints its id
+penguin org ticket attach <ticket_id> [--session <session_id>] # an existing session as a contributor (default: the calling session)
+penguin org channel ls [--json] # every channel for a person, its own for an employee
+penguin org channel create <channel_id> [--name <s>] [--purpose <s>] # a new channel holds only its creator; `ch_<slug>` by convention
+penguin org channel show <channel_id> [--json] # purpose, member count and the member list
+penguin org channel invite <channel_id> <principal>... # any member invites; one POST per principal
+penguin org channel join <channel_id> # people only; an employee waits to be invited
+penguin org channel leave <channel_id> # self-removal
+penguin org channel remove <channel_id> <principal> # people only
+penguin org channel archive <channel_id> | unarchive <channel_id> # people only; read-only while archived
penguin org channel tail [--channel <id>] [--date <d>] [-n <count>] [--json]
penguin org channel send -m <text> [--channel <id>] [--ref-ticket <id>] [--ref-session <id>]
penguin org handbook list [--json]
@@ -261,65 +339,135 @@ penguin org handbook rm <path>
penguin org finance [--period <YYYY-MM>] [--json]
```
-每个子命令都接受 `--org-id <id>`、`--project-id`、`--json` 与 `--server`。**`--org-id` 缺省取 `PENGUIN_ORG_ID`**——公司模式在「服务器连接」一节所述控制环境之外多注入的一个变量:服务端把它注入工位会话与工单会话的每个工具子进程,员工自己的 `penguin org` 调用因此无需点名组织;人类在 shell 里则显式给出。没有缺省组织——两者都没有时,命令在联系任何服务器之前即失败。`create` 是例外:它的 `--org-id` 是要创建的 id,绝不取自环境。`--json` 把响应以单行 JSON 打印;写入类命令否则打印一行确认。
+### 通用选项
+
+每个子命令都接受 `--org-id <id>`、`--project-id`、`--json` 和 `--server`。
+
+`--org-id` 默认取 `PENGUIN_ORG_ID`——公司模式加入[服务器连接](#服务器连接)所述环境的唯一一个变量。服务器把它注入工位会话和工单会话的每个工具子进程,员工自己调用 `penguin org` 时无需指名,请求就能到达自己所在的组织;人在 shell 里则显式传入这个选项。没有默认组织:选项和变量都不提供时,命令在联系任何服务器之前就会失败。`create` 是例外,因为它的 `--org-id` 就是要创建的 id,从不取自环境。
+
+`--json` 把响应打印为一行 JSON。不加时,写命令打印一行确认信息。
+
+### 会话内的调用方身份
+
+在会话内部,同一套环境变量标识调用方:
+
+- `calendar` 系列命令的 `--agent-id` 和 `desk` 的 `<agent_id>` 参数默认取 `PENGUIN_AGENT_ID`,员工借此安排自己的日程、换新自己的工位会话。不带选项的 `calendar ls` 列出所有员工的事件。
+- `ticket start` 启动工单会话:给了 `--agent-id` 就以它运行;否则在设置了 `PENGUIN_AGENT_ID` 时以它运行;再否则以工单负责人的身份运行,由服务器确定。命令还会发送 `PENGUIN_SESSION_ID`,服务器借此执行自己的规则:只有工单负责人或人才能启动工单会话。员工请求别人的工单,或请求没有员工负责人的工单时,会得到 `403 not_ticket_owner`,原样打印。错误信息会提示改为指派工单(`penguin org ticket assign <id> --owner agent:<employee>`),让那位员工的工位在下一轮巡检时接手。负责人也可以用 `--agent-id` 把同事拉到自己负责的工单上。
+- 工单写操作(`create`、`assign`、`move`、`block`、`unblock`、`progress`)和频道写操作(`create`、`invite`、`join`、`archive`、`unarchive`、`send`)在请求体里带上 `PENGUIN_SESSION_ID`,文件里记录的因此是会话对应的员工,而不是 token 的用户。`ticket attach` 在省略 `--session` 时挂接的就是这个会话;`--session` 与其他地方一样,接受完整 id 或唯一片段。
+- 频道读操作(`ls`、`show`、`tail`)以及 `leave` 和 `remove` 背后的成员 DELETE 没有请求体,改为通过 `?sessionId=` 发送同一个会话。不传的话,服务器会把员工当作登录的那个人来应答,`channel ls` 列出的会是所有频道而不是员工自己的频道。
+
+### ls、show 和 chart
+
+- `ls` 列出 Project 的组织,包括各自的员工数、工单数和支出。
+- `show` 打印一个组织的概览:名称、使命、状态和工作语言,员工按状态分布,看板各列的工单数,本期支出与 CEO 预算的对比。还会列出等你处理的事项:提及你的消息、待你审核的工单、因你而阻塞的工单。
+- `chart` 打印汇报树,按层级缩进,包含每个员工的职位、实时状态、自身支出、累计支出和预算。
+
+校验失败的组织或员工会带着 `invalid: <reason>` 出现在列表里,而不是直接略过。
+
+### create
+
+`--ceo-budget` 是 CEO 的月度预算,单位为美元,默认 100。预算沿累计线比较,即员工本人加上下面的所有人,所以 CEO 的预算覆盖整个公司。新组织因此有上限而非无限制,初始化运行的触发块会写明这个数字,CEO 据此规划招聘提案的规模。`0` 是真实的零预算。要再次解除上限,向 `PATCH .../employees/<org_id>_ceo` 发送 `budget: null`,Web App 的员工编辑器正是这么做的。
+
+`--language zh|en` 设置组织的工作语言。不给时由使命决定:使命文本里只要出现一个汉字,语言就是 `zh`。组织写出的一切都遵循这个语言:手册、员工简报、CEO 的初始化运行和工位会话标题。
+
+### hire
+
+`hire` 必须在 `--agent-id` 和 `--new-agent` 中恰好选一个:前者雇用已有的 Agent,后者新建一个。对新建的 Agent,用 `--name`、`--description` 和 `--skills` 描述它;`--skills` 列出额外的插件库插件,叠加在 `agent-company,agent-development` 之上,后者是每个员工都需要的。
+
+`--workspace` 是组织共享 Workspace 的子目录(`.` 表示整个共享 Workspace),或一个绝对路径。它从不相对 CLI 的工作目录解析。默认值是按员工命名的子目录,因为共享根目录存放共享的输入,不是任何人的工位。
+
+- 相对子目录会先做规范化,`./hr`、`hr/` 和 `hr` 是同一个分区。服务器在记录雇用信息时创建它,所以 `--workspace hr` 就够了,不需要事先存在任何东西。
+- 绝对路径指向用户自己的某个目录,且必须已经存在。
+- 用 `..` 跳出共享 Workspace 的路径一律拒绝,返回 400 `invalid_workspace`。
+
+工位会话或工单会话开启时同样会创建自己的目录。`--budget` 是月度预算,单位为美元,覆盖这名员工以及下面的所有人。
+
+### employee set
+
+`employee set` 只修改你给出的字段。`--workspace` 的用法与 `hire` 相同,但没有默认值:只有传了这个选项才改变分区。`--budget` 是月度预算,单位为美元,覆盖这名员工以及下面的所有人。模型对要么都给,要么都不给,与其他地方一致。
+
+### calendar
+
+`calendar` 使用与 `penguin schedule` 相同的写入方:`add` 创建启用的事件,除非传了 `--disabled`;`--start-at now` 表示当前时刻;`update` 读取已存储的事件,修改后写回;`rm` 不询问直接删除。事件触发到员工的工位会话里,且只在组织和员工都处于活跃状态时触发;否则状态列显示 `paused`。
+
+`add` 和 `update` 的响应包含事件本身,外加这次写入触发的排班提醒:另一位员工的周期性事件恰好定在同一个开始分钟;同一位员工有了第二个同周期的周期性事件;或周期性事件从 `now` 开始。CLI 把每条提醒单独打一行,形如 `Rota notice: …`。提醒从不阻塞写入,这些行保留服务器的英文原文。
+
+### ticket
+
+- `ls` 拉取整个看板后在本地过滤。`--status` 接受一列:`proposed`、`in_progress`、`review`、`done` 或 `rejected`。`--json` 下,`ls` 以 `{ tickets, invalidFiles }` 打印过滤后的列表。
+- `show` 先打印派生数据(所在列、运行状态、成本和汇总成本、贡献会话、子工单),然后是工单自身字段、正文各节,以及 `History:` 下的操作历史。
+- `create` 接受 `--goal`(配合 `--criteria`),或从 `--body-file` 读取完整的 Markdown 正文。两种方式都会生成 frontmatter。
+- `start` 打印裸 session id,与 `run --background` 一样,供 `penguin logs` 和 `penguin input` 接手。
+- `--owner <principal>` 指定唯一的负责主体:员工(Agent id 或 `agent:<id>`)或 Project 成员(`user:<id>`)。默认取调用方。未指定 `--notify` 时,负责人会成为完整的 `notify` 列表,但前提是负责人是员工:人不会就自己名下的工单收到通知,想收到通知需要用 `--notify` 把自己加进去。
+- 谁提交的工单不由选项指定:它就是工单历史里的 `created` 条目,取自命令运行时所处的环境。
+- 工单 id 的格式是 `<yyyy-mm-dd>-<slug>`,slug 是小写英文单词,用连字符连接。`--slug <words>` 用来设置它。标题里英文太少、服务器又无法用 Project 的模型为它起名时,就需要这个选项(400 `slug_required`)。
+- 表明已做了工作的写操作,还会把调用方所在的会话记为工单的贡献会话之一,它的成本因此计入工单。这类写操作包括 `progress`、编辑正文和 `move --to review`。移入其他任何列,以及 `block` 和 `unblock`,都不记录。
+- `progress -m` 接受一句平实的描述,说明做了什么、在哪里;服务器记录谁写的、什么时候写的。
+- `--goal`、`--criteria` 和 `progress -m` 要求所有输入、交付物和文件都用完整路径指名。
+
+### channel
-同一套环境在会话内标识调用方:
+`--channel` 默认为 `default_channel`,即全员频道,每个员工和 Project 成员都在其中。`ls` 把它列在第一位,显示本地化标签而非存储的名称。
-- `calendar` 各命令的 `--agent-id` 与 `desk` 的位置参数缺省取 `PENGUIN_AGENT_ID`——员工安排自己的日程、换自己的工位。`calendar ls` 不带该选项时列出全部员工的日程项。
-- `ticket start` 给了 `--agent-id` 就用它,否则用设置了的 `PENGUIN_AGENT_ID`,再否则由服务端取工单负责人。它同时携带 `PENGUIN_SESSION_ID`,服务端据此施加规则:**一张工单的会话只能由它的负责人或人发起**——员工对别人的工单(或没有员工负责人的工单)发起会得到 `403 not_ticket_owner`,原样打印,提示改用改派(`penguin org ticket assign <id> --owner agent:<员工>`),由那名员工的工位在下一次巡检时接手。`--agent-id` 则是负责人把同事拉进自己名下工单的方式。
-- 工单写入(`create`、`assign`、`move`、`block`、`unblock`、`progress`)与频道写入(`create`、`invite`、`join`、`archive`、`unarchive`、`send`)在请求体里携带 `PENGUIN_SESSION_ID`,文件因此记录该会话的员工而非 token 对应的用户;`ticket attach` 省略 `--session` 时挂接的就是它(完整 id 或唯一片段,同各处约定)。
-- 频道读取(`ls`、`show`、`tail`)以及 `leave` 与 `remove` 背后的成员 DELETE 没有请求体,同一个会话改由 `?sessionId=` 传入。不带它,服务端会把员工当作登录的那个人来应答,`channel ls` 便会列出全部频道而非该员工自己的。
+新频道里只有创建者。成员邀请后员工才能进入;人则可以 `join` 任何频道,并能阅读所有频道。`join` 和 `leave` 始终作用于调用方自身的主体(在工位会话或工单会话里是会话对应的员工,会话之外是当前登录的人),所以 `join` 绝不可能添加别人。`join`、`remove`、`archive` 和 `unarchive` 是给人用的操作:在会话里调用时,服务器会以 `403 not_a_member` 应答,与其他 API 错误一样原样打印。
-`--channel` 缺省为 `default_channel`,即全体员工与全体 Project 成员都在其中的全员频道;`ls` 把它排在最前,并显示本地化名称而非其存储的 name。新频道只有创建者一人:员工要由成员邀请才能进入,人可以自行 `join` 任何频道,也能读到全部频道。`join` 与 `leave` 提交的都是调用方自己的 principal——在工位会话或工单会话内是该会话的员工,在会话外是登录的那个人——因此 `join` 绝不会把别人拉进频道。`join`、`remove`、`archive` 与 `unarchive` 是人的操作,因此在会话内执行时服务端返回 `403 not_a_member`——与其他 API 错误一样原样透出。
+`tail` 以 `time sender text` 的格式打印当天的最后 20 条消息;`-n` 改变条数,`--date` 选择别的日期。`--json` 下打印当天的响应,包含这些消息。`send` 发送一条消息,`@agent:<id>` 和 `@all` 提及会触发对应员工的工位。`system` 行在英文文本之外还携带结构化的 `notice`,`tail` 因此能用 CLI 自身的语言渲染它;当前构建不认识的通知类型则保留英文文本。
-分组说明:
+### handbook
-- `ls` / `show` / `chart`:Project 的组织及其员工、工单与支出计数;单个组织的概览——名称、使命、状态与工作语言,按状态分的员工数,各列工单数,本期支出对照 CEO 预算,以及等你处理的事(@我、待审核工单、等我的阻塞);以及按层级缩进的汇报树,逐员工列出头衔、实时状态、自身与累计支出和预算。校验失败的组织或员工以 `invalid: <原因>` 列出,不隐藏。
-- `create`:`--ceo-budget` 是 CEO 的月预算(美元),缺省 **100**。预算按累计线比较——该员工及其全部下属——所以 CEO 的预算就是整家公司的:新组织一开始就有上限而非无限,初始化会话的触发块里也会带上这个数字,CEO 据此裁剪自己的招募方案。`0` 是真的零预算;要重新变回无限,用 `PATCH .../employees/<org_id>_ceo` 传 `budget: null`(Web App 的员工编辑即发此请求)。`--language zh|en` 指定组织的工作语言;不给则由使命决定(正文里出现任一汉字即为 `zh`),组织写下的一切——组织手册、员工简介、CEO 的初始化会话、工位会话标题——都随之而定。
-- `hire`:`--agent-id`(既有 Agent)与 `--new-agent`(新建)二选一;`--name`、`--description`、`--skills`(额外的插件库插件,追加在每个员工都需要的 `agent-company,agent-development` 之上)描述新 Agent。`--workspace` 是组织公共工作区的子目录(`.` 即整个工作区)或绝对路径,不按 CLI 的 cwd 解析;不给则缺省为以该员工命名的子目录——公共工作区的根目录放共享输入,不是任何人的工位。相对子目录会先归一化——`./hr`、`hr/` 与 `hr` 是同一个分区——并在写下这次招募时由服务端建好,因此 `--workspace hr` 就够了,无需事先存在;绝对路径指向用户自己的目录,必须已经存在;用 `..` 爬出公共工作区的写法直接以 400 `invalid_workspace` 拒收。`employee set --workspace` 规则相同,但没有缺省值:只有给出时才改动分区。工位会话与工单会话打开时也会补建该目录。`--budget` 是该员工及其全部下属的月预算(美元)。`employee set` 只改给出的字段;模型对「都给或都不给」,同各处约定。
-- `calendar`:与 `penguin schedule` 同一套写入器——`add` 缺省启用、`--disabled` 关闭,`--start-at now` 即当前时刻,`update` 读改写,`rm` 不做确认。日程项一律发往员工的工位会话,且只在组织与该员工都处于运行状态时触发;否则状态列显示 `paused`。`add` 与 `update` 在返回事件之外附上本次写入引出的排班提醒——同一起始分钟上已有另一位员工的常设日程项、同一员工已有同周期的常设日程项、常设日程项以 `now` 起算——每条一行,以「排班提醒:」打印。它们只是建议:写入一律成功,提醒文本保持服务端的英文。
-- `ticket`:`ls` 取整个看板后在本地过滤(`--status` 为列名:`proposed`、`in_progress`、`review`、`done`、`rejected`);`show` 先打印派生数据——所在列、运行状态、成本与含子工单成本、贡献会话数、子工单数——再打印工单自身的字段、正文各节,最后以 `History:` 打印操作历史。`create` 二选一:`--goal`(配合 `--criteria`)或以 `--body-file` 给出整个 Markdown 正文,frontmatter 都由服务端生成。`--json` 下 `ls` 以 `{ tickets, invalidFiles }` 打印过滤后的列表。`start` 像 `run --background` 一样打印裸 session id,供 `penguin logs` / `penguin input` 接续。`--owner <principal>` 指定这张工单**唯一**的责任人——组织的员工(Agent id 或 `agent:<id>`)或 Project 成员(`user:<id>`),缺省为调用方;没有 `--notify` 时它成为整个 `notify`,但仅限负责人是员工:人不会因为自己名下的工单收到通知,想收到就把自己写进 `--notify`。谁创建的不是一个选项——它记在工单 `history` 的 `created` 条目里,取自命令运行所在的环境。工单 id 形如 `<yyyy-mm-dd>-<slug>`,slug 是用连字符连接的小写英文单词;`--slug <words>` 直接指定它,标题里英文太少、服务端又无法让 Project 的模型代取时(400 `slug_required`)就必须用这个选项。声称做了活的写入——`progress`、正文编辑、`move --to review`——还会把调用方所在的会话记为该工单的贡献会话,其成本因此摊到工单上;移入其他列以及 `block`、`unblock` 都不记。`progress -m` 只写一句大白话——做了什么、东西在哪——谁写的、什么时候写的由服务端记录。`--goal`、`--criteria` 与 `progress -m` 要求把依赖的输入、预期交付物与涉及的文件一律写成完整路径。
-- `channel tail` 以 `time sender text` 打印当天最后 20 条消息(`-n` 改条数,`--date` 换一天),`--json` 下即当天的响应、只含这些消息;`channel send` 发一条——`@agent:<id>` 与 `@all` 会触发被提及员工的工位。`system` 消息在英文正文之外带一份结构化 `notice`,`tail` 因此按 CLI 自身的语言渲染;本版本不认识的种类保留英文原文。
-- `finance`:本期按员工(自身与沿汇报线累计,对照预算,附 `warned` / `paused` 标记)与按工单的支出,然后是合计;部分用量所用模型未配置价格时,stderr 上一行提示说明数字是下限。
+- `list` 列出手册的文件,包括路径、大小和最近更新,索引排在最前。
+- `show` 打印一个文档;不给路径时打印索引(`README.md`)。
+- `write` 存储文档,`-m <text>` 与 `--file <file>` 必须恰好提供其中一个。
+- `rm` 删除文档。索引不能删。
+
+含 `..` 段的路径一律拒绝。
+
+### finance
+
+`finance` 打印本期支出:按员工(自身支出与沿汇报线的累计支出,与预算对比,带 `warned` 和 `paused` 标记)和按工单分别列出,最后是总额。如果有用量发生在未配置价格的模型上,stderr 会提示这些数字只是下限。
## 审批模式(--approve)
| 模式 | 行为 |
| --- | --- |
-| `allow-all` | 自动批准所有工具调用(默认) |
-| `deny-all` | 自动拒绝所有工具调用 |
-| `read-only` | 自动批准只读工具,其余逐个询问 |
-| `always-ask` | 每次工具调用都询问 |
+| `allow-all` | 自动批准每一次工具调用(默认) |
+| `deny-all` | 自动拒绝每一次工具调用 |
+| `read-only` | 自动批准只读工具,其余逐一询问 |
+| `always-ask` | 每一次工具调用都询问 |
-交互询问时输入 `y` / `yes` 批准、`n` / `no` 拒绝;直接回车默认为批准。
+在审批提示处,`n` 或 `no` 拒绝这次调用。`y`、`yes` 或任何其他回答,包括直接回车,都会批准。
## penguin config
-管理 Project 的模型配置、Agent 级 vault 环境变量与界面语言。除 `lang` 外,以下子命令均支持 `--project-id <id>`(缺省为默认 Project)与 `--root <dir>`。
+管理 Project 的模型配置、每个 Agent 的 vault 环境变量以及界面语言。除 `lang` 外,每个子命令都接受 `--project-id <id>`(默认值:默认 Project)和 `--root <dir>`。
### model add
-新增或更新模型条目:
+添加或更新一条模型条目。
```bash
penguin config model add --provider deepseek --model-id deepseek-v4-pro --api-key sk-... --set-default
```
-| 选项 | 说明 |
-| --- | --- |
-| `--model-id <id>` | 必填,上游模型 id |
-| `--provider <group>` | 必填,条目所属的 Provider 分组。它绝不由模型 id 推导:网关会以上游 id 转售厂商模型,猜错分组会把凭据写到另一家厂商的接口上。内置分组之外的接口一律用 `custom`。 |
-| `--api-key <key>` | API Key,内联存入 Project 隐藏文件 `.project_config.toml` |
-| `--base-url <url>` | 自定义接口地址 |
-| `--context-window <n>` | 上下文窗口大小 |
-| `--max-tokens <n>` | 该模型的最大输出长度(正整数)。设置后覆盖 Agent 的 `model.max_tokens`,缺省沿用;小上下文模型建议调低 |
-| `--client-type <type>` | 客户端协议类型 |
-| `--vision` / `--no-vision` | 标记是否支持视觉输入 |
-| `--fast-mode` / `--no-fast-mode` | 开启 / 关闭快速模式(输出更快、按溢价计费;默认关闭)。在 AgentHub client 会拒绝该参数的模型上开启时,条目照常写入,但会在 stderr 给出警告。两者都不给则保留原值 |
-| `--price-cache-read <n>` | 缓存读价格 |
-| `--price-cache-write <n>` | 缓存写价格 |
-| `--price-output <n>` | 输出价格 |
-| `--set-default` | 同时设为默认模型 |
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--model-id <id>` | 上游模型 id。必填。 | — |
+| `--provider <group>` | 条目所属的供应商分组。必填。 | — |
+| `--api-key <key>` | API key,直接写在 Project 隐藏的 `.project_config.toml` 里。 | — |
+| `--base-url <url>` | 自定义端点的 base URL。 | 见下文 |
+| `--context-window <n>` | 上下文窗口大小,单位是 Token。 | — |
+| `--max-tokens <n>` | 这个模型的最大输出 Token 数,必须是正整数。设置后会覆盖 Agent 的 `model.max_tokens`;小上下文模型应调低此值。 | Agent 的 `model.max_tokens` |
+| `--client-type <type>` | AgentHub 客户端协议类型,例如 `openai-chat`。 | 见下文 |
+| `--vision` / `--no-vision` | 标记是否支持图片输入。 | 保持当前值 |
+| `--fast-mode` / `--no-fast-mode` | 开启或关闭快速模式(输出更快,价格更高)。 | 关闭;两个都不写则保持当前值 |
+| `--price-cache-read <n>` | 缓存读取价格,单位为美元每百万 Token。 | — |
+| `--price-cache-write <n>` | 缓存写入价格,单位为美元每百万 Token。 | — |
+| `--price-output <n>` | 输出价格,单位为美元每百万 Token。 | — |
+| `--set-default` | 同时把这条条目设为 Project 的默认模型。 | — |
+
+- CLI 绝不会从模型 id 推断 `--provider`。网关会按上游模型 id 转售厂商模型,靠猜测分组可能把凭证写到另一家厂商的端点上。内置分组之外的端点一律用 `custom`。
+- 新建条目时,`--client-type` 和 `--base-url` 默认取内置模型目录为对应 `(provider, model_id)` 组合设置的值。模型目录里没有这一条时由分组决定:指定了协议的分组就用它指定的协议;`custom`、用户自定义和网关分组用 `openai-chat`,网关分组的端点会自动填成 base URL;第一方厂商分组则两项都不设置。更新已有条目时,只有显式传入这两个选项才会改动。
+- 如果模型的 AgentHub 客户端不接受这个参数,开启 `--fast-mode` 仍会写入条目,但会在 stderr 上打印警告。
### model default / model vision / model list / model remove
@@ -330,13 +478,13 @@ penguin config model list
penguin config model remove --model-id <id> --provider <group>
```
-- `model default` 设置 Project 默认模型;`model vision` 设置视觉代理模型。两者的 `--model-id` 与 `--provider` 均为必填,且引用必须已存在于模型列表。
-- `model list` 列出已配置模型,默认模型以 `*` 标记。
-- `model remove` 删除一个模型条目,连同内联在其上的凭据一并删除。`--model-id` 与 `--provider` 均为必填,按成对引用精确匹配——同名上游 id 在其他分组下的条目不受影响;引用不在配置中时以非零码退出。若被删条目正是默认模型或视觉模型,对应设置一并清空:留下一个指向已不存在模型的指针,只会让下一次会话直接失败。
+- `model default` 设置 Project 的默认模型,`model vision` 设置视觉代理模型。两者都要求 `--model-id` 和 `--provider`,而且这对组合必须已经在模型列表里。
+- `model list` 列出已配置的模型,并用 `*` 标记默认模型。
+- `model remove` 删除一条模型条目,连同直接写在条目上的凭证一起删除。命令要求 `--model-id` 和 `--provider`,并精确匹配这对组合,所以另一个分组下相同上游 id 的条目不受影响。这对组合不在配置里时,命令以非零退出码退出。如果删除的条目是默认模型或视觉模型,相应设置会一并清空:指向已不存在的模型,会让下一次会话直接失败。
### vault
-按 Agent 存储环境变量,写入 `agent_state/.vault.toml`;值只注入工具子进程的环境变量,绝不进入模型上下文。
+每个 Agent 独立的环境变量存储,写入 `agent_state/.vault.toml`。这些值只注入工具子进程的环境,从不进入模型上下文。
```bash
penguin config vault set --key GITHUB_TOKEN --value ghp_xxx
@@ -350,92 +498,107 @@ penguin config vault remove --key GITHUB_TOKEN
| `vault list` | `[--agent-id <id>]` |
| `vault remove` | `--key <name>`(必填)、`[--agent-id <id>]` |
+`--agent-id` 默认为 `default_agent`。
+
### lang
```bash
-penguin config lang zh
+penguin config lang en
```
-设置 CLI 界面语言(`en` 或 `zh`),将 `PENGUIN_LANG` 写入 shell 启动文件。
+设置 CLI 的界面语言(`en` 或 `zh`),方式是把 `PENGUIN_LANG` 写入你的 shell 启动文件。在交互式终端里,命令随后会提议打开一个新 shell 让设置生效;否则会打印让设置生效的方法。Windows 上命令会拒绝执行,因为没有 POSIX shell 启动文件可写。
## penguin server / penguin web
-两者是同一服务进程的两个入口:`server` 为 headless 模式;`web` 额外等待服务就绪、打印 URL 并打开浏览器。
+同一个服务进程的两个入口。`server` 以无界面方式运行服务。`web` 还会等服务就绪,打印 URL 并打开浏览器。
```bash
-penguin web
+penguin server [--port <port>] [--host <host>]
+penguin web [--port <port>] [--host <host>] [--no-open]
```
-| 选项 | 说明 |
-| --- | --- |
-| `--port <port>` | 监听端口,默认 7364 |
-| `--host <host>` | 监听地址,默认 127.0.0.1 |
-| `--no-open` | 仅 `web`:不自动打开浏览器 |
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--port <port>` | 监听端口。 | `7364` |
+| `--host <host>` | 监听地址。 | `127.0.0.1` |
+| `--no-open` | 仅限 `web`:不打开浏览器。 | — |
-端口 / 地址优先级:命令行选项 > 环境变量 `PORT` / `HOST`(含 `.env`)> 默认值。
+端口和主机按以下顺序确定:命令行选项,然后是 `PORT` / `HOST` 环境变量(包括来自 `.env` 的),最后是默认值。
-两者都把服务作为子进程运行,自己留在后面做托管:终端的 Ctrl+C 会送达服务,命令以服务的退出码退出;当服务请求重启——`penguin update` 替换安装后,Web App 里的「重启并更新」——托管进程会在新版本上重新拉起它,并打印一行提示。经 `tsx` 的开发运行无法被普通 node 重新拉起,改为在本进程内运行服务;此时 Web App 会提示管理员手动重启。
+如果这个数据根目录上已经有服务在运行,`penguin server` 会说明情况并以退出码 1 退出;`penguin web` 则打印正在运行实例的 URL 并打开它(除非指定 `--no-open`),不会启动第二个实例。
+
+两个命令都把服务作为子进程运行,并以托管进程的身份守在它前面。终端里的 Ctrl+C 会传达给服务,命令以服务的退出码退出。当服务请求重启时——例如 `penguin update` 替换安装之后,Web App 的**重启并更新**就会发出这种请求——托管进程会在新版本上重新启动服务,并打印一行文字说明。通过 `tsx` 运行的开发版无法由普通 Node 重新拉起,因此服务改为在当前进程内运行,此时 Web App 会提示管理员手动重启。
+
+```bash
+penguin web
+```
### penguin server status
-以单行 JSON 打印本数据根目录的服务状态与本机 id。无论是否有服务在运行它都会作答——依据是数据根目录本身,而不是某个存活的进程:
+以一行 JSON 打印这个数据根目录的服务器状态和本机自身的 id。它能回答「服务器是否在运行」,因为它读取的是数据根目录本身,而不是去询问一个运行中的进程。
```bash
-penguin server status
+penguin server status [--root <dir>]
# {"running":true,"port":7364,"pid":41233,"machineId":"LNrJdHAZJ91G58i0"}
```
-`running` 为真要求记录的 pid 存活**且**其端口可建立连接,因此被回收复用的 pid 不会被读成一个活着的服务。`machineId` 在本机从未启动过服务之前是 `null`——该 id 在首次启动时铸出,此后永不改变。数据根目录一如既往由 `PENGUIN_HOME` 选定。
+只有当记录的 pid 还活着、端口也能建立连接时,`running` 才是 true,所以复用的 pid 不会冒充存活的服务器。没有服务器在运行时,`port` 和 `pid` 为 `null`。`machineId` 在本机至少启动过一次服务器之前为 `null`:id 在首次启动时生成,此后永不改变。数据根目录照常取自 `--root` 或 `PENGUIN_HOME`。
-机器页正是通过 ssh 运行这条命令来询问一台机器的状态,这也是它输出 JSON 而非人类散文的原因。
+**机器**页面通过 ssh 运行这条命令,询问一台机器正在做什么,这也是输出采用 JSON 而不是文字说明的原因。
### penguin server reset-admin-password
-忘记 Web 管理员密码时的离线救援。须在服务停止后执行——数据根目录上有服务在运行时会拒绝:
+忘记 Web 管理员密码时的离线补救手段。必须在服务器停止的状态下运行;数据根目录上还有服务器在运行时,命令会拒绝执行。
```bash
penguin server reset-admin-password
```
-内置 `admin` 会被恢复成未认领状态——密码随机生成且无人见过,admin 的全部会话一并吊销。重新启动服务,打开它打印的首次登录链接即可设置新密码;整个过程无需记下任何东西。其他账号由管理员在用户管理页重置,本命令只作用于 `admin`。数据根目录照常由 `PENGUIN_HOME` 决定。
+内置的 `admin` 账号回到未认领状态:密码换成一个没人见过的随机值,它的所有会话全部吊销。重新启动服务器,打开它打印的首次登录链接设置新密码即可,中间不需要记下任何东西。其他账号由管理员在**用户管理**页面重置,这条命令只处理 `admin`。数据根目录照常取自 `PENGUIN_HOME`。
### penguin server stop
-停止本数据根目录上的服务,并以单行 JSON 报告结果:
+停止这个数据根目录上的服务器,并以一行 JSON 报告结果。
```bash
-penguin server stop
+penguin server stop [--root <dir>]
# {"ok":true,"pid":41233}
```
-只发 `SIGTERM` 并等待,绝不 `SIGKILL`:那个服务端持有数据库、也可能正在收尾一个任务,调用方因为超时就决定销毁它,这不是它该做的决定。根目录上本来就没有服务在跑时答 `{"ok":true}`——那正是调用方要的结果,不是失败。
+命令发送 `SIGTERM`,最多等待 15 秒,让服务器释放数据根目录。它绝不会发送 `SIGKILL`:服务器持有数据库,可能还有任务在收尾,超时就强杀不是调用方有权做的决定。数据根目录上本来就没有服务器在运行时,命令返回 `{"ok":true}`,因为「没有进程在服务这个目录」正是调用方想要的结果。
+
+服务器停不下来时,命令打印 `{"ok":false,"pid":…,"detail":"…"}` 并以退出码 1 退出。出现这种情况的情形有:信号无法送达;`SIGTERM` 发出 15 秒后服务器仍占用着数据根目录;以及在 Windows 上——那里无法通过信号实现优雅停止,只能从服务器自己的控制台停止。
-Machines 页面重启一台机器时通过 ssh 执行它。之所以是命令而不是发给那个服务端的请求:需要被停止的机器,往往正是平台版本落后的那一台,而平台路由只有在机器已经跑上带它的构建之后才存在。
+**机器**页面重启一台机器时,会通过 ssh 运行这条命令。之所以用命令而不是直接向服务器发请求,是因为需要停止的机器通常正是平台版本过期的那台,而平台路由要等机器跑上带这条路由的构建版本才会存在。
## penguin version
-报告当前运行的是哪个构建。仅凭版本号回答不了这个问题——两次发布之间由源码 checkout 构建出来的每一个版本也都自称 `0.2.3`——因此发布版与源码构建给出的身份并不相同。
+报告当前运行的是哪个构建。只看版本号回答不了这个问题:两次发布之间从源码检出构建出的每个版本也都自称 `0.2.3`,所以发布版和源码构建版要用不同的方式标识自己。
```bash
-penguin version # v0.2.3 (发布版)
-penguin version # v0.2.3-14-g9e8f7d6-dirty (源码构建)
-penguin version --json # 完整构建信息
+penguin version # v0.2.3 (a release)
+penguin version # v0.2.3-14-g9e8f7d6-dirty (built from a checkout)
+penguin version --json # the full build info
```
-| 选项 | 说明 |
-| --- | --- |
-| `--json` | 输出完整版本报告而非单行:`{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}` |
-| `--root <dir>` | 以哪个数据根目录的 HMR store 作为 `harness` 上报。优先级:`--root` > `PENGUIN_HOME` > `~/.penguin/data` |
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--json` | 打印完整的版本报告,而不是一行:`{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}`。 | — |
+| `--root <dir>` | 指定把哪个数据根目录的 HMR 存储报告为 `harness`。仅在指定 `--json` 时使用。 | `PENGUIN_HOME`,否则 `~/.penguin/data` |
-不带选项时输出单行;源码构建下该行即 `git describe --tags --dirty` 的结果——`v0.2.3-14-g9e8f7d6-dirty` 表示位于 `v0.2.3` 之后 14 个提交、当前提交为 `9e8f7d6`、且工作区有未提交改动。`-v, --version` 输出的是同一行。
+不带选项时打印一行。对源码构建版来说,这一行就是 `git describe --tags --dirty` 的输出:`v0.2.3-14-g9e8f7d6-dirty` 表示在 `v0.2.3` 之后第十四个提交(`9e8f7d6`),且带有未提交的改动。`-v, --version` 打印同样的一行。
-`describe` 指向的是最近的可达 git tag,因此并不总是 `v` + `version`:发布准备会先用一个单独的提交抬升 `version`、之后才打 tag,所以这一窗口内的构建会报告 `v0.2.3-14-g9e8f7d6`,而 `version` 已经是 `0.2.4`。要版本号看 `version`,要在历史中的位置看 `describe`。
+`describe` 指向可达的最近的 git 标签,不一定等于 `version` 前面加个 `v`。准备发布时,`version` 先在自己的提交里升号,标签随后才创建,所以处于这个窗口期的构建会报告 `v0.2.3-14-g9e8f7d6`,而 `version` 已经是 `0.2.4`。要看发布号,读 `version`;要看在历史中的位置,读 `describe`。
-JSON 与 `GET /api/version` 返回的是同一份记录,因此在 HTTP 边界的任意一侧都能采集到同样的排障信息。其中 `channel` 取 `release` 或 `source`;`buildDate` 与 `commit` 由发布流程在构建时打入,源码构建为 null;`branch` 与 `dirty` 描述源码构建的 git 位置,发布版为 null——发布流程会先把常量写进工作区再构建,所以「是否干净」对发布产物本就不成立。
+这份 JSON 和 `GET /api/version` 返回的是同一条记录,所以 bug 报告可以从 HTTP 边界的任意一侧收集它。其中:
-### harness:这台机器上热更新推了什么
+- `channel` 取值为 `release` 或 `source`。
+- `buildDate` 和 `commit` 由发布流程写入构建,源码构建版为 null。
+- `branch` 和 `dirty` 描述源码构建版的 git 位置,发布版为 null——发布版用不上这两个字段,因为发布流程会在构建前把常量写入代码树。
-`harness` 描述的是该数据根目录的 HMR store——某次热更新提交进去、并会在重启后被恢复的 harness 代码。该根目录从未被推送过时为 null。
+### harness:这里热推送过什么
+
+`harness` 描述数据根目录的 HMR 存储:热更新提交进来的 harness 代码,重启后会恢复运行。这个数据根目录从未推送过任何内容时为 null。
```json
"harness": {
@@ -445,73 +608,92 @@ JSON 与 `GET /api/version` 返回的是同一份记录,因此在 HTTP 边界
}
```
-这正是单行版本无法表达的部分:推送过去的 bundle 落在任何 checkout 之外,它只能以自己被编译时的版本号自称;`source.revision`(由推送方记录,拼写方式与 `describe` 一致)是唯一能指明其背后 revision 的信息。`bundles` 是已提交产物的内容寻址指针,无论推送方声称了什么,它标识的都是被推送代码本身。
+这是版本那一行唯一报告不了的信息。推送出去的 bundle 落在所有检出之外,只能用编译时依据的版本来标识自己。`source.revision` 由推送方记录,写法与 `describe` 相同,是唯一能指明背后修订版本的字段。`bundles` 保存已提交产物的内容寻址指针。无论推送方怎么声称,这些指针标识的都是实际推送的代码本身。
-它描述的是 store 而非当前进程:`penguin` 运行的是随包发布的 CLI,`penguin-hmr` 才运行 store 里的那份,因此 `harness` 非 null 并不意味着打印它的这条命令本身就是被推送的代码。若推送方未记录来源(包括在该机制存在之前推送的版本),`source` 为 null。
+`harness` 描述的是存储,不是正在运行的进程。`penguin` 运行打包好的 CLI,`penguin-hmr` 运行存储里的 CLI,所以 `harness` 非 null 并不意味着打印它的命令就是推送来的代码。推送方客户端没有记录来源信息时,`source` 为 null——在来源信息机制出现之前推送的内容也都如此。
-已安装的 penguin 从不调用 git,只读取构建时打入的常量:发布版由发布流程打入,其余构建则由打包器把 git 位置内联进产物,因此产物离开生成它的 checkout 之后依然能说明自己的身份——位于 `<root>/hmr/store/` 下被热推送的 bundle,在既无 checkout 也未安装 git 的机器上,仍会报告它被构建时的 revision。运行时询问 git 只是兜底,用于未经打包的 `tsx` 运行;即便如此它也只问自己所在的那个 checkout,所以在无关仓库里执行 `penguin version` 报告的仍是 harness 自身的版本,而非该仓库的。
-## penguin auth
+安装好的 `penguin` 从不运行 git:它读取构建时打入的常量。发布版的常量来自发布流程。其他构建的 git 位置由生成它的打包器内联进去,所以产物离开检出之后仍能标识自己:`<root>/hmr/store/` 下的热推送 bundle 能报告自己构建时所在的修订版本,即使机器上没有任何检出、也没安装 git。运行时询问 git 只是未打包的 `tsx` 运行方式的兜底做法,而且问的也是自己的检出,所以在无关的仓库里运行 `penguin version`,报告的是 harness 的修订版本,而不是那个仓库的。
-在终端里登录正在运行的 PenguinHarness 服务。这是 CLI 里唯一以客户端身份与服务通信的部分——`config`、`run`、`chat` 都是直接操作数据根。
+## penguin auth
-有两种登录方式,取决于你站在哪里。
+从终端登录一台正在运行的 PenguinHarness 服务器。登录方式有两种,选哪种取决于你所处的位置。
```bash
-penguin auth login # 用密码登录该数据根上运行的服务
+penguin auth login # password, against the server on this data root
penguin auth login --server https://penguin.example --user-id alice
penguin auth status
penguin auth logout
-penguin auth token # 不需要密码:直接从数据根签发
+penguin auth token # no password: minted from this data root
```
-`login` 需要密码,向正在运行的服务请求会话,和浏览器登录页做的事完全一样。目标默认是该数据根上正在运行的服务(从锁文件读端口),所以登录自己的服务不必写 URL。
+每个 `auth` 子命令都接受 `--root <dir>` 来选择数据根目录;参见[全局约定](#全局约定)。
-交互运行时会先问账号,再问密码,并且密码提示里写明是哪个账号的,避免把一个账号的密码输到另一个账号上。如果用非交互方式给了密码(`--password` 或 `PENGUIN_PASSWORD`),两个问题都不会问——那是脚本,脚本没法回答。
+### penguin auth login
-| 选项 | 说明 |
-| --- | --- |
-| `--server <url>` | 要登录的服务;默认是该数据根上运行的那个 |
-| `--user-id <id>` | 账号;不给时会询问,直接回车即用 `admin` |
-| `--password <pw>` | 密码;也可用 `PENGUIN_PASSWORD`,都没给时会无回显地提示输入 |
-| `--print` | 同时把会话令牌打印到 stdout,便于管道使用 |
+`login` 使用密码向正在运行的服务器请求会话,和浏览器的登录页完全一样。目标默认是这个数据根目录上运行的服务器,从它的锁文件读出,所以登录你自己的服务器不需要 URL。
-优先用 `PENGUIN_PASSWORD` 或交互输入,而不是 `--password`:命令行参数可以被 `ps` 看到。
+交互式运行时,`login` 先问账号、再问密码,密码提示中会显示账号名,因此不会把一个账号的密码误输入给另一个账号。如果以非交互方式提供密码(`--password` 或 `PENGUIN_PASSWORD`),这两个问题都不会出现,因为脚本无法回答。
-`token` 完全不需要密码。它把一行会话直接写进数据根的 `web.db`,其授权依据就是你能读写这个数据根——而它本来就装着这个令牌所能触及的全部凭据。因此它是**数据根属主**的工具:多用户部署时数据根属于运行服务的那个操作系统账号,其他人一律用 `auth login` 凭密码登录。适用于没有密码可给的场合:管理员密码被人改过的机器、不该持有密码的脚本,以及控制端通过 ssh 管理机器时。
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--server <url>` | 要登录的服务器。 | 这个数据根目录上运行的服务器 |
+| `--user-id <id>` | 账号。省略时会询问;直接回车表示 `admin`。 | `admin` |
+| `--password <pw>` | 密码。也可以从 `PENGUIN_PASSWORD` 读取;否则会提示输入且不回显。 | — |
+| `--print` | 同时把 session token 打印到 stdout,供管道使用。 | — |
-| 选项 | 说明 |
-| --- | --- |
-| `--user-id <id>` | 账号,默认 `admin` |
-| `--ttl-seconds <n>` | 有效期秒数,默认 3600 |
-| `--mark` | 在令牌前打印固定标记行——供需要从 shell 输出里解析它的调用方使用,因为登录 profile 可能打印横幅 |
+> [!WARNING]
+> 优先用 `PENGUIN_PASSWORD` 或交互提示,而不是 `--password`:机器上的任何人都能通过 `ps` 读到命令行。
+
+### penguin auth token
+
+`token` 完全不需要密码。它直接往数据根目录的 `web.db` 里写一条会话记录,授权依据是:你能读写这个数据根目录,而它本来就保存着 token 能触达的全部凭证。因此 `token` 是**数据根目录所有者**的工具:多用户部署时,数据根目录属于运行服务器的操作系统账号,其他人一律用 `auth login` 登录。数据根目录上从未运行过服务器时命令会失败,因为还没有 `web.db` 可写。在拿不出密码的场合使用它:
-会话写入 `<root>/cli-session.json`,权限 0600;`status` 读它,`logout` 吊销并删除它。`logout` 会先告诉服务端,让会话真正失效,而不只是本地忘记;连不上服务时会明说,本地文件照样删除。
+- 管理员密码由人手动设置过的机器。
+- 不能保存密码的脚本。
+- 通过 ssh 连接受管机器的控制器。
+
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--user-id <id>` | 账号。 | `admin` |
+| `--ttl-seconds <n>` | 会话有效期(秒):正整数,上限 30 天。 | `3600` |
+| `--mark` | 在 token 之前打印一行固定标记,供从 shell 输出中解析 token 的调用方使用——这类 shell 的登录配置可能会打印横幅。 | — |
+
+### penguin auth status / penguin auth logout
+
+会话保存在 `<root>/cli-session.json`,文件权限为 0600。`login` 写入它;数据根目录上有服务器在运行时,`token` 也会写入。`status` 读取它。`logout` 吊销会话并删除文件:它会先通知服务器,因此会话在服务器端结束,而不只是本地把它忘掉。连不上服务器时,`logout` 会说明情况,然后照样删除本地文件。
## penguin update
-原地升级当前安装,并沿用它当初的安装方式。安装方式由运行中 CLI 的真实路径判定,不做猜测。
+使用当初安装时所用的机制,原地升级当前安装。命令根据正在运行的 CLI 的真实路径判断安装类型,绝不猜测。
```bash
-penguin update --check # 只报告版本
-penguin update # 确认后升级到最新版
+penguin update --check # report versions only
+penguin update # upgrade to the latest release, after confirming
```
-| 选项 | 说明 |
-| --- | --- |
-| `--check` | 只报告已安装版本与最新版本,不做任何修改;两种情况下退出码均为 0 |
-| `--release <tag>` | 指定目标版本而不是最新版(`v0.1.2` 或 `0.1.2`);允许低于当前版本,会明确提示为降级 |
-| `-y, --yes` | 跳过确认提示 |
+| 选项 | 说明 | 默认值 |
+| --- | --- | --- |
+| `--check` | 只报告已安装版本和最新版本,不做任何改动。无论哪种情况都以退出码 0 结束。 | — |
+| `--release <tag>` | 升级到指定发布版本而不是最新版(`v0.1.2` 或 `0.1.2`)。允许指定更旧的标签,并会按降级报告。 | 最新发布版 |
+| `-y, --yes` | 跳过确认提示。 | — |
-目标版本参数叫 `--release` 而不是 `--version`,因为 `-v, --version` 是 CLI 自身的版本参数,会优先生效。
+这个选项是 `--release` 而不是 `--version`,因为 `-v, --version` 是 CLI 自身的版本选项,会抢先生效。
-版本发现和 tarball 下载遵循 `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`,与稳定安装入口使用相同策略。默认的 `auto` 模式读取 OSS `latest.json`,优先选择该不可变版本,并按同一 tag 回退到 GitHub;安装包本身则由安装器测速选出的来源提供。强制 `oss` 或 `github` 时不会切换来源。`--release <tag>` 会跳过最新版查询,但仍遵循所选下载源策略。显式设置的 HTTPS `PENGUIN_DOWNLOAD_BASE_URL` 对安装脚本和发布包下载具有最高优先级,并可通过 `PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` 为发布包配置后备地址。
-
-| 安装方式 | 升级方式 |
+| 安装类型 | 升级方式 |
| --- | --- |
-| tarball(`install.sh`,默认 `~/.penguin`) | 重新执行官方安装脚本,并保持原安装目录以及是否内置 Node 运行时 |
-| npm/pnpm/yarn/bun 全局安装 | 用该包管理器全局安装 `@prismshadow/penguin-cli@<目标版本>`;无法确定包管理器时,只打印命令而不猜测 |
-| 源码检出 | 拒绝执行——请用 `git pull` 更新并重新构建 |
+| 压缩包(`install.sh`,默认 `~/.penguin`) | 重新运行官方安装器,保留原安装目录以及安装包是否自带 Node 运行时 |
+| npm、pnpm、yarn 或 bun 全局安装 | 用对应的包管理器全局安装 `@prismshadow/penguin-cli@<target>`。无法识别包管理器时,打印命令而不是猜测 |
+| 源码检出 | 拒绝:请用 `git pull` 加重新构建来更新 |
+| 桌面应用内置的 CLI | 拒绝:应用更新时会随之替换,请从应用菜单检查更新 |
+| 无法识别的布局 | 拒绝:请用官方安装器重新安装,或用当初的包管理器升级 |
+
+不带 `-y` 时,命令会打印它将要做的事(升级机制、目标版本和安装目录),并要求确认。stdin 不是终端时,命令要求提供 `--yes`,而不是等一个没人能回答的提示。**数据根目录完全不受影响**:升级只替换 `bin`、`lib`、`web` 和 `node`。Windows 上两种升级路径都无法原地执行。安装器是 POSIX shell 脚本;全局安装也无法从这里驱动,因为 Node 离开 shell 就无法执行 `npm` 或 `pnpm` 的 `.cmd` shim,所以命令会把完整命令打印出来,由你自己运行。
+
+发布版本的发现和下载遵循 `PENGUIN_DOWNLOAD_SOURCE=auto|oss|github`,与稳定版安装入口使用相同的策略:
-不带 `-y` 时,命令会先打印它将要做什么——方式、目标版本与安装目录——再请求确认;当 stdin 不是终端时,它要求显式加 `--yes`,而不是卡在无人能回答的提示上。**数据目录不会被改动**:升级只替换 `bin`、`lib`、`web` 与 `node`。两条路径在 Windows 上都不做原地升级:安装脚本是 POSIX shell 脚本,而全局安装也无法由此驱动——Node 不会在没有 shell 的情况下执行 `npm`/`pnpm` 的 `.cmd` 包装脚本——因此命令会直接打印出应当由你自己执行的命令。
+- `auto` 是默认值:读取 OSS 的 `latest.json`,优先使用那个不可变的发布版本,失败时退回匹配的 GitHub 标签。安装包本身则来自安装器测速后选定的源。
+- `oss` 和 `github` 是严格模式:命令只使用指定的源。
+- `--release <tag>` 跳过最新版本探测,但仍遵循所选的源策略。
+- 显式设置的 HTTPS `PENGUIN_DOWNLOAD_BASE_URL` 拥有最高优先级,安装器和安装包下载都遵循它;`PENGUIN_DOWNLOAD_FALLBACK_BASE_URL` 可选,为安装包提供回退地址。
-相关文档:[配置参考](/configuration)、[模型与 Provider](/models)。
+另请参阅:[配置参考](/configuration)、[模型与供应商](/models)。
diff --git a/packages/docs/content/company-mode.en.md b/packages/docs/content/company-mode.en.md
index db2c4eac..2cd3d2e7 100644
--- a/packages/docs/content/company-mode.en.md
+++ b/packages/docs/content/company-mode.en.md
@@ -1,114 +1,249 @@
---
title: Company Mode
-description: Turn a one-sentence mission into an organization of Agents — a CEO that hires, a calendar that drives every desk, a ticket board that carries the work, channels where only @mentions interrupt anyone, and budgets that pause spending before it runs away.
+description: Turn a one-sentence mission into an organization of agents that runs on a calendar, a ticket board and channels, while you act as its board.
---
-## What it is
+Development mode is one person talking to one agent. Company mode, the Web App's second work mode, organizes a Project's agents into a **company** that runs by itself for weeks: a calendar drives it, a ticket board carries its work, and its employees talk in channels. You give it a mission in one sentence and sit on its board, deciding only what needs a person.
-**Company mode is a beta feature**: it may still be unstable, so please report anything you hit.
+> [!WARNING]
+> Company mode is a beta feature. It may still be unstable; please report anything you run into.
-Development mode is one person talking to one Agent. Company mode is the second work mode of the Web App: a Project's Agents organized into a **company** that runs by itself for weeks — driven by a calendar, carrying its work on a ticket board, talking in channels — while you sit on the board and decide only what needs a person. You give it a mission in one sentence; it creates the CEO; the CEO hires HR, finance and whoever the mission needs, partitions the shared workspace, schedules everyone and files the first tickets.
+- To switch company mode on, see [Turn on company mode](#turn-on-company-mode).
+- To start a company, see [Create an organization](#create-an-organization).
+- To understand how a company works, see [What an organization is made of](#what-an-organization-is-made-of), [How work flows](#how-work-flows) and [Channels](#channels).
+- To know what is guaranteed and what is only guidance, see [Budgets](#budgets) and [What the server enforces](#what-the-server-enforces).
+- To run experiments and write papers, see [Research organizations](#research-organizations).
+- To build a company that mirrors a real one, see [Mirror organizations](#mirror-organizations).
-Everything the company is lives in **files** under the Project directory. SQLite keeps caches that are rebuilt from those files on every pass, plus each user's read cursor in each channel — the same rule development mode follows for Agent State and Traces. Delete the caches and nothing changes; edit a file by hand and the next pass picks it up.
+## Turn on company mode
-Switch modes with the Development | Company control at the top-left of the sidebar. It is there when the admin's master switch is on (System settings › Server › Company mode, **off by default** — an admin turns it on) and you have not hidden it yourself (System settings › Personal › Company mode).
+**Before you begin**
-A desk or ticket session is stamped as the organization's on the row itself when it is opened, so it is listed in company mode and never in development mode's session list — including after the organization's directory is removed by hand or the master switch is turned off, when nothing else could tell whose it was. Organizations that already existed get their sessions stamped on the runtime's next pass over their files.
+- You need an admin account. Company mode is off by default on every server, and only admins see its server switch.
-## Creating one
+1. Open **System settings** › Server › **Company mode**, and turn on **Enable company mode**. The change is saved at once.
+2. At the top left of the sidebar, the mode switch reads **Development** | **Company**, with a **Beta** tag. Select **Company**.
-Three entry points, one server call behind all of them:
+To go back, select **Development**. Every user sees the mode switch while the server switch is on. To hide it for yourself only, turn off **Company mode** under **System settings** › Personal › **General**; organizations keep running. See [Switches and lifecycle](#switches-and-lifecycle).
-- **the Web App** — 新建组织 in the organization switcher: the display name comes first, and a button beside the id field asks the server to derive an id from it (the Project's default model proposes a short English snake_case id, an ASCII slug of the name answers when it cannot, and a name neither can name is filled with a dated placeholder that says under the field why and asks to be replaced — the button always leaves an id in the box); four mission examples fill the mission with one click;
-- **the CLI** — `penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>]`;
-- **the general agent** — ask any Agent carrying the `agent-company` plugin to set a company up and its `company-setup` skill takes over: one question at a time (id, name, mission, shared workspace, model, CEO budget), a summary to confirm, then that same command. It stops there — hiring, scheduling and tickets are the CEO's, after the board answers. The plugin is not preinstalled, so an Agent that has never been part of a company needs it installed first — the Plugins field of the create-agent dialog, or the Skills tab of an Agent already in the Project; a CEO and its employees carry it from the day they are hired.
+## Create an organization
-Ids are lowercase snake_case, 2–64 characters, starting with a letter, and by convention they say what they name: an organization id starts with `co_` and a channel id with `ch_` (`co_plugin_marketplace`, `ch_site`). The App's id proposal and the `company-setup` skill both write the prefix; the server does not enforce it, so a hand-typed id is taken as written and ids created before the convention keep working.
+An organization lives inside a Project, at `<project>/organizations/<org_id>/`, and a Project can hold several. There are three ways to create one, with the same server call behind all of them.
-Creation writes the organization's directory, its all-hands channel and its handbook, and exactly one employee: the **CEO**, with a monthly budget of **100 USD** unless creation named another (`ceoBudget` in the API, `--ceo-budget` on the CLI, the CEO budget field in the dialog). Budgets are compared on the cumulative line, so that one number is the whole company's cap; it lives in `org_chart.yaml` and is raised, lowered or cleared from the org chart at any time. Then the CEO's desk opens with an initialization run, which posts one proposal in the all-hands channel and stops until the board answers it.
+### From the Web App
-An organization also works in one **language**. It is `language` in `org_config.toml`, detected from the mission at creation — one Han character anywhere makes it `zh`, everything else `en` — unless creation names one (`--language`, `language` in the API, the Working language field in the create dialog), and changed afterwards in the organization settings. The handbook, the employee briefs (`AGENTS.md`), the CEO's initialization run and the desk session titles are written in it, and the skills tell every employee to write its channel messages, tickets, documents and reports in it too; commands, ids, file names and field names stay ASCII whatever it is. An organization created before the field has none stored and reads as whatever its mission is written in, so nothing had to be migrated.
+1. In company mode, open the organization switcher and select **New organization**.
+2. Enter a **Display name**.
+3. Next to **Organization id**, select **Generate with AI** to derive an id from the name, or type one yourself.
+4. Enter the **Mission**, or select one of the four examples below the field to fill it in.
+5. Optional: choose a **Model**, a **Company workspace** and a **CEO budget**.
+6. Select **Create**. The CEO's desk session opens.
-## The pieces
+**Generate with AI** always leaves an id in the box. The Project's default model proposes a short English snake_case id. When it cannot, an ASCII slug of the name is used. When neither works, the field gets a dated placeholder, and a note under it says why and asks you to replace it.
+
+### From the CLI
+
+```text
+penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>]
+```
+
+### From an agent
+
+Ask an agent that has the `agent-company` plugin to set up a company. Its `company-setup` Skill takes over: it asks one question at a time (id, name, mission, shared workspace, model, CEO budget), shows a summary for you to confirm, and runs the same `penguin org create` command. It stops there. Hiring, scheduling and tickets are the CEO's job, after the board answers.
+
+The plugin is not preinstalled, so an agent that has never been part of a company needs it first. Install it in the **Plugins** field of the create-agent dialog, or on the **Skills** tab of an agent already in the Project. A CEO and its employees carry it from the day they are hired.
+
+### Ids
+
+Ids are lowercase snake_case, 2 to 64 characters, and start with a letter. By convention, an id also says what it names: organization ids start with `co_` and channel ids with `ch_`, as in `co_plugin_marketplace` and `ch_site`. The Web App's id proposal and the `company-setup` Skill both add the prefix. The server does not enforce it, so an id you type is taken as written, and ids created before the convention keep working.
+
+### What creation does
+
+Creating an organization writes its directory, its all-hands channel and its handbook, and hires exactly one employee: the **CEO**. The CEO's monthly budget is **100 USD** unless creation names another (`ceoBudget` in the API, `--ceo-budget` on the CLI, **CEO budget** in the dialog). Because a budget counts every subordinate, the CEO's budget is the cap for the whole company. See [Budgets](#budgets).
+
+Then the CEO's desk opens with an initialization run. The CEO posts one proposal in the all-hands channel and stops until the board answers it.
+
+### Working language
+
+Each organization works in one language, `language` in `org_config.toml`. At creation it is detected from the mission: a single Han character anywhere makes it `zh`, and anything else is `en`. The CLI (`--language`) and the API (`language`) can name it instead, and you can change it later under **Working language** in the organization settings.
+
+The handbook, the employee briefs (`AGENTS.md`), the CEO's initialization run and the desk session titles are written in that language. The Skills tell every employee to write channel messages, tickets, documents and reports in it too. Commands, ids, file names and field names stay ASCII in either language. An organization created before this field existed has none stored and uses the language its mission is written in, so nothing needed migrating.
+
+## What an organization is made of
| Piece | What it is | Where it lives |
| --- | --- | --- |
-| Organization | one company: a name, a mission, a status, a timezone, a working language, an approval mode | `<project>/organizations/<org_id>/org_config.toml` |
-| Employees | Agents in a reporting tree rooted at the CEO — no departments, no positions; each entry carries a title, duties, a workspace and a monthly budget | `org_chart.yaml` |
-| Desk sessions | one standing session per employee, opened the moment that employee is hired: calendar events, channel mentions and people land there; it schedules work and opens ticket sessions rather than doing the work itself. The reconcile pass opens the desk of an employee that has none — one added to `org_chart.yaml` by hand, or one whose session was deleted | `desks.toml` (written by the server) |
-| Calendar | per-employee events in the scheduled-task format, minus target fields — the only periodic driver | `calendar/<agent_id>/<event>.toml` |
-| Tickets | one Markdown file each — YAML frontmatter (`title`, `status`, `owner`, `notify`, `priority`, `due`, `blocked`, `sessions`, `history`) then `## Goal`, `## Acceptance criteria`, `## Progress`, `## Result` — in a column directory that is the status. The slug is lowercase English words joined by hyphens | `tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md` |
-| Channels | one directory per channel: an intent file with its name, purpose and members, and one JSON line per message, split by day | `channels/<channel_id>/channel.toml`, `channels/<channel_id>/<yyyy-mm-dd>.jsonl` |
-| Shared workspace | the company's working directory; its root holds the shared inputs and is nobody's desk — the CEO works in `ceo/`, a hire lands in a sub-directory named after its Agent id unless the CEO assigns another, and a relative sub-directory is created by the server as it is assigned (an absolute path must already exist) | `workspace/` |
-| Handbook | the company's knowledge base; its `README.md` is the index every work run reads first, the other documents are listed there and read on demand | `handbook/` |
+| Organization | One company: a name, a mission, a status, a timezone, a working language and an approval mode | `<project>/organizations/<org_id>/org_config.toml` |
+| Employees | Agents in a reporting tree rooted at the CEO, with no departments or positions. Each entry has a title, duties, a Workspace and a monthly budget | `org_chart.yaml` |
+| Desk sessions | One standing Session per employee, where its triggers arrive | `desks.toml` (written by the server) |
+| Calendar | Per-employee events in the scheduled-task format, without the target fields. The calendar is the only recurring driver | `calendar/<agent_id>/<event>.toml` |
+| Tickets | One Markdown file per ticket, in a column directory that is its status | `tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md` |
+| Channels | One directory per channel: an intent file with its name, purpose and members, and one JSON line per message, split by day | `channels/<channel_id>/channel.toml`, `channels/<channel_id>/<yyyy-mm-dd>.jsonl` |
+| Shared workspace | The company's working directory | `workspace/` |
+| Handbook | The company's knowledge base | `handbook/` |
+
+### Desk sessions
-The handbook is progressive loading in practice: every trigger points at `handbook/README.md`, the index names the layout, the protocols, the role conventions and every document with one line saying when it matters, and a run reads a document only when that line says so. Board decisions go in `handbook/decisions/<yyyy-mm-dd>-<slug>.md`, conventions and how-tos next to them; the Handbook page of the Web App browses, edits and creates them, and `penguin org handbook list | show | write | rm` does the same from a session. The index cannot be deleted.
+Each employee gets one standing desk session the moment it is hired. Calendar events, channel mentions and people all arrive there. A desk schedules work and opens ticket sessions rather than doing the work itself. The server opens a desk for any employee that has none: one added to `org_chart.yaml` by hand, or one whose Session was deleted.
-An employee's company skills are kept current by the server: every reconcile pass compares the `agent-company` and `agent-development` each employee carries against the plugin library and reinstalls the whole plugin wherever it has fallen behind, so a skill added to the library reaches employees already at work without anyone updating each Agent by hand. Nothing is written while the versions match, and an update that fails is recorded as an error without disturbing the rest of the pass. Hiring is unchanged: a new employee installs the current version to begin with.
+### Tickets
-People and employees are named the same way everywhere: `user:<user_id>` and `agent:<agent_id>`; `@all` is every member of the channel it is written in, `system` is the scheduler.
+A ticket file has YAML frontmatter (`title`, `status`, `owner`, `parent`, `notify`, `priority`, `due`, `blocked`, `blocked_by`, `sessions`, `history`), followed by four sections: `## Goal`, `## Acceptance criteria`, `## Progress` and `## Result`. The column directory the file is in is its status. The slug in the file name is lowercase English words joined by hyphens.
+
+### The shared workspace
+
+The root of `workspace/` holds the shared inputs and is nobody's desk. The CEO works in `ceo/`, and a new hire gets a sub-directory named after its agent id unless the CEO assigns another. The server creates a relative sub-directory when it is assigned; an absolute path must already exist.
+
+### The handbook
+
+The handbook loads progressively. Every trigger points at `handbook/README.md`, the index every work run reads first. The index describes the layout, the protocols and the role conventions, and lists every other document with one line saying when it matters, so a run reads a document only when that line applies.
+
+Board decisions go in `handbook/decisions/<yyyy-mm-dd>-<slug>.md`, with conventions and how-tos next to them. The **Handbook** page browses, edits and creates documents, and `penguin org handbook list | show | write | rm` does the same from a Session. The index cannot be deleted.
+
+### The board
+
+People are never employees: the org chart holds only agents. Project members act as the board. They are in the all-hands channel, can join and read every channel, can own tickets, and can be mentioned.
+
+People and employees are named the same way everywhere: `user:<user_id>` and `agent:<agent_id>`. `@all` means every member of the channel it is written in, and `system` is the scheduler.
## How work flows
-1. **A trigger reaches a desk.** A calendar event fires, someone mentions the employee in a channel it is in, or a person talks to the desk directly — that is the whole list. The server sends the desk session one message that starts with an `[org_trigger]` block — the organization, the employee, the kind of trigger and the employee's spend against its budget — followed by the content. The Web App folds the block into a one-line banner; the Trace keeps it verbatim. **A ticket change never starts a run**: an owner assigned, a ticket blocked, a blocker closed, done, rejected are recorded and listed in the body of that employee's next calendar sweep, under `## Since your last sweep`, one line per change with the ticket, its title, what happened and the reason or blocker it carries.
-2. **The desk schedules.** Following the `company-employee` skill it reads the handbook, looks at the board, and opens a **ticket session** for each ticket it should push (`penguin org ticket start <id>`), a separate ordinary session of the same Agent in the desk's workspace. The desk never edits a ticket's files itself: the moment it would, it starts the session and lets that session do it. **A ticket's sessions are started by its owner's desk, or by a person** — an employee asking for anyone else's ticket gets `403 not_ticket_owner`. Work moves between employees by reassigning the ticket (`penguin org ticket assign <id> --owner agent:<employee>`), which the new owner's desk picks up in its next sweep; a colleague is pulled onto a ticket the other way round, its owner starting a session with `--agent-id <colleague>`. Several sessions, from several employees, may contribute to one ticket; each is recorded in the ticket's `sessions` list.
-3. **The ticket session works and writes back.** It opens with where it stands — its workspace, the rule that every reference and deliverable is named by its full path, and the ticket as filed. Before it ends it appends progress (`penguin org ticket progress`) — a plain sentence saying what was done and where, with no ids and no names, because the server writes the `history` entry that records who and when — and moves the ticket (`penguin org ticket move`). A write that claims work — a progress line, an edit of the body, a move into review — books that session as one of the ticket's contributing sessions, so its cost is split onto the ticket; accepting, closing, blocking and unblocking book nothing. Stuck — waiting for a decision, another ticket, a missing key — it blocks the ticket with a reason and who can unblock it (`penguin org ticket block`) and stops; blocked tickets are skipped by every sweep until unblocked.
-4. **Closing notifies.** A ticket reaching done or rejected notifies its `notify` list, and its owner when an employee owns it: each hears about it in its own next sweep's list. **Ticket changes are never posted in a channel** — a channel holds what people and employees say to each other, and a board that narrates itself buries the conversation. You read closures on the board and in the overview's inbox, which lists the tickets closed this period. A ticket that was waiting on it tells its owner the blocker closed.
-5. **People decide in the channels and on the board.** The CEO never takes an important decision alone: hiring plans, budgets, rejecting someone else's ticket, anything that reaches outside the organization — it posts a proposal in the all-hands channel mentioning you, and waits for your answer before acting. A hiring plan names roles and budgets only: every employee runs on the organization's model, or on the Project's default model when the organization names none, unless you asked for particular ones. The same gate binds every employee for whatever touches your machine or the world outside the organization — a long training or evaluation run, a large build or download, a process that outlives the run, spending money, writing outside the shared workspace, deleting what it did not create, a credential it lacks: it asks you in the all-hands channel with what it wants to run, for how long, on what and how to stop it, blocks its ticket on you (the overview lists the ticket as waiting on you) and ends its run; only a clear yes starts it. Only `@<employee>` and `@all` deliver a message to a desk, and only inside that channel's membership: the trigger names the channel it came from, and the employee answers there. A message that names someone the channel does not hold is refused rather than half-delivered, and a message that reaches the mention-chain limit is recorded but delivers nothing, so two employees cannot ping-pong forever. Accepting, rejecting and reviewing tickets is yours or the CEO's, as the handbook says.
+1. **A trigger reaches a desk.** There are exactly three triggers: a calendar event fires, someone mentions the employee in a channel it belongs to, or a person talks to the desk directly. The server sends the desk session one message that starts with an `[org_trigger]` block, which names the organization, the employee, the kind of trigger and the employee's spend against its budget, followed by the content. The Web App folds the block into a one-line banner; the Trace keeps it verbatim.
+
+ **A ticket change never starts a run.** An owner assigned, a ticket blocked, a blocker closed, a ticket done or rejected: each change is recorded and listed in the employee's next calendar sweep, under `## Since your last sweep`, one line per change with the ticket, its title, what happened, and the reason or blocker it carries.
-Budgets are monthly caps per employee for its own sessions plus every subordinate's — the CEO's budget is the whole company. At 80% a system line appears in the all-hands channel; at 100% that employee's calendar (and its subordinates') is paused until the next month or a raised budget. Mentions and direct conversations keep working, so you can always tell a paused employee what to do.
+2. **The desk schedules.** Following the `company-employee` Skill, the desk reads the handbook, looks at the board, and opens a **ticket session** for each ticket it should push (`penguin org ticket start <id>`). A ticket session is a separate, ordinary Session of the same agent in the desk's Workspace. The desk never edits a ticket's files itself; when it would, it starts a ticket session and lets that session do it.
+
+ **A ticket's sessions are started by its owner's desk, or by a person.** An employee that starts a session on someone else's ticket gets `403 not_ticket_owner`. To hand work to another employee, reassign the ticket (`penguin org ticket assign <id> --owner agent:<employee>`); the new owner's desk picks it up at its next sweep. To pull a colleague onto a ticket, the owner starts a session with `--agent-id <colleague>`. Several sessions, from several employees, can contribute to one ticket, and each is recorded in the ticket's `sessions` list.
+
+3. **The ticket session works and writes back.** It opens with its situation: its Workspace, the rule that every reference and deliverable is named by its full path, and the ticket as filed. Before it ends, it appends progress (`penguin org ticket progress`) in a plain sentence saying what was done and where, with no ids and no names, because the server records who and when in `history`. Then it moves the ticket (`penguin org ticket move`).
+
+ A write that claims work (a progress line, an edit of the body, a move into review) books that session as one of the ticket's contributing sessions, so its cost is split onto the ticket. Accepting, closing, blocking and unblocking book nothing. When the session is stuck, waiting for a decision, another ticket or a missing key, it blocks the ticket with a reason and who can unblock it (`penguin org ticket block`) and stops. Every sweep skips a blocked ticket until it is unblocked.
+
+4. **Closing a ticket notifies.** When a ticket reaches done or rejected, its `notify` list hears about it, and so does its owner if an employee owns it, each in its own next sweep. A ticket that was waiting on the closed one tells its owner that the blocker closed. **Ticket changes are never posted in a channel**: channels hold what people and employees say to each other, and a board narrating itself would bury the conversation. You see closed tickets on the board, and in the overview's **Inbox**, which lists the tickets closed this period.
+
+5. **People decide in the channels and on the board.** The Skills and the handbook tell the CEO not to take an important decision alone, such as a hiring plan, a budget, rejecting someone else's ticket, or anything that reaches outside the organization. It posts a proposal in the all-hands channel mentioning you, and waits for your answer before acting. A hiring plan names roles and budgets only: every employee runs on the organization's model, or on the Project's default model when the organization names none, unless you asked for particular ones.
+
+ The same gate binds every employee before heavy or irreversible work: long compute, spending money, writing outside the shared workspace, deleting what it did not create, a process that outlives the run, or a credential it lacks. It asks you in the all-hands channel with what it wants to run, for how long, on what and how to stop it, blocks its ticket on you and ends its run. The overview lists that ticket as waiting on you, and only a clear yes starts the work.
+
+ Accepting, rejecting and reviewing tickets is yours or the CEO's, as the handbook says. These are instructions to the agents, not checks the server makes; see [What the server enforces](#what-the-server-enforces).
## Channels
-Talk is partitioned like the workspace. Every organization is created with one **all-hands channel**, `default_channel`, that every employee and every Project member is in implicitly — it is where proposals, budget alerts, hires and milestones go, and where the board reads. Anyone else may open a channel per stream or per big ticket, so a thread does not drown the all-hands one.
+Talk is partitioned like the Workspace. Every organization is created with one **all-hands channel**, `default_channel`. Every employee and every Project member is in it implicitly. Proposals, budget alerts, hires and milestones go there, and it is where the board reads. Anyone can open further channels for a stream of work or a big ticket, so that one thread does not drown the all-hands channel.
+
+- **Create**: any person or employee can create a channel, with `penguin org channel create ch_<id>` or the **+** (**New channel**) beside the channel list. A new channel holds only its creator. Its id follows the organization id rules, with `ch_` by convention; `default_channel` is reserved.
+- **Join**: an employee enters a channel only when a member invites it. A person can join any channel and read every channel, since the board sees everything. Only members can post.
+- **Mentions**: `@agent:<id>` wakes that employee's desk only if the employee is a member of the channel, and `@all` means the channel's members minus the sender. The trigger names the channel it came from, and the employee answers there. A message that mentions a non-member is refused (`mention_not_member`) rather than written and silently not delivered.
+- **Chain limit**: a message that reaches the organization's mention chain limit is recorded but delivers nothing, so two employees cannot mention each other back and forth forever. A person's message starts a fresh chain.
+- **Lifecycle**: any member can rename a channel or change its purpose. People archive and unarchive channels; an archived channel is read-only and folded away. The all-hands channel cannot be archived or left, and its membership cannot be edited: everyone is in it by definition, and the Web App always shows it as **All hands**.
-- **Creating**: any person or employee may (`penguin org channel create ch_<id>`, or the **+** beside the channel list in the App). A new channel holds only its creator; the id follows the same rule as an organization id — `ch_` by convention — and `default_channel` is reserved.
-- **Getting in**: an employee reaches a channel only when a member invites it. A person may join any channel and read every channel — the board sees everything. Only members post.
-- **Delivery**: `@agent:<id>` wakes that employee's desk only inside the channel's membership, and `@all` is that channel's members minus the sender. A message naming a non-member is refused (`mention_not_member`) rather than written and silently undelivered.
-- **Lifecycle**: any member renames a channel or changes its purpose; people archive and unarchive it, which makes it read-only and folds it away. The all-hands channel cannot be archived, left, or have its membership edited — everyone is in it by definition, and only its rendered label ("All hands") is ever shown.
+The `system` lines in a channel (hires and departures; a channel created, joined, left or archived; budget warnings and pauses) appear in the reader's language and with display names, both in the Web App and in `penguin org channel tail`. Message bodies render as Markdown in the Web App.
-The `system` lines a channel carries — hires and departures, a channel created, joined, left or archived, budget warnings and pauses, a ticket blocked, done or rejected — record a structured notice beside their English text, so the App and `penguin org channel tail` render them in the reader's language and with display names. Message bodies render as Markdown in the App.
+Unread counts and each person's read position are kept per channel. Keeping the channel membership of new hires and departing employees straight is HR's job.
-Unread counts and each person's read cursor are per channel, and a hire's or a leaver's channel membership is HR's to keep straight.
+People get no push notifications. A mention of you shows up in the unread counts, the **@me** filter and the overview's **Inbox**. The one exception is a mirror twin bound to a chat bot; see [Mirror organizations](#mirror-organizations).
-## The example: a plugin marketplace
+## Budgets
+
+A budget is a monthly cap in USD, set per employee. It counts the employee's own Sessions plus those of every subordinate, so the CEO's budget is the cap for the whole company. A period is a calendar month in the organization's timezone.
+
+| Spend reaches | What happens |
+| --- | --- |
+| 80% of a budget | A system line is posted in the all-hands channel. |
+| 100% of a budget | Another system line is posted, and the calendar of that employee and all of its subordinates pauses until the next month, or until the budget is raised or cleared. |
+
+A budget pause is narrower than it may sound:
+
+- Only calendar events stop. Mentions and direct conversations still reach the employee, so you can always tell a paused employee what to do.
+- Calendar events that come due during the pause are skipped, not replayed later.
+- Sessions that are already running are not stopped.
+- Spend is checked on each scheduler pass, not on every request, so spend can go past the cap before the pause takes effect.
+
+After you raise or clear a budget, the next check lifts the pause. There are no Token budgets and no per-ticket budgets; ticket cost is only reported.
+
+Budgets are stored in `org_chart.yaml`. Set them in the create dialog (**CEO budget**) or with `--ceo-budget`, with `penguin org hire --budget` or `penguin org employee set --budget`, or from the **Org Chart** and **Finance** pages. The 80% and 100% thresholds are `budget_warn_ratio` and `budget_pause_ratio` in `org_config.toml`; the Web App has no field for them.
+
+## What the server enforces
+
+Much of how a company behaves is guidance: instructions in the `agent-company` Skills, the handbook and the CEO's initialization prompt. The server enforces only part of it.
+
+The server enforces these rules:
+
+- Only the owner's desk, or a person, starts a ticket's sessions (`403 not_ticket_owner`).
+- An employee joins a channel only by invitation.
+- Only people archive channels.
+- A message that mentions a non-member is refused (`mention_not_member`).
+- Mentions stop at the mention chain limit (`mention_chain_limit`, 3 by default).
+- A budget at 100% pauses the calendar.
+
+These are guidance only, followed by the agents but not checked by the server:
+
+- The CEO proposes and waits for the board's answer before it acts on its reading of the mission, a hiring plan, setting or raising a budget, rejecting someone else's ticket or closing a P0 or P1 ticket without review, anything that reaches outside the organization (publishing, accounts, mail, money), or a change to the handbook's rules or the organization's structure.
+- Every employee asks the board before heavy or irreversible work, blocks its ticket on the person it asked, and ends its run.
+- Who accepts, rejects and reviews tickets.
+- Escalating to a manager.
+- Writing in the organization's working language.
+- Which twin a mirror organization relays a question to.
+
+Hiring, changing an employee's budget, pausing the organization and moving tickets have no role check and no people-only check: an employee can do each of them from its own Session. The reporting tree itself drives only a few things in code: budget roll-up, a pause cascading to subordinates, block notices to the manager, and re-parenting when someone leaves.
+
+### Tool approvals
+
+Tool calls in desk and ticket sessions follow the organization's **Approval mode**, set in the organization settings: **Allow all** by default, or **Read only** or **Deny all**. There is no `always-ask` mode, because unattended runs never stop to ask a person.
+
+## Example: a plugin marketplace
The mission *"Build a DeepSeek Harness plugin marketplace, promote it on social media and SEO into the top three results, and earn from paid featured slots on the home page"* plays out like this:
-1. You create the organization from the switcher; the CEO's desk opens with an initialization run that posts one proposal in the all-hands channel — its reading of the mission, the first tickets, the roles it wants with budgets — and waits for your answer.
-2. You confirm; the CEO hires HR and finance, then a developer and a marketer, creates `workspace/site` and `workspace/marketing`, assigns them, opens a `ch_site` channel and a `ch_marketing` channel and invites each stream's owner into its own, and schedules everyone at their own hour (daily for the builders, every three days for HR, weekly for finance).
-3. It files a parent ticket for the marketplace and children per stream: build the site, SEO to the top three, the social launch, paid featured slots. Nothing wakes the owners: each hears about its assignment in its next sweep.
-4. The next sweep opens a ticket session for the site in `workspace/site`; the marketer blocks SEO on it ("nothing to index until the site is live") and says so in the `ch_marketing` channel, where the site's own back-and-forth never lands.
-5. The site session builds, writes progress, moves the ticket to review; the CEO reviews it to done. The developer's next sweep says so, the marketer's says its blocker closed, and it verifies and unblocks SEO.
-6. Marketing works SEO and the launch from one session attached to both tickets; finance rolls the spend up per employee and per ticket — the shared session is split between the tickets it serves, the parent sums its children.
-7. Paid featured slots ship and the CEO reports to the board in the all-hands channel, mentioning you.
+1. You create the organization from the switcher. The CEO's desk opens with an initialization run that posts one proposal in the all-hands channel, with its reading of the mission, the first tickets, and the roles it wants with their budgets, and then waits for your answer.
+2. You confirm. The CEO hires HR and finance, then a developer and a marketer. It creates `workspace/site` and `workspace/marketing` and assigns them, opens a `ch_site` channel and a `ch_marketing` channel and invites each stream's owner into its own, and schedules everyone at their own hour: daily for the builders, every three days for HR, weekly for finance.
+3. It files a parent ticket for the marketplace and a child ticket per stream: build the site, SEO into the top three, the social launch, paid featured slots. Nothing wakes the owners; each hears about its assignment in its next sweep.
+4. The next sweep opens a ticket session for the site in `workspace/site`. The marketer blocks the SEO ticket on it ("nothing to index until the site is live") and says so in the `ch_marketing` channel, where the site's own back-and-forth never lands.
+5. The site session builds, writes progress, and moves the ticket to review; the CEO reviews it and moves it to done. The developer's next sweep reports that. The marketer's next sweep reports that its blocker closed, and the marketer verifies and unblocks SEO.
+6. Marketing works on SEO and the launch from one session attached to both tickets. Finance rolls up the spend per employee and per ticket: the shared session is split between the tickets it serves, and the parent ticket sums its children.
+7. Paid featured slots ship, and the CEO reports to the board in the all-hands channel, mentioning you.
The server test `organization-scenario.test.ts` runs exactly this story on the runtime's seams.
-## A research organization
+## Research organizations
+
+The first mission example, **Research Paper Lab**, is a company that runs experiments and writes papers:
-The first mission example is a lab. *"Set up a company that does research for me and produces papers fit for top-tier conferences. Experiments run autoresearch-style: fix the evaluation script and the metric first, edit one file only, give every experiment the same time budget, log each result as one line and keep only the changes that improve the metric. Before any experiment loop starts, the researcher asks me in the channel for resources — the machine and its GPU/CPU, concurrency, total hours, disk and data, paid APIs — then runs unattended inside what I approved and asks again before exceeding it. Papers go through adversarial review between two kinds of employee: reviewers reproduce the results, check baselines and ablations, hunt for test-set leakage and metric gaming, and return a score with required changes; authors revise or rebut point by point until the reviewer accepts."*
+> *"Set up a company that does research for me and produces papers fit for top-tier conferences. Experiments run autoresearch-style: fix the evaluation script and the metric first, edit one file only, give every experiment the same time budget, log each result as one line and keep only the changes that improve the metric. Before any experiment loop starts, the researcher asks me in the channel for resources — the machine and its GPU/CPU, concurrency, total hours, disk and data, paid APIs — then runs unattended inside what I approved and asks again before exceeding it. Papers go through adversarial review between two kinds of employee: reviewers reproduce the results, check baselines and ablations, hunt for test-set leakage and metric gaming, and return a score with required changes; authors revise or rebut point by point until the reviewer accepts."*
-Such a mission keeps the CEO on the standard checklist and puts the researchers and reviewers on the `company-research` skill, which adds three things:
+Such a mission keeps the CEO on the standard checklist and puts the researchers and the reviewers on the `company-research` Skill, which adds three rules to the employee protocol:
-- **The resource envelope comes first.** Before the first experiment of a ticket, its owner asks you in the all-hands channel for the envelope — which machine and GPU/CPU, how many runs at once, total hours or experiments, disk and data, paid APIs or keys — with the estimated load and the way to stop the loop, blocks the ticket on you and ends its run. Inside an approved envelope the loop runs unattended; exceeding it, or needing something new (a dataset, a key, a second GPU), is a new ask. An employee asks for what it lacks instead of working around it.
-- **The loop is autoresearch's.** One evaluation harness and one metric, frozen before the loop and never edited during it; one editable surface; the same wall-clock budget for every experiment; a branch per run; one line per experiment in `results.tsv` (commit, metric, memory, keep / discard / crash, a description); the commit kept only when the metric improves and reset otherwise; a run past twice its budget killed and counted as a crash; crashes diagnosed from the log tail.
-- **Authors and reviewers are different employees.** The CEO hires at least one dedicated reviewer. A claim goes to `review`; the reviewer tries to break it — reproduces the key numbers from the kept commit, checks baselines and ablations, looks for test-set leakage and metric gaming, weighs the claims against the evidence and the novelty against prior work — and writes a scored review with required changes. The author revises or rebuts point by point; the ticket travels between `in_progress` and `review` until the reviewer accepts, and a research ticket is never closed without that accept in its history. After three rounds without acceptance the reviewer blocks the ticket on the CEO, who decides or brings it to you.
+- **The resource envelope comes first.** Before a ticket's first experiment, its owner asks you in the all-hands channel for the envelope: which machine and GPU or CPU, how many runs at once, total hours or experiments, disk and data, paid APIs or keys, together with the estimated load and the way to stop the loop. It then blocks the ticket on you and ends its run. Inside an approved envelope the loop runs unattended. Exceeding it, or needing something new such as a dataset, a key or a second GPU, is a new request; an employee asks for what it lacks instead of working around it.
+- **The loop is autoresearch's.** One evaluation harness and one metric, frozen before the loop and never edited during it. One editable surface, the same wall-clock budget for every experiment, and a branch per run. Each experiment is one line in `results.tsv` (commit, metric, memory, keep / discard / crash, a description), and the commit is kept only when the metric improves and reset otherwise. A run past twice its budget is killed and counted as a crash, and crashes are diagnosed from the log tail.
+- **Authors and reviewers are different employees.** The CEO hires at least one dedicated reviewer. A claim goes to `review` and the reviewer tries to break it: reproducing the key numbers from the kept commit, checking baselines and ablations, looking for test-set leakage and metric gaming, and weighing the claims against the evidence and the novelty against prior work. It writes a scored review with the changes it requires, and the author revises or rebuts point by point. The ticket travels between `in_progress` and `review` until the reviewer accepts, and a research ticket is never closed without that acceptance in its `history`. After three rounds without one, the reviewer blocks the ticket on the CEO, who decides or brings it to you.
-## A mirror organization
+Like the rest of the protocol, this is Skill and handbook guidance rather than something the server checks.
-The fourth mission example is a company with no work of its own. *"Set up a company that mirrors our real company: I will give the CEO our real org chart and the CEO creates one digital twin per real employee; each twin's desk session is bound to that colleague's Feishu bot. A twin only receives its own colleague's messages by default, answers what it can on its own and relays the rest to the relevant colleague's twin, who passes it on to the real person. The CEO hires nobody on its own, schedules nothing and files no tickets; the company only relays and solves what it can."*
+## Mirror organizations
-Such a mission puts the CEO on the `company-mirror` skill instead of the standard checklist, and the company it builds is shaped differently:
+The fourth mission example, **Digital-twin company**, is a company with no work of its own:
-- **The roster comes from outside.** The CEO's initialization run asks the board for the real org chart — every person's name, title, reporting line and which bot will be theirs — and ends there. Once the board answers and confirms the roster, the CEO hires one twin per person, `--reports-to` mirroring the real line, and writes each twin's brief.
-- **Nothing recurring drives it.** No calendar events, no tickets, no per-stream channels. A twin runs when its own human writes to it through the bound bot, or when another twin `@`-mentions it.
-- **The binding is the setup's last step.** Each twin's desk session has to be bound to that colleague's bot — open the desk session and use its Remote control panel, or take the session id from `penguin org desk show <agent_id>`. An unbound twin can neither hear its human nor answer them.
-- **Relay, then write it down.** A twin answers from the handbook when it can and otherwise relays the question to the right colleague's twin, which asks its own human and passes the answer back. Everything that comes back is written into the handbook (`people/<name>.md`, `faq.md`), so the same question is answered alone next time. Relays spend the mention chain, but a person's message (through the bot or the chat page) starts a fresh one, so a question out and an answer back always fit the default `mention_chain_limit`; only twins talking among themselves run into it.
+> *"Set up a company that mirrors our real company: I will give the CEO our real org chart and the CEO creates one digital twin per real employee; each twin's desk session is bound to that colleague's Feishu bot. A twin only receives its own colleague's messages by default, answers what it can on its own and relays the rest to the relevant colleague's twin, who passes it on to the real person. The CEO hires nobody on its own, schedules nothing and files no tickets; the company only relays and solves what it can."*
+
+Such a mission puts the CEO on the `company-mirror` Skill instead of the standard checklist, and the company it builds is shaped differently:
+
+- **The roster comes from you.** The CEO's initialization run asks the board for the real org chart: each person's name, title, reporting line, and which bot will be theirs. When you answer, the CEO proposes a roster. Only after you confirm it does the CEO hire one twin per person, with `--reports-to` mirroring the real reporting line, and write each twin's brief. Nothing imports a directory or an HR system.
+- **Nothing recurring drives it.** There are no calendar events, no tickets and no per-stream channels. A twin runs only when its own person writes to it through the bound bot, or when another twin mentions it.
+- **Binding is the last setup step, and a person does it.** Bind each twin's desk session to that colleague's bot in the desk session's **Remote control** panel (Feishu, Telegram, QQ or WeChat; see [Remote control](/remote-control)). `penguin org desk show <agent_id>` prints the desk session id. An unbound twin can neither hear its person nor answer them.
+- **Relay, then write it down.** A twin answers from the handbook when it can. Otherwise it relays the question to the right colleague's twin, which asks its own person and passes the answer back. Everything that comes back is written into the handbook (`people/<name>.md`, `faq.md`), so the next time the same question is answered without a relay.
+
+Know the limits before you rely on a mirror organization:
+
+- One bot account can be enabled on only one Session at a time (`409 account_enabled_elsewhere`), so each twin needs its own bot.
+- A bot delivers replies only after its person has written to it once.
+- Relays go through the all-hands channel, which every employee and board member reads, so a relay is never private.
+- Choosing which twin to ask is the model's judgment, based on its brief and the handbook; there is no routing engine.
+- Relays use up the mention chain, but a person's message, through the bot or the chat page, starts a fresh chain. One question out and one answer back fit within the default `mention_chain_limit`; a relay that goes on to a third twin and back does not.
## Commands
-Inside a desk or ticket session the `penguin org` commands already know the organization, Project, Agent and session from the environment (`PENGUIN_ORG_ID` joins the other control variables). From a shell, pass `--org-id`. See [the CLI reference](/cli#penguin-org) for every subcommand; the essentials:
+Inside a desk or ticket session, the `penguin org` commands already know the organization, Project, agent and Session from the environment (`PENGUIN_ORG_ID` joins the other control variables). From a shell, pass `--org-id`. The essentials are below; see [the CLI reference](/cli#penguin-org) for every subcommand.
```text
penguin org show # employees, board counts, spend vs budget
@@ -125,18 +260,46 @@ penguin org channel send -m "@<employee> …" [--channel <id>] # default: defa
penguin org finance # spend per employee (cumulative) and per ticket
```
-## The pages
+## Organization pages
+
+In company mode, the sidebar lists the organization's pages: **Overview**, **Org Chart**, **Calendar**, **Tickets**, **Finance** and **Handbook**.
+
+- **Overview** is where an organization opens. It shows the mission folded to one line, this period's spend against the CEO's budget, and a KPI strip, followed by three full-width sections: the **Inbox** (all-hands messages that mention you or `@all`, every blocked ticket whoever it waits on, and the tickets closed this period), today's calendar, and the budget alerts. No card is a link; each has one corner button that names the page it summarizes.
+- **Org Chart** shows the reporting tree. Each employee's menu offers **Hire a subordinate**, **Set budget**, **Change reporting line**, **New desk session** and **Leave the organization**.
+- **Handbook** shows the knowledge base as an explorer tree beside the rendered document. At every level, folders come before documents; folders stay collapsed until opened, and the arrow keys move through the tree.
+- **Finance** shows the period in three rows: the KPI panel beside the daily trend, then the spend tree and the ticket table side by side, then the period's warnings and pauses.
+- **Calendar** and **Tickets** each show a single create button while they are empty, under a hint you can dismiss for good.
+
+The organization settings include **Working language**, **Approval mode** and **Pause organization**.
+
+## Switches and lifecycle
+
+| Switch | Where | Effect |
+| --- | --- | --- |
+| Server | **System settings** › Server › **Company mode** (admins only; off by default) | Off stops the organization scheduler: nothing fires, and nothing is backfilled when it is turned back on. Every organization route answers 404, and the mode switch disappears for everyone. |
+| Personal | **System settings** › Personal › **General** › **Company mode** (shown only while the server switch is on) | Hides the mode switch for you only. Organizations keep running. |
+| Organization | **Pause organization** in the organization settings | Stops all of the organization's automatic triggers. People can still open any desk and talk to it. |
+
+**There is no delete.** An organization is either running or paused, and that is its whole lifecycle. Deleting one would throw away the only way back to its conversations, employees, desks and tickets, while a paused organization costs nothing to keep: it fires nothing, and every desk is still there to talk to.
+
+The only way to remove an organization is to delete its directory by hand. The runtime stops seeing it on its next pass, and the Web App says so and offers to create another in its place. Employees are ordinary agents, and their desk and ticket sessions are ordinary Sessions, so both survive. The Sessions keep the mark that says they belonged to the organization, so they never reappear in development mode's session list.
+
+## How it works
+
+### Files are the source of truth
+
+Everything the company is lives in files under the Project directory. SQLite keeps caches that are rebuilt from those files on every pass, plus each person's read position in each channel, the same rule development mode follows for Agent State and Traces. Delete the caches and nothing changes; edit a file by hand and the next pass picks it up.
+
+The organization scheduler runs a pass every 30 seconds, and immediately after every write through the API. It runs only while the server is up, and it never backfills events it missed.
-An organization opens on its **overview**: the mission folded to one line, this period's spend against the CEO's budget, a KPI strip, and then three full-width runs — the inbox (the all-hands messages that name you or `@all`, every blocked ticket whoever it waits on, and the tickets closed this period), today's timeline, and the budget alerts. No card is a link; each carries one corner button naming the page it summarizes.
+### Session marks
-The **handbook** page lists the knowledge base as an explorer tree — folders before documents at every level, collapsed until opened, walked with the arrow keys — beside the rendered document. **Finance** reads the period in three rows: the KPI panel beside the daily trend, then the spend tree and the ticket table side by side, then the period's warnings and pauses. The **calendar** and the **board** each keep one create button while they are empty, under a hint that can be dismissed for good.
+A desk or ticket session is marked as the organization's on the Session row itself when it is opened. It is therefore listed in company mode and never in development mode's session list, even after the organization's directory is removed by hand or the server switch is turned off, when nothing else could tell whose it was. Organizations that already existed get their Sessions marked on the runtime's next pass over their files.
-## Switches
+### Skill updates
-- **Server**: the admin's company-mode switch, off by default — a fresh server enables it under System settings › Server › Company mode. Off stops the organization scheduler (nothing fires, nothing is backfilled when it is turned on again), every organization route answers 404, and the mode switch disappears for everyone.
-- **Personal**: hides the mode switch for you only; the organizations keep running.
-- **Organization**: pausing an organization stops all of its automatic triggers; people can still open any desk and talk.
+The server keeps each employee's company Skills current. On every pass it compares the `agent-company` and `agent-development` plugins each employee carries with the plugin library, and reinstalls the whole plugin wherever an employee has fallen behind. A Skill added to the library therefore reaches employees already at work, without anyone updating each agent by hand. Nothing is written while the versions match, and a failed update is recorded as an error without disturbing the rest of the pass. A new hire installs the current version to begin with.
-**There is no delete.** An organization is turned on or off, and that is its whole lifecycle. Deleting one would throw away the only way back to its conversations, employees, desks and tickets, while a paused organization costs nothing to keep — it fires nothing, and every desk is still there to talk to.
+### Structured system lines
-Removing the organization's directory by hand is the only way one goes away. The runtime stops seeing it on its next pass, and the App says so and offers to create another in its place. Employees are ordinary Agents and their desk and ticket sessions are ordinary sessions: both survive, and the sessions keep the mark that says they were the organization's, so they never reappear in development mode's list.
+The `system` lines a channel carries store a structured notice beside their English text. That is what lets the Web App and `penguin org channel tail` show them in the reader's language and with display names.
diff --git a/packages/docs/content/company-mode.zh.md b/packages/docs/content/company-mode.zh.md
index 8697cb53..3173cd6e 100644
--- a/packages/docs/content/company-mode.zh.md
+++ b/packages/docs/content/company-mode.zh.md
@@ -1,142 +1,305 @@
---
title: 公司模式
-description: 把一句话使命变成一家由 Agent 组成的公司——CEO 负责招募,日程驱动每个工位,工单承载工作,频道里只有 @ 才会打扰谁,预算在失控前暂停支出。
+description: 把一句话的使命变成一个由 Agent 组成的组织:它靠日历、看板和频道运转,你来当它的董事会。
---
-## 是什么
+开发模式是一个人和一个 Agent 对话。公司模式是 Web App 的第二种工作模式,它把一个 Project 里的 Agent 组织成一家能自主运转数周的**公司**:日历驱动它,看板承载工作,员工在频道里交流。你用一句话给出使命,然后坐进董事会,只对必须由人拍板的事做决定。
-**公司模式目前是内测功能**:可能有不稳定的现象,遇到问题请反馈。
+> [!WARNING]
+> 公司模式是内测功能,可能有不稳定的现象,遇到问题请反馈。
-开发模式是一个人和一个 Agent 对话。公司模式是 Web App 的第二种工作模式:把一个 Project 内的 Agent 组织成一家**公司**,由日程驱动、以工单承载工作、在频道里沟通,自主运转数周;你只做董事会,只在需要人拍板的地方出手。你用一句话给出使命,系统只生成 CEO;CEO 招募人事、财务和使命需要的角色,划分公共工作区,为大家安排日程,开出首批工单。
+- 要打开公司模式,见[开启公司模式](#开启公司模式)。
+- 要创办一家公司,见[创建组织](#创建组织)。
+- 要了解公司如何运转,见[组织的构成](#组织的构成)、[工作如何流转](#工作如何流转)和[频道](#频道)。
+- 要分清哪些有保证、哪些只是指引,见[预算](#预算)和[服务端强制执行的规则](#服务端强制执行的规则)。
+- 要做实验、写论文,见[科研组织](#科研组织)。
+- 要建一家镜像现实公司的组织,见[镜像组织](#镜像组织)。
-公司的一切都是 Project 目录下的**文件**。SQLite 只存每一轮对账都能从文件重建的缓存,以及每个用户在每个频道里的已读游标——与开发模式对 Agent State 和 Trace 的规则相同。删掉缓存什么也不会变;手工改一个文件,下一轮对账就会生效。
+## 开启公司模式
-在侧栏左上角的「开发 | 公司」控件切换模式。它在管理员总开关打开(系统设置 › 服务器 › 公司模式,**缺省关闭**,需管理员打开)且你没有自己隐藏它(系统设置 › 个人 › 公司模式)时出现。
+**开始之前**
-工位会话与工单会话在打开时就被标记在会话记录本身上,因此它们只列在公司模式里,从不出现在开发模式的会话列表——包括组织目录被手工删除、总开关被关掉之后,那时已经没有别的东西能说明它们属于谁。已经存在的组织,其会话会在运行时下一次扫过它的文件时补上这个标记。
+- 需要管理员账号。公司模式在每台服务器上都默认关闭,只有管理员能看到服务器开关。
-## 怎么创建
+1. 打开**系统设置** › 服务器 › **公司模式**,开启**启用公司模式**。改动会立即保存。
+2. 侧边栏左上角的模式切换显示为**开发** | **公司**,并带有**内测版**标记。选择**公司**。
-三个入口,背后是同一个服务端调用:
+要切回去,选择**开发**。服务器开关开着时,所有用户都能看到模式切换。只想对自己隐藏,就在**系统设置** › 个人 › **通用**里关闭**公司模式**,组织照常运转。见[开关与生命周期](#开关与生命周期)。
-- **Web App**——组织切换器里的「新建组织」:显示名在前,id 字段旁的按钮请服务端据名称推导一个 id(Project 的缺省 Model 提出一个简短的英文 snake_case id,模型给不出时以名称的 ASCII slug 兜底,两条路都命名不了的名称则填入一个带日期的占位 id,并在字段下方说明原因、请你改成有含义的名字——按钮一定会在框里留下一个 id);使命字段下另有四个示例,点一下即填入;
-- **CLI**——`penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>]`;
-- **通用 Agent**——让任何装有 `agent-company` 插件的 Agent 帮你开一家公司,它的 `company-setup` Skill 接手:一次只问一个问题(id、名称、使命、公共工作区、Model、CEO 预算),确认一屏摘要,然后执行上面这条命令。它到此为止——招募、排日程和开工单是 CEO 在董事会答复之后的事。该插件不预装,所以从未进过公司的 Agent 要先装上它——新建 Agent 对话框的「插件」字段,或 Project 里既有 Agent 的技能标签页;CEO 与员工自受雇之日起就带着它。
+## 创建组织
-id 一律是小写 snake_case、2–64 字符、以字母开头,并按约定表明它命名的是什么:组织 id 以 `co_` 开头,频道 id 以 `ch_` 开头(`co_plugin_marketplace`、`ch_site`)。App 的 id 推导与 `company-setup` Skill 都会带上前缀;服务端并不强制,手工输入的 id 按原样接受,约定之前建立的 id 也继续有效。
+组织位于 Project 内的 `<project>/organizations/<org_id>/`,一个 Project 可以有多个组织。创建组织有三种方式,背后调用的都是同一个服务端接口。
-创建会写下组织目录、全员频道与组织手册,以及唯一一名员工:**CEO**,月预算缺省 **100 美元**,除非创建时另行指定(API 的 `ceoBudget`、CLI 的 `--ceo-budget`、对话框里的 CEO 预算字段)。预算按累计线比较,所以这一个数字就是整家公司的上限;它写在 `org_chart.yaml` 里,随时可以在组织图上调高、调低或清除。随后 CEO 的工位随初始化会话打开,在全员频道里发出一份提案,然后停下来等董事会答复。
+### 在 Web App 中创建
-组织还有唯一的**工作语言**。它是 `org_config.toml` 的 `language`,创建时从使命判定——正文里出现任一汉字即 `zh`,否则 `en`——除非创建时指定(`--language`、API 的 `language`、创建对话框里的「工作语言」);之后可在组织设置里修改。组织手册、员工简介(`AGENTS.md`)、CEO 的初始化会话与工位会话标题都用它书写,Skill 也要求每位员工用它写频道消息、工单、文档与汇报;无论哪种语言,命令、id、文件名与字段名都保持 ASCII。该字段出现之前创建的组织没有存这一项,读作它使命本身的语言,因此无需任何迁移。
+1. 在公司模式下,打开组织切换器,选择**新建组织**。
+2. 填写**显示名**。
+3. 在**组织 id** 旁选择**用 AI 生成**,从名称推导出 id;也可以自己填写。
+4. 填写**使命**,或者点字段下方四个示例中的一个自动填入。
+5. 可选:选择**模型**、**公司工作区**和 **CEO 预算**。
+6. 选择**创建**。CEO 的工位会话随即打开。
-## 组成部分
+**用 AI 生成**一定会在输入框里留下一个 id:Project 的默认模型先提议一个简短的英文 snake_case id;模型给不出时,改用名称转写成的 ASCII slug;两者都不行时,字段里会填入一个带日期的占位 id,下方写明原因,并请你改掉。
-| 部分 | 是什么 | 在哪里 |
+### 用 CLI 创建
+
+```text
+penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>]
+```
+
+### 让 Agent 创建
+
+让一个装有 `agent-company` 插件的 Agent 帮你开一家公司,它的 `company-setup` Skill 会接手:一次只问一个问题(id、名称、使命、公共工作区、模型、CEO 预算),汇总成摘要请你确认,然后执行同一条 `penguin org create` 命令。它做到这一步就停下。招募、排日程和开工单是 CEO 的事,要等董事会答复之后才开始。
+
+这个插件不预装,从没进过公司的 Agent 得先装上它:在新建 Agent 对话框的**插件**字段里装,或者在 Project 里已有 Agent 的**技能**标签页里装。CEO 和员工从受雇那天起就带着这个插件。
+
+### id 规则
+
+id 使用小写 snake_case,长 2 到 64 个字符,以字母开头。按惯例,id 还表明它命名的是什么:组织 id 以 `co_` 开头,频道 id 以 `ch_` 开头,比如 `co_plugin_marketplace` 和 `ch_site`。Web App 提议的 id 和 `company-setup` Skill 都会带上前缀。服务端不强制这条惯例,手工输入的 id 按原样接受,惯例出现之前建立的 id 也照常可用。
+
+### 创建时会发生什么
+
+创建组织会写入组织目录、全员频道和手册,并招募唯一一名员工:**CEO**。CEO 的月度预算默认是 **100 美元**,创建时也可以另定(API 里的 `ceoBudget`、CLI 的 `--ceo-budget`、对话框里的 **CEO 预算**)。预算会把所有下属算在内,所以 CEO 的预算就是整家公司的上限。见[预算](#预算)。
+
+随后 CEO 的工位打开,执行一次初始化运行:在全员频道里发出一份提案,然后停下来等董事会答复。
+
+### 工作语言
+
+每个组织只用一种语言工作,即 `org_config.toml` 里的 `language`。创建时根据使命判断:只要使命里出现一个汉字就是 `zh`,否则是 `en`。CLI(`--language`)和 API(`language`)也可以直接指定;之后可以在组织设置的**工作语言**里修改。
+
+手册、员工简报(`AGENTS.md`)、CEO 的初始化运行和工位会话标题都用这种语言书写,Skill 也要求每位员工用它写频道消息、工单、文档和汇报。无论哪种语言,命令、id、文件名和字段名都保持 ASCII。这个字段出现之前创建的组织没有存这一项,按使命本身所用的语言读取,所以不需要迁移。
+
+## 组织的构成
+
+| 组成部分 | 说明 | 存放位置 |
| --- | --- | --- |
-| 组织 | 一家公司:名称、使命、状态、时区、工作语言、审批模式 | `<project>/organizations/<org_id>/org_config.toml` |
-| 员工 | 以 CEO 为根、经汇报线连成一棵树的 Agent——没有部门与岗位;每个条目带头衔、职责、工作区和月度预算 | `org_chart.yaml` |
-| 工位会话 | 每个员工一个常设会话,招募当时就开好:日程项、频道里的提及与人都发到这里;它负责调度、发起工单会话,不亲自做工单。对账扫描会为没有工位的员工补开——手工写进 `org_chart.yaml` 的人,或者会话被删掉的人 | `desks.toml`(服务端写入) |
-| 日程 | 按员工分组的日程项,格式同定时任务、去掉目标字段——唯一的周期性驱动 | `calendar/<agent_id>/<event>.toml` |
-| 工单 | 一个工单一个 Markdown 文件——YAML frontmatter(`title`、`status`、`owner`、`notify`、`priority`、`due`、`blocked`、`sessions`、`history`)加 `## Goal`、`## Acceptance criteria`、`## Progress`、`## Result` 四节;所在列目录即状态,slug 为用连字符连接的小写英文单词 | `tickets/<yyyy-mm>/<列>/<yyyy-mm-dd>-<slug>.md` |
-| 频道 | 一个频道一个目录:一份写有名称、用途与成员的意图文件,加上一行一条消息、按天分的 JSON Lines | `channels/<channel_id>/channel.toml`、`channels/<channel_id>/<yyyy-mm-dd>.jsonl` |
-| 公共工作区 | 公司的工作目录;根目录放共享输入、不是任何人的工位——CEO 在 `ceo/` 里工作,新员工不另行指定就落在以其 Agent id 命名的子目录里;相对子目录在指定时由服务端建好,绝对路径必须已经存在 | `workspace/` |
-| 组织手册 | 公司知识库;根部 `README.md` 是每个工作轮先读的索引,其余文档在索引中列出、按需读取 | `handbook/` |
+| 组织 | 一家公司:名称、使命、状态、时区、工作语言和审批模式 | `<project>/organizations/<org_id>/org_config.toml` |
+| 员工 | 以 CEO 为根、按汇报线连成一棵树的 Agent,没有部门和职位。每条记录有头衔、职责、工作区和月度预算 | `org_chart.yaml` |
+| 工位会话 | 每位员工一个常设会话,它的触发都送到这里 | `desks.toml`(由服务端写入) |
+| 日历 | 按员工存放的日程项,格式同定时任务,但去掉了目标字段。日历是唯一的周期性驱动 | `calendar/<agent_id>/<event>.toml` |
+| 工单 | 每张工单一个 Markdown 文件,所在的列目录就是它的状态 | `tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md` |
+| 频道 | 每个频道一个目录:一份写有名称、用途和成员的意图文件,加上按天分文件、每行一条消息的 JSON Lines | `channels/<channel_id>/channel.toml`、`channels/<channel_id>/<yyyy-mm-dd>.jsonl` |
+| 公共工作区 | 公司的工作目录 | `workspace/` |
+| 手册 | 公司的知识库 | `handbook/` |
+
+### 工位会话
-手册就是渐进加载的落地:每次触发都指向 `handbook/README.md`,索引写明目录布局、协议、职责约定,以及每份文档一行「何时需要读」,工作轮只在那一行说相关时才读对应文档。董事会的决策记在 `handbook/decisions/<yyyy-mm-dd>-<slug>.md`,约定与操作指南放在旁边;Web App 的「手册」页可以浏览、编辑与新建文档,会话里用 `penguin org handbook list | show | write | rm` 做同样的事。索引不可删除。
+员工一受雇就有一个常设的工位会话。日程项、频道里的提及和真人的消息都送到这里。工位负责调度,开工单会话去干活,自己不动手。服务端会为没有工位的员工补开一个,比如手工写进 `org_chart.yaml` 的员工,或者工位会话已删除的员工。
-员工装着的公司 Skill 由服务端保持在当前版本:每一轮对账都会把每位员工的 `agent-company` 与 `agent-development` 与插件库比对,落后的整包重装——插件库里新增的 Skill 因此也会落到早已在岗的员工身上,不必逐个 Agent 手工更新。版本一致时不写任何文件;某位员工更新失败只记一条错误,不影响该轮的其余工作。招募时不变:新员工装的本来就是当前版本。
+### 工单
-人和员工在所有结构化字段里都用同一种记号:`user:<user_id>` 与 `agent:<agent_id>`;`@all` 表示它所在频道的全体成员,`system` 是调度器。
+工单文件先是 YAML frontmatter(`title`、`status`、`owner`、`parent`、`notify`、`priority`、`due`、`blocked`、`blocked_by`、`sessions`、`history`),后面是四节:`## Goal`、`## Acceptance criteria`、`## Progress` 和 `## Result`。文件所在的列目录就是它的状态。文件名里的 slug 是用连字符连接的小写英文单词。
-## 工作怎么流转
+### 公共工作区
-1. **触发到达工位。** 日程项到期、有人在它所在的频道里 @ 了这位员工、或有人直接同工位说话——就这三种。服务端向工位会话发送一条以 `[org_trigger]` 块开头的消息——组织、员工、触发种类、该员工的支出与预算——后面跟着触发内容。Web App 把块折叠成一行提示,Trace 原样保留。**工单的变化从不启动一轮运行**:指派负责人、标记阻塞、阻塞解除、完成、拒绝,都只被记录下来,列在该员工下一次日历巡检正文的 `## Since your last sweep` 一节里——一条变化一行,写明工单、标题、发生了什么,以及工单自身带的理由或阻塞方。
-2. **工位负责调度。** 员工按 `company-employee` Skill 先读手册,再看看板,为该推进的工单各发起一个**工单会话**(`penguin org ticket start <id>`)——同一 Agent 在工位工作区里的另一个普通会话。工位自己绝不动工单的文件:一旦要动,就发起工单会话交给它做。**一张工单的会话只能由它的负责人的工位、或由人发起**——员工对别人的工单发起会话会得到 `403 not_ticket_owner`。要把活交给别的员工,就改派负责人(`penguin org ticket assign <id> --owner agent:<员工>`),新负责人的工位在下一次巡检时接手;反过来,要拉同事来帮自己的工单,则由负责人用 `--agent-id <同事>` 发起会话。一个工单可以由多个会话、多名员工共同贡献,每个会话都记录在工单的 `sessions` 列表里。
-3. **工单会话做事并回写。** 它以自己的处境开场——工作区、「一切引用与交付物都写完整路径」的规则,以及工单原文。结束前追加进展(`penguin org ticket progress`)——一句大白话,写清做了什么、东西在哪,不写 id 也不写人名,因为谁写的、什么时候写的由服务端记进 `history`——并移列(`penguin org ticket move`)。声称做了活的写入——一条进展、正文编辑、移入审核中——会把该会话记为这张工单的贡献会话,其成本因此摊到工单上;接受、关闭、阻塞与解除阻塞都不记。卡住了——等人拍板、等另一个工单、缺 key——就给工单标记阻塞、写明原因与等谁解开(`penguin org ticket block`),然后停手;被阻塞的工单会被每一次巡检跳过,直到解除。
-4. **结束即通知。** 工单进入已完成或已拒绝时通知它的 `notify` 名单,负责人是员工时也通知负责人:各自在自己下一次巡检的清单里看到。**工单的变化从不发到频道里**——频道装的是人和员工彼此说的话,一块自己讲述自己的看板只会把对话淹掉。完成的事,你在看板上看,也在组织概览的 inbox 里看(它列出本周期内关闭的工单)。等着它的工单会告诉负责人「阻塞已解除」。
-5. **人在频道与看板上拍板。** CEO 不会擅自做重大决定:招募计划、预算、拒绝他人的工单、任何触及组织之外的动作,都先在全员频道里 @ 你提案,等你答复后才执行。招募计划只写角色与预算:除非你指定了特定的 Model,每名员工都用组织的 Model,组织未指定时用 Project 的默认 Model。同一道关卡对每名员工都成立——凡是动到你的机器或组织之外的事:长时间的训练或评测、大型构建或下载、会在本轮之后继续运行的进程、花钱、公共工作区之外的写入、删除不是它创建的数据、缺少的凭据——它都会先在全员频道里向你请示:要跑什么、多久、用什么资源、怎么停,把工单阻塞在你身上(概览里会列出等你处理的工单),然后结束本轮;只有明确的同意才会开始。只有 `@<员工>` 和 `@all` 会把消息投递到工位,且只在该频道的成员范围内生效:触发块写明消息来自哪个频道,员工也回到那里作答。提及了不在该频道的人,整条消息会被拒收,而不是写下去却投递不出;达到 @ 连锁上限的消息只记录不投递,两个员工不会无休止地互相 @。接受、拒绝与审核工单由你或 CEO 决定,规则写在组织手册里。
+`workspace/` 根目录放共享的输入,不是任何人的工位。CEO 在 `ceo/` 里工作;新员工默认分到一个以自己 Agent id 命名的子目录,CEO 另行指定的除外。指定的是相对子目录时,服务端会自动创建;绝对路径必须事先存在。
-预算是每个员工的月度上限,口径是本人加全部下属的会话——CEO 的预算就是整家公司。到 80% 时全员频道里出现一条系统消息;到 100% 时该员工(及其下属)的日程暂停,直到下个月或上调预算。@提及和直接对话照常,你随时可以告诉一个被暂停的员工该做什么。
+### 手册
+
+手册是渐进式加载的。每次触发都指向 `handbook/README.md`,也就是每个工作轮最先读的索引。索引写明目录布局、协议和角色约定,并列出其余每份文档,各配一行说明什么时候需要读;工作轮只在那一行说明适用时才去读对应的文档。
+
+董事会的决定记在 `handbook/decisions/<yyyy-mm-dd>-<slug>.md`,约定和操作指南放在旁边。**手册**页面可以浏览、编辑和新建文档,会话里用 `penguin org handbook list | show | write | rm` 也能做同样的事。索引不能删除。
+
+### 董事会
+
+真人永远不是员工:组织图里只有 Agent。Project 成员就是董事会。他们都在全员频道里,可以加入、阅读每个频道,可以做工单负责人,别人也可以提及他们。
+
+真人和员工在所有地方都用同一种写法:`user:<user_id>` 和 `agent:<agent_id>`。`@all` 指它所在频道的全体成员,`system` 指调度器。
+
+## 工作如何流转
+
+1. **触发到达工位。** 触发只有三种:日程项到点、有人在员工所在的频道里提及它、真人直接找工位说话。服务端向工位会话发送一条消息,开头是 `[org_trigger]` 块,写明组织、员工、触发种类,以及这名员工的支出与预算,后面跟着触发的内容。Web App 把这个块折叠成一行提示,Trace 里原样保留。
+
+ **工单的变化从不启动运行。** 指派负责人、工单被阻塞、阻塞解除、工单完成或拒绝,每一项变化都只记录下来,列在这名员工下一次日历巡检的 `## Since your last sweep` 一节里。每项变化占一行,写明工单、标题、发生了什么,以及工单带着的理由或阻塞方。
+
+2. **工位负责调度。** 工位按 `company-employee` Skill 先读手册,再看看板,为每张该推进的工单开一个**工单会话**(`penguin org ticket start <id>`)。工单会话是同一个 Agent 在工位工作区里另开的一个普通会话。工位从不亲自改工单的文件,需要改的时候,就开一个工单会话交给它去做。
+
+ **工单的会话只能由负责人的工位或真人发起。** 员工给别人的工单开会话,会得到 `403 not_ticket_owner`。要把活交给另一名员工,就改派工单(`penguin org ticket assign <id> --owner agent:<employee>`),新负责人的工位在下一次巡检时接手。要拉同事来帮忙,由负责人用 `--agent-id <colleague>` 开会话。多名员工的多个会话可以共同推进一张工单,每个会话都记在工单的 `sessions` 列表里。
+
+3. **工单会话干活并回写。** 它开场先交代处境:自己的工作区、「所有引用和交付物都写完整路径」这条规则,以及工单原文。结束前,它用 `penguin org ticket progress` 追加进展,用一句大白话说清做了什么、东西在哪,不写 id,也不写人名,因为谁在什么时候写的由服务端记进 `history`。然后移动工单(`penguin org ticket move`)。
+
+ 声称做了活的写入(一条进展、修改正文、移入审核中)会把这个会话记为工单的贡献会话,它的成本也随之分摊到工单上;接受、关闭、阻塞和解除阻塞都不记。会话卡住了,比如在等人拍板、等另一张工单或缺一个密钥,就用 `penguin org ticket block` 阻塞工单,写明原因和谁能解开,然后停手。每次巡检都会跳过被阻塞的工单,直到它解除阻塞。
+
+4. **工单关闭时发通知。** 工单进入已完成或已拒绝时,`notify` 名单会收到通知;负责人是员工时,负责人也会收到,各自在自己下一次巡检里看到。在等这张工单的那张工单,会告诉它的负责人阻塞已解除。**工单的变化从不发到频道里**:频道装的是真人和员工之间说的话,看板要是自己播报自己,就会把对话淹没。关闭了哪些工单,你在看板上看,也可以看概览的**收件箱**,它列出本周期关闭的工单。
+
+5. **真人在频道和看板上拍板。** Skill 和手册要求 CEO 不要独自做重大决定,比如招募计划、预算、拒绝别人的工单,或任何触及组织之外的事。CEO 会在全员频道里提及你并发出提案,等你答复后才行动。招募计划只写角色和预算:除非你指定了特定模型,每名员工都跑在组织的模型上,组织没有指定模型时跑在 Project 的默认模型上。
+
+ 同一道关卡也约束每名员工:开始重负载或不可逆的工作之前——长时间计算、花钱、写到公共工作区之外、删除不是自己创建的数据、启动比本次运行更长命的进程,或者缺少某个凭证——员工先在全员频道里问你要跑什么、跑多久、在哪台机器上跑、怎么停下,把工单阻塞在你身上,然后结束本次运行。概览里会把这张工单列为正在等你,只有明确的同意才会让工作开始。
+
+ 接受、拒绝和审核工单由你或 CEO 负责,具体按手册的规定。这些是给 Agent 的指令,不是服务端会检查的规则,见[服务端强制执行的规则](#服务端强制执行的规则)。
## 频道
-沟通与工作区一样是分区的。每个组织创建时自带一个**全员频道** `default_channel`,全体员工与全体 Project 成员隐式在其中——提案、预算告警、招募与里程碑都发在这里,董事会也在这里读。其余频道由大家按条线或按大工单自行新建,以免一条线的讨论淹没全员频道。
+沟通和工作区一样是分区的。每个组织创建时自带一个**全员频道** `default_channel`,全体员工和全体 Project 成员默认都在其中。提案、预算告警、招募和里程碑都发在这里,董事会也在这里看。其他频道由大家按工作线或大工单自行开设,免得一条线的讨论淹没全员频道。
+
+- **创建**:真人和员工都可以创建频道,用 `penguin org channel create ch_<id>`,或者点频道列表旁的 **+**(**新建频道**)。新频道只有创建者一人。频道 id 的规则同组织 id,按惯例以 `ch_` 开头;`default_channel` 是保留名。
+- **加入**:员工只能由频道成员邀请进入。真人可以加入任何频道、阅读所有频道,董事会什么都看得到。只有成员能发言。
+- **提及**:`@agent:<id>` 只在这名员工是频道成员时唤醒它的工位,`@all` 指除发送者以外的全体频道成员。触发里写明消息来自哪个频道,员工就回到那个频道作答。提及非成员的消息会直接拒收(`mention_not_member`),不会写下去却投递不出。
+- **提及连锁上限**:达到组织提及连锁上限的消息只记录、不投递,两名员工因此不会无休止地互相提及。真人的消息会开始一条新的连锁。
+- **生命周期**:任何成员都可以修改频道名称和用途。归档与取消归档只有真人能做,归档后的频道只读并折叠收起。全员频道不能归档、不能退出,成员也不能编辑:所有人本就在其中,Web App 里也始终显示为**全员频道**。
-- **新建**:人和员工都可以(`penguin org channel create ch_<id>`,或 App 里频道列表标题旁的 **+**)。新频道只有创建者一人;id 规则同组织 id——按约定以 `ch_` 开头——`default_channel` 为保留字。
-- **加入**:员工只能由频道成员邀请进入;人可以自行加入任何频道,也能读到所有频道——董事会看得到全部。只有成员能发言。
-- **投递**:`@agent:<id>` 只在该频道的成员范围内唤醒对方工位,`@all` 指该频道的成员(不含发送者)。提及非成员的消息会被拒收(`mention_not_member`),而不是写下去却投递不出。
-- **生命周期**:任一成员可改名称与用途;归档与取消归档只有人能做,归档后频道只读并折叠收起。全员频道不能归档、不能退出、成员不可编辑——所有人本就在其中,界面上也只显示它的固定名称「全员频道」。
+频道里的系统消息(招募与离任;频道的创建、加入、退出与归档;预算告警与暂停)在 Web App 和 `penguin org channel tail` 里都按阅读者的语言、用显示名呈现。消息正文在 Web App 里按 Markdown 渲染。
-频道里的 `system` 消息——招募与离任,频道的创建、加入、退出与归档,预算预警与暂停,工单被阻塞、完成或否决——在英文正文之外记下一份结构化 notice,App 与 `penguin org channel tail` 因此按读者的语言、用显示名渲染它们。消息正文在 App 里按 Markdown 渲染。
+未读数和每个人的已读位置都按频道分别记录。新员工和离任员工的频道成员关系由 HR 负责维护。
-未读计数与每个人的已读游标都按频道分别计算;新员工与离任员工的频道成员关系由人事负责维护。
+真人收不到推送通知。提及你的消息会体现在未读数、**@我**筛选和概览的**收件箱**里。唯一的例外是绑定了聊天机器人的镜像分身,见[镜像组织](#镜像组织)。
-## 案例:插件 Marketplace
+## 预算
-使命是「做一个 DeepSeek Harness 插件 Marketplace,通过社交媒体和 SEO 把搜索排名做到前三,靠首页限时置顶曝光位盈利」,它会这样跑:
+预算按员工设置,是以美元计的月度上限。它统计员工本人的会话加上全部下属的会话,所以 CEO 的预算就是整家公司的上限。一个周期是组织时区里的一个自然月。
-1. 你在组织切换器里新建组织;CEO 的工位随初始化会话打开,在全员频道里发出一份提案——它对使命的理解、首批工单、拟招募的角色与预算——然后等你答复。
-2. 你确认后,CEO 先招募人事与财务,再招募开发与市场,建立 `workspace/site` 和 `workspace/marketing` 并指定给各工位,开出 `ch_site` 与 `ch_marketing` 两个频道、把各条线的负责人分别邀请进去,并按角色为每个人排定各自的时刻(建站的每日、人事每三天、财务每周)。
-3. 它开出一个 Marketplace 父工单,再按条线开子工单:建站、SEO 做到前三、社交媒体发布、付费置顶位。这不会惊动任何人:各负责人在自己下一次巡检里才看到指派。
-4. 下一次巡检为建站工单在 `workspace/site` 里发起工单会话;市场把 SEO 阻塞在建站上(「站点上线前没有可索引的内容」),并在 `ch_marketing` 频道里说明——建站自身的来回讨论从不落到这里。
-5. 建站会话完成开发、回写进展、把工单移到审核中;CEO 审核后移到已完成。开发在下一次巡检里看到这件事,市场在自己的巡检里看到「阻塞已解除」,核验后解除 SEO 的阻塞。
-6. 市场用一个挂在两个工单上的会话同时推进 SEO 与发布;财务按员工与工单上卷支出——共用会话在它服务的工单之间均分,父工单汇总子工单。
-7. 付费置顶位上线,CEO 在全员频道里 @ 你向董事会汇报。
+| 支出达到 | 结果 |
+| --- | --- |
+| 预算的 80% | 全员频道里出现一条系统消息。 |
+| 预算的 100% | 再出现一条系统消息,这名员工及其全部下属的日历暂停,直到下个月,或者预算调高、清空为止。 |
-服务端测试 `organization-scenario.test.ts` 在运行时接缝上完整跑通了这个故事。
+预算暂停的范围比听起来要窄:
+
+- 只停日程项。提及和直接对话照常送达,你随时可以告诉暂停中的员工该做什么。
+- 暂停期间到点的日程项直接跳过,之后不补发。
+- 已经在运行的会话不会停止。
+- 调度器每轮检查一次支出,而不是每个请求都查,所以暂停生效前,支出可能已经超出上限。
+
+调高或清空预算后,下一次检查就会解除暂停。没有 Token 预算,也没有按工单的预算,工单成本只做统计。
+
+预算存放在 `org_chart.yaml` 里。可以在创建对话框(**CEO 预算**)或用 `--ceo-budget` 设置,可以用 `penguin org hire --budget` 或 `penguin org employee set --budget` 设置,也可以在**组织图**和**财务**页面设置。80% 和 100% 这两个阈值是 `org_config.toml` 里的 `budget_warn_ratio` 和 `budget_pause_ratio`,Web App 里没有对应的字段。
+
+## 服务端强制执行的规则
+
+公司的很多行为规范只是指引,也就是 `agent-company` Skill、手册和 CEO 初始化 Prompt 里的指令。服务端只强制执行其中一部分。
+
+服务端强制执行这些规则:
+
+- 工单的会话只能由负责人的工位或真人发起(`403 not_ticket_owner`)。
+- 员工只能经邀请加入频道。
+- 只有真人能归档频道。
+- 提及非成员的消息直接拒收(`mention_not_member`)。
+- 提及达到提及连锁上限(`mention_chain_limit`,默认 3)即不再投递。
+- 预算达到 100% 时暂停日历。
+
+下面这些只是指引,Agent 会遵守,但服务端不检查:
+
+- 以下事项,CEO 先提案,等董事会答复后才行动:它对使命的理解、招募计划、设定或调高预算、拒绝别人的工单或不经审核就关闭 P0、P1 工单、任何触及组织之外的事(发布、账号、邮件、资金),以及修改手册的规则或组织结构。
+- 每名员工在开始重负载或不可逆的工作之前先向董事会请示,把工单阻塞在被请示的人身上,并结束本次运行。
+- 由谁接受、拒绝和审核工单。
+- 向上级上报问题。
+- 用组织的工作语言书写。
+- 镜像组织把问题转给哪个分身。
+
+招募、修改员工预算、暂停组织和移动工单都没有角色检查,也没有「仅限真人」的检查:员工在自己的会话里就能做这些事。汇报树本身在代码里只管几件事:预算上卷、暂停向下级联、阻塞通知发给上级,以及有人离任时重新挂接汇报线。
+
+### 工具审批
+
+工位会话和工单会话里的工具调用遵循组织的**审批模式**,在组织设置里配置:默认**全部放行**,也可以选**只读**或**全部拒绝**。没有 `always-ask` 模式,因为无人值守的运行不会停下来问人。
+
+## 示例:插件 Marketplace
+
+使命「做一个 DeepSeek Harness 插件 Marketplace,通过社交媒体和 SEO 把搜索排名做到前三,靠首页限时置顶曝光位盈利」会这样展开:
+
+1. 你在组织切换器里创建组织。CEO 的工位随初始化运行打开,在全员频道里发出一份提案,写明它对使命的理解、首批工单、想招募的角色和各自的预算,然后等你答复。
+2. 你确认后,CEO 先招募 HR 和财务,再招募一名开发和一名市场人员。它建立 `workspace/site` 和 `workspace/marketing` 并分配下去,开出 `ch_site` 和 `ch_marketing` 两个频道,把各条线的负责人分别邀请进去,再为每个人排定各自的时刻:做开发的每天一次,HR 每三天一次,财务每周一次。
+3. 它为 Marketplace 开一张父工单,再按工作线开子工单:建站、SEO 做到前三、社交媒体发布、付费置顶位。这不会唤醒任何负责人,各人在自己下一次巡检时才看到指派。
+4. 下一次巡检为建站工单在 `workspace/site` 里开出工单会话。市场人员把 SEO 工单阻塞在建站上(「站点上线前没有可索引的内容」),并在 `ch_marketing` 频道里说明;建站本身的来回讨论从不落到这里。
+5. 建站会话完成开发、写好进展,把工单移到审核中;CEO 审核后移到已完成。开发人员的下一次巡检会看到这件事,市场人员的下一次巡检会看到阻塞已解除,核实后解除 SEO 工单的阻塞。
+6. 市场人员用一个挂在两张工单上的会话同时推进 SEO 和发布。财务按员工和工单汇总支出:共用的会话在它服务的工单之间分摊,父工单汇总子工单。
+7. 付费置顶位上线,CEO 在全员频道里提及你,向董事会汇报。
+
+服务端测试 `organization-scenario.test.ts` 在运行时的接缝上完整跑通了这个故事。
## 科研组织
-第一个使命示例是一家实验室:「新建一个公司帮我做科研,产出可以投稿顶级会议的学术论文。实验按 autoresearch 的方式跑:先固定评测脚本与指标,只改一个文件,每次实验限定时长,结果逐行记入日志,只保留有提升的改动。开始任何实验循环之前,研究员先在群里向我申请资源——机器与 GPU/CPU、并发数、总时长、磁盘与数据、付费 API——批准后在额度内自主运行,要超出就再申请。论文由作者与审稿人两类员工对抗评审:审稿人复现结果、查基线与消融、找测试集泄漏与指标作弊,给出评分与必改项;作者逐条修改或反驳,直到审稿人接受。」
+第一个使命示例**科研论文公司**是一家做实验、写论文的公司:
+
+> 「新建一个公司帮我做科研,产出可以投稿顶级会议的学术论文。实验按 autoresearch 的方式跑:先固定评测脚本与指标,只改一个文件,每次实验限定时长,结果逐行记入日志,只保留有提升的改动。开始任何实验循环之前,研究员先在群里向我申请资源——机器与 GPU/CPU、并发数、总时长、磁盘与数据、付费 API——批准后在额度内自主运行,要超出就再申请。论文由作者与审稿人两类员工对抗评审:审稿人复现结果、查基线与消融、找测试集泄漏与指标作弊,给出评分与必改项;作者逐条修改或反驳,直到审稿人接受。」
-这样的使命让 CEO 照常走标准清单,而研究员与审稿人改按 `company-research` Skill 行事;它补了三件事:
+这样的使命下,CEO 仍按标准清单行事,研究员和审稿人则改用 `company-research` Skill,它在员工协议之上加了三条规则:
-- **先申请资源额度。** 一张工单的第一个实验开始之前,负责人先在全员频道向你申请额度——用哪台机器与 GPU/CPU、同时跑几个、总时长或总实验数、磁盘与数据、付费 API 或密钥——并写明预计负载与停止方式,把工单阻塞在你身上,然后结束本轮。批准的额度之内循环自主运行;要超出额度,或需要新的东西(数据集、密钥、第二块 GPU),都要再申请一次。员工缺什么就开口要,而不是绕过去。
-- **循环照 autoresearch 的做法。** 一个评测脚本、一个指标,循环开始前固定、进行中绝不改;只改一个文件;每次实验同样的时长预算;每次运行一个分支;`results.tsv` 里每次实验一行(commit、指标、内存、keep / discard / crash、一句描述);只有指标提升才保留 commit,否则回退;超过两倍时长的运行被杀掉并记为 crash;崩溃从日志尾部诊断。
-- **作者与审稿人是不同的员工。** CEO 至少招一名专职审稿人。结论进入 `review` 列后,审稿人设法推翻它——从保留的 commit 复现关键数字、查基线与消融、找测试集泄漏与指标作弊、把结论对照证据、把新颖性对照已有工作——写出带评分与必改项的审稿意见。作者逐条修改或反驳;工单在 `in_progress` 与 `review` 之间往返,直到审稿人接受,而一张科研工单的 history 里没有审稿人的接受就不能关闭。三轮仍未接受,审稿人把工单阻塞在 CEO 身上,由 CEO 决定或带给你。
+- **先申请资源额度。** 一张工单跑第一个实验之前,负责人先在全员频道里向你申请额度:用哪台机器、GPU 还是 CPU、同时跑几个、总时长或实验总数、磁盘与数据、付费 API 或密钥,并说明运行期间的负载估计和停下来的方法。然后把工单阻塞在你身上,结束本次运行。在批准的额度之内,循环自主运行;要超出额度,或需要新的东西(一份数据集、一个密钥、第二块 GPU),都要重新申请。缺什么就申请什么,而不是绕过去。
+- **循环按 autoresearch 的方式跑。** 一套评测脚本、一个指标,在循环开始前固定,循环期间绝不修改。只改一处可编辑的地方,每个实验用同样的墙钟时长,每次运行开一个分支。每个实验在 `results.tsv` 里占一行(commit、指标、内存、保留 / 丢弃 / 崩溃,以及一句描述);只有指标有提升时才保留这次 commit,否则回退。超过时长上限两倍的运行会被杀掉并记为崩溃,崩溃则从日志末尾诊断。
+- **作者和审稿人是不同的员工。** CEO 至少招募一名专职审稿人。结论进入 `review` 后,审稿人设法推翻它:从保留的 commit 复现关键数字、核对基线与消融、寻找测试集泄漏与指标作弊,并衡量结论与证据是否相称、创新性与已有工作相比如何。审稿人给出评分和必改项,作者逐条修改或反驳。工单在 `in_progress` 和 `review` 之间往返,直到审稿人接受;`history` 里没有这一次接受,科研工单就不会关闭。三轮仍未通过时,审稿人把工单阻塞在 CEO 身上,由 CEO 决定或提交给你。
+
+和协议的其余部分一样,这些是 Skill 和手册的指引,不是服务端会检查的规则。
## 镜像组织
-第四个使命示例是一家没有自己的活要干的公司:「新建一个公司,作为我们现实公司的镜像:我会把现实公司的组织图告诉 CEO,CEO 为每位现实员工创建一个数字分身;每个分身的工位会话绑定到那位同事的飞书机器人。分身默认只被动接收自己同事的消息,能自己解决的就直接回答,解决不了的转给相关同事的分身、再由对方分身转给真人。CEO 不主动招募、不排日程、不开工单,公司只做传话和自主解决问题。」
+第四个使命示例**员工数字分身公司**是一家没有自己的活要干的公司:
+
+> 「新建一个公司,作为我们现实公司的镜像:我会把现实公司的组织图告诉 CEO,CEO 为每位现实员工创建一个数字分身;每个分身的工位会话绑定到那位同事的飞书机器人。分身默认只被动接收自己同事的消息,能自己解决的就直接回答,解决不了的转给相关同事的分身、再由对方分身转给真人。CEO 不主动招募、不排日程、不开工单,公司只做传话和自主解决问题。」
+
+这样的使命会让 CEO 改按 `company-mirror` Skill 行事,不走标准清单,建出来的公司形态也不同:
+
+- **花名册由你提供。** CEO 的初始化运行向董事会索要现实公司的组织图:每个人的姓名、头衔、汇报线,以及哪个机器人归他。你答复后,CEO 提出花名册;你确认之后,CEO 才为每人招募一个分身,用 `--reports-to` 照搬现实的汇报线,并为每个分身写好简报。不会从任何通讯录或 HR 系统导入。
+- **没有周期性驱动。** 不排日程、不开工单,也不按工作线开频道。分身只在两种时候运行:它对应的真人通过绑定的机器人发来消息,或者另一个分身提及它。
+- **绑定是设置的最后一步,由真人完成。** 在每个分身工位会话的**远程控制**面板里,把会话绑定到那位同事的机器人(飞书、Telegram、QQ 或微信,见[远程控制](/remote-control))。`penguin org desk show <agent_id>` 会打印工位会话 id。没绑定的分身既听不到它对应的真人,也回不了话。
+- **先传话,再写下来。** 分身能从手册里答的就直接答;答不了就把问题转给相关同事的分身,由那个分身去问自己对应的真人,再把答案带回来。带回来的内容都写进手册(`people/<name>.md`、`faq.md`),下次同样的问题就不必再传话。
-这样的使命会让 CEO 改按 `company-mirror` Skill 行事,而不是走标准清单;由此建起来的公司形状也不同:
+依赖镜像组织之前,先了解这些限制:
-- **花名册来自外部。** CEO 的初始化运行向董事会索要现实公司的组织图——每个人的姓名、头衔、向谁汇报,以及哪个机器人归他——然后就结束本轮。董事会答复并确认花名册之后,CEO 才为每人招募一个分身,`--reports-to` 照搬现实汇报线,并为每个分身写下简介。
-- **没有任何周期性驱动。** 不排日程、不开工单、不按工作线开频道。分身只在两种时候运行:自己的同事通过绑定的机器人写来消息,或别的分身在频道里 `@` 它。
-- **绑定是设置的最后一步。** 每个分身的工位会话都要绑定到那位同事的机器人——打开该工位会话、用它的「远程控制」面板,或者从 `penguin org desk show <agent_id>` 取会话 id。没绑定的分身既听不见自己的同事,也回不了话。
-- **先传话,再写下来。** 分身能从手册里答就直接答,答不了就把问题转给相关同事的分身,由它去问自己的真人再把答复带回来。带回来的东西一律写进手册(`people/<姓名>.md`、`faq.md`),下次同样的问题就能自己答掉。传话会消耗提及连锁,但真人的每条消息(经机器人或对话页)都开始一条新连锁,所以一问一答的往返总在缺省的 `mention_chain_limit` 之内;只有分身之间自说自话才会撞上它。
+- 一个机器人账号同一时间只能在一个 Session 上启用(`409 account_enabled_elsewhere`),所以每个分身都需要自己的机器人。
+- 对应的真人先给机器人发过一条消息,机器人才能送出回复。
+- 传话经过全员频道,每名员工和每位董事会成员都看得到,所以传话从来不是私聊。
+- 该问哪个分身,由模型根据自己的简报和手册判断,没有路由引擎。
+- 传话会消耗提及连锁,但真人的每条消息(经机器人或对话页)都会开始一条新连锁。一问一答的往返在默认的 `mention_chain_limit` 之内;传到第三个分身再传回来就会超出。
## 命令
-在工位会话或工单会话里,`penguin org` 命令已经从环境里知道组织、Project、Agent 与当前会话(`PENGUIN_ORG_ID` 与其他控制变量一起注入);在 shell 里则传 `--org-id`。全部子命令见 [CLI 参考](/cli#penguin-org),常用的几条:
+在工位会话或工单会话里,`penguin org` 命令已经从环境中知道组织、Project、Agent 和当前 Session(`PENGUIN_ORG_ID` 与其他控制变量一起注入);在 shell 里则要传 `--org-id`。下面是常用的几条,全部子命令见 [CLI 参考](/cli#penguin-org)。
```text
-penguin org show # 员工、看板计数、支出对预算
+penguin org show # employees, board counts, spend vs budget
penguin org hire --new-agent <id> --title <s> --reports-to <agent_id> [--workspace <sub>] [--budget <usd>]
-penguin org calendar add <name> --prompt <s> --start-at 2026-09-03T09:00:00+08:00 --period 1d # 排班:各占时刻,按角色定节奏
+penguin org calendar add <name> --prompt <s> --start-at 2026-09-03T09:00:00+08:00 --period 1d # a rota: own hour, role cadence
penguin org ticket create --title <s> --goal <s> [--owner agent:<id>] [--parent <ticket_id>] [--slug <words>]
-penguin org ticket start <ticket_id> [-m <note>] [--agent-id <员工>] # 为自己名下的工单发起工单会话,打印会话 id
+penguin org ticket start <ticket_id> [-m <note>] [--agent-id <employee>] # a ticket session on a ticket you own, printed as its id
penguin org ticket progress <ticket_id> -m <text>
penguin org ticket move <ticket_id> --to review|done|rejected [--reason <s>]
-penguin org channel create ch_site --name "Site" --purpose "推进 Marketplace 站点"
-penguin org channel invite ch_site agent:<employee> # 员工只能由成员邀请进入频道
+penguin org channel create ch_site --name "Site" --purpose "Shipping the marketplace site"
+penguin org channel invite ch_site agent:<employee> # an employee reaches a channel only by invitation
penguin org channel tail [--channel <id>] [-n <count>]
-penguin org channel send -m "@<employee> …" [--channel <id>] # 缺省 default_channel
-penguin org finance # 按员工(累计)与按工单的支出
+penguin org channel send -m "@<employee> …" [--channel <id>] # default: default_channel
+penguin org finance # spend per employee (cumulative) and per ticket
```
-## 页面
+## 组织页面
+
+在公司模式下,侧边栏列出组织的各个页面:**概览**、**组织图**、**日历**、**工单**、**财务**和**手册**。
+
+- **概览**是打开组织时的落脚页。它显示折成一行的使命、本周期支出与 CEO 预算的对照、一条 KPI 带,下面是三段通栏:**收件箱**(全员频道里提及你或 `@all` 的消息,不论在等谁的全部阻塞工单,以及本周期关闭的工单)、今日日程和预算告警。卡片本身都不是链接,每张卡片角上各有一个按钮,写明它汇总的是哪个页面。
+- **组织图**展示汇报树。每名员工的菜单里有**招募下属**、**设预算**、**调整汇报线**、**换工位**和**离任**。
+- **手册**以资源管理器式的树展示知识库,旁边是渲染好的文档。每一层都是文件夹排在文档前面;文件夹默认收起,可以用方向键在树中移动。
+- **财务**把本周期分成三行:KPI 面板与逐日趋势并排,然后是支出树与工单表左右并排,最后是本周期的告警与暂停。
+- **日历**和**工单**在空的时候只留一个新建按钮,按钮上方的提示可以永久关掉。
+
+组织设置里包括**工作语言**、**审批模式**和**暂停组织**等项。
+
+## 开关与生命周期
+
+| 开关 | 位置 | 效果 |
+| --- | --- | --- |
+| 服务器 | **系统设置** › 服务器 › **公司模式**(仅管理员可见,默认关闭) | 关闭即停止组织调度器:不再触发任何东西,重新打开时也不补发。所有组织路由返回 404,模式切换对所有人消失。 |
+| 个人 | **系统设置** › 个人 › **通用** › **公司模式**(仅在服务器开关打开时显示) | 只对你自己隐藏模式切换,组织照常运转。 |
+| 组织 | 组织设置里的**暂停组织** | 停止这个组织的一切自动触发。真人仍可打开任意工位直接对话。 |
+
+**没有删除。** 组织只有运行和暂停两种状态,这就是它的全部生命周期。删除会丢掉回到它的对话、员工、工位和工单的唯一途径;而暂停的组织留着不花任何成本:它不触发任何东西,每个工位也都还在,随时可以对话。
+
+手工删除组织目录是移除组织的唯一方式。运行时在下一轮就不再看到它,Web App 会如实说明,并提供在原处新建一个组织的入口。员工就是普通 Agent,工位会话和工单会话就是普通 Session,所以两者都会保留。这些会话带着「属于这个组织」的标记,因此不会重新出现在开发模式的会话列表里。
+
+## 工作原理
+
+### 文件是唯一事实来源
+
+公司的一切都保存在 Project 目录下的文件里。SQLite 只存每一轮都能从这些文件重建的缓存,以及每个人在每个频道里的已读位置,这与开发模式对 Agent State 和 Trace 的规则相同。删掉缓存不会有任何变化;手工改一个文件,下一轮就会生效。
+
+组织调度器每 30 秒运行一轮,每次通过 API 写入后也会立即运行一轮。它只在服务端运行期间工作,错过的事件从不补发。
-组织打开时落在**概览**:折成一行的使命、本期支出对照 CEO 预算、一条 KPI 带,然后是三段通栏——收件箱(全员频道里 @ 我或 `@all` 的消息、全部被阻塞的工单——无论它在等谁、以及本期内关闭的工单)、今日日程、告警。卡片本身都不是链接,而是各带一个角上的按钮,写明跳到哪一页。
+### 会话标记
-**手册**页把知识库画成资源管理器式的树——每一层文件夹在文档之前,默认收起,可用方向键走——正文渲染在旁边。**财务**页把本期分成三行:KPI 面板与逐日趋势并列,然后是支出树与工单表左右分列,最后是本期的预警与暂停。**日历**与**看板**在空态下只留一个新建按钮,下方的说明可以永久关掉。
+工位会话或工单会话一打开,Session 记录本身就会打上「属于这个组织」的标记。因此它只出现在公司模式里,从不出现在开发模式的会话列表中;即使有人手工删掉了组织目录、服务器开关也已关闭,再没有别的东西能说明它属于谁,也是如此。已经存在的组织,运行时下一轮扫描它的文件时,会给它的会话补上标记。
-## 开关
+### Skill 更新
-- **服务器**:管理员的公司模式总开关,缺省关闭——新装的服务器要先在系统设置 › 服务器 › 公司模式里打开它。关闭即停止组织调度器(不再触发任何东西,重新打开也不补发),所有组织路由回 404,模式切换对所有人消失。
-- **个人**:只对你自己隐藏模式切换,组织照常运转。
-- **组织**:暂停一个组织会停止它的一切自动触发;人仍可打开任一工位直接对话。
+服务端会让每名员工的公司 Skill 保持最新。每一轮,它都把每名员工装着的 `agent-company` 和 `agent-development` 插件与插件库比对,谁落后了就整包重装。插件库里新增的 Skill 因此也会装到早已在岗的员工身上,不必逐个 Agent 手工更新。版本一致时不写任何文件;更新失败只记一条错误,不影响这一轮的其他工作。新员工受雇时装的本来就是当前版本。
-**没有删除。** 组织只有开与关,这就是它的全部生命周期。删除会连回到它的对话、员工、工位与工单的路一并丢掉;而暂停着的组织并不占用什么——它不触发任何东西,每个工位也仍在那里可以对话。
+### 结构化的系统消息
-手工删掉组织目录是组织唯一的消失方式。运行时在下一轮对账时就不再看见它,App 会如实说明并给出新建一个的入口。员工就是普通 Agent,工位会话与工单会话就是普通会话:两者都保留,且会话上「属于该组织」的标记仍在,因此它们不会回到开发模式的会话列表里。
+频道里的系统消息在英文正文之外另存一份结构化通知。Web App 和 `penguin org channel tail` 正是靠它按阅读者的语言、用显示名呈现这些消息。
diff --git a/packages/docs/content/concepts.en.md b/packages/docs/content/concepts.en.md
new file mode 100644
index 00000000..600d7660
--- /dev/null
+++ b/packages/docs/content/concepts.en.md
@@ -0,0 +1,231 @@
+---
+title: Key concepts
+description: The terms PenguinHarness uses, grouped by topic, each with a link to the page that covers it in depth.
+---
+
+PenguinHarness uses a small set of terms with specific meanings. This page defines them, grouped by topic, and each entry links to the page that covers the term in depth.
+
+- [How work is organized](#how-work-is-organized): Project, agent, Agent State, Workspace, data root
+- [How work runs](#how-work-runs): Session, Task, Trace, OmniMessage, approval mode, subagent
+- [What an agent can use](#what-an-agent-can-use): tools, Skill, plugin, hook package, MCP server, memory, Vault, scheduled task
+- [How agents improve](#how-agents-improve): Benchmark, case, evaluation, optimization, version, snapshot
+- [Models](#models): provider, model, thinking level, Token
+- [Company mode](#company-mode): organization, employee, desk session, ticket, channel
+
+## How work is organized
+
+### Project
+
+A Project is the top-level unit that groups agents. It holds the model table and credentials its agents use, and its Benchmarks. Every user starts with an initial Project and can create more, and several users can share a Project.
+
+See [Web App](/web-app).
+
+### Agent
+
+An agent carries out the goals you give it. Each agent has its own Agent State and can run many times, each time in a Workspace. An agent is not tied to a model: you choose the model when you start a Session.
+
+See [Agents](/agents).
+
+### Agent State
+
+Agent State is an agent's persistent directory, `agent_state/`. It holds the agent's configuration (`system_config.yaml`), its editable prompt file `AGENTS.md`, tool and MCP server settings, Skills, hook packages, memory, Vault and scheduled tasks. An agent's behavior lives entirely in these files: you can change it by editing them, and so can another agent.
+
+See [Configuration Reference](/configuration).
+
+### Workspace
+
+A Workspace is the directory an agent works in during a Session: the files it reads, creates and changes. You choose the Workspace when you start a Session. If you don't, PenguinHarness creates a temporary Workspace inside the agent's directory.
+
+See [Sessions & Traces](/sessions-and-traces#run-model).
+
+### Data root
+
+The data root is the directory where PenguinHarness keeps Projects, agents, model settings and Traces. It is `~/.penguin/data` by default (`%USERPROFILE%\.penguin\data` on Windows), and the desktop app, the CLI and the SDK on one machine all use it. Set `PENGUIN_HOME` to use another directory.
+
+See [Quickstart](/quickstart).
+
+## How work runs
+
+### Session
+
+A Session is one continuous conversation with an agent in one Workspace. You can send many prompts in a Session, and each prompt starts a Task. The model and the Workspace are fixed when the Session is created; in the Web App, a Session is a conversation.
+
+See [Conversations](/chat).
+
+### Task
+
+A Task is the work one prompt starts. The agent calls the model one or more times, one request per call, and runs tools in between. The Task ends when the model replies without calling a tool, or when the run is cut off, for example because you stopped it.
+
+See [The Agent Loop](/agent-loop).
+
+### Trace
+
+A Trace is the record of a Session: every message, tool call, approval decision and Token usage, appended in order to JSON Lines files. PenguinHarness restores a Session from its Trace, and the usage and cost figures come from the same records.
+
+See [Sessions & Traces](/sessions-and-traces).
+
+### OmniMessage
+
+OmniMessage is the single message format PenguinHarness uses everywhere: the SDK streams it, the Trace stores it, and the engine works with it internally. Marketing materials also call it Penguin Message; the documentation uses OmniMessage.
+
+See [The OmniMessage Protocol](/omni-message).
+
+### Approval mode
+
+Every tool call is allowed or denied before it runs, and the approval mode decides how. There are four modes: `allow-all`, `deny-all`, `read-only` (read-only tools run, the rest wait for you) and `always-ask`. You set the mode for each Session.
+
+See [Tools & Approval](/tools#approval).
+
+### Subagent
+
+A subagent is a child agent that an agent starts with the `run_subagent` tool to handle a self-contained subtask in the same Workspace. It runs in a Session of its own, with its own Trace, and returns its final answer to the agent that started it.
+
+See [Tools & Approval](/tools#subagents).
+
+## What an agent can use
+
+### Tools
+
+Tools are the actions an agent can take. The built-in tools run shell commands (`exec_command`, `input_command`), read and edit files (`read_file`, `edit_file`, `write_file`), and delegate work to subagents (`run_subagent`, `input_subagent`).
+
+See [Tools & Approval](/tools).
+
+### Skill
+
+A Skill is a set of reusable instructions: a directory with a `SKILL.md` file and any files it references. The system prompt lists only the name and description of each installed Skill, and the agent reads the full `SKILL.md` when a task calls for it.
+
+See [Skills & Plugins](/skills).
+
+### Plugin
+
+A plugin is what the plugin library installs. It ships Skills, a hook package, or both, and installing it on an agent puts them into that agent's Agent State. A server plugin is a different kind: an npm package of server modules, such as a sandbox backend, that a Project asks the server to run.
+
+See [Skills & Plugins](/skills).
+
+### Hook package
+
+A hook package is a set of scripts that PenguinHarness runs at fixed points of the agent loop: when a prompt is submitted, before each tool call is approved, and when a Task ends. A hook can, for example, deny a tool call or start another Task to keep the agent working.
+
+See [Skills & Plugins](/skills#hook-packages).
+
+### MCP server
+
+An MCP server is a program or service that offers tools through the Model Context Protocol. The tools it offers join the agent's toolset and go through the same approval as the built-in tools.
+
+See [Tools & Approval](/tools#mcp-servers).
+
+### Memory
+
+Memory is what an agent remembers between Sessions, such as your preferences and decisions about a project. It is kept as Markdown files in the agent's Agent State: one user scope that every Session reads, and one scope for each Workspace. Agents never share memory.
+
+See [Configuration Reference](/configuration#memory).
+
+### Vault
+
+The Vault holds an agent's secrets as environment variables. The values reach only the processes the agent's tools start, never the model or the Trace; the model sees at most the key names.
+
+See [Configuration Reference](/configuration#vault).
+
+### Scheduled task
+
+A scheduled task sends a prompt to an agent at set times, either into an existing Session or into a new Session each time. Scheduled tasks run only while the server is running.
+
+See [Scheduled tasks](/schedules).
+
+## How agents improve
+
+### Benchmark
+
+A Benchmark is a set of cases that measures how well an agent handles a kind of work. It belongs to the Project, not to one agent, so it can evaluate any agent in the Project.
+
+See [Evaluation Center](/evaluation-center).
+
+### Case
+
+A case is one test in a Benchmark. It has a statement, which the agent under test receives, and a private rubric used for scoring, which that agent never sees. Every run of a case is scored out of 100.
+
+See [Self-Improvement](/self-improvement#benchmark-storage).
+
+### Evaluation
+
+An evaluation runs an agent through every case of a Benchmark, a set number of times per case, and records the scores, cost and duration on the Benchmark's scoreboard. Scores are comparable only when the agent, the model and the thinking level are the same.
+
+See [Evaluation Center](/evaluation-center).
+
+### Optimization
+
+Optimization improves an agent from its evaluation results. An optimizer agent edits the agent's `AGENTS.md`, Skills and configuration, evaluates the change, and keeps it only when the score strictly improves; otherwise it rolls the change back.
+
+See [Self-Improvement](/self-improvement).
+
+### Version
+
+An agent's version is a number in its `system_config.yaml`. It increases each time an optimization is kept.
+
+See [Self-Improvement](/self-improvement#snapshots-and-versions).
+
+### Snapshot
+
+A snapshot is a packed copy of one version of an agent's Agent State, saved as `snapshots/v<version>.tar.gz` without the Vault. Before optimization changes an agent, it makes sure a snapshot of the current version exists. You can export and import snapshots, and create a new agent from an exported one.
+
+See [Self-Improvement](/self-improvement#snapshots-and-versions).
+
+## Models
+
+### Provider
+
+A provider is a named group of models in the Project's model table, such as `deepseek`, `anthropic` or the `tokendance` gateway. PenguinHarness includes built-in groups, and you can add your own.
+
+See [Models & Providers](/models).
+
+### Model
+
+A model is always identified by the pair `(provider, model_id)`: its provider group and its id at that provider. PenguinHarness never guesses the provider from the id. Each Project has a default model, and you pick the model when you start a Session.
+
+See [Models & Providers](/models).
+
+### Thinking level
+
+The thinking level sets how much a model reasons before it answers: `none`, `low`, `medium`, `high`, `xhigh` or `max`. Each agent has a default level, `medium` unless you change it, and you can pick another level inside a Session.
+
+See [Models & Providers](/models).
+
+### Token
+
+A Token is the unit a model counts text in. Usage and cost are measured in Tokens, and the Cost Center reports them by agent, model and time range.
+
+See [Cost Center](/usage).
+
+## Company mode
+
+Company mode is a beta work mode of the Web App in which a Project's agents run as a company. It is off until an admin turns it on in **System settings**.
+
+### Organization
+
+An organization is one company: a mission, its employees, and the calendar, tickets, channels and shared workspace they work with. It belongs to a Project, and one Project can hold several organizations that cannot see each other.
+
+See [Company Mode](/company-mode).
+
+### Employee
+
+An employee is an agent hired into an organization, with a title, duties and a manager it reports to. Employees form a reporting tree with the CEO at the root.
+
+See [Company Mode](/company-mode).
+
+### Desk session
+
+Each employee has one desk session, a standing Session in the organization. Calendar events, @mentions in channels and messages from people reach the employee there. The desk session plans the work and starts ticket sessions to do it.
+
+See [Company Mode](/company-mode).
+
+### Ticket
+
+A ticket is a unit of the organization's work, kept as a Markdown file on the board. It moves through the board's columns from proposed to done or rejected, and one or more ticket sessions work on it.
+
+See [Company Mode](/company-mode).
+
+### Channel
+
+A channel is a message stream inside an organization, where people and employees talk. A message reaches an employee only when it @mentions that employee or @all. Every organization has an all-hands channel that everyone is in.
+
+See [Company Mode](/company-mode).
diff --git a/packages/docs/content/concepts.zh.md b/packages/docs/content/concepts.zh.md
new file mode 100644
index 00000000..4b1ba8a9
--- /dev/null
+++ b/packages/docs/content/concepts.zh.md
@@ -0,0 +1,231 @@
+---
+title: 核心概念
+description: PenguinHarness 使用的术语,按主题分组,每条都附有深入讲解它的页面链接。
+---
+
+PenguinHarness 用到一组含义明确的术语。本页按主题分组给出定义,每条定义都链接到详细讲解它的页面。
+
+- [工作如何组织](#工作如何组织):Project、Agent、Agent State、Workspace、数据目录
+- [工作如何运行](#工作如何运行):Session、Task、Trace、OmniMessage、审批模式、子 Agent
+- [Agent 可用的能力](#agent-可用的能力):工具、Skill、插件、钩子包、MCP Server、记忆、Vault、定时任务
+- [Agent 如何进化](#agent-如何进化):Benchmark、题目、评估、优化、版本、快照
+- [模型与 Token](#模型与-token):供应商、模型、思考等级、Token
+- [公司模式](#公司模式):组织、员工、工位会话、工单、频道
+
+## 工作如何组织
+
+### Project
+
+Project 是组织 Agent 的顶层单位,保存其下 Agent 共用的模型表与凭据,以及属于它的 Benchmark。每个用户都自带一个初始 Project,还可以创建更多;一个 Project 也可以由多个用户共同使用。
+
+见 [Web App](/web-app)。
+
+### Agent
+
+Agent 是执行你所交代目标的主体。每个 Agent 都有自己的 Agent State,可以多次运行,每次运行都使用一个 Workspace。Agent 不绑定模型:模型在启动 Session 时由你选择。
+
+见 [Agent](/agents)。
+
+### Agent State
+
+Agent State 是 Agent 的持久化目录 `agent_state/`,存放 Agent 的配置(`system_config.yaml`)、可编辑的提示词文件 `AGENTS.md`、工具与 MCP Server 设置、Skill、钩子包、记忆、Vault 和定时任务。Agent 的行为完全由这些文件决定:你可以通过编辑文件改变它,其他 Agent 也可以。
+
+见[配置参考](/configuration)。
+
+### Workspace
+
+Workspace 是 Agent 在一个 Session 中工作的目录,它读取、创建和修改的文件都在这里。启动 Session 时由你选择 Workspace;如果不选,PenguinHarness 会在 Agent 的目录下创建一个临时 Workspace。
+
+见 [Session 与 Trace](/sessions-and-traces#运行模型)。
+
+### 数据目录
+
+数据目录是 PenguinHarness 存放 Project、Agent、模型设置和 Trace 的地方,默认为 `~/.penguin/data`(Windows 为 `%USERPROFILE%\.penguin\data`)。同一台机器上的桌面应用、CLI 和 SDK 都使用它。要改用其他目录,设置 `PENGUIN_HOME` 即可。
+
+见[快速开始](/quickstart)。
+
+## 工作如何运行
+
+### Session
+
+Session 是你与一个 Agent 在一个 Workspace 里的一段连续对话。一个 Session 里可以发送多条 Prompt,每条 Prompt 发起一个 Task。模型和 Workspace 在创建 Session 时就已确定。在 Web App 里,一个 Session 就是一个对话。
+
+见[对话](/chat)。
+
+### Task
+
+Task 是一条 Prompt 发起的工作。Agent 会调用模型一次或多次(每次调用是一个请求),并在调用之间执行工具。模型不再调用工具、直接给出回复时,Task 结束;运行中途中止时,Task 也会结束,比如你手动停止了它。
+
+见 [Agent 运行循环](/agent-loop)。
+
+### Trace
+
+Trace 是一个 Session 的记录:每条消息、每次工具调用、每个审批决定和 Token 用量,都按顺序追加写入 JSON Lines 文件。PenguinHarness 依据 Trace 恢复 Session,用量与成本的数据也来自这些记录。
+
+见 [Session 与 Trace](/sessions-and-traces)。
+
+### OmniMessage
+
+OmniMessage 是 PenguinHarness 各处通用的统一消息格式:SDK 用它流式输出,Trace 用它存储,引擎内部也用它运转。产品宣传中也叫 Penguin Message,文档一律使用 OmniMessage。
+
+见 [OmniMessage 协议](/omni-message)。
+
+### 审批模式
+
+每次工具调用在执行前都要经过放行或拒绝,由审批模式决定怎么做。审批模式有四种:`allow-all`、`deny-all`、`read-only`(只读工具直接执行,其余等你确认)和 `always-ask`。审批模式按 Session 分别设置。
+
+见[工具与审批](/tools#审批)。
+
+### 子 Agent
+
+子 Agent 是 Agent 用 `run_subagent` 工具启动的下级 Agent,在同一个 Workspace 里处理一项独立的子任务。它运行在自己的 Session 中,有自己的 Trace,完成后把最终答复交回启动它的 Agent。
+
+见[工具与审批](/tools#子-agent)。
+
+## Agent 可用的能力
+
+### 工具
+
+工具是 Agent 能执行的操作。内置工具可以运行 shell 命令(`exec_command`、`input_command`),读取和编辑文件(`read_file`、`edit_file`、`write_file`),以及把工作交给子 Agent(`run_subagent`、`input_subagent`)。
+
+见[工具与审批](/tools)。
+
+### Skill
+
+Skill 是一套可复用的指令:一个包含 `SKILL.md` 及其引用文件的目录。系统提示词里只列出每个已安装 Skill 的名称和描述,任务需要时,Agent 再读取完整的 `SKILL.md`。
+
+见[技能与插件](/skills)。
+
+### 插件
+
+插件是插件库安装的单位,包含 Skill、钩子包,或两者都有。把插件装到某个 Agent 上,这些内容就会放进这个 Agent 的 Agent State。服务端插件是另一类插件:由服务端模块组成的 npm 包,例如沙箱后端,由 Project 要求服务器运行。
+
+见[技能与插件](/skills)。
+
+### 钩子包
+
+钩子包是一组脚本,PenguinHarness 会在 Agent 运行循环的几个固定节点运行它们:提交 Prompt 时、每次工具调用审批之前,以及 Task 结束时。钩子可以拒绝一次工具调用,也可以再发起一个 Task,让 Agent 继续工作。
+
+见[技能与插件](/skills#钩子包)。
+
+### MCP Server
+
+MCP Server 是通过 Model Context Protocol 提供工具的程序或服务。它提供的工具会加入 Agent 的工具集,和内置工具走同样的审批。
+
+见[工具与审批](/tools#mcp-server)。
+
+### 记忆
+
+记忆是 Agent 在不同 Session 之间记住的内容,比如你的偏好和项目中的决定。记忆以 Markdown 文件的形式存放在 Agent State 里,分为每个 Session 都会读取的用户作用域,以及每个 Workspace 各自的作用域。不同 Agent 之间从不共享记忆。
+
+见[配置参考](/configuration#记忆)。
+
+### Vault
+
+Vault 以环境变量的形式保存 Agent 的密钥等机密。变量值只会注入 Agent 的工具启动的进程,绝不会进入模型或 Trace;模型最多只能看到变量名。
+
+见[配置参考](/configuration#vault)。
+
+### 定时任务
+
+定时任务按设定的时间向 Agent 发送 Prompt,可以发到已有的 Session,也可以每次新建一个 Session。只有服务端在运行时,定时任务才会执行。
+
+见[定时任务](/schedules)。
+
+## Agent 如何进化
+
+### Benchmark
+
+Benchmark 是一组题目,用来衡量 Agent 处理某类工作的能力。Benchmark 属于 Project 而不属于某个 Agent,因此可以评估 Project 里的任何 Agent。
+
+见[评估中心](/evaluation-center)。
+
+### 题目
+
+题目是 Benchmark 里的一道测试。它包含题面和私有的评分标准:题面交给被测 Agent,评分标准只用来打分,被测 Agent 看不到。题目的每次运行都按满分 100 分打分。
+
+见[自我进化](/self-improvement#benchmark-存储)。
+
+### 评估
+
+评估让 Agent 把 Benchmark 的每道题目按设定的次数跑完,并把分数、成本和耗时记录到 Benchmark 的记分板上。只有 Agent、模型和思考等级都相同时,分数之间才可以比较。
+
+见[评估中心](/evaluation-center)。
+
+### 优化
+
+优化是根据评估结果改进 Agent。优化器 Agent 修改被优化 Agent 的 `AGENTS.md`、Skill 和配置,再评估改动的效果:分数严格提升才保留改动,否则回滚。
+
+见[自我进化](/self-improvement)。
+
+### 版本
+
+Agent 的版本是 `system_config.yaml` 里的一个数字,每保留一次优化就加一。
+
+见[自我进化](/self-improvement#快照与版本)。
+
+### 快照
+
+快照是 Agent State 某个版本的打包副本,保存为 `snapshots/v<version>.tar.gz`,不包含 Vault。优化在修改 Agent 之前,会先确保当前版本已经有快照。快照可以导出、导入,也可以用导出的快照创建新的 Agent。
+
+见[自我进化](/self-improvement#快照与版本)。
+
+## 模型与 Token
+
+### 供应商
+
+供应商是 Project 模型表里的一个具名分组,例如 `deepseek`、`anthropic` 或 `tokendance` 网关。PenguinHarness 内置了一批分组,你也可以添加自己的分组。
+
+见[模型与 Provider](/models)。
+
+### 模型
+
+模型始终以 `(provider, model_id)` 二元组标识:它所属的供应商分组,加上它在该供应商处的 id。PenguinHarness 绝不根据 id 猜测供应商。每个 Project 都有一个默认模型,启动 Session 时由你选择模型。
+
+见[模型与 Provider](/models)。
+
+### 思考等级
+
+思考等级决定模型在回答前推理多少,可选 `none`、`low`、`medium`、`high`、`xhigh` 或 `max`。每个 Agent 都有默认等级,没改过就是 `medium`;在 Session 里也可以换成其他等级。
+
+见[模型与 Provider](/models)。
+
+### Token
+
+Token 是模型计量文本的单位。用量和成本都按 Token 计算,成本中心会按 Agent、模型和时间范围统计它们。
+
+见[成本中心](/usage)。
+
+## 公司模式
+
+公司模式是 Web App 的一种 Beta 工作模式,让一个 Project 的 Agent 像一家公司那样自行运转。它默认关闭,需要管理员在**系统设置**里开启。
+
+### 组织
+
+组织就是一家公司:一个使命、一批员工,以及他们共用的日历、工单、频道和公共工作区。组织属于某个 Project,一个 Project 可以有多个组织,组织之间互不可见。
+
+见[公司模式](/company-mode)。
+
+### 员工
+
+员工是被任用进组织的 Agent,有头衔、职责和汇报对象。全体员工组成一棵汇报树,CEO 是树根。
+
+见[公司模式](/company-mode)。
+
+### 工位会话
+
+每个员工都有一个工位会话,也就是员工在组织里的常设 Session。日程项、频道里的 @提及和人发来的消息都送到这里。工位会话负责安排工作,并发起工单会话去完成它。
+
+见[公司模式](/company-mode)。
+
+### 工单
+
+工单是组织里的一个工作单位,以 Markdown 文件的形式放在看板上。工单沿着看板的各列流转,从「提议」到「已完成」或「已拒绝」,由一个或多个工单会话推进。
+
+见[公司模式](/company-mode)。
+
+### 频道
+
+频道是组织内的一条消息流,人和员工在这里交流。消息只有 @ 了某个员工或 @all,才会送达那个员工。每个组织都有一个全员频道,所有人都在其中。
+
+见[公司模式](/company-mode)。
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index 202d4091..3f934aa2 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -1,13 +1,13 @@
---
title: Configuration Reference
-description: Complete field reference for environment variables, Project config, Agent config, the Vault, and Schedules.
+description: Every PenguinHarness setting with its default and constraints, from environment variables to the Project, agent, memory, Vault and schedule files.
---
-PenguinHarness configuration has three layers: environment variables shape the deployment, the Project config manages models and credentials, and the Agent config defines a single Agent's behavior. Each Agent additionally has two kinds of state files: the Vault (private environment variables) and Schedules (timed tasks).
+PenguinHarness configuration has three layers: environment variables shape the deployment, the Project config manages models and credentials, and the agent config defines one agent's behavior. Each agent also keeps state files for its [Memory](#memory), [Vault](#vault) and [Schedules](#schedules).
## Environment variables
-The CLI and the server automatically load a `.env` file from the working directory on startup.
+The CLI and the server load a `.env` file from the working directory on startup.
| Variable | Description | Default |
| --- | --- | --- |
@@ -15,68 +15,108 @@ The CLI and the server automatically load a `.env` file from the working directo
| `PORT` | Web service listen port | `7364` |
| `HOST` | Web service listen address | `127.0.0.1` |
| `PENGUIN_WEB_DB` | Server SQLite database path | `<root>/web.db` |
-| `PENGUIN_WEB_DIST` | Front-end static assets directory | the npm server package falls back to its bundled web-dist |
-| `PENGUIN_PREVIEW_ORIGIN` | Origin that serves Workspace HTML previews, e.g. `https://preview.example.com` | unset — the loopback counterpart is derived per request |
-| `PENGUIN_GO_ORIGIN` | Trusted origin used by the server-side Penguin Go key authorization flow | `https://token.penguin.ooo` |
-| `PENGUIN_TRUST_PROXY` | `1` trusts the `x-forwarded-proto` header — set it behind a reverse proxy that terminates TLS (and sets/strips the header itself) so session cookies are marked `Secure` and the hot-update network gate sees HTTPS | unset — the header is ignored |
-| `PENGUIN_SEED_ADMIN_PASSWORD` | Fixed initial password for the seeded built-in admin (automated tests / e2e) | unset — the seed generates a random password, hashed and discarded unseen; the account is claimed through the first-login link |
-| `PENGUIN_LANG` | CLI language (`en` / `zh`), set via `penguin config lang` | `en` |
-| `PENGUIN_UPDATE_CHECK` | `off` disables the web app's new-release check | enabled |
-| `PENGUIN_NO_LOGIN_SHELL_ENV` | Any non-empty value stops the desktop app from importing the login shell's environment on macOS/Linux GUI launches (see [Desktop quickstart](/quickstart-desktop)) | unset — the import runs, filling only variables the launch left unset |
-| `PENGUIN_CLI_ENTRY` | The CLI entry script this installation offers the Agents it runs (see below) | set for you by `penguin server` / `penguin web` and by the desktop app; falls back to the checkout's own `packages/cli/dist/penguin.js` when the server was started from one |
+| `PENGUIN_WEB_DIST` | Front-end static assets directory | The server package's bundled `web-dist` (in a source checkout, `packages/web/dist`) |
+| `PENGUIN_PREVIEW_ORIGIN` | Origin that serves Workspace HTML previews, e.g. `https://preview.example.com` | Unset: the loopback counterpart is derived per request |
+| `PENGUIN_GO_ORIGIN` | Trusted origin the server-side Penguin Go key authorization calls | `https://token.penguin.ooo` |
+| `PENGUIN_TRUST_PROXY` | `1` trusts the `x-forwarded-proto` header | Unset: the header is ignored |
+| `PENGUIN_SEED_ADMIN_PASSWORD` | Fixed initial password for the seeded built-in admin (automated tests / e2e) | Unset: a random password is generated |
+| `PENGUIN_LANG` | CLI language (`en` / `zh`), set with `penguin config lang` | `en` |
+| `PENGUIN_UPDATE_CHECK` | `off` disables the Web App's new-release check | Enabled |
+| `PENGUIN_NO_LOGIN_SHELL_ENV` | Any non-empty value stops the desktop app from importing the login shell's environment on macOS/Linux GUI launches | Unset: the import runs |
+| `PENGUIN_SHELL` | The shell that runs agent commands (an executable name or path) | Unset: picked automatically, see [Tools & Approval](/tools#command-sessions) |
+| `PENGUIN_CLI_ENTRY` | The CLI entry script this installation offers the agents it runs (see [PATH launcher](#path-launcher)) | Set by `penguin server` / `penguin web` and by the desktop app |
-These configure PenguinHarness itself, so `PORT`, `HOST`, `PENGUIN_WEB_DIST` and `PENGUIN_CLI_ENTRY` are **removed from the environment of commands the Agent runs** — otherwise a dev server started by `exec_command` would read `PORT` and try to bind the port meant for PenguinHarness instead of choosing its own. The rest of the host environment passes through, with one further exception: `GIT_EDITOR`, `GIT_TERMINAL_PROMPT`, `TERM`, `NO_COLOR`, `PAGER` and `GIT_PAGER` are always forced to fixed values, so that a command cannot hang waiting on an editor, a credential prompt or a pager. The Agent's [vault](#vault) is applied on top of the host environment — setting `PORT` there does reach commands — but not on top of those six.
+Notes:
-One thing travels the other way: **this installation's own `penguin` is first on the PATH of every command an Agent runs**. At startup the server writes a launcher script at `<root>/bin/penguin` — it runs the CLI entry named above, on the server's own Node — and puts that directory at the front of PATH for each command. So `penguin` inside a command is the harness the Agent is running in, whatever version happens to be installed globally on the machine. The directory is prepended inside the shell as well as in the environment, because commands run through a login shell whose profile routinely rewrites PATH afterwards; that also puts it ahead of a `PATH` set in the [vault](#vault), which otherwise replaces the inherited value outright. The launcher is rewritten at every start, so a moved installation is picked up by the next one, and when there is no entry to point at none is written and `penguin` resolves however it did before.
+- `PENGUIN_TRUST_PROXY`: set it behind a reverse proxy that terminates TLS and sets or strips the header itself. Session cookies are then marked `Secure`, and the hot-update network gate sees HTTPS.
+- `PENGUIN_SEED_ADMIN_PASSWORD`: without it, the seed generates a random password that is hashed and discarded unseen, and you claim the account through the first-login link.
+- `PENGUIN_GO_ORIGIN`: server configuration, not an endpoint the browser can name. It must be a bare HTTPS origin; plain HTTP is accepted only for `localhost`, `127.0.0.1` and `[::1]`, for integration environments. A path, credentials, a query string or a fragment is rejected at startup. See [Authorize a new API key](/models#authorize-a-new-api-key).
+- `PENGUIN_UPDATE_CHECK`: `off` turns off the automatic release check, nothing else. Model requests, an enabled remote-control connection, provider key authorization and the proxy test still reach the network.
+- `PENGUIN_NO_LOGIN_SHELL_ENV`: without it, the import fills only variables the launch left unset. See [Desktop quickstart](/quickstart-desktop).
+- `PENGUIN_CLI_ENTRY`: when the server was started from a source checkout, it falls back to that checkout's `packages/cli/dist/penguin.js`.
-`PENGUIN_PREVIEW_ORIGIN` must differ from the app's origin by **hostname**, not just port: cookies ignore ports, so a second port would still share the session cookie. Leave it unset for local use — the app is canonicalized onto `localhost` and previews are served from `127.0.0.1`, which needs no configuration and no DNS. Set it when the app is reached over a LAN address or a real domain; otherwise previews there fall back to a same-origin sandbox where `localStorage`, cookies and third-party embeds do not work. When you do set it on a real domain, keep the session cookie host-only (no `Domain=`), or a sibling subdomain shares it. An unparseable value is a startup error rather than a silent fallback.
+### Environment of agent-run commands
-`PENGUIN_GO_ORIGIN` is server configuration, not a browser-supplied endpoint. It must be a bare HTTPS origin; plain HTTP is accepted only for `localhost`, `127.0.0.1`, or `[::1]` integration environments. Paths, credentials, query strings, and fragments are rejected at startup.
+Commands an agent runs with `exec_command` inherit the host environment, with these changes:
+
+- **Removed:** `PORT`, `HOST`, `FORCE_COLOR`, `CLICOLOR_FORCE` and every `PENGUIN_*` variable. They configure PenguinHarness itself, not the command. Without this, a dev server started by `exec_command` would read `PORT` and try to bind the port meant for PenguinHarness instead of choosing its own.
+- **Proxy:** in Sessions the server runs, the **Agent environment uses the proxy** switch in [System settings](/settings#proxy-options) decides the proxy variables. Off removes `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY`; on injects the configured proxy address, or passes the host's variables through when no address is set.
+- **Vault:** the agent's [Vault](#vault) is applied on top, so setting `PORT` or a `PENGUIN_*` variable there does reach commands.
+- **Control variables:** a server-driven Session then injects `PENGUIN_API_URL`, `PENGUIN_API_TOKEN`, `PENGUIN_PROJECT_ID`, `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID` (plus `PENGUIN_ORG_ID` in company mode), so the agent's own `penguin` calls reach the server that runs it. These override Vault entries of the same name. See [CLI Reference](/cli).
+- **Forced:** `GIT_EDITOR`, `GIT_TERMINAL_PROMPT`, `TERM`, `NO_COLOR`, `PAGER` and `GIT_PAGER` always get fixed values, so a command cannot hang waiting on an editor, a credential prompt or a pager. Nothing overrides them, the Vault included.
+
+### PATH launcher
+
+This installation's own `penguin` is first on the PATH of every command an agent runs. At startup the server writes a launcher script at `<root>/bin/penguin`, which runs the CLI entry from `PENGUIN_CLI_ENTRY` on the server's own Node, and puts that directory at the front of PATH for each command. So `penguin` inside a command is the harness the agent is running in, whatever version is installed globally on the machine.
+
+The directory is prepended inside the shell as well as in the environment, because commands run through a login shell whose profile often rewrites PATH afterwards. This also puts it ahead of a `PATH` set in the [Vault](#vault), which otherwise replaces the inherited value outright.
+
+The launcher is rewritten at every start, so the next start picks up a moved installation. When there is no entry to point at, no launcher is written and `penguin` resolves as it would without one.
+
+### Workspace preview origin
+
+`PENGUIN_PREVIEW_ORIGIN` must differ from the app's origin by **hostname**, not just by port: cookies ignore ports, so a second port would still share the session cookie.
+
+- **Local use:** leave it unset. The app is canonicalized onto `localhost` and previews are served from `127.0.0.1`, which needs no configuration and no DNS.
+- **LAN address or real domain:** set it. Otherwise previews fall back to a same-origin sandbox where `localStorage`, cookies and third-party embeds do not work. On a real domain, keep the session cookie host-only (no `Domain=`), or a sibling subdomain shares it.
+
+An unparseable value stops the server at startup instead of falling back silently.
### Provider credential variables
-When a model entry has no inline `api_key`, AgentHub falls back to the provider's environment variable. A `*_BASE_URL` value is used only when the entry does not already inline `base_url`:
+When a model entry has no inline `api_key`, AgentHub falls back to the provider's environment variable. A `*_BASE_URL` value is used only when the entry does not inline `base_url`.
| Provider | API key | Base URL |
| --- | --- | --- |
| deepseek | `DEEPSEEK_API_KEY` | `DEEPSEEK_BASE_URL` |
| anthropic | `ANTHROPIC_API_KEY` | `ANTHROPIC_BASE_URL` |
-| openai, openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
+| openai, openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, vllm, custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
+| penguin-go | `PENGUIN_GO_API_KEY` | `PENGUIN_GO_BASE_URL` |
| minimax | `MINIMAX_API_KEY` | `MINIMAX_BASE_URL` |
| google | `GEMINI_API_KEY` | `GEMINI_BASE_URL` |
| zhipu | `ZAI_API_KEY` | `ZAI_BASE_URL` |
| moonshot | `MOONSHOT_API_KEY` | `MOONSHOT_BASE_URL` |
-The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, and custom groups speak the OpenAI-compatible protocol, hence the shared `OPENAI_*` variables. The direct MiniMax M3 Responses client uses `MINIMAX_*`; the built-in MiniMax preset already pins the official endpoint. Provider groups and the built-in model catalog are covered in [Models & Providers](/models).
+The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, vllm and custom groups speak an OpenAI-compatible protocol, hence the shared `OPENAI_*` variables. The Penguin Go relay keeps a pair of its own, so the app never offers a vendor credential for it. The direct MiniMax M3 Responses client uses `MINIMAX_*`, and the built-in MiniMax preset already pins the official endpoint. For provider groups and the built-in model catalog, see [Models & Providers](/models).
## Project config
-`<root>/<project>/.project_config.toml` is the Project's single config file: a hidden file written with mode 0600, with credentials inlined on the model entries. Model identity is always the `(provider, model_id)` pair — string concatenation is forbidden everywhere, and every reference into this file carries both halves: the provider is never inferred from a bare `model_id`.
-
-| Field | Description |
-| --- | --- |
-| `name` | Project display name (the id is shown when unset) |
-| `default_model` | Paired reference `{ provider, model_id }` to the default model; must point to an entry in `models` |
-| `vision_model` | The vision model that reads images on behalf of text-only models (`read_file` hands images to it); a paired reference |
-| `[command_policy]` | Sandbox command policy: deny rules for shell commands, applied ahead of the approval mode — see [Command policy](#command-policy) |
-| `[[models]]` | The list of available model entries |
-
-Model entry (`[[models]]`) fields:
-
-| Field | Description |
-| --- | --- |
-| `provider` | Provider group; together with `model_id` forms the entry's unique key |
-| `model_id` | Upstream request id, sent to AgentHub unchanged |
-| `context_window` | Context window size |
-| `client_type` | AgentHub client protocol; inferred from `model_id` by default — custom endpoints use a generic protocol client: `openai-responses`, `ant-messages`, or `openai-chat` (the Web dialog can detect which one a base URL serves; the pre-0.4.2 `openai` spelling is a deprecated alias of `openai-chat`, normalized on read) |
-| `display_name` | Display name; persisted only when it differs from the built-in catalog |
-| `vision` | Whether image input is supported; defaults to supported |
-| `max_tokens` | Per-model max output tokens; overrides the Agent's `model.max_tokens` when set, omitted = inherit it |
-| `fast_mode` | Per-model fast mode (premium faster serving tier); off by default, only `true` is persisted. Offered only for models whose AgentHub client can serve it; the others reject requests carrying it — see [Models](/models#fast-mode) |
-| `pricing` | Three price buckets `cache_read` / `cache_write` / `output`, in USD per million Tokens (`unit = "usd_per_mtok"`). Always the list price: a running promotion is stored by the server in `web.db` and taken off when cost is computed — see [Models](/models#built-in-provider-groups) |
-| `api_key` | Inline credential; when empty, falls back to the provider environment variable |
-| `base_url` | Custom base URL; preset by the built-in catalog for gateways and for the direct rows that pin a client — MiniMax M3 and DeepSeek `deepseek-flash` |
-| `created_at` | Write timestamp of `api_key` (ISO 8601; a display field maintained by the interface layer) |
+`<root>/<project>/.project_config.toml` is the Project's single config file: a hidden file written with mode 0600, with credentials inlined on the model entries. A model's identity is always the `(provider, model_id)` pair. Strings are never concatenated into one id, every reference into this file carries both halves, and the provider is never inferred from a bare `model_id`.
+
+| Key | Type | Default | Description |
+| --- | --- | --- | --- |
+| `name` | string | — | Project display name; the id is shown when unset |
+| `default_model` | pair | — | Paired `{ provider, model_id }` reference to the default model; must point to an entry in `models` |
+| `vision_model` | pair | — | The vision model that reads images for text-only models (`read_file` hands images to it); a paired reference |
+| `[default_chat]` | table | — | Prefilled defaults for new chats; see [New chat defaults](#new-chat-defaults) |
+| `[command_policy]` | table | Factory set | Deny rules for shell commands, applied ahead of the approval mode; see [Command policy](#command-policy) |
+| `[plugins]` | table | — | The server plugins the Project asks for; see [Plugins](#plugins) |
+| `[[models]]` | array of tables | — | The available model entries |
+
+### Model entries
+
+| Key | Type | Default | Description |
+| --- | --- | --- | --- |
+| `provider` | string | — | Provider group; with `model_id`, the entry's unique key |
+| `model_id` | string | — | Upstream request id, sent to AgentHub unchanged |
+| `context_window` | number | — | Context window size |
+| `client_type` | string | Inferred from `model_id` | AgentHub client protocol |
+| `display_name` | string | The built-in catalog name | Display name; persisted only when it differs from the catalog |
+| `vision` | boolean | `true` | Whether the model accepts image input |
+| `max_tokens` | number | The agent's `model.max_tokens` | Per-model max output Tokens; overrides the agent's `model.max_tokens` when set |
+| `fast_mode` | boolean | Off | Per-model fast mode (the provider's premium faster serving tier) |
+| `pricing` | table | — | Three price buckets, `cache_read` / `cache_write` / `output`, in USD per million Tokens (`unit = "usd_per_mtok"`). Always the list price |
+| `api_key` | string | The provider's environment variable | Inline credential |
+| `base_url` | string | Preset for some catalog entries | Custom base URL |
+| `created_at` | string | — | When `api_key` was written (ISO 8601); a display field maintained by the interface layer |
+
+Field notes:
+
+- `client_type`: custom endpoints use a generic protocol client: `openai-responses`, `ant-messages` or `openai-chat`. The Web dialog can detect which one a base URL serves. The pre-0.4.2 spelling `openai` is a deprecated alias of `openai-chat`, normalized on read.
+- `fast_mode`: only `true` is persisted. It is offered only for models whose AgentHub client can serve it, and the others reject requests that carry it. See [Models](/models#fast-mode).
+- `pricing`: the figure here is the list price. A running promotion is not written to this file: the server keeps it in `web.db` and takes it off when it computes cost. See [Prices and promotions](/models#prices-and-promotions).
+- `base_url`: the built-in catalog presets it for gateways and for the direct rows that pin a client, MiniMax M3 and DeepSeek `deepseek-flash`.
+- `api_key`: when empty, AgentHub falls back to the provider's environment variable.
```toml
default_model = { provider = "deepseek", model_id = "deepseek-flash" }
@@ -97,24 +137,59 @@ cache_write = 0.285714
output = 1.142857
```
-`pricing.unit` is currently always `usd_per_mtok` (USD per million tokens); the three buckets map onto `token_usage`'s three counters.
+`pricing.unit` is currently always `usd_per_mtok` (USD per million Tokens). The three buckets map onto the three counters of `token_usage`.
-Edit this file via the CLI (`penguin config model …`) or the Web Models page — never by hand while the service is running, and never by the model itself, which has no right to read or write it.
+Edit this file with the CLI (`penguin config model …`) or on the Web App's Models page.
-### Command policy
+> [!WARNING]
+> Do not edit `.project_config.toml` by hand while the service is running. The model has no right to read or write it.
-The `[command_policy]` block is the Project's sandbox guardrail for shell commands: a deny-rule list applied at the approval boundary itself to both tools that reach a shell — `exec_command`'s `cmd` (the launch) and `input_command`'s `chars` (what gets typed into an already-running one) — `Session.run` wraps the injected approval callback with it, so a hit is rejected before the host is asked, under every approval mode, allow-all included. The model receives the fixed line `Tool call denied by policy.` — distinct from a person's cancellation — and changes course. The policy also outranks a [pre-tool-use hook's](/agent-loop#pre-tool-use-hooks) `allow`: a vetoed call stays forbidden no matter what an installed hook answers. The policy lives in the Project config rather than in Agent State: an Agent editing its own configuration through its settings surface cannot reach it. It sits in the strict tier of runtime parameters: read once per model context, when the context opens — an edit reaches a running Session at its next rotation (compaction), and new conversations at once. It is not a filesystem permission — a tool that writes arbitrary paths can still rewrite the config file itself, and the rewrite takes effect at the next rotation: an accident guardrail, not a security boundary.
+### New chat defaults
-The rules are **plain data with no special tiers**: the factory set is seeded into each new project exactly like the model presets — copied in at creation, never rewritten afterward — and every rule can then be edited, disabled, deleted, or joined by new ones. A project from before the seeding (no `rules` list stored) behaves as the factory set until its first saved edit materializes the list; the settings page's "Restore defaults" loads the factory set back into the editor, and Save writes it.
+The `[default_chat]` block prefills new chats in the Web App. It is managed on the **Defaults** tab of **Project settings**. Every key is optional and independent, and an invalid value is dropped on load without affecting the other keys.
-| Field | Description |
-| --- | --- |
-| `enabled` | Master switch; absent = **on** (stored only as `enabled = false`) |
-| `[[command_policy.rules]]` | The deny-rule list, matched in order: `name` (identifies the rule in the settings UI) + `pattern` (a JavaScript regex source, matched against the whitespace-normalized command) + optional `description` + per-rule `enabled` (absent = on). A stored empty list means no rules; an absent list means the factory set |
+| Key | Type | Default | Description |
+| --- | --- | --- | --- |
+| `agent_id` | string | — | The agent preselected for a new chat; must name an existing agent |
+| `workspace` | string | A temporary Workspace | The prefilled Workspace directory |
+| `approval_mode` | string | `allow-all` | The prefilled approval mode: `allow-all`, `deny-all`, `read-only` or `always-ask` |
+| `thinking_level` | string | — | Fallback thinking level (`low` / `medium` / `high` / `xhigh` / `max`) for agents whose config sets no `model.thinking_level` |
-The factory set is deliberately small — commands whose verbatim execution is destructive with no undo: `rm` carrying both a recursive and a force flag, `mkfs`, `dd` writing straight to a block device, the classic fork bomb, and shell redirection onto a block device (`/dev/null` and friends stay legal). Four more are the Windows counterparts of the same five, since `exec_command` will resolve pwsh or cmd there: a recursive force delete (`Remove-Item -Recurse -Force`, `rd /s /q`), a volume format (`format C:`, `Format-Volume`), a raw disk overwrite (`\\.\PhysicalDriveN`, `Clear-Disk`), and the cmd fork bomb.
+The default model is not part of this block: it stays the top-level `default_model`.
-Matching normalizes ordinary spellings before the rules run, so plain typing does not slip through by accident: a leading path (`/bin/rm`), a wrapper (`sudo`, `env`, `command`, `nice`, `xargs`), quoting or a backslash escape of the command word (`"rm"`, `r''m`, `\rm`), and a literal `sh -c 'rm -rf /'` payload all match. Removing quote marks is all that happens — nothing is expanded, substituted, or decoded.
+### Plugins
+
+The `[plugins]` table lists the [server plugins](/skills#server-plugins) the Project asks for. It is managed on the **Plugins** page. Each key is a package name, and each value is a requirement in the shape of Cargo's `[dependencies]`:
+
+```toml
+[plugins]
+"@prismshadow/penguin-plugin-sandbox-bwrap" = "*"
+"@scope/name" = "1.2.3"
+"@scope/other" = { version = "1.2" }
+```
+
+- `"*"` asks for whatever version the deployment ships. A version string and the `{ version = "…" }` form are kept as the requirement; loading currently goes by the package name alone.
+- The server runs the union of every Project's table, so a plugin one Project asks for is loaded for all of them.
+- An entry of any other shape is dropped when the file is read, and the rest of the file still loads. A `plugins` key that is not a table asks for no plugins.
+- An empty table is written as an empty table: the Project asks for no plugins.
+
+## Command policy
+
+The `[command_policy]` block is the Project's guardrail for shell commands: a list of deny rules applied at the approval boundary itself.
+
+| Key | Type | Default | Description |
+| --- | --- | --- | --- |
+| `enabled` | boolean | On | Master switch; stored only as `enabled = false` |
+| `[[command_policy.rules]]` | array of tables | The factory set | The deny rules, matched in order. A stored empty list means no rules; an absent list means the factory set |
+
+Each rule has these keys:
+
+| Key | Type | Default | Description |
+| --- | --- | --- | --- |
+| `name` | string | — | Identifies the rule in the settings UI |
+| `pattern` | string | — | JavaScript regex source, matched against the whitespace-normalized command |
+| `description` | string | — | Optional description |
+| `enabled` | boolean | On | Per-rule switch |
```toml
[command_policy]
@@ -131,53 +206,112 @@ pattern = "git push [^;|&]*--force"
enabled = false
```
-This is an **accident guardrail, not a security boundary**, and that is a statement about what pattern matching can do rather than modesty about this implementation. Shell is a programming language; deciding what a program will do by reading its text before it runs is not a problem more rules get closer to solving. So the policy covers the spellings people and models actually type, and stops there:
+Manage the policy on the **Security policy** tab of **Project settings** in the Web App. Only the Project owner can edit it; members see the effective policy.
+
+### Enforcement
+
+- **What it checks:** both tools that reach a shell: `exec_command`'s `cmd` (the launch) and `input_command`'s `chars` (what gets typed into a running command).
+- **When it applies:** `Session.run` wraps the injected approval callback with the policy, so a hit is rejected before the host is asked, under every approval mode, allow-all included.
+- **What the model sees:** the fixed line `Tool call denied by policy.`, distinct from a person's cancellation, so the model changes course.
+- **Hooks:** the policy outranks a [pre-tool-use hook's](/agent-loop#pre-tool-use-hooks) `allow`. A vetoed call stays forbidden whatever an installed hook answers.
+- **Where it lives:** in the Project config, not in Agent State, so an agent that edits its own configuration through its settings cannot reach it.
+- **When edits apply:** the policy is a strict-tier runtime parameter, read once when a model context opens. An edit reaches a running Session at its next rotation (compaction) and new conversations at once.
+
+### Factory rules
+
+The rules are **plain data with no special tiers**. The factory set is seeded into each new Project exactly like the model presets: copied in at creation and never rewritten afterward. Every rule can then be edited, disabled or deleted, and you can add your own. A Project created before the seeding (no stored `rules` list) behaves as the factory set until its first saved edit writes the list. On the settings page, **Restore defaults** loads the factory set back into the editor, and saving writes it.
+
+The factory set is deliberately small. It covers commands whose verbatim execution is destructive with no undo:
-- **A command computed at run time is not covered and will not be.** `$IFS` in place of spaces, a variable or alias (`X=rm; $X -rf /`), a command substitution, `eval`, base64 piped into a shell, `python -c`, an interpreter reached through a pipe. Each would take a pattern that costs maintenance forever and buys only the appearance of coverage. Anyone who wants the command to run can get it to run.
-- **MCP tools are a different surface.** This policy reads `exec_command` and `input_command` only. An MCP server's own `permission` level is the knob that exists there, but read what it does before relying on it: it fixes the level its tools report to the approval mode and nothing else — it does not sandbox the server or restrict what its tools do when they run (see [Tools & Approval](/tools)). Extending a shell-text matcher into arbitrary MCP arguments would be a second, weaker control over a surface that needs a real one.
-- **Commands not on the list.** `shred`, `wipefs`, `find -delete`, `git clean -xfd`, `chmod -R 000 /` match no factory rule — the list is deliberately small. Add your own rules for what your project cares about.
+- `rm` with both a recursive and a force flag
+- `mkfs`
+- `dd` writing straight to a block device
+- the classic fork bomb
+- shell redirection onto a block device (`/dev/null` and friends stay allowed)
-What it does buy is that a destructive one-liner does not run by accident, in either of the two ways a model reaches a shell, in either the POSIX or the Windows spelling, under any approval mode. That is a speed bump, and a speed bump is worth having in front of an irreversible command. For an actual boundary — a process that *cannot* reach the rest of the filesystem regardless of what it runs — the mechanism is confinement (bubblewrap, dsh), which is a separate layer this policy complements rather than replaces.
+Four more rules cover the same ground in Windows spellings, since `exec_command` can resolve pwsh or cmd there:
-Manage it from the Security policy tab of Project Settings in the Web App (owner-only to edit; members see the effective policy).
+- a recursive force delete (`Remove-Item -Recurse -Force`, `rd /s /q`)
+- a volume format (`format C:`, `Format-Volume`)
+- a raw disk overwrite (`\\.\PhysicalDriveN`, `Clear-Disk`)
+- the cmd fork bomb
+
+### Matching
+
+Before the rules run, matching normalizes ordinary spellings so that plain typing does not slip through by accident. All of these match:
+
+- a leading path (`/bin/rm`)
+- a wrapper (`sudo`, `env`, `command`, `nice`, `xargs`)
+- quoting or a backslash escape of the command word (`"rm"`, `r''m`, `\rm`)
+- a literal `sh -c 'rm -rf /'` payload
+
+Normalization only removes quote marks. Nothing is expanded, substituted or decoded.
+
+### What the policy does not cover
+
+The command policy is an **accident guardrail, not a security boundary**. This is a statement about what pattern matching can do, not modesty about this implementation. Shell is a programming language, and more rules do not get closer to deciding what a program will do by reading its text before it runs. The policy covers the spellings people and models actually type, and stops there:
+
+- **Commands computed at run time are not covered and will not be.** Examples: `$IFS` in place of spaces, a variable or alias (`X=rm; $X -rf /`), a command substitution, `eval`, base64 piped into a shell, `python -c`, an interpreter reached through a pipe. Each would need a pattern that costs maintenance forever and buys only the appearance of coverage. Anyone who wants the command to run can get it to run.
+- **MCP tools are a different surface.** The policy reads `exec_command` and `input_command` only. An MCP server's own `permission` level is the setting that exists there, but it only fixes the level the server's tools report to the approval mode. It does not sandbox the server or restrict what its tools do when they run (see [Tools & Approval](/tools)). Extending a shell-text matcher to arbitrary MCP arguments would add a second, weaker control to a surface that needs a real one.
+- **Commands not on the list are not covered.** `shred`, `wipefs`, `find -delete`, `git clean -xfd` and `chmod -R 000 /` match no factory rule. Add your own rules for what your Project cares about.
+- **It is not a filesystem permission.** A tool that writes arbitrary paths can still rewrite the config file itself, and the change takes effect at the next rotation.
+
+What the policy does buy: a destructive one-liner does not run by accident, through either tool that reaches a shell, in POSIX or Windows spelling, under any approval mode. That is a speed bump, and a speed bump is worth having in front of an irreversible command. For an actual boundary, a process that cannot reach the rest of the filesystem whatever it runs, the mechanism is confinement (bubblewrap, dsh), a separate layer this policy complements rather than replaces.
## Agent config
-`agent_state/system_config.yaml` defines a single Agent's behavior (YAML; comments are preserved when edited via the Web UI):
+`agent_state/system_config.yaml` defines one agent's behavior. It is YAML, and comments are preserved when you edit it in the Web App.
| Field | Default | Description |
| --- | --- | --- |
-| `name` | — | Agent display name (falls back to the id) |
+| `name` | — | Agent display name; falls back to the id |
| `description` | — | Agent description |
| `version` | `1` | Agent State version (a natural number), incremented on each successful optimization |
-| `kernel_version` | current kernel version | Config kernel version (a date string): which generation of the built-in defaults this config is based on, stamped at creation, restore-defaults and kernel update; unrelated to `version`, never changed by user edits; missing = predates the mechanism (i.e. outdated) |
-| `system_prompt` | built-in template | Required; the only template with placeholder substitution |
-| `max_turns` | `-1` | Maximum LLM turns per Task (`-1` = unlimited; a positive integer caps the Task) |
-| `model.max_tokens` | `32000` | Output Token ceiling per Request (-1 = no cap, provider default); each request clamps the effective value to the model's `context_window` minus the estimated input, so a small-window model never gets asked for more than fits |
-| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`; the level each model context opens at unless the Session pins one — fixed for the context, so a change lands at the next compaction |
-| `model.timeoutMs` | `300000` | **Idle** budget for a Request (milliseconds): the longest wait for the next upstream event, reset by every event — not a cap on the request's total duration. It bounds the connect + first-event wait and the gaps between events; a model that keeps its reasoning off the wire spends its whole thinking phase inside that first gap, which is what the default leaves room for |
-| `compaction.max_context_length` | `256000` | Context Token threshold that triggers compaction; the effective threshold is the smaller of this and the model's `context_window` − 2048, so a small-window model compacts inside its window while a window above 258048 fires at this number (an entry with no `context_window` assumes a 128000 window) |
-| `compaction.max_session_turns` | `-1` | Cumulative Session turn threshold (`-1` = unlimited) |
+| `kernel_version` | The current kernel version | Which generation of the built-in defaults the config is based on (a date string) |
+| `system_prompt` | Built-in template | Required; the only template with placeholder substitution |
+| `max_turns` | `-1` | Maximum LLM turns per Task |
+| `model.max_tokens` | `32000` | Output Token ceiling per Request |
+| `model.thinking_level` | `medium` | The thinking level each model context opens at, unless the Session pins one |
+| `model.timeoutMs` | `300000` | **Idle** budget for a Request, in milliseconds |
+| `compaction.max_context_length` | `256000` | Context Token threshold that triggers compaction |
+| `compaction.max_session_turns` | `-1` | Cumulative Session turn threshold |
| `compaction.mode` | `summarize` | `summarize` / `discard` |
-| `compaction.prompt` | built-in template | Prompt used for summarize compaction |
-
-The four `compaction.*` fields are the one part of this file a running conversation does not have to wait for: the engine re-reads the section at every compaction checkpoint (after each request reports its token usage, and on a manual `/compact`), so a saved change applies to Sessions already running. Everything else here is read when a model context opens and lands at the next compaction. The Web App can also change the threshold straight from the context panel — drag the dashed cutter on its bar.
+| `compaction.prompt` | Built-in template | Prompt used for summarize compaction |
| `memory.enabled` | `true` | Whether Memory enters the context and Memory directories are prepared |
-| `memory.prompt` | built-in template | Always-injected half of the `{{MEMORY}}` block, editable on the Memory tab — carries `{{USER_MEMORY_INDEX}}` |
-| `memory.workspace_prompt` | built-in template | Appended only in a persistent Workspace, editable on the Memory tab — carries `{{WORKSPACE_MEMORY_INDEX}}` and `{{WORKSPACE_MEMORY_DIR}}` |
-| `vault.enabled` | `true` | Whether the vault section enters the context (with it off, values are still injected into subprocess environments — the model just doesn't see the key-name list) |
-| `vault.prompt` | built-in template | The `{{VAULT}}` block, editable on the Vault tab — carries `{{VAULT_KEYS}}` |
-| `skills.enabled` | `true` | Whether the skills section enters the context (with it off, installed skills remain explicitly invocable via `[use_skills]`) |
-| `skills.prompt` | built-in template | The `{{SKILLS}}` block, editable on the Skills tab — carries `{{SKILL_METADATA}}` |
-| `schedules.enabled` | `true` | Whether the scheduled-tasks section enters the context (with it off, the server still fires tasks — the model just isn't taught the task system) |
-| `schedules.prompt` | built-in template | The `{{SCHEDULES}}` block, editable on the Schedules tab — teaches the model file-based task management, carries `{{SCHEDULE_LIST}}` |
-| `hooks.enabled` | `true` | Whether a new Session runs the installed hook packages at the loop's hook points (with it off the packages stay installed and nothing consults them). The one section with no prompt half: hook packages are scripts, not context text |
-| `tools.builtin` | full default toolset when omitted | Tool entries: `name` / `description` / `parameters` / `permission` (`r` or `rw`) / `forModel` / `timeoutMs` / `maxOutputLength` / `call_description` (per-tool toggle for the `description` call argument, required while on; missing = kept); once written it replaces the default list wholesale |
-| `tools.mcpServers` | `[]` | MCP Server configuration (`name` + `config`): transport is `stdio` / `http` / `sse`, and discovered tools join the toolset as `mcp__<server>__<tool>`; `config.permission` (`auto` / `r` / `rw`, default `auto`) fixes the approval level of every tool of that Server instead of trusting its `readOnlyHint`; see the MCP Servers section of [Tools & Approval](/tools) |
-
-Tool permissions and approval semantics are covered in [Tools & Approval](/tools).
-
-A partial-override example (edit the file the init step generated). Note that this file is **not deep-merged with the defaults**: a key you write out takes effect wholesale, and only omitted keys fall back to the defaults above at their use sites; `system_prompt` is required (loading refuses without it), so keep the full generated template when editing other fields:
+| `memory.prompt` | Built-in template | The always-injected half of the `{{MEMORY}}` block; carries `{{USER_MEMORY_INDEX}}` |
+| `memory.workspace_prompt` | Built-in template | Appended only in a persistent Workspace; carries `{{WORKSPACE_MEMORY_INDEX}}` and `{{WORKSPACE_MEMORY_DIR}}` |
+| `vault.enabled` | `true` | Whether the Vault section enters the context |
+| `vault.prompt` | Built-in template | The `{{VAULT}}` block; carries `{{VAULT_KEYS}}` |
+| `skills.enabled` | `true` | Whether the Skills section enters the context |
+| `skills.prompt` | Built-in template | The `{{SKILLS}}` block; carries `{{SKILL_METADATA}}` |
+| `schedules.enabled` | `true` | Whether the scheduled-tasks section enters the context |
+| `schedules.prompt` | Built-in template | The `{{SCHEDULES}}` block, which teaches file-based task management; carries `{{SCHEDULE_LIST}}` |
+| `hooks.enabled` | `true` | Whether a new Session runs the installed hook packages at the loop's hook points |
+| `tools.builtin` | The full default toolset when omitted | Tool entries; once written, replaces the default list wholesale |
+| `tools.mcpServers` | `[]` | MCP Server configuration (`name` + `config`) |
+
+### Field details
+
+- `kernel_version`: stamped at creation, when defaults are restored and at a kernel update. It is unrelated to `version` and never changed by your edits. A missing value means the config predates the mechanism, which counts as outdated.
+- `max_turns`: `-1` means unlimited; a positive integer caps the Task.
+- `model.max_tokens`: `-1` means no cap (the provider default). Each request clamps the effective value to the model's `context_window` minus the estimated input, so a small-window model is never asked for more than fits.
+- `model.thinking_level`: `none` / `low` / `medium` / `high` / `xhigh` / `max`. The level is fixed for a model context, so a change lands at the next compaction. Without this field, the Project's `[default_chat]` `thinking_level` applies, then `medium`.
+- `model.timeoutMs`: the longest wait for the next upstream event, reset by every event. It is not a cap on the request's total duration. It bounds the wait to connect and receive the first event, and the gaps between events. A model that keeps its reasoning off the wire spends its whole thinking phase inside that first gap, which the default leaves room for.
+- `compaction.max_context_length`: the effective threshold is the smaller of this value and the model's `context_window` − 2048. A small-window model therefore compacts inside its window, while a window above 258048 fires at this number. An entry with no `context_window` assumes a 128000 window.
+- `compaction.max_session_turns`: `-1` means unlimited.
+- `*.prompt`: each section prompt is editable on its settings tab: both Memory prompts on **Memory**, `vault.prompt` on **Vault**, `skills.prompt` on **Skills**, and `schedules.prompt` on **Schedules**.
+- `vault.enabled`: when off, values are still injected into subprocess environments; the model just does not see the key-name list.
+- `skills.enabled`: when off, installed Skills can still be invoked explicitly with `[use_skills]`.
+- `schedules.enabled`: when off, the server still fires tasks; the model just is not taught the task system.
+- `hooks.enabled`: the one section with no prompt half, because hook packages are scripts, not context text. When off, the packages stay installed and nothing consults them.
+- `tools.builtin`: each entry has `name` / `description` / `parameters` / `permission` (`r` or `rw`) / `forModel` / `timeoutMs` / `maxOutputLength` / `call_description`. `call_description` is the per-tool switch for the `description` call argument, which is required while on; missing means kept.
+- `tools.mcpServers`: the transport is `stdio`, `http` or `sse`, and discovered tools join the toolset as `mcp__<server>__<tool>`. `config.permission` (`auto` / `r` / `rw`, default `auto`) fixes the approval level of every tool of that server instead of trusting its `readOnlyHint`. See [MCP Servers](/tools#mcp-servers).
+
+The four `compaction.*` fields are the one part of this file a running conversation does not wait for. The engine re-reads the section at every compaction checkpoint (after each request reports its token usage, and on a manual `/compact`), so a saved change applies to Sessions already running. Everything else is read when a model context opens and lands at the next compaction. In the Web App you can also [change the threshold](/chat#change-the-compaction-threshold) from the context panel by dragging the dashed cutter on its bar.
+
+For tool permissions and approval semantics, see [Tools & Approval](/tools).
+
+This file is **not deep-merged with the defaults**. A key you write out takes effect wholesale, and only omitted keys fall back to the defaults above where they are used. `system_prompt` is required and loading refuses a file without it, so keep the full generated template when you edit other fields. A partial-override example, edited from the file the init step generated:
```yaml
name: default_agent
@@ -206,29 +340,42 @@ compaction:
# parameters JSON Schema) for every tool you keep — see Tools & Approval.
```
-An existing Agent always runs with its on-disk config verbatim — newer code defaults are never merged in automatically. When the built-in defaults change substantively, the config's `kernel_version` falls behind the current kernel and the settings page and agents list show an update hint. Two paths adopt the current defaults (side by side on the settings overview):
+### Kernel updates
+
+An existing agent always runs with its on-disk config as written; newer code defaults are never merged in automatically. When the built-in defaults change substantively, the config's `kernel_version` falls behind the current kernel, and the settings page and the agents list show an update hint. Two actions on the settings overview adopt the current defaults.
+
+**Update kernel** is a lossless merge, done one settings tab at a time (**System Prompt**, **Runtime**, **Tools**, **Skills**, **Memory**, **Vault**, **Schedules**):
+
+- A tab the config lacks entirely, or one whose hash still matches a *recorded* generation's built-in default, is rewritten from the current defaults. This is also how tools added by a later version reach an existing agent.
+- A tab you have changed in any way stays unchanged **in full** and is listed in the result. If you edit one built-in tool, the whole **Tools** tab is kept: tools you added and tools you deleted both survive, and that tab stops following new defaults until you restore defaults.
+- `name`, `description`, `version`, `hooks` and `tools.mcpServers` belong to no tab and are never touched.
+- The config is then stamped with the current `kernel_version`.
+- Matching is **conservative**: only a tab whose hash matches a recorded generation counts as an old default. A tab from a generation too old to be recorded is kept as if customized.
-- **Update kernel**: a lossless merge, **one settings tab at a time** (System Prompt, Runtime, Tools, Skills, Memory, Vault, Schedules). A tab the config lacks entirely, or one still hashing to a *recorded* generation's built-in default, is rewritten from the current defaults — that wholesale rewrite is also how tools added by a later version reach an existing Agent. A tab you have changed in any way stays unchanged **in full** and is listed in the result: edit one built-in tool and the entire Tools tab is kept, so tools you added and tools you deleted both survive, and the rest of that tab stops following new defaults until you restore defaults. `name`, `description`, `version` and `tools.mcpServers` belong to no tab and are never touched. The config is then stamped with the current `kernel_version`. Matching is **conservative**: only a tab whose hash hits a recorded generation counts as an old default — a tab from a generation too old to be recorded is kept as if customized.
-- **Restore default configuration**: like a skill update, overwrites the existing configuration with the current defaults — custom system prompt, tool list, model/compaction settings and MCP Servers — keeping only `name`, `description` and `version`. The full-refresh fallback when the kernel update's conservative matching leaves fields behind.
+**Restore default configuration** works like a Skill update: it overwrites the configuration with the current defaults and keeps only `name`, `description` and `version`. Everything else is replaced, including a custom system prompt, the tool list, the model and compaction settings, and MCP Servers. Use it as the full refresh when the kernel update's conservative matching leaves fields behind.
-For developers: `kernel_version` advances manually, and only on a substantive change to the built-in defaults (using that day's date). The pinned-hash test in CI (`core/test/kernel-version.test.ts`) recomputes every tab hash against `KERNEL_DEFAULT_TAB_HASHES` in `kernel-history.ts` and fails on drift, naming each tab that moved and the edit it needs: bump `KERNEL_VERSION`, append the tab's previous hash to `KERNEL_SUPERSEDED_TAB_HASHES`, and write the recomputed hash in. Several changes on the same day may reuse that day's version. The superseded hashes are frozen forever — they are what identifies "still the old default".
+For developers:
+
+- `kernel_version` advances manually, and only on a substantive change to the built-in defaults, using that day's date. Several changes on the same day may reuse that day's version.
+- The pinned-hash test in CI (`core/test/kernel-version.test.ts`) recomputes every tab hash against `KERNEL_DEFAULT_TAB_HASHES` in `kernel-history.ts`. On drift it fails and names each tab that moved and the edit it needs: bump `KERNEL_VERSION`, append the tab's previous hash to `KERNEL_SUPERSEDED_TAB_HASHES`, and write in the recomputed hash.
+- The superseded hashes are frozen forever: they are what identifies a tab that is still the old default.
### System prompt placeholders
-`system_prompt` is the only template with placeholder substitution. Available placeholders:
+`system_prompt` is the only template with placeholder substitution. The available placeholders:
| Placeholder | Injected content |
| --- | --- |
| `{{AGENTS_MD}}` | Full text of `AGENTS.md` |
-| `{{VAULT}}` | The rendered `vault.prompt` block (the vault section); empty when `vault.enabled` is off. A template without it injects no vault section — the Vault tab offers inserting/migrating it explicitly |
-| `{{SKILLS}}` | The rendered `skills.prompt` block (the skills section); empty when `skills.enabled` is off. A template without it injects no skills section — the Skills tab offers inserting/migrating it explicitly |
-| `{{MEMORY}}` | The rendered `memory.prompt` block, plus `memory.workspace_prompt` in a persistent Workspace; empty when Memory is off. A template without it injects no Memory — the Memory tab offers inserting it explicitly |
-| `{{SCHEDULES}}` | The rendered `schedules.prompt` block (the scheduled-tasks section); empty when `schedules.enabled` is off. A template without it injects no schedules section — the Schedules tab offers inserting it explicitly |
-| `{{VAULT_KEYS}}` | Inside `vault.prompt`: the Vault key-name list (names only, one `- KEY` line per key). For legacy templates, an occurrence directly in the template body is still substituted, honoring `vault.enabled` the same way |
-| `{{SKILL_METADATA}}` | Inside `skills.prompt`: the installed Skills' metadata lines. For legacy templates, an occurrence directly in the template body is still substituted, honoring `skills.enabled` the same way |
+| `{{VAULT}}` | The rendered `vault.prompt` block (the Vault section); empty when `vault.enabled` is off |
+| `{{SKILLS}}` | The rendered `skills.prompt` block (the Skills section); empty when `skills.enabled` is off |
+| `{{MEMORY}}` | The rendered `memory.prompt` block, plus `memory.workspace_prompt` in a persistent Workspace; empty when Memory is off |
+| `{{SCHEDULES}}` | The rendered `schedules.prompt` block (the scheduled-tasks section); empty when `schedules.enabled` is off |
+| `{{VAULT_KEYS}}` | Inside `vault.prompt`: the Vault key-name list (names only, one `- KEY` line per key) |
+| `{{SKILL_METADATA}}` | Inside `skills.prompt`: the installed Skills' metadata lines |
| `{{SCHEDULE_LIST}}` | Inside `schedules.prompt`: the current task-name list (one `- name` line per task; an empty-roster note when none exist) |
-| `{{USER_MEMORY_INDEX}}` | Inside the Memory prompts: content of the user scope's `MEMORY.md` index (at most 200 lines and 25,000 characters total) |
-| `{{WORKSPACE_MEMORY_INDEX}}` | Inside `memory.workspace_prompt` only: content of the Workspace scope's `MEMORY.md` index (at most 200 lines and 25,000 characters total) |
+| `{{USER_MEMORY_INDEX}}` | Inside the Memory prompts: the user scope's `MEMORY.md` index (at most 200 lines and 25,000 characters total) |
+| `{{WORKSPACE_MEMORY_INDEX}}` | Inside `memory.workspace_prompt` only: the Workspace scope's `MEMORY.md` index (at most 200 lines and 25,000 characters total) |
| `{{WORKSPACE_MEMORY_DIR}}` | Inside `memory.workspace_prompt` only: absolute path of the current Workspace's Memory directory |
| `{{PLATFORM}}` | Runtime platform |
| `{{OS_VERSION}}` | Operating system version |
@@ -240,26 +387,24 @@ For developers: `kernel_version` advances manually, and only on a substantive ch
| `{{MODEL_ID}}` | Upstream model id |
| `{{SESSION_ID}}` | Session id |
-`{{PROJECT_DIR}}` is surfaced to the model as the **App Data Dir**: PenguinHarness's application data root, holding every Agent's data files (`agents/<agent_id>/…`) and the project-level data — deliberately not described as a project or task directory, so the model does not mistake it for the task's working directory (`CWD`).
+**Section placeholders.** The Vault, Skills, Memory and Schedules sections share one pattern: a placeholder, a switch and an editable prompt. The template holds only the `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` placeholder, the section text lives in the matching `*.prompt` key (edited on its settings tab), and turning `*.enabled` off empties the whole block. A template without one of these placeholders injects no such section; the matching settings tab offers to insert the placeholder explicitly, or to migrate a legacy template. The four section placeholders are expanded last, in a single pass at assembly time. Expanded text is never rescanned, so placeholder-looking text inside a memory index or a section prompt stays literal.
-On Windows, `{{PROJECT_DIR}}` and `{{CWD}}` are injected with forward slashes — like every other path core composes for the model (attachment lines, the goal-file line, truncated-output recovery paths). The model re-emits these spellings into JSON tool arguments and shell commands; forward slashes are accepted by Node's fs APIs and the package's (Git) Bash tool shell, and avoid JSON backslash-escaping mistakes.
+**App Data Dir.** `{{PROJECT_DIR}}` is shown to the model as the **App Data Dir**: PenguinHarness's application data root, which holds every agent's data files (`agents/<agent_id>/…`) and the Project-level data. It is deliberately not described as a project or task directory, so the model does not mistake it for the task's working directory (`CWD`).
-`agent_state/AGENTS.md` is the developer-editable instruction file, injected via `{{AGENTS_MD}}` and empty by default — it is also the file an optimizer edits most (see [Self-Improvement](/self-improvement)). Like the rest of the Agent State — `system_config.yaml` included — it is read whenever a model context opens: at Session creation and again when a compaction opens the next context. An edit therefore takes effect at the next compaction of a running Session, not only in new Sessions, and never inside the context that is running (the `compaction` section is the exception — see [Compaction](/agent-loop)).
+**Windows paths.** On Windows, `{{PROJECT_DIR}}` and `{{CWD}}` are injected with forward slashes, like every other path core composes for the model (attachment lines, the goal-file line, truncated-output recovery paths). The model copies these spellings into JSON tool arguments and shell commands. Node's fs APIs and the package's (Git) Bash tool shell accept forward slashes, and they avoid JSON backslash-escaping mistakes.
-The Vault / Skills / Memory / Schedules sections all follow the same placeholder + toggle + editable prompt pattern: the template holds only the `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` placeholders, the section text lives in the corresponding `*.prompt` config (edited on its settings tab), and turning `*.enabled` off empties the whole block. The four section placeholders are expanded **last, in a single pass** at assembly time: expansion products are never rescanned, so placeholder-looking text inside a memory index or a section prompt stays literal instead of triggering a second substitution.
+**AGENTS.md.** `agent_state/AGENTS.md` is the developer-editable instruction file, injected through `{{AGENTS_MD}}` and empty by default. It is also the file an optimizer edits most; see [Self-Improvement](/self-improvement). Like the rest of the Agent State, `system_config.yaml` included, it is read whenever a model context opens: at Session creation, and again when a compaction opens the next context. An edit therefore takes effect at the next compaction of a running Session, not only in new Sessions, and never inside the running context. The `compaction` section is the exception; see [Compaction](/agent-loop).
-**Legacy templates**: `system_config.yaml` is materialized at Agent creation and never auto-upgraded, so an Agent created before this mechanism carries hardcoded `# Vault` / `# Skills` section text with inline `{{VAULT_KEYS}}` / `{{SKILL_METADATA}}` in its template. Such templates keep working: the inline placeholders are still substituted, and now honor the new toggles (an off switch substitutes an empty string). The matching tab reports the legacy template and offers one-click migration — replacing the old default section verbatim, in place, with the new placeholder, leaving the assembled prompt unchanged; a template whose section text was customized doesn't match the verbatim migration and is treated as missing the placeholder instead, with a one-click insert (before `# Environment`).
+**Legacy templates.** `system_config.yaml` is written at agent creation and never upgraded automatically. An agent created before the section placeholders carries hardcoded `# Vault` / `# Skills` section text with inline `{{VAULT_KEYS}}` / `{{SKILL_METADATA}}` in its template. Such templates keep working: the inline placeholders are still substituted and honor the section switches (an off switch substitutes an empty string). The matching tab reports the legacy template and offers one-click migration, which replaces the old default section text verbatim, in place, with the new placeholder and leaves the assembled prompt unchanged. If the section text was customized, verbatim migration does not match; the template is treated as missing the placeholder, with a one-click insert before `# Environment`.
## Memory
-`agent_state/memory/` is what the Agent remembers between Sessions: user feedback, project decisions, working conventions and entry points into external systems — the things that cannot be re-derived from the Workspace or its code history. It is not context compaction, which preserves one Session's short-term state.
-
-Memory has two scopes, both belonging to one Agent and never shared with another:
+`agent_state/memory/` holds what the agent remembers between Sessions: user feedback, project decisions, working conventions and entry points into external systems, the things that cannot be re-derived from the Workspace or its code history. It is not context compaction, which preserves one Session's short-term state.
-- **User scope** (`memory/user/`) — what stays true wherever the Agent works: who the user is, their standing preferences, reference material not tied to one codebase. Every Session reads it, including one running in a temporary Workspace, which has no other place to write.
-- **Workspace scope** (`memory/<workspace_memory_key>/`) — facts about one Workspace. Sessions of one Agent in one Workspace share it; different Workspaces keep their topic files apart.
+Memory has two scopes. Both belong to one agent and are never shared with another agent:
-Each scope carries its own `MEMORY.md` index, and different Agents never share Memory even in the same Workspace. Because Memory lives in Agent State it travels with export / import and snapshots, and every Project member who can reach the Agent can read it — so credentials and sensitive personal data never belong in it.
+- **User scope** (`memory/user/`): what stays true wherever the agent works, such as who the user is, their standing preferences, and reference material not tied to one codebase. Every Session reads it, including one running in a temporary Workspace, which has no other place to write.
+- **Workspace scope** (`memory/<workspace_memory_key>/`): facts about one Workspace. Sessions of the same agent in the same Workspace share it; different Workspaces keep their topic files apart.
```text
agent_state/memory/
@@ -272,11 +417,24 @@ agent_state/memory/
└── testing-conventions.md
```
-`user` is a reserved directory name, safe because every generated workspace memory key is `<base>-<8 hex>` and therefore always carries a hyphen — a hyphen-free name can never be produced.
+Each scope has its own `MEMORY.md` index, and different agents never share Memory, even in the same Workspace. Because Memory lives in Agent State, it travels with export, import and snapshots.
+
+> [!WARNING]
+> Every Project member who can reach the agent can read its Memory. Keep credentials and sensitive personal data out of it.
-The workspace memory key is `<safe-basename>-<8 hex of the real path's sha256>`. Identity is the directory itself and has nothing to do with Git: two symlinks to one directory resolve to one key, while moving or renaming a directory makes it a new Workspace (the old Memory stays on disk under the old key). A temporary Workspace — one PenguinHarness allocated under `agents/<agent_id>/workspaces/` — gets no Workspace scope at all, a subagent inheriting one included: a temporary Workspace is allocated per Session, so no later Session would ever run there to read it back. Such a Session still gets the user scope, which is where anything it learns belongs anyway.
+To read or delete memories, or to ask the agent to edit them, use the **Memory** tab of the [agent settings](/agents).
-A topic file is a semantic subject, not one per Task, Session or date, and carries frontmatter:
+### Workspace memory keys
+
+A workspace memory key is `<safe-basename>-<8 hex of the real path's sha256>`.
+
+- `user` is a reserved directory name. It is safe because every generated key has the form `<base>-<8 hex>` and so always contains a hyphen.
+- Identity is the directory itself and has nothing to do with Git. Two symlinks to one directory resolve to one key, while moving or renaming a directory makes it a new Workspace; the old Memory stays on disk under the old key.
+- A temporary Workspace, one PenguinHarness allocated under `agents/<agent_id>/workspaces/`, gets no Workspace scope at all, including when a subagent inherits it. A temporary Workspace is allocated per Session, so no later Session would ever run there to read it back. Such a Session still gets the user scope, which is where anything it learns belongs anyway.
+
+### Topic files
+
+Each topic file holds one fact or subject, not one file per Task, Session or date, and carries frontmatter:
```markdown
---
@@ -288,44 +446,72 @@ updated_at: 2026-08-07
- Integration tests connect to a real database; no mock repositories.
```
-These three fields are all the frontmatter there is — which layer a memory belongs to is expressed by its directory, so there is no `type` field (a `type:` line left in an earlier file is ignored as an unknown field). Worth saving: who the user is (role, expertise, standing preferences) and how they want the Agent to work, with the why; decisions, constraints and plans not derivable from the code; stable entry points into external systems, documents and services. The prompt also names the moments that produce such a fact — a request made a second time, a correction that holds beyond the current task, a habit or development practice stated more than once, or a reusable working detail handed over that the Agent would otherwise ask for again. A repeat is a strong signal rather than a condition, so one clear statement of a standing preference is enough; when the Agent cannot tell whether something is worth keeping, it asks in the conversation. A topic that turns out to be wrong is deleted together with its index line, and dates are written absolute (`YYYY-MM-DD`) — relative ones mean nothing to a later Session. What must never be saved: facts the code, config or Git history already states; short-lived task progress and debugging notes; credentials, tokens or secrets; unconfirmed guesses; long transcript excerpts.
+These three fields are all the frontmatter there is. The directory says which scope a memory belongs to, so there is no `type` field; a `type:` line left in an earlier file is ignored as an unknown field.
+
+The default Memory prompt tells the model what to save:
+
+- who the user is and how they want the agent to work, with the reason
+- goals, decisions and constraints that cannot be derived from the code
+- pointers to external systems, documents and resources
+
+It also names the moments that produce such a fact: a request made a second time, a correction that holds beyond the current task, a habit or practice stated more than once, or a reusable working detail the agent would otherwise ask for again. A repeat only makes a fact obvious; one clear statement of a standing preference is enough. When the agent cannot tell whether something is worth keeping, it asks in the conversation.
+
+The prompt rules out:
-Each `MEMORY.md` lists its scope's memories one line each — `- [Title](file.md) — hook`, links relative to the scope directory — and is updated in the same round as the file, so the two never disagree.
+- facts the code, config or Git history already states
+- unconfirmed guesses
+- transcript excerpts (asked to save one anyway, the agent saves the non-obvious part)
-Only the indexes reach the context, through the template's `{{MEMORY}}` placeholder. It expands to `memory.prompt` — what Memory is for, the save mechanics, then a `## User memory` section with its index (`{{USER_MEMORY_INDEX}}`) — plus `memory.workspace_prompt`, a `## Workspace memory` section with `{{WORKSPACE_MEMORY_INDEX}}`, when the Session runs in a persistent Workspace. Both prompts are per-Agent config, editable on the settings page's Memory tab, and organized by Markdown headings like the template's other sections. The `User Memory Dir` line is the literal pattern `<app_data_dir>/agents/<agent_id>/agent_state/memory/user`, resolvable from the Environment section; the `Workspace Memory Dir` line renders resolved via `{{WORKSPACE_MEMORY_DIR}}`, because its final segment — the workspace memory key — is a path hash the model could never compose itself.
+Anything else can be saved if the user wants it. For corrections and decisions, the model adds **Why:** and **How to apply:** lines. A memory that proves wrong is deleted together with its index line. Dates are written absolute (`YYYY-MM-DD`), because relative dates mean nothing to a later Session.
-A blank index injects an explicit "nothing saved yet" note. Injection is capped at 200 lines per scope (one memory per line by convention), then at 25,000 characters total as a backstop for indexes whose few lines are enormous — past a cap a truncation note tells the model to open the full `MEMORY.md` itself, and the file on disk is never touched. The default Memory prompt declares the line cap and asks for index lines under ~150 characters, so the model keeps the index short before ever hitting the caps; the character backstop lives only in code. Topic bodies are read on demand by the model.
+### Injection
-The two halves are separate config keys because substitution has no conditionals: a temporary Workspace must never be handed the Workspace section (its directory line and the scope-choice rule), so that half is simply not appended there. The Harness only decides where Memory lives and keeps writes inside it — deciding what is worth keeping, splitting topics and maintaining the indexes is the model's job, done with the ordinary file tools.
+Only the indexes reach the context, through the template's `{{MEMORY}}` placeholder. Each `MEMORY.md` lists its scope's memories one per line, as `- [Title](file.md) — hook` with links relative to the scope directory. The model updates the index together with the file, deletions included, so the two never disagree.
-A template without `{{MEMORY}}` injects no Memory — an Agent created before Memory shipped, for instance. The Memory tab reports this and offers inserting the placeholder (before `# Environment`, the position the default template gives it) as an explicit one-click action; nothing is ever spliced in automatically. The assembled prompt is recorded in `session_meta`.
+`{{MEMORY}}` expands to:
-To read, delete or ask the Agent to edit what it has saved, use the settings page's [Memory tab](/web-app#agent-settings-agents).
+- `memory.prompt`: what Memory is for and how to save, then a `## User memory` section with its index (`{{USER_MEMORY_INDEX}}`).
+- `memory.workspace_prompt`, only when the Session runs in a persistent Workspace: a `## Workspace memory` section with `{{WORKSPACE_MEMORY_INDEX}}`.
+
+Both prompts are per-agent config, editable on the **Memory** tab, and organized by Markdown headings like the template's other sections. The `User Memory Dir` line is the literal pattern `<app_data_dir>/agents/<agent_id>/agent_state/memory/user`, which the model resolves from the Environment section. The `Workspace Memory Dir` line is rendered already resolved through `{{WORKSPACE_MEMORY_DIR}}`, because its final segment, the workspace memory key, is a path hash the model could not compose itself.
+
+Limits:
+
+- A blank index injects an explicit "nothing saved yet" note.
+- Injection is capped at 200 lines per scope (one memory per line by convention), then at 25,000 characters total as a backstop for an index with a few enormous lines. Past a cap, a truncation note tells the model to open the full `MEMORY.md` itself. The file on disk is never touched.
+- The default Memory prompt states the line cap and asks for index lines under about 150 characters, so the model keeps the index short before it reaches the caps. The character backstop exists only in code.
+- The model reads topic bodies on demand.
+
+The two halves are separate config keys because substitution has no conditionals. A temporary Workspace must never receive the Workspace section (its directory line and the rule for choosing a scope), so that half is simply not appended there. The harness only decides where Memory lives and keeps writes inside it. Deciding what is worth keeping, splitting topics and maintaining the indexes is the model's job, done with the ordinary file tools.
+
+A template without `{{MEMORY}}` injects no Memory; an agent created before Memory shipped is one example. The **Memory** tab reports this and offers to insert the placeholder before `# Environment`, where the default template has it, as an explicit one-click action. Nothing is ever spliced in automatically. The assembled prompt is recorded in `session_meta`.
## Vault
-`agent_state/.vault.toml` is the Agent-level environment-variable vault: a hidden file written with mode 0600.
+`agent_state/.vault.toml` is the agent-level environment-variable vault: a hidden file written with mode 0600.
-- Key names must match `^[A-Za-z_][A-Za-z0-9_]*$` (shell environment variable naming rules);
-- Values are injected only into tool subprocess environments and never enter the model context or the Trace;
-- Only key names are disclosed in the system prompt: the template's `{{VAULT}}` placeholder expands to `vault.prompt` (carrying the `{{VAULT_KEYS}}` key-name list), editable on the Vault tab; with `vault.enabled` off the block is empty — values are still injected into subprocesses, the model just doesn't see the key-name list. A legacy template's inline `{{VAULT_KEYS}}` is still substituted under the same toggle, and the tab offers one-click migration (see "System prompt placeholders");
-- Saving through the Web/API invalidates the Agent's cached Session runtimes: the next Task on any of its Sessions re-resumes and runs with the new values; a Task already in flight keeps the values it started with (a direct CLI file edit reaches a running server only when a Session is next created or resumed);
-- Managed via `penguin config vault set/list/remove` or the Web Vault tab.
+- Key names must match `^[A-Za-z_][A-Za-z0-9_]*$` (shell environment variable naming rules). Values are limited to 8,192 characters.
+- Values are injected only into tool subprocess environments. They never enter the model context or the Trace.
+- Only key names are shown in the system prompt. The template's `{{VAULT}}` placeholder expands to `vault.prompt`, which carries the `{{VAULT_KEYS}}` key-name list and is editable on the **Vault** tab. With `vault.enabled` off the block is empty: values are still injected into subprocesses, and the model just does not see the key names. A legacy template's inline `{{VAULT_KEYS}}` is still substituted under the same switch, and the tab offers one-click migration (see [System prompt placeholders](#system-prompt-placeholders)).
+- A saved change reaches new Sessions at once and a running Session at its next compaction, like any other Agent State change. This is the same whether you save in the Web App, through the API or with the CLI.
+- Manage it with `penguin config vault set/list/remove` or on the **Vault** tab.
## Schedules
-Each file `agent_state/schedule/<name>.toml` describes one scheduled task (the filename is its identity) that sends a preset Prompt to the Agent on a cadence. Schedules execute only while the Web service (the server runtime) is running, and are managed in the Web Agent settings → Schedule tab.
+Each file `agent_state/schedule/<name>.toml` describes one scheduled task, which sends a preset Prompt to the agent on a cadence. The file name is the task's identity. Scheduled tasks run only while the Web service (the server runtime) is running. Manage them on the **Schedules** tab of the agent settings or from the chat page; see [Scheduled tasks](/schedules).
-| Field | Required | Description |
-| --- | --- | --- |
-| `prompt` | yes | The Prompt sent on each trigger |
-| `enabled` | no | Enabled switch; defaults to `false` |
-| `start_at` | yes | First trigger time (ISO 8601) |
-| `period` | no | Cadence such as `30m` / `12h` / `7d`, minimum 5 minutes; omitted means a one-shot task |
-| `end_at` | no | End time; must be later than `start_at` |
-| `session_id` | no | Bind to an existing Session; mutually exclusive with the three fields below |
-| `workspace` | no | Workspace for new-Session mode |
-| `provider` / `model_id` | no | Paired model reference for new-Session mode; write both or neither — a lone `model_id` is rejected, and with neither the Project's default model is used |
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `prompt` | string | Required | The Prompt sent on each trigger |
+| `enabled` | boolean | `false` | Whether the task fires |
+| `start_at` | datetime (ISO 8601) | Required | First trigger time |
+| `period` | string | Omitted: a one-shot task | Cadence such as `30m` / `12h` / `7d`; minimum 5 minutes |
+| `end_at` | datetime (ISO 8601) | — | End time; must be later than `start_at` |
+| `session_id` | string | — | Binds the task to an existing Session; mutually exclusive with the three fields below |
+| `workspace` | string | — | Workspace for new-Session mode |
+| `provider` / `model_id` | string pair | The Project's default model | Paired model reference for new-Session mode |
+
+Write both `provider` and `model_id`, or neither. A lone `model_id` is rejected; with neither, the Project's default model is used.
```toml
prompt = "Check yesterday's builds and summarize the failures"
@@ -334,8 +520,8 @@ start_at = 2026-08-01T09:00:00Z
period = "12h"
```
-The template's `{{SCHEDULES}}` placeholder expands to `schedules.prompt`: it teaches the model to manage these TOML files with its own file tools (the directory, the field rules, the ~30-second automatic pickup, and the hygiene rules against duplicates), ending with the current task-name list via `{{SCHEDULE_LIST}}`. The prompt is editable on the Schedules tab; with `schedules.enabled` off the block is empty — the server still fires tasks on schedule, the model just isn't taught the task system. An Agent created before this mechanism has no such placeholder in its template; the tab offers one-click insertion.
+The template's `{{SCHEDULES}}` placeholder expands to `schedules.prompt`. It teaches the model to manage these TOML files with its own file tools: the directory, the field rules, the automatic pickup within about 30 seconds, and the rules against duplicates. It ends with the current task-name list through `{{SCHEDULE_LIST}}`. The prompt is editable on the **Schedules** tab. With `schedules.enabled` off the block is empty: the server still fires tasks on schedule, and the model just is not taught the task system. An agent created before this mechanism has no such placeholder in its template, and the tab offers a one-click insert.
## Design principle
-An Agent's behavior lives entirely in editable files on disk — prompts, Skills, and configuration are data, not code. That is what makes Agents improvable by Agents: an optimizer edits exactly the same files you edit by hand. See [Self-Improvement](/self-improvement) and the [CLI Reference](/cli).
+An agent's behavior lives entirely in editable files on disk: prompts, Skills and configuration are data, not code. That is what lets agents improve agents: an optimizer edits exactly the files you edit by hand. See [Self-Improvement](/self-improvement) and the [CLI Reference](/cli).
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index cc900280..8fa014a9 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -1,82 +1,122 @@
---
title: 配置参考
-description: 环境变量、Project 配置、Agent 配置、Vault 与定时任务的完整字段参考。
+description: PenguinHarness 的每一项设置及其默认值与限制,从环境变量到 Project、Agent、记忆、密钥保险柜和定时任务文件。
---
-PenguinHarness 的配置分三层:环境变量决定部署形态,Project 配置管理模型与凭证,Agent 配置定义单个 Agent 的行为。此外每个 Agent 还有 Vault(私有环境变量)与 Schedule(定时任务)两类状态文件。
+PenguinHarness 的配置分三层:环境变量决定部署形态,Project 配置管理模型和凭证,Agent 配置定义单个 Agent 的行为。每个 Agent 还有自己的[记忆](#记忆)、[Vault](#vault) 和[定时任务](#定时任务)状态文件。
## 环境变量
-CLI 与服务端启动时会自动加载工作目录下的 `.env` 文件。
+CLI 和服务器启动时会从工作目录加载 `.env` 文件。
-| 变量 | 说明 | 缺省值 |
+| 变量 | 说明 | 默认值 |
| --- | --- | --- |
| `PENGUIN_HOME` | 数据根目录 | `~/.penguin/data` |
| `PORT` | Web 服务监听端口 | `7364` |
| `HOST` | Web 服务监听地址 | `127.0.0.1` |
-| `PENGUIN_WEB_DB` | 服务端 SQLite 数据库路径 | `<root>/web.db` |
-| `PENGUIN_WEB_DIST` | 前端静态资源目录 | npm 安装的服务端包回退到内置 web-dist |
-| `PENGUIN_PREVIEW_ORIGIN` | 提供 Workspace HTML 预览的独立源,如 `https://preview.example.com` | 未设置,按请求推导回环对应名 |
-| `PENGUIN_GO_ORIGIN` | 服务端发起 Penguin Go Key 授权时使用的可信源 | `https://token.penguin.ooo` |
-| `PENGUIN_TRUST_PROXY` | 设为 `1` 信任 `x-forwarded-proto` 请求头——在终结 TLS 的反向代理(且由代理自行设置/清除该头)之后设置,使会话 Cookie 带 `Secure` 标记、热更新网络门禁识别 HTTPS | 未设置,忽略该请求头 |
-| `PENGUIN_SEED_ADMIN_PASSWORD` | 固定内置管理员的种子初始密码(自动化测试 / e2e 使用) | 未设置,种子时随机生成一个密码,哈希后即丢弃、无人见过;账号通过首次登录链接认领 |
+| `PENGUIN_WEB_DB` | 服务器 SQLite 数据库路径 | `<root>/web.db` |
+| `PENGUIN_WEB_DIST` | 前端静态资源目录 | 服务器包自带的 `web-dist`(源码检出中为 `packages/web/dist`) |
+| `PENGUIN_PREVIEW_ORIGIN` | 提供 Workspace HTML 预览的源,例如 `https://preview.example.com` | 未设置:每次请求推导对应的回环地址 |
+| `PENGUIN_GO_ORIGIN` | 服务端发起 Penguin Go Key 授权时调用的可信源 | `https://token.penguin.ooo` |
+| `PENGUIN_TRUST_PROXY` | 设为 `1` 时信任 `x-forwarded-proto` 请求头 | 未设置:忽略请求头 |
+| `PENGUIN_SEED_ADMIN_PASSWORD` | 预置内置管理员的固定初始密码(自动化测试 / e2e) | 未设置:生成随机密码 |
| `PENGUIN_LANG` | CLI 语言(`en` / `zh`),用 `penguin config lang` 设置 | `en` |
-| `PENGUIN_UPDATE_CHECK` | 设为 `off` 关闭 Web 应用的新版本检查 | 开启 |
-| `PENGUIN_NO_LOGIN_SHELL_ENV` | 任意非空值可禁止桌面版在 macOS/Linux 图形界面启动时导入登录 shell 环境变量(见[桌面版速上手](/quickstart-desktop)) | 未设置,导入开启,且只补启动环境中缺失的变量 |
-| `PENGUIN_CLI_ENTRY` | 本安装提供给其所运行 Agent 的 CLI 入口脚本(见下文) | 由 `penguin server` / `penguin web` 与桌面版自动设置;若服务端从仓库检出启动,则回退到该检出的 `packages/cli/dist/penguin.js` |
+| `PENGUIN_UPDATE_CHECK` | 设为 `off` 时关闭 Web App 的新版本检查 | 启用 |
+| `PENGUIN_NO_LOGIN_SHELL_ENV` | 设为任意非空值后,桌面应用在 macOS/Linux 上从图形界面启动时不再导入登录 shell 的环境变量 | 未设置:照常导入 |
+| `PENGUIN_SHELL` | 运行 Agent 命令的 shell(可执行文件名或路径) | 未设置:自动选择,见[工具与审批](/tools#命令会话) |
+| `PENGUIN_CLI_ENTRY` | 本安装提供给所运行 Agent 的 CLI 入口脚本(见 [PATH 启动脚本](#path-启动脚本)) | 由 `penguin server` / `penguin web` 和桌面应用设置 |
-这些变量配置的是 PenguinHarness 自身,因此 `PORT`、`HOST`、`PENGUIN_WEB_DIST` 与 `PENGUIN_CLI_ENTRY` **不会出现在 Agent 所执行命令的环境变量中**——否则 `exec_command` 启动的开发服务器会读到 `PORT`,去占用留给 PenguinHarness 的端口,而不是自己另选一个。宿主环境中的其余变量原样透传,但还有一处例外:`GIT_EDITOR`、`GIT_TERMINAL_PROMPT`、`TERM`、`NO_COLOR`、`PAGER`、`GIT_PAGER` 一律被固定值覆盖,以免命令因等待编辑器、凭证输入或分页器而挂起。Agent 的 [vault](#vault) 覆盖在宿主环境之上——在 vault 里设置 `PORT` 仍然可以送达命令——但覆盖不了这六个变量。
+说明:
-有一样东西是反向流动的:**本安装自己的 `penguin` 会排在 Agent 所执行的每一条命令的 PATH 最前面**。服务端启动时会在 `<root>/bin/penguin` 写下一个启动脚本——它用服务端自己的 Node 运行上表所指的 CLI 入口——并把该目录置于每条命令 PATH 的最前。于是命令里的 `penguin` 就是该 Agent 正运行其中的这套 harness,而不是机器上全局安装的那个版本。该目录既写进子进程环境,也在 shell 内部再前置一次:命令经由登录 shell 执行,而登录 profile 往往会在子进程环境设定之后重写 PATH;这同时意味着它也排在 [vault](#vault) 中设置的 `PATH` 之前——而 vault 里的 `PATH` 本身是整体替换继承值的。该脚本在每次启动时重写,因此安装位置变动会在下次启动被跟上;没有可指向的入口时则不写,`penguin` 的解析与此前无异。
+- `PENGUIN_TRUST_PROXY`:只在反向代理终结 TLS、并由代理自己设置或清除这个请求头时启用。启用后,会话 Cookie 会带上 `Secure` 标记,热更新的网络检查也能识别出 HTTPS。
+- `PENGUIN_SEED_ADMIN_PASSWORD`:不设置时,预置管理员时会生成一个随机密码,哈希后立即丢弃,没有人见过;账号通过首次登录链接认领。
+- `PENGUIN_GO_ORIGIN`:它是服务端配置,不接受浏览器指定的端点。取值必须是不带路径的 HTTPS 源;只有 `localhost`、`127.0.0.1` 和 `[::1]` 这类集成环境可以用明文 HTTP。带路径、凭据、查询参数或 fragment 的取值会在启动时被拒绝。见[授权获取新 API key](/models#授权获取新-api-key)。
+- `PENGUIN_UPDATE_CHECK`:设为 `off` 只关闭自动的版本检查,不影响其他对外请求:模型请求、已启用的远程控制连接、Key 授权和代理测试照常联网。
+- `PENGUIN_NO_LOGIN_SHELL_ENV`:不设置时,导入只填补启动过程没有设置的变量。见[桌面应用快速开始](/quickstart-desktop)。
+- `PENGUIN_CLI_ENTRY`:服务器从源码检出启动时,会回退到检出目录中的 `packages/cli/dist/penguin.js`。
-`PENGUIN_PREVIEW_ORIGIN` 必须与应用源在**主机名**上不同,只换端口不行:Cookie 不区分端口,换端口仍然共用会话 Cookie。本地使用不必配置——App 固定在规范主机 `localhost`,预览用 `127.0.0.1`,既不需要配置也不需要 DNS。经 LAN 地址或真实域名访问时才需要设置,否则那里的预览会回退到同源沙箱,`localStorage`、Cookie 与第三方 embed 都不可用。在真实域名上设置时,会话 Cookie 必须保持 host-only(不带 `Domain=`),否则同注册域下的兄弟子域会共享它。取值无法解析时启动即报错,不会静默回退。
+### Agent 所执行命令的环境
-`PENGUIN_GO_ORIGIN` 是服务端配置,不允许由浏览器指定端点。它必须是一个不带路径的 HTTPS 源;仅本地集成环境的 `localhost`、`127.0.0.1` 或 `[::1]` 可以使用明文 HTTP。带路径、凭据、查询参数或 fragment 的取值会使服务端在启动时直接报错。
+Agent 用 `exec_command` 运行的命令继承宿主环境,但有以下改动:
-### Provider 凭证环境变量
+- **移除:** `PORT`、`HOST`、`FORCE_COLOR`、`CLICOLOR_FORCE` 以及所有 `PENGUIN_*` 变量。这些变量配置的是 PenguinHarness 本身,不是命令。如果不移除,`exec_command` 启动的开发服务器会读到 `PORT`,试图绑定本应留给 PenguinHarness 的端口,而不是自己另选。
+- **代理:** 在服务器运行的 Session 中,由[系统设置](/settings#代理选项)里的 **Agent 环境使用代理** 开关决定代理变量。关闭时移除 `HTTP_PROXY`、`HTTPS_PROXY` 和 `ALL_PROXY`;开启时注入已配置的代理地址,没有配置地址时透传宿主的变量。
+- **密钥保险柜:** 之后再叠加 Agent 的[密钥保险柜](#vault),所以在保险柜里设置的 `PORT` 或 `PENGUIN_*` 变量确实能传给命令。
+- **控制变量:** 由服务器驱动的 Session 随后注入 `PENGUIN_API_URL`、`PENGUIN_API_TOKEN`、`PENGUIN_PROJECT_ID`、`PENGUIN_AGENT_ID` 和 `PENGUIN_SESSION_ID`(公司模式下还有 `PENGUIN_ORG_ID`),Agent 自己发起的 `penguin` 调用因此能到达运行它的服务器。这些变量会覆盖密钥保险柜里的同名条目。见 [CLI 参考](/cli)。
+- **强制:** `GIT_EDITOR`、`GIT_TERMINAL_PROMPT`、`TERM`、`NO_COLOR`、`PAGER` 和 `GIT_PAGER` 始终取固定值,命令不会因为等待编辑器、凭证提示或分页器而卡住。任何来源都无法覆盖它们,密钥保险柜也不例外。
-当模型条目未内联 `api_key` 时,AgentHub 按 Provider 回退读取对应环境变量;仅当条目未内联 `base_url` 时才使用 `*_BASE_URL`:
+### PATH 启动脚本
-| Provider | API Key | Base URL |
+Agent 运行的每条命令,PATH 的第一位都是本安装自带的 `penguin`。服务器启动时会在 `<root>/bin/penguin` 写入一个启动脚本:脚本用服务器自己的 Node 运行 `PENGUIN_CLI_ENTRY` 指向的 CLI 入口,并把这个目录放到每条命令 PATH 的最前面。这样,命令里调用的 `penguin` 就是 Agent 正在运行的这套 harness,无论机器上全局装的是什么版本。
+
+这个目录既前置到环境变量里,也前置到 shell 内部,因为命令通过登录 shell 运行,而登录 shell 的 profile 常常随后重写 PATH。这也让它排在[密钥保险柜](#vault)里设置的 `PATH` 之前,而保险柜里的 `PATH` 原本会整体替换继承来的值。
+
+启动脚本在每次启动时都会重写,因此安装位置移动后,下次启动会自动跟上。没有可指向的入口时就不写启动脚本,`penguin` 的解析结果与没有启动脚本时相同。
+
+### Workspace 预览源
+
+`PENGUIN_PREVIEW_ORIGIN` 与应用本身的源必须在**主机名**上不同,不能只是端口不同:Cookie 不区分端口,换个端口仍然共享同一个会话 Cookie。
+
+- **本地使用:** 保持不设置。应用会规范化到 `localhost`,预览由 `127.0.0.1` 提供,不需要配置,也不需要 DNS。
+- **局域网地址或正式域名:** 必须设置。否则预览会回退到同源沙箱,`localStorage`、Cookie 和第三方嵌入都无法工作。使用正式域名时,会话 Cookie 要保持 host-only(不设 `Domain=`),否则同级子域名会共享这个 Cookie。
+
+值无法解析时,服务器会在启动时直接停止,而不是静默回退。
+
+### 供应商凭证变量
+
+模型条目没有内联 `api_key` 时,AgentHub 会回退到供应商的环境变量。`*_BASE_URL` 的值只在条目没有内联 `base_url` 时才会使用。
+
+| 供应商 | API key | Base URL |
| --- | --- | --- |
| deepseek | `DEEPSEEK_API_KEY` | `DEEPSEEK_BASE_URL` |
| anthropic | `ANTHROPIC_API_KEY` | `ANTHROPIC_BASE_URL` |
-| openai、openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
+| openai、openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、vllm、custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
+| penguin-go | `PENGUIN_GO_API_KEY` | `PENGUIN_GO_BASE_URL` |
| minimax | `MINIMAX_API_KEY` | `MINIMAX_BASE_URL` |
| google | `GEMINI_API_KEY` | `GEMINI_BASE_URL` |
| zhipu | `ZAI_API_KEY` | `ZAI_BASE_URL` |
| moonshot | `MOONSHOT_API_KEY` | `MOONSHOT_BASE_URL` |
-openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan 与 custom 分组走 OpenAI 兼容协议,因此复用 `OPENAI_*` 变量。直连 MiniMax M3 Responses 客户端使用 `MINIMAX_*`;内置 MiniMax 预设已固定官方端点。Provider 分组与内置模型目录见[模型与 Provider](/models)。
+openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、vllm 和 custom 这几组供应商使用 OpenAI 兼容协议,因此共用 `OPENAI_*` 变量。Penguin Go 中转分组单独使用一对自己的变量,应用因此不会为它推荐任何厂商凭证。MiniMax M3 的直连 Responses 客户端使用 `MINIMAX_*`,内置的 MiniMax 预设也已经固定为官方端点。供应商分组和内置模型目录见[模型与供应商](/models)。
## Project 配置
-`<root>/<project>/.project_config.toml` 是 Project 唯一的配置文件:隐藏文件,落盘权限 0600,凭证内联在模型条目上。模型身份始终是 `(provider, model_id)` 成对引用,禁止任何形式的字符串拼接;指向本文件的每一处引用都要带上两半,provider 绝不由裸 `model_id` 推断。
-
-| 字段 | 说明 |
-| --- | --- |
-| `name` | Project 展示名(缺省显示 id) |
-| `default_model` | 缺省模型的成对引用 `{ provider, model_id }`,必须指向 `models` 中的条目 |
-| `vision_model` | 代读图片的视觉模型(纯文本模型用 `read_file` 读图时由它代读),成对引用 |
-| `[command_policy]` | 沙箱安全策略:针对 shell 命令的拒绝规则,先于审批模式生效——见[沙箱安全策略](#沙箱安全策略) |
-| `[[models]]` | 可用模型条目列表 |
-
-模型条目(`[[models]]`)字段:
-
-| 字段 | 说明 |
-| --- | --- |
-| `provider` | Provider 分组;与 `model_id` 共同构成条目唯一键 |
-| `model_id` | 上游请求 id,原样发送给 AgentHub |
-| `context_window` | 上下文窗口大小 |
-| `client_type` | AgentHub 客户端协议;缺省由 `model_id` 推断。自定义端点使用通用协议客户端 `openai-responses` / `ant-messages` / `openai-chat`(Web 对话框可按 base URL 检测其中哪一种;0.4.2 之前的旧写法 `openai` 为 `openai-chat` 的已废弃别名,读取时归一化) |
-| `display_name` | 展示名;仅在与内置目录不同时持久化 |
-| `vision` | 是否支持图片输入;缺省视为支持 |
-| `max_tokens` | 单模型最大输出 Token;设置后覆盖 Agent 的 `model.max_tokens`,缺省则继承 |
-| `fast_mode` | 单模型快速模式(厂商的溢价快速推理档位);默认关闭,只持久化 `true`。只对 AgentHub client 支持该档位的模型开放,其余模型会拒绝携带该参数的请求——见[模型与 Provider](/models#快速模式) |
-| `pricing` | 三档价格 `cache_read` / `cache_write` / `output`,单位 USD 每百万 Token(`unit = "usd_per_mtok"`)。恒为牌价:促销折扣由服务端存于 `web.db`,计算成本时扣除——见[模型与 Provider](/models#内置-provider-分组) |
-| `api_key` | 内联凭证;留空回退到 Provider 环境变量 |
-| `base_url` | 自定义 Base URL;内置目录会为网关,以及固定了 client 的直连条目——MiniMax M3 与 DeepSeek `deepseek-flash`——预置 |
-| `created_at` | `api_key` 写入时间(ISO 8601,界面维护的展示字段) |
+`<root>/<project>/.project_config.toml` 是 Project 唯一的配置文件:隐藏文件,以 0600 权限写入,凭证内联在模型条目上。模型的标识始终是 `(provider, model_id)` 这一对,绝不把字符串拼接成单个 id;指向这个文件的每处引用都同时带上两部分,也绝不会只凭 `model_id` 推断供应商。
+
+| 键 | 类型 | 默认值 | 说明 |
+| --- | --- | --- | --- |
+| `name` | 字符串 | — | Project 显示名;未设置时显示 id |
+| `default_model` | 成对引用 | — | 指向默认模型的 `{ provider, model_id }` 成对引用;必须指向 `models` 里的条目 |
+| `vision_model` | 成对引用 | — | 为纯文本模型读取图像的视觉模型(`read_file` 会把图像交给它);成对引用 |
+| `[default_chat]` | 表 | — | 新对话的预填默认值;见[新对话默认值](#新对话默认值) |
+| `[command_policy]` | 表 | 出厂规则集 | shell 命令的拒绝规则,先于审批模式生效;见[命令策略](#命令策略) |
+| `[plugins]` | 表 | — | Project 要求的服务端插件;见[插件](#插件) |
+| `[[models]]` | 表数组 | — | 可用的模型条目 |
+
+### 模型条目
+
+| 键 | 类型 | 默认值 | 说明 |
+| --- | --- | --- | --- |
+| `provider` | 字符串 | — | 供应商分组;与 `model_id` 一起构成条目的唯一键 |
+| `model_id` | 字符串 | — | 上游请求 id,原样发给 AgentHub |
+| `context_window` | 数字 | — | 上下文窗口大小 |
+| `client_type` | 字符串 | 从 `model_id` 推断 | AgentHub 客户端协议 |
+| `display_name` | 字符串 | 内置模型目录中的名称 | 显示名;与模型目录不同时才会持久化 |
+| `vision` | 布尔 | `true` | 模型是否接受图像输入 |
+| `max_tokens` | 数字 | Agent 的 `model.max_tokens` | 单个模型的最大输出 Token;设置后覆盖 Agent 的 `model.max_tokens` |
+| `fast_mode` | 布尔 | 关闭 | 单个模型的快速模式(供应商收取溢价的快速服务档位) |
+| `pricing` | 表 | — | 三档价格 `cache_read` / `cache_write` / `output`,以美元每百万 Token 计价(`unit = "usd_per_mtok"`)。这里记的始终是牌价 |
+| `api_key` | 字符串 | 供应商的环境变量 | 内联凭证 |
+| `base_url` | 字符串 | 部分模型目录条目有预设 | 自定义 base URL |
+| `created_at` | 字符串 | — | `api_key` 的写入时间(ISO 8601);由界面层维护的展示字段 |
+
+字段说明:
+
+- `client_type`:自定义端点使用通用协议客户端:`openai-responses`、`ant-messages` 或 `openai-chat`。Web 对话框能根据 base URL 识别用的是哪一种。0.4.2 之前的写法 `openai` 是 `openai-chat` 的废弃别名,读取时会规范化。
+- `fast_mode`:只持久化 `true`。只有 AgentHub 客户端能支持快速模式的模型才会提供这个选项,其他模型会拒绝携带它的请求。见[模型](/models#快速模式)。
+- `pricing`:这里记的是牌价。正在进行的促销不写入这个文件:服务端把它保存在 `web.db` 里,计算成本时再从牌价中扣除。见[价格与促销](/models#价格与促销)。
+- `base_url`:内置模型目录为网关以及固定客户端的直连条目预设了这个字段,即 MiniMax M3 和 DeepSeek 的 `deepseek-flash`。
+- `api_key`:为空时,AgentHub 回退到供应商的环境变量。
```toml
default_model = { provider = "deepseek", model_id = "deepseek-flash" }
@@ -97,24 +137,59 @@ cache_write = 0.285714
output = 1.142857
```
-`pricing.unit` 目前固定为 `usd_per_mtok`(USD 每百万 Token);三档对应 `token_usage` 的三个计数桶。
+`pricing.unit` 目前始终是 `usd_per_mtok`(美元每百万 Token)。三档价格对应 `token_usage` 的三个计数器。
-该文件通过 CLI `penguin config model …` 或 Web 的 Models 页面修改——服务运行期间不要手工编辑,模型本身则永远无权读写它。
+通过 CLI(`penguin config model …`)或 Web App 的「模型库」页面编辑这个文件。
-### 沙箱安全策略
+> [!WARNING]
+> 服务运行期间不要手动编辑 `.project_config.toml`。模型无权读写这个文件。
-`[command_policy]` 块是 Project 级的 shell 命令沙箱护栏:一组拒绝规则,在审批边界本身对两个能碰到 shell 的工具生效——`exec_command` 的 `cmd`(启动命令)与 `input_command` 的 `chars`(敲进已运行命令的内容)——`Session.run` 用它包装注入进来的审批回调,命中即在宿主被问到之前拒绝,任何审批模式(包括全部放行)都不能放过它,模型收到固定文案 `Tool call denied by policy.`——与人工取消可区分——从而换路。策略同样压过 [pre-tool-use hook](/agent-loop#pre-tool-use-hook) 的 `allow`:被否决的调用无论已装钩子怎么答都保持 forbidden。策略放在 Project 配置而不是 Agent State:Agent 经自己的配置面改不到它。它属于运行参数的严格层:随模型上下文在开启时读取一次,修改在各运行中 Session 的下一次轮换(压缩)生效,新对话立即生效。它不是文件系统权限——能写任意路径的工具照样能改写配置文件本身,改动同样在下一次轮换生效。
+### 新对话默认值
-规则是**纯数据,没有特殊层级**:出厂规则集像模型预设一样播种进每个新项目——创建时拷入、之后绝不自动改写——此后每条规则都可编辑、停用、删除,也可新增。播种之前的存量项目(未存 `rules` 列表)在首次保存编辑前按出厂集生效,首次保存即把列表物化进文件;设置页的「恢复默认」把出厂集读回编辑区,由 Save 落盘。
+`[default_chat]` 块为 Web App 的新对话预填默认值,在 **Project 设置** 的 **默认值** 标签页管理。每个键都可选且相互独立;加载时发现无效的值会直接丢弃,不影响其他键。
-| 字段 | 说明 |
-| --- | --- |
-| `enabled` | 总开关;缺省 = **启用**(仅在关闭时落盘 `enabled = false`) |
-| `[[command_policy.rules]]` | 拒绝规则列表,按顺序匹配:`name`(在设置页标识该规则)+ `pattern`(JavaScript 正则源码,对空白归一化后的命令做匹配)+ 可选 `description` + 每条 `enabled`(缺省 = 启用)。存储空列表 = 没有规则;缺失列表 = 出厂集 |
+| 键 | 类型 | 默认值 | 说明 |
+| --- | --- | --- | --- |
+| `agent_id` | 字符串 | — | 新对话预选的 Agent;必须是已存在的 Agent |
+| `workspace` | 字符串 | 临时 Workspace | 预填的 Workspace 目录 |
+| `approval_mode` | 字符串 | `allow-all` | 预填的审批模式:`allow-all`、`deny-all`、`read-only` 或 `always-ask` |
+| `thinking_level` | 字符串 | — | 回退思考等级(`low` / `medium` / `high` / `xhigh` / `max`),供配置里没有设置 `model.thinking_level` 的 Agent 使用 |
-出厂规则集刻意保持很小——只收录一旦照原样执行就不可挽回的命令:同时带递归与强制标志的 `rm`、`mkfs`、`dd` 直写块设备、经典 fork bomb、以及重定向写入块设备(`/dev/null` 等仍然合法)。另有四条是同样这五条的 Windows 对应写法(`exec_command` 在 Windows 上会解析到 pwsh 或 cmd):递归强制删除(`Remove-Item -Recurse -Force`、`rd /s /q`)、格式化卷(`format C:`、`Format-Volume`)、裸盘覆写(`\\.\PhysicalDriveN`、`Clear-Disk`)、以及 cmd 版 fork bomb。
+默认模型不在这个块里:它仍然是顶层的 `default_model`。
-匹配会先把常规写法归一化再套规则,免得平常的敲法平白漏过去:带路径(`/bin/rm`)、带前缀命令(`sudo`、`env`、`command`、`nice`、`xargs`)、给命令词加引号或反斜杠转义(`"rm"`、`r''m`、`\rm`)、以及字面量形式的 `sh -c 'rm -rf /'` 都会命中。归一化只做一件事:去掉引号标记——不展开、不替换、不解码。
+### 插件
+
+`[plugins]` 表列出 Project 要求的[服务端插件](/skills#服务端插件),在**插件市场**页面管理。每个键是一个包名,值是形如 Cargo `[dependencies]` 的要求:
+
+```toml
+[plugins]
+"@prismshadow/penguin-plugin-sandbox-bwrap" = "*"
+"@scope/name" = "1.2.3"
+"@scope/other" = { version = "1.2" }
+```
+
+- `"*"` 表示部署发布的任意版本。版本字符串和 `{ version = "…" }` 形式会作为要求保留下来;目前加载只看包名。
+- 服务器运行所有 Project 表的并集,因此任何一个 Project 要求的插件,都会为所有 Project 加载。
+- 读取文件时,其他形式的条目会被丢弃,文件的其余部分照常加载。`plugins` 键不是表时,视为不要求任何插件。
+- 空表照样写成空表,表示这个 Project 不要求任何插件。
+
+## 命令策略
+
+`[command_policy]` 块是 Project 为 shell 命令设下的护栏:一组在审批边界直接生效的拒绝规则。
+
+| 键 | 类型 | 默认值 | 说明 |
+| --- | --- | --- | --- |
+| `enabled` | 布尔 | 启用 | 总开关;只以 `enabled = false` 的形式存储 |
+| `[[command_policy.rules]]` | 表数组 | 出厂规则集 | 拒绝规则,按顺序匹配。存储为空列表表示没有规则;不存储列表则表示使用出厂规则集 |
+
+每条规则包含以下键:
+
+| 键 | 类型 | 默认值 | 说明 |
+| --- | --- | --- | --- |
+| `name` | 字符串 | — | 在设置界面中标识这条规则 |
+| `pattern` | 字符串 | — | JavaScript 正则表达式源码,与空白符归一化后的命令匹配 |
+| `description` | 字符串 | — | 可选的描述 |
+| `enabled` | 布尔 | 启用 | 单条规则的开关 |
```toml
[command_policy]
@@ -122,7 +197,7 @@ enabled = true
[[command_policy.rules]]
name = "rm-recursive-force"
-pattern = "…" # 播种自出厂集
+pattern = "…" # seeded from the factory set
description = "rm with recursive + force flags in one command (rm -rf and friends)"
[[command_policy.rules]]
@@ -131,64 +206,123 @@ pattern = "git push [^;|&]*--force"
enabled = false
```
-这是**防事故的护栏,不是安全边界**——这句话讲的是模式匹配本身能做到什么,而不是对这份实现的谦辞。shell 是一门编程语言,靠在程序跑起来之前读它的文本来判断它会做什么,不是加规则就能逼近的事。所以策略覆盖的是人和模型真正会敲出来的写法,到此为止:
+打开 Web App 的 **Project 设置**,在 **安全策略** 标签页管理这套策略。只有 Project 所有者能编辑;成员看到的是当前生效的策略。
+
+### 生效方式
+
+- **检查范围:** 两个会触达 shell 的工具:`exec_command` 的 `cmd`(启动的命令)和 `input_command` 的 `chars`(往运行中的命令键入的内容)。
+- **生效时机:** `Session.run` 会用策略包住注入的审批回调,所以只要命中规则,在任何审批模式下(`allow-all` 也不例外)都会在询问宿主之前直接拒绝。
+- **模型看到什么:** 一行固定的 `Tool call denied by policy.`,与人为取消不同,模型会据此改变做法。
+- **钩子:** 策略的优先级高于 [pre-tool-use 钩子](/agent-loop#pre-tool-use-hook)的 `allow`。策略否决的调用,无论已安装的钩子给出什么答复,都保持禁止。
+- **存放位置:** 策略存放在 Project 配置里,而不是 Agent State 里,所以 Agent 通过自身设置修改配置时碰不到它。
+- **修改何时生效:** 策略属于严格层级的运行时参数,只在模型上下文开启时读取一次。改动要等运行中的 Session 下一次轮换(压缩)才生效,新对话则立即生效。
+
+### 出厂规则
+
+规则就是**普通数据,没有特殊层级**。出厂规则集会像模型预设一样预置到每个新建 Project 里:创建时复制一份,之后绝不重写。此后每条规则都能编辑、停用或删除,你也可以添加自己的规则。在预置机制上线之前创建的 Project(存储中没有 `rules` 列表)会按出厂规则集运作,直到第一次保存编辑、把列表写进去为止。设置页面上的 **恢复默认** 会把出厂规则集重新载入编辑器,保存后写回。
+
+出厂规则集刻意保持精简,只覆盖那些原样执行就会造成破坏、且无法撤销的命令:
-- **运行期才拼出来的命令不在覆盖范围内,将来也不会在。** 用 `$IFS` 代替空格、走变量或别名(`X=rm; $X -rf /`)、命令替换、`eval`、base64 喂给 shell、`python -c`、经管道进入的解释器。每一条都要一个从此长期维护的模式,换来的只是覆盖的表象。存心要让命令跑起来的人,总能让它跑起来。
-- **MCP 工具是另一个面。** 本策略只读 `exec_command` 与 `input_command`。MCP Server 自己的 `permission` 等级是那边现有的旋钮,但依赖它之前先看清它做什么:它只决定该 Server 的工具向审批模式报告哪个等级,仅此而已——不隔离 Server,也不限制其工具运行时能做什么(见[工具与审批](/tools))。把匹配 shell 文本的正则伸进任意 MCP 参数,只会给一个需要真控制的面再加一层更弱的控制。
-- **不在名单上的命令。** `shred`、`wipefs`、`find -delete`、`git clean -xfd`、`chmod -R 000 /` 都不匹配任何出厂规则——名单是刻意保持小的。项目在意什么,就自己加规则。
+- 同时带递归和强制标志的 `rm`
+- `mkfs`
+- 直接向块设备写入的 `dd`
+- 经典的 fork 炸弹
+- 重定向到块设备的 shell 命令(`/dev/null` 这类仍然允许)
-它换来的是:毁灭性单行命令不会被误跑——模型碰到 shell 的两条路都算,POSIX 与 Windows 两种写法都算,任何审批模式下都算。这是一道减速带,而在不可逆的命令前面,减速带是值得有的。要真正的边界——一个无论跑什么都碰不到文件系统其余部分的进程——机制是进程隔离(bubblewrap、dsh),那是另一层,本策略与之互补而非替代。
+另有四条规则用 Windows 写法覆盖同样的场景,因为 `exec_command` 在 Windows 上可能解析为 pwsh 或 cmd:
-在 Web App Project 设置的「安全策略」页管理(仅 owner 可改;成员只读展示生效策略)。
+- 递归强制删除(`Remove-Item -Recurse -Force`、`rd /s /q`)
+- 卷格式化(`format C:`、`Format-Volume`)
+- 裸盘覆写(`\\.\PhysicalDriveN`、`Clear-Disk`)
+- cmd 版的 fork 炸弹
+
+### 匹配规则
+
+在规则运行之前,匹配逻辑会先归一化几种常见写法,避免直白的输入碰巧漏网。下面这些写法全部都能命中:
+
+- 开头带路径(`/bin/rm`)
+- 前面套了一层包装命令(`sudo`、`env`、`command`、`nice`、`xargs`)
+- 命令词加了引号或反斜杠转义(`"rm"`、`r''m`、`\rm`)
+- 原样传入的 `sh -c 'rm -rf /'`
+
+归一化只删除引号。展开、替换、解码,一律不做。
+
+### 策略不覆盖的范围
+
+命令策略是一道**防误操作的护栏,不是安全边界**。这句话描述的是模式匹配能做到什么,不是对本实现的自谦。Shell 是一门编程语言,规则加得再多,也无法在程序运行前靠阅读它的文本来更准确地判断它会做什么。策略覆盖人和模型实际会敲出来的写法,到此为止:
+
+- **运行时计算出来的命令不在覆盖范围内,以后也不会有。** 例如:用 `$IFS` 代替空格、变量或别名(`X=rm; $X -rf /`)、命令替换、`eval`、通过管道把 base64 送进 shell、`python -c`、经由管道调用的解释器。每一种都得配一条需要永久维护的模式,换来的只是「已覆盖」的假象。真想让命令跑起来的人,总有办法让它跑起来。
+- **MCP 工具是另一个层面。** 策略只读 `exec_command` 和 `input_command`。MCP Server 自身的 `permission` 等级才是那个层面上的设置,但它只设定 Server 的工具向审批模式上报的等级,既不给 Server 加沙箱,也不限制工具运行时的行为(见[工具与审批](/tools))。把 shell 文本匹配器扩展到任意 MCP 参数,只会给一个真正需要硬控制的层面再叠一道更弱的控制。
+- **不在清单上的命令不覆盖。** `shred`、`wipefs`、`find -delete`、`git clean -xfd`、`chmod -R 000 /` 都匹配不到任何出厂规则。为你的 Project 在意的命令自行添加规则。
+- **它不是文件系统权限。** 能写任意路径的工具仍然可以改写配置文件本身,改动在下一次轮换时生效。
+
+这套策略确实换来的是:一条破坏性的单行命令,无论通过哪个触达 shell 的工具、写成 POSIX 还是 Windows 的形式、处于哪种审批模式,都不会因误操作而执行。这是一道减速带,而在不可逆的命令前面,减速带值得设置。至于真正的边界,也就是让进程无论执行什么都碰不到文件系统的其他部分,靠的是隔离机制(bubblewrap、dsh)。那是独立的另一层,这套策略补充它,而不是取代它。
## Agent 配置
-`agent_state/system_config.yaml` 定义单个 Agent 的行为(YAML;经 Web UI 编辑时保留注释):
+`agent_state/system_config.yaml` 定义一个 Agent 的行为。文件是 YAML 格式,在 Web App 中编辑时,注释会保留。
-| 字段 | 缺省值 | 说明 |
+| 字段 | 默认值 | 说明 |
| --- | --- | --- |
-| `name` | — | Agent 展示名(缺省回退到 id) |
+| `name` | — | Agent 显示名称;未设置时回退到 id |
| `description` | — | Agent 描述 |
-| `version` | `1` | Agent State 版本号(自然数),每次成功优化自增 |
-| `kernel_version` | 当前内核版本 | 配置内核版本(日期字符串):记录该配置基于哪一代内置默认,创建、还原默认与更新内核时盖章;与 `version` 无关,用户编辑不改变它,缺失视为早于内核版本机制(即过期) |
-| `system_prompt` | 内置模板 | 必填;唯一进行占位符替换的模板 |
-| `max_turns` | `-1` | 单个 Task 的最大 LLM 轮数(`-1` 不限制,正整数为上限) |
-| `model.max_tokens` | `32000` | 单次输出 Token 天花板(-1 不设上限,用服务商默认);每次请求会把实际值收敛到模型 `context_window` 减估算输入以内,小窗口模型不会被索要放不下的输出 |
-| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`;每个模型上下文开启时采用的档位(Session 钉住的档位优先),上下文内固定,修改在下一次压缩后生效 |
-| `model.timeoutMs` | `300000` | 单次 Request 的**空闲**超时(毫秒):等待上游下一个事件的上限,收到任一事件即归零重计,不是整次请求的总时长上限。它约束的是连接建立与首个事件的等待、以及流式过程中的事件间隔——思考不外露的模型整段推理都落在「首个事件」这一段里,缺省值为此留足余量 |
-| `compaction.max_context_length` | `256000` | 触发压缩的上下文 Token 阈值;生效阈值取它与模型 `context_window` − 2048 中的较小者,故小窗口模型在自己的窗口内压缩,窗口大于 258048 时则在该数值处触发(条目未配置 `context_window` 时按 128000 的假定窗口计) |
-| `compaction.max_session_turns` | `-1` | Session 累计轮数阈值(`-1` 不限制) |
+| `version` | `1` | Agent State 版本(自然数),每次成功优化后递增 |
+| `kernel_version` | 当前内核版本 | 配置基于哪一代内置默认值(日期字符串) |
+| `system_prompt` | 内置模板 | 必填;唯一支持占位符替换的模板 |
+| `max_turns` | `-1` | 每个 Task 的最大 LLM 轮数 |
+| `model.max_tokens` | `32000` | 每次 Request 的输出 Token 上限 |
+| `model.thinking_level` | `medium` | 每个模型上下文开启时使用的思考等级,除非 Session 钉住了等级 |
+| `model.timeoutMs` | `300000` | 每次 Request 的**空闲**时间预算,单位毫秒 |
+| `compaction.max_context_length` | `256000` | 触发压缩的上下文 Token 阈值 |
+| `compaction.max_session_turns` | `-1` | Session 累计轮数阈值 |
| `compaction.mode` | `summarize` | `summarize` / `discard` |
-| `compaction.prompt` | 内置模板 | summarize 压缩使用的 Prompt |
-
-`compaction.*` 四项是本文件里唯一不必等待的部分:引擎在每个压缩检查点(每次请求回报 token 用量之后,以及手动 `/compact`)重读该节,保存后对已在运行的 Session 立即生效;其余各项都在模型上下文开启时读取,于下一次压缩生效。Web App 也可以直接在上下文构成面板里改阈值——拖动条形上的虚线切刀即可。
-| `memory.enabled` | `true` | 记忆是否进入上下文、是否为持久 Workspace 准备记忆目录 |
-| `memory.prompt` | 内置模板 | `{{MEMORY}}` 区块中恒注入的一半,可在记忆标签页编辑——含 `{{USER_MEMORY_INDEX}}` |
-| `memory.workspace_prompt` | 内置模板 | 仅持久 Workspace 追加,可在记忆标签页编辑——含 `{{WORKSPACE_MEMORY_INDEX}}` 与 `{{WORKSPACE_MEMORY_DIR}}` |
-| `vault.enabled` | `true` | 保险柜小节是否进入上下文(关闭后值仍注入子进程环境,只是模型看不到键名清单) |
-| `vault.prompt` | 内置模板 | `{{VAULT}}` 区块内容,可在 Vault 标签页编辑——含 `{{VAULT_KEYS}}` |
-| `skills.enabled` | `true` | 技能小节是否进入上下文(关闭后已装技能仍可被 `[use_skills]` 显式调用) |
-| `skills.prompt` | 内置模板 | `{{SKILLS}}` 区块内容,可在技能标签页编辑——含 `{{SKILL_METADATA}}` |
-| `schedules.enabled` | `true` | 定时任务小节是否进入上下文(关闭后 server 照常触发任务,只是模型不了解任务体系) |
-| `schedules.prompt` | 内置模板 | `{{SCHEDULES}}` 区块内容,可在定时任务标签页编辑——教模型用文件工具管理任务,含 `{{SCHEDULE_LIST}}` |
-| `hooks.enabled` | `true` | 新建的 Session 是否在循环的钩子点运行已安装的钩子包(关闭后包仍在磁盘上,只是无人咨询)。唯一没有 prompt 一半的小节:钩子包是脚本,不是上下文文本 |
-| `tools.builtin` | 缺省时为完整默认工具集 | 工具条目:`name` / `description` / `parameters` / `permission`(`r` 或 `rw`)/ `forModel` / `timeoutMs` / `maxOutputLength` / `call_description`(条目级开关:控制 `description` 调用参数,开启时为必填,缺省保留);一旦写出即整体替换默认列表 |
-| `tools.mcpServers` | `[]` | MCP Server 配置(`name` + `config`):transport 取 `stdio` / `http` / `sse`,工具以 `mcp__<server>__<tool>` 并入工具集;`config.permission`(`auto` / `r` / `rw`,缺省 `auto`)固定该 Server 全部工具的审批等级,不再采信其 `readOnlyHint`;详见[工具与审批](/tools)的 MCP Server 一节 |
+| `compaction.prompt` | 内置模板 | summarize 模式压缩使用的提示词 |
+| `memory.enabled` | `true` | 记忆是否进入上下文,以及是否准备记忆目录 |
+| `memory.prompt` | 内置模板 | `{{MEMORY}}` 块中始终注入的那一半;包含 `{{USER_MEMORY_INDEX}}` |
+| `memory.workspace_prompt` | 内置模板 | 仅在持久 Workspace 中追加;包含 `{{WORKSPACE_MEMORY_INDEX}}` 和 `{{WORKSPACE_MEMORY_DIR}}` |
+| `vault.enabled` | `true` | 密钥保险柜小节是否进入上下文 |
+| `vault.prompt` | 内置模板 | `{{VAULT}}` 块;包含 `{{VAULT_KEYS}}` |
+| `skills.enabled` | `true` | 技能小节是否进入上下文 |
+| `skills.prompt` | 内置模板 | `{{SKILLS}}` 块;包含 `{{SKILL_METADATA}}` |
+| `schedules.enabled` | `true` | 定时任务小节是否进入上下文 |
+| `schedules.prompt` | 内置模板 | `{{SCHEDULES}}` 块,讲解基于文件的任务管理;包含 `{{SCHEDULE_LIST}}` |
+| `hooks.enabled` | `true` | 新 Session 是否在循环的钩子点运行已安装的钩子包 |
+| `tools.builtin` | 省略时为完整默认工具集 | 工具条目;一旦写入,就整体替换默认列表 |
+| `tools.mcpServers` | `[]` | MCP Server 配置(`name` + `config`) |
+
+### 字段说明
+
+- `kernel_version`:在创建时、还原为默认配置时以及内核更新时打上标记。它与 `version` 无关,也不会因你的编辑而改变。值缺失说明配置早于这套机制,视为过时。
+- `max_turns`:`-1` 表示不限制;正整数则为单个 Task 的轮数上限。
+- `model.max_tokens`:`-1` 表示不设上限(使用供应商默认值)。每次请求都会把实际生效值限制在「模型 `context_window` − 估算输入」以内,因此不会向窗口小的模型要求放不下的输出量。
+- `model.thinking_level`:可选 `none` / `low` / `medium` / `high` / `xhigh` / `max`。思考等级在一个模型上下文内固定,修改要等下一次压缩才生效。没有此字段时,采用 Project `[default_chat]` 中的 `thinking_level`;若仍未设置,则为 `medium`。
+- `model.timeoutMs`:等待下一个上游事件的最长时长,每收到一个事件就重新计时。它限制的不是请求总时长,而是两段等待:从建立连接到收到第一个事件,以及事件之间的空档。有的模型在思考阶段不向网络输出任何内容,整个思考期都落在第一段空档里,默认值已为这种情况留出余量。
+- `compaction.max_context_length`:实际阈值取此值与「模型 `context_window` − 2048」中较小的一个。因此窗口小的模型会在自己的窗口内触发压缩;窗口超过 258048 的模型则按此数值触发。没有 `context_window` 的模型条目按 128000 窗口处理。
+- `compaction.max_session_turns`:`-1` 表示不限制。
+- `*.prompt`:各小节的提示词都能在对应的设置标签页编辑:两段记忆提示词在 **记忆**,`vault.prompt` 在 **密钥保险柜**,`skills.prompt` 在 **技能**,`schedules.prompt` 在 **定时任务**。
+- `vault.enabled`:关闭时,值仍会注入子进程环境,只是模型看不到键名列表。
+- `skills.enabled`:关闭时,已安装的 Skill 仍可通过 `[use_skills]` 显式调用。
+- `schedules.enabled`:关闭时,服务端仍会触发任务,只是模型不再了解任务系统。
+- `hooks.enabled`:唯一没有提示词的小节,因为钩子包是脚本,不是上下文文本。关闭时,钩子包仍保持安装,只是不再有任何环节调用它们。
+- `tools.builtin`:每个条目包含 `name` / `description` / `parameters` / `permission`(`r` 或 `rw`)/ `forModel` / `timeoutMs` / `maxOutputLength` / `call_description`。`call_description` 是按工具控制调用参数 `description` 的开关;开启时调用必须带上这个参数;字段缺失则视为保留。
+- `tools.mcpServers`:传输方式为 `stdio`、`http` 或 `sse`,发现的工具以 `mcp__<server>__<tool>` 的形式加入工具集。`config.permission`(`auto` / `r` / `rw`,默认 `auto`)为对应 Server 的所有工具固定审批等级,不再采信它们的 `readOnlyHint`。见 [MCP Server](/tools#mcp-server)。
+
+四个 `compaction.*` 字段是本文件中唯一即时生效的部分,运行中的对话无需等待。引擎会在每个压缩检查点重新读取这一节(每次请求上报 Token 用量之后,以及手动执行 `/compact` 时),因此保存的修改对已在运行的 Session 同样生效。其余内容都在模型上下文开启时读取,修改要到下一次压缩才生效。在 Web App 里,你还可以在上下文面板中拖动条上的虚线切刀来[修改阈值](/chat#修改压缩阈值)。
工具权限与审批语义见[工具与审批](/tools)。
-局部调整示例(在初始化生成的文件基础上修改)。注意本文件**不与默认值做 deep merge**:写出的字段整体生效,省略的字段才在使用处回退表中缺省值;`system_prompt` 是必填字段(缺失会拒绝加载),编辑其他字段时应保留初始化写入的完整模板:
+本文件**不与默认值做深度合并**。写出的键整体生效;只有省略的键,才会在用到时回退到上述默认值。`system_prompt` 必填,缺少此字段的文件无法加载,因此编辑其他字段时请保留完整生成的模板。下面是一个部分覆盖的示例,由 init 步骤生成的文件修改而来:
```yaml
name: default_agent
description: General-purpose agent
version: 3
-# 必填:保留初始化生成的完整默认模板(含 {{AGENTS_MD}} 等占位符,此处从略)。
+# Required: keep the full generated default template ({{AGENTS_MD}} and friends; elided here).
system_prompt: |
…
-# -1(缺省)不限制轮数;设为正整数则限制单个 Task 的轮数。
+# -1 (the default) = unlimited; set a positive integer to cap the turns of a single Task.
max_turns: -1
model:
@@ -201,141 +335,193 @@ compaction:
max_session_turns: -1
mode: summarize
-# tools 整段省略 = 使用完整默认工具集。一旦写出 tools.builtin,将**整体替换**
-# 默认列表:必须为每个要保留的工具携带完整定义(含 parameters JSON Schema),
-# 参见「工具与审批」页。
+# Omitting the whole tools section = the full default toolset. Writing tools.builtin
+# REPLACES the default list wholesale: carry the complete definition (including the
+# parameters JSON Schema) for every tool you keep — see Tools & Approval.
```
-既有 Agent 始终按其磁盘上的配置原样运行——更新后的代码默认值不会自动合并。内置默认发生实质变化时,配置的 `kernel_version` 落后于当前内核版本,详情页与智能体列表会给出更新提示。采用当前默认值有两条路径(同在设置页概览、相邻放置):
+### 内核更新
-- **更新内核**:无损合并,**以设置页为单位**逐页比对(系统提示词、运行参数、工具、技能、记忆、密钥保险柜、定时任务)。配置中整页缺失、或整页哈希仍等于某一代已记录的内置默认,即按当前默认整页重写——后续版本新增的工具也正是借这次整页重写进入既有 Agent。只要该页被改动过,就**整页**保持不变并在结果中列出:改了一个内置工具,整个「工具」页都会被保留,因此自加的工具与删掉的工具都会留存,而该页其余内容在还原默认配置之前不再跟进新默认。`name`、`description`、`version` 与 `tools.mcpServers` 不属于任何设置页,永不触碰。完成后盖章 `kernel_version`。比对是**保守**的:只有整页哈希命中已记录代际才被视为旧默认,太老而无法识别的代际一律按自定义保留。
-- **还原为默认配置**:与 Skill 更新同语义,用当前默认值覆盖现有配置——自定义系统提示词、工具列表、模型/压缩参数与 MCP Server——仅保留 `name`、`description` 与 `version`。更新内核因保守保留而没跟上时,这是全量刷新的兜底。
+已有 Agent 始终按磁盘上的配置原样运行,新版代码的默认值绝不会自动合并进来。当内置默认值发生实质性变化时,配置的 `kernel_version` 会落后于当前内核,设置页面和智能体列表会显示更新提示。设置总览上有两个操作可以采纳当前默认值。
-面向开发者:`kernel_version` 只在对内置默认做出实质修改时手动前进(取当日日期)。CI 的 pinned-hash 测试(`core/test/kernel-version.test.ts`)重算各设置页哈希并与 `kernel-history.ts` 中的 `KERNEL_DEFAULT_TAB_HASHES` 比对,不一致即失败,并逐个列出变动的设置页及其对应改动:更新 `KERNEL_VERSION`、把该页旧哈希追加到 `KERNEL_SUPERSEDED_TAB_HASHES`、再写入新哈希。同日多次变更可复用当日版本号。已记录的旧哈希一经写入即冻结——它们就是「仍是旧默认」的识别依据。
+**更新内核**是一次无损合并,按设置标签页逐一进行(**系统提示词**、**运行参数**、**工具**、**技能**、**记忆**、**密钥保险柜**、**定时任务**):
+
+- 配置里完全没有的标签页,或者哈希仍与某一*已记录*代的内置默认值一致的标签页,会按当前默认值重写。之后版本新增的工具,也是通过这条途径进入已有 Agent 的。
+- 只要你以任何方式改动过,标签页就会**完整**保持不变,并列入结果。哪怕只改了一个内置工具,整个**工具**标签页也会保留:你新增的工具和删除的工具都原样留存,这个标签页也不再跟随新默认值,直到你执行还原为默认配置。
+- `name`、`description`、`version`、`hooks` 和 `tools.mcpServers` 不属于任何标签页,更新永远不会碰它们。
+- 最后,配置会打上当前 `kernel_version` 的标记。
+- 匹配是**保守**的:只有哈希与某一已记录代一致的标签页才算旧默认值。代太老、不在记录之内的标签页,会当作自定义内容保留。
+
+**还原为默认配置**的工作方式类似 Skill 更新:用当前默认值覆盖配置,只保留 `name`、`description` 和 `version`。其余全部替换,包括自定义系统提示词、工具列表、模型与压缩设置,以及 MCP Server。当内核更新的保守匹配留下旧字段时,用它做一次彻底刷新。
+
+面向开发者的说明:
+
+- `kernel_version` 由人工推进,且只在内置默认值发生实质性变化时更新,取当天日期。同一天的多次改动可能复用同一天的版本。
+- CI 中的固定哈希测试(`core/test/kernel-version.test.ts`)会重新计算每个标签页的哈希,并与 `kernel-history.ts` 里的 `KERNEL_DEFAULT_TAB_HASHES` 比对。发现偏差时测试失败,并列出每个变动的标签页及所需的修改:递增 `KERNEL_VERSION`,把这个标签页原先的哈希追加到 `KERNEL_SUPERSEDED_TAB_HASHES`,再写入重新计算出的哈希。
+- 已淘汰的哈希永久冻结:判断一个标签页是否仍是旧默认值,靠的就是它们。
### 系统提示词占位符
-`system_prompt` 是唯一进行占位符替换的模板,可用占位符:
+`system_prompt` 是唯一支持占位符替换的模板。可用占位符如下:
| 占位符 | 注入内容 |
| --- | --- |
-| `{{AGENTS_MD}}` | `AGENTS.md` 的全文 |
-| `{{VAULT}}` | 渲染后的 `vault.prompt` 区块(保险柜小节);`vault.enabled` 关闭时为空。模板没有它就不注入该小节——Vault 标签页提供显式插入/迁移 |
-| `{{SKILLS}}` | 渲染后的 `skills.prompt` 区块(技能小节);`skills.enabled` 关闭时为空。模板没有它就不注入该小节——技能标签页提供显式插入/迁移 |
-| `{{MEMORY}}` | 渲染后的 `memory.prompt` 区块,持久 Workspace 下再追加 `memory.workspace_prompt`;关闭记忆时为空。模板没有它就不注入记忆——记忆标签页提供显式插入 |
-| `{{SCHEDULES}}` | 渲染后的 `schedules.prompt` 区块(定时任务小节);`schedules.enabled` 关闭时为空。模板没有它就不注入该小节——定时任务标签页提供显式插入 |
-| `{{VAULT_KEYS}}` | `vault.prompt` 内:Vault 的键名列表(仅键名,每键一行 `- KEY`)。为兼容旧模板,直接写在模板正文中的该占位符仍会被替换,并同样受 `vault.enabled` 控制 |
-| `{{SKILL_METADATA}}` | `skills.prompt` 内:已安装 Skill 的元数据行。为兼容旧模板,直接写在模板正文中的该占位符仍会被替换,并同样受 `skills.enabled` 控制 |
-| `{{SCHEDULE_LIST}}` | `schedules.prompt` 内:现有定时任务名列表(每任务一行 `- name`;无任务时为空清单说明) |
-| `{{USER_MEMORY_INDEX}}` | 记忆提示词内:用户作用域 `MEMORY.md` 索引的内容(最多注入 200 行、总计 25000 字符) |
-| `{{WORKSPACE_MEMORY_INDEX}}` | 仅 `memory.workspace_prompt` 内:Workspace 作用域 `MEMORY.md` 索引的内容(最多注入 200 行、总计 25000 字符) |
-| `{{WORKSPACE_MEMORY_DIR}}` | 仅 `memory.workspace_prompt` 内:当前 Workspace 记忆目录的绝对路径 |
+| `{{AGENTS_MD}}` | `AGENTS.md` 全文 |
+| `{{VAULT}}` | 渲染后的 `vault.prompt` 块(密钥保险柜小节);`vault.enabled` 关闭时为空 |
+| `{{SKILLS}}` | 渲染后的 `skills.prompt` 块(技能小节);`skills.enabled` 关闭时为空 |
+| `{{MEMORY}}` | 渲染后的 `memory.prompt` 块,持久 Workspace 中还会加上 `memory.workspace_prompt`;记忆关闭时为空 |
+| `{{SCHEDULES}}` | 渲染后的 `schedules.prompt` 块(定时任务小节);`schedules.enabled` 关闭时为空 |
+| `{{VAULT_KEYS}}` | 在 `vault.prompt` 内:密钥保险柜的密钥名称列表(只有名称,每个密钥一行 `- KEY`) |
+| `{{SKILL_METADATA}}` | 在 `skills.prompt` 内:已安装 Skill 的元数据行 |
+| `{{SCHEDULE_LIST}}` | 在 `schedules.prompt` 内:当前的任务名称列表(每个任务一行 `- name`;没有任务时显示空列表说明) |
+| `{{USER_MEMORY_INDEX}}` | 在记忆提示词内:用户作用域的 `MEMORY.md` 索引(最多 200 行,总计不超过 25,000 字符) |
+| `{{WORKSPACE_MEMORY_INDEX}}` | 仅在 `memory.workspace_prompt` 内:Workspace 作用域的 `MEMORY.md` 索引(最多 200 行,总计不超过 25,000 字符) |
+| `{{WORKSPACE_MEMORY_DIR}}` | 仅在 `memory.workspace_prompt` 内:当前 Workspace 记忆目录的绝对路径 |
| `{{PLATFORM}}` | 运行平台 |
| `{{OS_VERSION}}` | 操作系统版本 |
| `{{DATE}}` | 当前日期 |
-| `{{PROJECT_DIR}}` | App Data Dir:PenguinHarness 应用数据根目录(即 Project 目录) |
+| `{{PROJECT_DIR}}` | App Data Dir:PenguinHarness 的应用数据根目录(即 Project 目录) |
| `{{AGENT_ID}}` | Agent id |
| `{{CWD}}` | Workspace 路径 |
-| `{{PROVIDER}}` | 模型 provider 分组 |
+| `{{PROVIDER}}` | 模型供应商分组 |
| `{{MODEL_ID}}` | 上游模型 id |
| `{{SESSION_ID}}` | Session id |
-`{{PROJECT_DIR}}` 在提示词中以 **App Data Dir** 名义暴露给模型:PenguinHarness 的应用数据根目录,存放全部 Agent 的数据文件(`agents/<agent_id>/…`)与 Project 级数据——特意不以 Project/任务目录的口径描述,避免模型将其误认为本次任务的工作目录(`CWD`)。
+**小节占位符。** 密钥保险柜、技能、记忆、定时任务四个小节共用一套模式:一个占位符、一个开关、一段可编辑的提示词。模板里只保留 `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` 占位符,小节文本放在对应的 `*.prompt` 键里(在设置标签页编辑),关闭 `*.enabled` 则整块为空。模板缺少其中某个占位符时,对应小节不会注入;相应的设置标签页会提供显式插入占位符或迁移旧版模板的操作。四个小节占位符在组装时最后展开,一趟完成。展开后的文本不会再次扫描,因此记忆索引或小节提示词里看起来像占位符的文本会按字面保留。
-Windows 上注入的 `{{PROJECT_DIR}}` 与 `{{CWD}}` 统一使用正斜杠——与 core 产出的其他模型可见路径(附件行、Goal file 行、截断输出 recovery 路径)同一拼写。模型会把这些拼写原样带入 JSON 工具参数和 Shell 命令;正斜杠被 Node 的 fs API 与包内 (Git) Bash 工具 Shell 接受,也避免 JSON 反斜杠转义出错。
+**App Data Dir。** `{{PROJECT_DIR}}` 会以 **App Data Dir** 的名义展示给模型:这是 PenguinHarness 的应用数据根目录,存放所有 Agent 的数据文件(`agents/<agent_id>/…`)和 Project 级数据。刻意不把它描述成 Project 或 Task 目录,避免模型误以为它是任务的工作目录(`CWD`)。
-`agent_state/AGENTS.md` 是开发者可编辑的指令文件,经 `{{AGENTS_MD}}` 注入系统提示词,缺省为空——它也是优化器最常改动的文件(见[自我进化](/self-improvement))。与 Agent State 的其余部分(含 `system_config.yaml`)一样,它在每次模型上下文开启时重新读取——Session 创建时一次,压缩开启下一个上下文时再一次——因此修改在运行中 Session 的下一次压缩即生效,不只作用于新 Session,也绝不会作用于正在运行的上下文(`compaction` 一节例外,见[上下文压缩](/agent-loop))。
+**Windows 路径。** 在 Windows 上,`{{PROJECT_DIR}}` 和 `{{CWD}}` 一律以正斜杠注入;core 为模型拼出的其他路径也是如此(附件行、目标模式的 goal 文件行、截断输出的恢复路径)。模型会把这种写法照搬进 JSON 工具参数和 shell 命令。Node 的 fs API 和包内工具所用的 Git Bash 都接受正斜杠,还能避开 JSON 反斜杠转义错误。
-Vault / 技能 / 记忆 / 定时任务四个小节均采用「段落占位符 + 开关 + 可编辑提示词」模式:模板只保留 `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` 占位符,小节文本存于各自的 `*.prompt` 配置、在对应设置标签页编辑,`*.enabled` 关闭即整段为空。四个段落占位符在装配时**最后单趟展开**:展开产物不再被扫描,因此记忆索引或提示词正文里出现的占位符字样只会保持字面原样,不会引发二次替换。
+**AGENTS.md。** `agent_state/AGENTS.md` 是开发者可编辑的指令文件,通过 `{{AGENTS_MD}}` 注入,默认为空。它也是优化器编辑最多的文件;参见[自我进化](/self-improvement)。与 Agent State 的其余内容(包括 `system_config.yaml`)一样,它在每次模型上下文开启时读取:创建 Session 时读一次,压缩开启下一个上下文时再读一次。因此,修改会在运行中 Session 的下一次压缩时生效,而不只对新建 Session 生效,且绝不会影响正在运行的上下文。`compaction` 一节是例外;见[上下文压缩](/agent-loop)。
-**旧模板兼容**:`system_config.yaml` 在 Agent 创建时物化、从不自动升级,早于本机制创建的 Agent 模板中是硬编码的 `# Vault` / `# Skills` 段落文字加内联 `{{VAULT_KEYS}}` / `{{SKILL_METADATA}}`。这类模板继续工作:内联占位符仍被替换,且同样受新开关控制(关闭时替换为空串)。对应标签页会提示「旧版模板」并提供一键迁移——把旧默认段落逐字原位替换为新占位符,装配结果不变;自定义改动过段落文字的模板不匹配逐字迁移,则按缺占位符处理、提供一键插入(插到 `# Environment` 之前)。
+**旧版模板。** `system_config.yaml` 在创建 Agent 时写入,此后不会自动升级。在小节占位符出现之前创建的 Agent,模板里硬编码了 `# Vault` / `# Skills` 小节文本,并内联了 `{{VAULT_KEYS}}` / `{{SKILL_METADATA}}`。这类模板仍然可用:内联占位符照常替换,并遵守小节开关(开关关闭时替换为空字符串)。对应的设置标签页会提示旧版模板并提供一键迁移:把旧的默认小节文本原封不动地就地替换为新占位符,组装出的提示词保持不变。如果小节文本有过自定义,原样迁移便匹配不上,此时模板按缺少占位符处理,可在 `# Environment` 之前一键插入。
## 记忆
-`agent_state/memory/` 保存 Agent 跨 Session 的长期记忆:用户反馈、项目决策、协作约定与外部系统入口——这些无法从 Workspace 或代码历史可靠重新推导。它不是上下文压缩:压缩保存单个 Session 的短期工作状态。
+`agent_state/memory/` 保存 Agent 在多次 Session 之间记住的内容:用户反馈、项目决策、工作惯例、外部系统的入口,也就是无法从 Workspace 或它的代码历史中重新推导的内容。记忆不是上下文压缩,压缩保留的是单个 Session 的短期状态。
-记忆有两个作用域,都归属于单个 Agent,绝不跨 Agent 共享:
+记忆分两个作用域。两者都只属于一个 Agent,绝不与其他 Agent 共享:
-- **用户作用域**(`memory/user/`)——无论在哪工作都成立的内容:用户是谁、其长期偏好、与具体代码库无关的参考。每个 Session 都会读到,包括运行在临时 Workspace 中的会话——那种会话没有别处可写。
-- **Workspace 作用域**(`memory/<workspace_memory_key>/`)——关于某一个 Workspace 的事实。同一 Agent、同一 Workspace 的多个 Session 共享;不同 Workspace 的主题文件相互隔离。
-
-每个作用域各带一份 `MEMORY.md` 索引;不同 Agent 即使使用同一 Workspace 也各自维护。记忆位于 Agent State,因此随导出、导入与快照一同流转,Project 内有权访问该 Agent 的成员都能读到——所以凭据与敏感个人信息绝不应写入。
+- **用户作用域**(`memory/user/`):Agent 无论在哪里工作都成立的内容,比如用户是谁、长期偏好,以及不绑定某个代码库的参考资料。每个 Session 都会读取它,包括运行在临时 Workspace 里的 Session,因为这种 Session 没有别的地方可写。
+- **Workspace 作用域**(`memory/<workspace_memory_key>/`):关于某个 Workspace 的事实。同一 Agent 在同一 Workspace 中的 Session 共享这些内容;不同 Workspace 的主题文件彼此独立。
```text
agent_state/memory/
-├── user/ # 用户作用域(无 marker:它不对应任何路径)
-│ ├── MEMORY.md # 本作用域索引
+├── user/ # user scope (no marker: it stands for no path)
+│ ├── MEMORY.md # this scope's index
│ └── prefers-pnpm.md
-└── my-app-a81f32c4/ # 单个 Workspace
- ├── .workspace # 该 key 对应的 Workspace 路径
+└── my-app-a81f32c4/ # one Workspace
+ ├── .workspace # the Workspace path this key stands for
├── MEMORY.md
└── testing-conventions.md
```
-`user` 是保留目录名。之所以安全:生成的 workspace memory key 一律是 `<base>-<8 位十六进制>`,必然含连字符——不含连字符的名字永远不会被生成出来。
+每个作用域都有自己的 `MEMORY.md` 索引,而且不同 Agent 绝不共享记忆,即使在同一个 Workspace 里也是如此。记忆存放在 Agent State 中,因此会随导出、导入和快照一起迁移。
+
+> [!WARNING]
+> 能访问这个 Agent 的所有 Project 成员都能读到它的记忆。不要把凭证和敏感的个人数据存进去。
+
+要读取或删除记忆,或者让 Agent 来修改,使用 [Agent 设置](/agents)的 **记忆** 标签页。
-workspace memory key 为 `<安全 basename>-<真实路径 sha256 的 8 位十六进制>`。身份只由实际目录决定,与 Git 无关:指向同一目录的两个软链接得到同一 key;目录移动或重命名后视为新的 Workspace(旧记忆仍以旧 key 留在磁盘上)。PenguinHarness 自动创建的临时 Workspace(位于 `agents/<agent_id>/workspaces/` 下)没有 Workspace 作用域,子 Agent 继承该临时 Workspace 时同样没有:临时 Workspace 是每个 Session 分配一个,之后不会有任何 Session 再跑进去读它。这类会话仍然拥有用户作用域——它能学到的东西本来也属于那一层。
+### Workspace 记忆键
-主题文件按语义划分,不按 Task、Session 或日期划分,并带 frontmatter:
+Workspace 记忆键的格式是 `<safe-basename>-<8 hex of the real path's sha256>`。
+
+- `user` 是保留的目录名,这样做是安全的:生成的键都形如 `<base>-<8 hex>`,一定包含连字符。
+- 标识就是目录本身,与 Git 无关。指向同一目录的两个符号链接解析出同一个键;移动或重命名目录会让它变成一个新 Workspace,旧记忆仍以旧键留在磁盘上。
+- 临时 Workspace 由 PenguinHarness 分配在 `agents/<agent_id>/workspaces/` 下,完全没有 Workspace 作用域,子 Agent 继承时也不例外。临时 Workspace 按 Session 分配,之后不会再有 Session 在那里运行并读回内容。这种 Session 仍然会拿到用户作用域,它学到的东西本来也该存在那里。
+
+### 主题文件
+
+每个主题文件保存一个事实或主题,而不是每个 Task、Session 或日期一个文件,并带有 frontmatter:
```markdown
---
name: testing-conventions
-description: 项目的测试环境和验证规则
+description: the project's test environment and verification rules
updated_at: 2026-08-07
---
-- 集成测试必须连接真实数据库,不使用 mock repository。
+- Integration tests connect to a real database; no mock repositories.
```
-frontmatter 只有这三个字段——记忆属于哪一层由所在目录表达,不设 `type` 字段(早期文件里残留的 `type:` 行会被当作未知字段忽略)。值得保存的是:用户是谁(角色、专长、长期偏好)以及希望 agent 如何工作(连同原因);无法仅从代码推导的决策、约束与计划;外部系统、文档与服务的稳定入口。提示词还点明了这类事实出现的时机——同一诉求被再次提出、以超出当前任务的方式纠正某项结果、反复讲到的习惯或开发实践、以及交代过一次、否则还要再问一遍的可复用工作信息。「重复」是强信号而非硬性条件,长期偏好只讲一次同样成立;拿不准是否值得记住时,agent 会在对话里直接询问用户。记错的主题连同其索引行一并删除;日期写绝对日期(`YYYY-MM-DD`),相对日期对后续 Session 没有意义。不应保存:可从代码、配置或 Git 历史直接获得的事实;短期任务进度与调试流水;凭据、Token 等敏感值;未经确认的推测;大段对话原文。
+frontmatter 就只有这三个字段。记忆属于哪个作用域由所在目录决定,因此没有 `type` 字段;早期文件里遗留的 `type:` 行会当作未知字段忽略。
+
+默认的记忆提示词告诉模型保存哪些内容:
+
+- 用户是谁、希望 Agent 怎么工作,以及背后的原因
+- 从代码推导不出的目标、决策和约束
+- 指向外部系统、文档和资源的指引
+
+它还列出了会产生这类事实的时刻:同一个请求第二次出现、一条超出当前任务仍然成立的纠正、不止一次提到的习惯或做法,或者一个不记住就得再问的可复用工作细节。重复只会让事实更明显;长期偏好只要清楚地说过一次就够了。分不清某件事值不值得保存时,Agent 会在对话里直接询问。
+
+提示词明确排除以下内容:
-每份 `MEMORY.md` 一行列一条记忆——`- [标题](file.md) — 一句钩子`,链接相对本作用域目录——并与记忆文件同轮更新,两者永不脱节。
+- 代码、配置或 Git 历史里已经写明的事实
+- 未经验证的猜测
+- 对话记录摘录(即使用户要求保存,Agent 也只保存其中非显然的部分)
-进入上下文的只有索引,入口是模板的 `{{MEMORY}}` 占位符。它展开为 `memory.prompt`——记忆的用途、写入规范,以及 `## User memory` 小节与其索引(`{{USER_MEMORY_INDEX}}`)——持久 Workspace 的会话再追加 `memory.workspace_prompt`(`## Workspace memory` 小节,含 `{{WORKSPACE_MEMORY_INDEX}}`)。两个提示词都是 Agent 级配置,可在设置页记忆标签直接编辑;区块和模板其他小节一样用 Markdown 标题组织。`User Memory Dir` 行是字面模式 `<app_data_dir>/agents/<agent_id>/agent_state/memory/user`,模型可据 Environment 段自行拼出;`Workspace Memory Dir` 行经 `{{WORKSPACE_MEMORY_DIR}}` 直接渲染为解析后的路径——它的末段(工作区记忆键)是路径哈希,模型无从自行推得。
+用户想保存的其他内容都可以存。对于纠正和决策,模型会加上 **Why:** 和 **How to apply:** 两行。事后证明有误的记忆会连同索引行一起删除。日期一律写绝对日期(`YYYY-MM-DD`),因为相对日期对后续 Session 毫无意义。
-空索引会注入一句"尚未保存任何内容"的占位说明。每个作用域最多注入 200 行索引(按约定每条记忆一行),再以总计 25000 字符兜底——防住行数不多但单行超长的索引;超出上限的部分以截断提示替代、由模型自行读取完整 `MEMORY.md`,磁盘上的文件不受影响。默认记忆提示词只声明行数上限,并要求每行索引保持在约 150 字符以内,模型在撞线之前就会把索引保持在限内;字符兜底仅存在于代码中。主题正文由模型按需读取。
+### 注入方式
-两半之所以是两个独立配置键:替换引擎没有条件分支,临时 Workspace 绝不能被塞进 Workspace 小节(它的目录行和作用域二选一规则),所以那一半在临时 Workspace 下干脆不追加。Harness 只负责确定记忆位置并限制写入边界,判断什么值得保存、如何划分主题、如何维护索引都由模型用现有文件工具完成。
+只有索引会进入上下文,通过模板中的 `{{MEMORY}}` 占位符注入。每个 `MEMORY.md` 每行列出本作用域的一条记忆,格式为 `- [Title](file.md) — hook`,链接相对于作用域目录。模型更新文件时同步更新索引,删除也不例外,两者始终保持一致。
-模板中没有 `{{MEMORY}}` 的 Agent(例如创建于记忆功能之前)不会注入任何内容;记忆标签页会给出提示并提供一键插入占位符(插到 `# Environment` 之前,即默认模板中的位置)——不存在任何自动拼接。组装后的完整提示词记录在 `session_meta`。
+`{{MEMORY}}` 展开为:
-查看、删除或让 Agent 修改已保存的记忆,见设置页的[记忆标签](/web-app#agent-设置agents)。
+- `memory.prompt`:记忆的用途和保存方法,然后是一个 `## User memory` 小节,内含索引(`{{USER_MEMORY_INDEX}}`)。
+- `memory.workspace_prompt`:仅当 Session 运行在持久 Workspace 中时存在,是一个包含 `{{WORKSPACE_MEMORY_INDEX}}` 的 `## Workspace memory` 小节。
+
+这两段提示词都是 Agent 级配置,可在 **记忆** 标签页编辑,和模板其他小节一样按 Markdown 标题组织。`User Memory Dir` 一行是字面模板 `<app_data_dir>/agents/<agent_id>/agent_state/memory/user`,模型根据 Environment 小节自行解析。`Workspace Memory Dir` 一行则通过 `{{WORKSPACE_MEMORY_DIR}}` 直接渲染为解析后的路径,因为它的最后一段是 Workspace 记忆键,这是模型自己拼不出来的路径哈希。
+
+限制:
+
+- 索引为空时,会注入一条明确的「还没有保存任何内容」提示。
+- 每个作用域的注入上限是 200 行(按惯例一条记忆一行),另外还有一个 25,000 字符的总量兜底上限,应对索引里出现几条超长行的情况。超过上限时,会附上一条截断说明,让模型自己去打开完整的 `MEMORY.md`。磁盘上的文件始终原样不动。
+- 默认记忆提示词写明了行数上限,并要求索引行控制在约 150 字符以内,让模型在触及上限之前就把索引保持得很短。字符数兜底只存在于代码中。
+- 模型按需读取主题正文。
+
+这两段是各自独立的配置键,因为占位符替换不支持条件判断。临时 Workspace 绝不能收到 Workspace 小节(即它的目录行和选择作用域的规则),所以那一段在那里根本不会追加。Harness 只决定记忆存放在哪里,并把写入限制在这个范围内。判断什么值得保存、拆分主题、维护索引,这些都是模型的工作,用普通文件工具完成。
+
+模板里没有 `{{MEMORY}}` 就不会注入任何记忆;在记忆功能发布之前创建的 Agent 就是例子。**记忆** 标签页会说明这一情况,并提供一个明确的一键操作:把占位符插入到 `# Environment` 之前,也就是默认模板中它所在的位置。任何内容都不会自动拼接进去。组装好的完整提示词记录在 `session_meta` 中。
## Vault
-`agent_state/.vault.toml` 是 Agent 级的环境变量保险库:隐藏文件,落盘权限 0600。
+`agent_state/.vault.toml` 是 Agent 级的环境变量密钥保险柜:一个隐藏文件,以 0600 权限写入。
-- 键名须匹配 `^[A-Za-z_][A-Za-z0-9_]*$`(shell 环境变量命名规则);
-- 值只注入工具子进程的环境变量,永远不进入模型上下文与 Trace;
-- 系统提示词中只披露键名:模板的 `{{VAULT}}` 占位符展开为 `vault.prompt`(内含 `{{VAULT_KEYS}}` 键名列表),提示词可在 Vault 标签页编辑;`vault.enabled` 关闭则整段为空——值照旧注入子进程,只是模型看不到键名清单。旧模板的内联 `{{VAULT_KEYS}}` 仍被替换并受同一开关控制,标签页提供一键迁移(见「系统提示词占位符」一节);
-- 经 Web/API 保存会使该 Agent 已缓存的 Session 运行时失效:其任意 Session 的下一个任务会重新恢复(resume)并使用新值;进行中的任务保持其启动时的值(CLI 直接改文件对运行中的 server 则要等 Session 下次创建或恢复时生效);
-- 通过 CLI `penguin config vault set/list/remove` 或 Web 的 Vault 标签页管理。
+- 键名必须匹配 `^[A-Za-z_][A-Za-z0-9_]*$`(即 shell 环境变量的命名规则)。值的长度上限为 8,192 个字符。
+- 值只注入工具子进程的环境。这些值绝不会进入模型上下文,也不会出现在 Trace 里。
+- 系统提示词里只显示键名。模板中的 `{{VAULT}}` 占位符展开为 `vault.prompt`,其中带有 `{{VAULT_KEYS}}` 键名列表,可在 **密钥保险柜** 标签页编辑。`vault.enabled` 关闭时这一块为空:值仍会注入子进程,只是模型看不到键名。旧版模板里内联的 `{{VAULT_KEYS}}` 在同一个开关控制下仍会照常替换,标签页还提供一键迁移(参见[系统提示词占位符](#系统提示词占位符))。
+- 保存后的更改立即对新 Session 生效;正在运行的 Session 则在下一次压缩时生效,与其他 Agent State 的更改一样。无论在 Web App 里保存、通过 API 保存还是用 CLI 保存,行为都相同。
+- 用 `penguin config vault set/list/remove` 管理,或在 **密钥保险柜** 标签页操作。
## 定时任务
-`agent_state/schedule/<name>.toml` 每个文件描述一个定时任务(文件名即任务标识),按节律向 Agent 发送预设 Prompt。定时任务仅在 Web 服务(server 运行时)运行期间执行,在 Web 的 Agent 设置 → Schedule 标签页管理。
+每个文件 `agent_state/schedule/<name>.toml` 描述一个定时任务,按设定的周期向 Agent 发送预设 Prompt。文件名就是任务的标识。定时任务只在 Web 服务(服务器运行时)运行期间执行。可以在 Agent 设置的 **定时任务** 标签页或对话页面管理,见[定时任务](/schedules)。
-| 字段 | 必填 | 说明 |
-| --- | --- | --- |
-| `prompt` | 是 | 触发时发送的 Prompt |
-| `enabled` | 否 | 是否启用,缺省 `false` |
-| `start_at` | 是 | 首次触发时刻(ISO 8601) |
-| `period` | 否 | 周期,形如 `30m` / `12h` / `7d`,下限 5 分钟;缺省为一次性任务 |
-| `end_at` | 否 | 结束时刻,须晚于 `start_at` |
-| `session_id` | 否 | 绑定既有 Session;与下列三项互斥 |
-| `workspace` | 否 | 新建 Session 模式的 Workspace |
-| `provider` / `model_id` | 否 | 新建 Session 模式的模型成对引用;要写就两个都写,只写 `model_id` 会被拒绝,两个都不写则使用 Project 默认模型 |
+| 字段 | 类型 | 默认值 | 说明 |
+| --- | --- | --- | --- |
+| `prompt` | 字符串 | 必填 | 每次触发时发送的 Prompt |
+| `enabled` | 布尔 | `false` | 任务是否触发 |
+| `start_at` | 日期时间(ISO 8601) | 必填 | 首次触发时间 |
+| `period` | 字符串 | 省略表示一次性任务 | 执行周期,如 `30m` / `12h` / `7d`;最小 5 分钟 |
+| `end_at` | 日期时间(ISO 8601) | — | 结束时间;必须晚于 `start_at` |
+| `session_id` | 字符串 | — | 把任务绑定到一个已有 Session;与下面三个字段互斥 |
+| `workspace` | 字符串 | — | 新建 Session 模式使用的 Workspace |
+| `provider` / `model_id` | 字符串对 | Project 的默认模型 | 新建 Session 模式的成对模型引用 |
+
+`provider` 和 `model_id` 要么都写,要么都不写。只写 `model_id` 的文件无效;两者都不写时使用 Project 的默认模型。
```toml
-prompt = "检查昨日构建结果并汇总失败原因"
+prompt = "Check yesterday's builds and summarize the failures"
enabled = true
start_at = 2026-08-01T09:00:00Z
period = "12h"
```
-模板的 `{{SCHEDULES}}` 占位符展开为 `schedules.prompt`:教模型用文件工具自行管理这些 TOML 文件(目录、字段规则、约 30 秒自动生效、防重复等卫生规则),末尾经 `{{SCHEDULE_LIST}}` 注入现有任务名列表。提示词可在定时任务标签页编辑;`schedules.enabled` 关闭则整段为空——server 照常按计划触发任务,只是模型不了解任务体系。早于本机制创建的 Agent 模板没有该占位符,标签页提供一键插入。
+模板中的 `{{SCHEDULES}}` 占位符展开为 `schedules.prompt`。它教模型用自己的文件工具管理这些 TOML 文件:目录位置、字段规则、约 30 秒内自动生效,以及防止重复的规则。末尾通过 `{{SCHEDULE_LIST}}` 附上当前的任务名列表。这段提示词可在 **定时任务** 标签页编辑。`schedules.enabled` 关闭时这一块为空:服务器仍按计划触发任务,只是不再教模型这套任务系统。在这个机制出现之前创建的 Agent,模板里没有这个占位符,标签页提供一键插入。
## 设计原则
-Agent 的行为完整地存放于磁盘上的可编辑文件——提示词、Skill、配置都是数据而非代码。正因如此,Agent 才能被 Agent 改进:优化器编辑的与你手工编辑的是同一批文件。参见[自我进化](/self-improvement)与 [CLI 参考](/cli)。
+Agent 的行为完全由磁盘上可编辑的文件决定:Prompt、Skill 和配置都是数据,而不是代码。正因如此,Agent 才能改进 Agent:优化器编辑的正是你手动编辑的那些文件。参见[自我进化](/self-improvement)和 [CLI 参考](/cli)。
diff --git a/packages/docs/content/evaluation-center.en.md b/packages/docs/content/evaluation-center.en.md
new file mode 100644
index 00000000..b87184d3
--- /dev/null
+++ b/packages/docs/content/evaluation-center.en.md
@@ -0,0 +1,196 @@
+---
+title: Evaluation Center
+description: Create Benchmarks, score agents on them, and improve agents against those scores in the Web App.
+---
+
+The Evaluation Center is where you measure and improve agents in the Web App. A **Benchmark** is a set of cases, each with a task statement and a private scoring rubric. A Benchmark belongs to the Project rather than to one agent, so it can score any agent in the Project.
+
+- To build a Benchmark, see [Create a Benchmark with AI](#create-a-benchmark-with-ai) or [Create a Benchmark manually](#create-a-benchmark-manually).
+- To read the cases, the score chart and past evaluations, see [Read a Benchmark](#read-a-benchmark).
+- To score an agent, see [Evaluate an agent](#evaluate-an-agent).
+- To improve an agent against its scores, see [Optimize an agent](#optimize-an-agent).
+- To change the questions or clean up, see [Replace a Benchmark](#replace-a-benchmark) and [Delete a Benchmark](#delete-a-benchmark).
+
+For how evaluation and optimization work behind these pages, see [Self-Improvement](/self-improvement).
+
+## Open the Evaluation Center
+
+In the sidebar, select **Evaluation Center**. The page (`/benchmark`) lists every Benchmark of the current Project as a card.
+
+Under the title, three numbered step cards outline the loop: **Create**, **Evaluate** and **Optimize**. Each says where to do that step: with the create buttons at the top right, or with **Use** on a Benchmark followed by the matching tab. The owner gets two create buttons, **Create with AI** and **Create manually**; a member gets **Create with AI** alone, and the first card names only that.
+
+Each Benchmark card shows:
+
+- the title, the directory name and the description;
+- the number of cases and the runs per case;
+- when the Benchmark was last evaluated, and the agents it has tested;
+- a sparkline of its scores, and the newest score with its change from the previous evaluation under the same [label](#score-chart).
+
+A card's actions are **Use**, **View** and, for the Project owner, a delete icon. Selecting the card itself does the same as **View**.
+
+To narrow the list, type in the search box; it matches titles, descriptions and tested agents. The address `/benchmark?agentId=<agent>` lists only the Benchmarks that have evaluated that agent; select **Show all** to see every Benchmark again.
+
+### Benchmarks that are not ready
+
+A Benchmark that is not finished is masked. Its card is dimmed under a notice, **Use** and **View** are disabled, and its page shows the same notice in place of the cases and the chart. Only the owner's delete icon still works.
+
+- **Being built**: AI is still writing the cases and calibrating their difficulty. The Benchmark opens once that is done.
+- **Creation failed**: the difficulty calibration never finished. The owner deletes the Benchmark and creates it again; a member is only told that calibration did not finish, because deleting is the owner's to do.
+
+### The example Benchmark
+
+Every Project comes with `example-benchmark`, whose sample evaluations test `default_agent`, so the page has data from the start. If you delete it, it comes back the next time `default_agent` loads.
+
+## Create a Benchmark with AI
+
+AI writes the cases for an agent, trial-runs each case to calibrate its difficulty, and records the agent's first score, the baseline.
+
+1. At the top right of the Evaluation Center, select **Create with AI**.
+2. In the **Create a Benchmark with AI** dialog, choose a **Test Agent**: the agent the cases are written for. Its scores are recorded under it.
+3. Describe the capability and the scenarios to test, or start from one of the examples under **Try an example**.
+4. Select **Edit in a new conversation**. The prompt opens in a new conversation's composer, with the `benchmark-design` and `agent-evaluation` Skills selected.
+5. Review the prompt and send it. Nothing runs until you do.
+
+The dialog's "Done by … in a new conversation" line names the agent that does the writing: the Project's default agent, not the Test Agent.
+
+The Builder runs the Test Agent on the model of this new conversation, for the trial runs and for the baseline. Evaluations started later from the **Evaluate** tab run the agent on the model it is configured with, and the chart gives each model its own line. To keep the baseline on the same line as later scores, pick the Test Agent's configured model in the composer before you send.
+
+While the cases are being written, the Benchmark's card shows **Being built**. The Benchmark opens once the baseline is recorded. If calibration fails, the card shows **Creation failed**; the owner then deletes the Benchmark and creates it again.
+
+## Create a Benchmark manually
+
+**Before you begin**
+
+- Only the Project owner can create a Benchmark manually.
+
+1. At the top right of the Evaluation Center, select **Create manually**.
+2. In the **Create a Benchmark manually** form, fill in **Title**, **Benchmark id** and **Description**. The id is also the directory name: letters, digits, `_` and `-` only. It does not follow the title as you type; select **Generate with AI** beside the field to derive a kebab-case id from the title.
+3. Set **Runs per case**, an integer from 1 to 1000. Evaluations and optimizations run every case this many times by default and average the results.
+4. For each case, fill in **Directory suffix**, **Case title**, **Statement** and **Scoring rubric**. The statement goes to the agent under test. The rubric lists observable scoring items that total 100 points, and never reaches the agent under test. Select **Add case** to add another case.
+5. Select **Create Benchmark**. The Benchmark's page opens.
+
+You do not choose an owning agent. A manual Benchmark is published at once but has no baseline yet, so [evaluate an agent](#evaluate-an-agent) on it before you optimize.
+
+## Read a Benchmark
+
+Select a Benchmark card, or **View**, to open the Benchmark's page (`/benchmark/<benchmark>`). **Back to list** returns to the list.
+
+The header shows the Benchmark's directory, `benchmarks/<benchmark>`, beside the title, with a **Copy directory path** button, and its own **Use** button.
+
+### Cases
+
+**Cases** lists the Benchmark's cases. Select **View details** on a case to open it.
+
+The case dialog shows the case's files in the same file browser as the plugin details: a file tree on the left, listed level by level, and a read-only preview on the right. The tree has two top-level folders:
+
+- **Task materials**: what the agent under test works from.
+- **Scoring rubric**: what the evaluator scores against. This folder is marked **Hidden from Target Agent**.
+
+### Score chart
+
+The **Score over time** chart plots each evaluation's score over time, with one line per **label**. A label combines the tested agent, the model ID and the thinking level, so only comparable scores share a line. A record without a label falls into a grey **Unlabeled** series.
+
+The Agent State version is deliberately left out of the label. Successive versions of one agent on the same model and thinking level stay on one line, which is where an improvement becomes visible. Hover over a point to see the version it tested.
+
+### Evaluations
+
+The **Evaluations** table lists the Benchmark's evaluations, newest first. Its columns are **Time**, **Tested agent**, **Version**, **Model ID**, **Thinking level**, **Score**, **Cost** and **Duration**. A Benchmark with no evaluations shows **No evaluations yet** instead.
+
+Select a row to open that evaluation in a dialog. The dialog shows:
+
+- the label, with the tested agent and its version;
+- the score, cost and duration;
+- the evaluation's summary, with its title and body shown separately;
+- a per-case table whose rows expand to every run's raw result and the Session it ran in.
+
+Select a case in that table to open the case dialog on top.
+
+## Ask AI about a case or an evaluation
+
+The case dialog and the evaluation dialog both end with **Ask AI**. It opens a prompt dialog with a question already filled in, and example questions you can switch to. The default question is also the first example, so you can bring it back after trying another.
+
+In the case dialog, the examples are:
+
+- **Explain what this case tests and what a strong answer looks like** (the default)
+- **What does the rubric reward?**
+- **Why did a run score low here?**
+- **How could the statement be clearer?**
+
+In the evaluation dialog, the examples are:
+
+- **Explain this evaluation's result** (the default)
+- **Why is the score low?**
+- **Which cases are weakest, and what should change?**
+- **What changed against the previous evaluation?**
+
+A fixed ending passes along the facts on screen:
+
+- For a case: the paths of its `statement/README.md` and `rubric/README.md`, and how the latest evaluation's runs scored it.
+- For an evaluation: the Benchmark id and directory, the time, the label, the version, the evaluation runtime, the total and per-case scores, every run's Session id, and the summary.
+
+The agent is asked to read those files and Traces and explain what it finds. It only reads and analyzes, and changes neither the Benchmark nor the tested agent. Select **Edit in a new conversation**, then send the prompt.
+
+## Evaluate an agent
+
+An evaluation runs an agent on every case of a Benchmark and adds one labelled score to the Benchmark's scoreboard.
+
+1. On a Benchmark card, or in a Benchmark page's header, select **Use**. The dialog opens on the **Evaluate** tab.
+2. In **Tested agent**, choose the agent to evaluate. It defaults to the agent of the newest evaluation.
+3. In **Evaluator agent**, choose the agent that runs and scores the evaluation. It needs the `agent-evaluation` Skill, and the dialog warns you when that Skill is missing.
+4. Optional: change **Model of the evaluation conversation** (preset to the Project's default model) or **Runs per case** (preset to the Benchmark's configured count), and add a **Note**.
+5. Select **Edit in a new conversation**, review the prompt, and send it.
+
+The dialog has no field for the model or thinking level the tested agent runs on. **Model of the evaluation conversation** only sets the model of the conversation that dispatches and totals the runs.
+
+The evaluation conversation, and every Test Session it starts, is filed under the **Evaluations** folder of the session list. The finished evaluation becomes the newest row of the Benchmark's **Evaluations** table.
+
+## Optimize an agent
+
+Optimization changes an agent one hypothesis at a time and keeps a new version only when its score strictly improves. It measures against the agent's baseline on this Benchmark.
+
+**Before you begin**
+
+- The agent has a complete evaluation on this Benchmark. A Benchmark created with AI has one for its Test Agent; otherwise, [evaluate the agent](#evaluate-an-agent) first.
+
+1. On a Benchmark card, or in a Benchmark page's header, select **Use**, then the **Optimize** tab.
+2. In **Tested agent**, choose the agent to improve. The tab shows its current baseline and the target.
+3. In **Optimizer agent**, choose the agent that does the work. It needs the `agent-optimization` Skill, and the dialog warns you when that Skill is missing.
+4. Set **Runs per case**, **Round limit** (3 by default) and **Target score**. The target defaults to the baseline rounded up plus 10, at most 100.
+5. Optional: change **Model of the optimizer's conversation** (preset to the Project's default model), and describe a **Focus**.
+6. Select **Edit in a new conversation**, review the prompt, and send it.
+
+The optimizer stops early when it reaches the target score, and otherwise after the round limit. Its evaluations keep the model and thinking level the baseline recorded. Each accepted version appears as a new point on the same chart line, and its version shows in the **Version** column and in the point's hover text.
+
+> [!WARNING]
+> When the tested agent has no baseline on this Benchmark, the tab warns you to take one on the **Evaluate** tab first, and the target defaults to 80. Sending is not blocked, but the `agent-optimization` Skill stops and explains that it needs a baseline.
+
+## Replace a Benchmark
+
+A Benchmark's cases are frozen once it exists. Neither the Web App nor the server API can edit a statement or a rubric: changing the questions would make the scores already on the scoreboard incomparable. The calibration AI does while writing the cases happens before the baseline is taken, as part of creating them.
+
+To ask different questions, create a new Benchmark and delete the old one:
+
+1. Open a case, select **Ask AI**, choose **How could the statement be clearer?**, and send the conversation.
+2. Select **Create with AI**, and describe the old Benchmark together with the suggested changes.
+3. Once the new Benchmark is published, [delete the old one](#delete-a-benchmark).
+
+## Delete a Benchmark
+
+Only the Project owner can delete a Benchmark, and only from its card in the list, not from the Benchmark's page.
+
+1. On the Benchmark's card, select the delete icon (**Delete Benchmark**).
+2. Read the confirmation: every case and evaluation record will be removed, and this cannot be undone.
+3. Select **Delete**.
+
+> [!NOTE]
+> Deleting `example-benchmark` does not last: it is written again the next time `default_agent` loads.
+
+## How it works
+
+- **Storage.** A Benchmark is the directory `benchmarks/<benchmark>/` in the Project, beside `agents/`, named by its Benchmark id. Each case has `statement/README.md` and `rubric/README.md`, and the scores are in `scoreboard.yaml`. See [Benchmark storage](/self-improvement#benchmark-storage).
+- **Status.** `status` in `benchmark_config.toml` drives the mask: `draft` shows **Being built**, `failed` shows **Creation failed**, and `published` lifts the mask.
+- **Creating with AI.** The prompt's fixed ending hands the `benchmark-design` Skill the Test Agent's id, a desired baseline score and a pilot-iteration limit, and asks for the baseline to be taken.
+- **Creating manually.** The server writes the form to disk in the layout the Skills read (`POST …/benchmarks`, owner only), with the status `published`.
+- **Evaluating.** The prompt asks for the full Case × runs matrix through self-spawned `agent-evaluation` subagents. Every result must report the same agent, model and thinking level, and exactly one labelled evaluation is appended to `scoreboard.yaml`. The tested agent and the Benchmark are left untouched.
+- **Deleting.** The server removes the directory whole (`DELETE …/benchmarks/:id`). Deleting a Benchmark while an evaluation is still running can leave a directory behind, because the evaluation keeps writing into it. That directory has no `benchmark_config.toml`, so it is not listed, and you can delete it by hand.
+- **The example Benchmark.** `example-benchmark` is written whenever `benchmarks/example-benchmark/` is missing and `default_agent` loads.
diff --git a/packages/docs/content/evaluation-center.zh.md b/packages/docs/content/evaluation-center.zh.md
new file mode 100644
index 00000000..8862fec9
--- /dev/null
+++ b/packages/docs/content/evaluation-center.zh.md
@@ -0,0 +1,196 @@
+---
+title: 评估中心
+description: 在 Web App 中创建 Benchmark、给 Agent 打分,并根据分数改进 Agent。
+---
+
+评估中心是 Web App 里衡量和改进 Agent 的地方。**Benchmark** 是一组题目,每道题包含任务题干和一份私有的评分细则。Benchmark 属于 Project,不属于某个 Agent,所以它可以给 Project 里的任何 Agent 打分。
+
+- 要创建 Benchmark,见[让 AI 创建 Benchmark](#让-ai-创建-benchmark) 或[手动创建 Benchmark](#手动创建-benchmark)。
+- 要查看题目、分数曲线和历次评估,见[查看 Benchmark](#查看-benchmark)。
+- 要给 Agent 打分,见[评估 Agent](#评估-agent)。
+- 要根据分数改进 Agent,见[优化 Agent](#优化-agent)。
+- 要换一批题目或清理 Benchmark,见[替换 Benchmark](#替换-benchmark) 和[删除 Benchmark](#删除-benchmark)。
+
+这些页面背后的评估与优化机制,见[自我进化](/self-improvement)。
+
+## 打开评估中心
+
+在侧边栏中选择**评估中心**。这个页面(`/benchmark`)以卡片形式列出当前 Project 的所有 Benchmark。
+
+标题下方有三张带编号的步骤卡片,概括了整个循环:**出题**、**评估**和**优化**。每张卡片都写明在哪里做这一步:用右上角的创建按钮,或者在某个 Benchmark 上点**使用**,再选对应的标签页。owner 有**用 AI 创建**和**手动创建**两个按钮;成员只有**用 AI 创建**,第一张卡片也只写这一个。
+
+每张 Benchmark 卡片显示:
+
+- 标题、目录名和描述;
+- 题目数量和每题运行次数;
+- 最近一次评估的时间,以及测过的 Agent;
+- 分数走势小图,以及最新分数和它相对同一[标签](#分数曲线)下上一次评估的变化。
+
+卡片上的操作有**使用**、**查看**,Project owner 还能看到一个删除图标。直接点卡片和点**查看**效果相同。
+
+要缩小列表范围,在搜索框里输入即可,搜索匹配标题、描述和被测智能体。访问 `/benchmark?agentId=<agent>` 只列出评估过这个 Agent 的 Benchmark;点**显示全部**可以重新看到所有 Benchmark。
+
+### 尚未就绪的 Benchmark
+
+未完成的 Benchmark 显示为遮罩状态:卡片变暗并盖上一条提示,**使用**和**查看**不可用,它的页面也在题目和曲线的位置显示同样的提示。只有 owner 的删除图标仍然可用。
+
+- **构建中**:AI 还在出题并校准难度,完成后即可打开这个 Benchmark。
+- **创建失败**:难度校准没有完成。由 owner 删除这个 Benchmark 再重新创建;成员只会看到校准没有完成,因为删除是 owner 的操作。
+
+### 示例 Benchmark
+
+每个 Project 都自带 `example-benchmark`,其中的示例评估测的是 `default_agent`,所以页面一开始就有数据。删掉之后,下次加载 `default_agent` 时它又会回来。
+
+## 让 AI 创建 Benchmark
+
+AI 为一个 Agent 出题,逐题试测来校准难度,并记录这个 Agent 的第一个分数,也就是基线分。
+
+1. 在评估中心右上角,选择**用 AI 创建**。
+2. 在**让 AI 创建 Benchmark** 对话框中,选择**被测智能体**,也就是这套题要考的 Agent。分数会记在它名下。
+3. 描述要考察的能力和场景,或者从**试试这些示例**里选一个作为起点。
+4. 选择**在新对话中编辑**。提示词会填进一个新对话的输入框,并已选好 `benchmark-design` 和 `agent-evaluation` 两个 Skill。
+5. 检查提示词,然后发送。发送之前什么都不会运行。
+
+对话框里「将由『…』在新对话中完成」这一行写明了实际出题的 Agent:Project 的默认 Agent,而不是被测智能体。
+
+Builder 试测题目和记录基线分时,都用这个新对话的模型来运行被测智能体。之后在**评估**标签页发起的评估,则用这个 Agent 自己配置的模型运行,而图表会为每个模型单独画一条线。想让基线分和之后的分数落在同一条线上,发送前在输入框里选好被测智能体配置的模型。
+
+出题期间,这个 Benchmark 的卡片显示**构建中**。记录好基线分后,Benchmark 即可打开。校准失败时,卡片显示**创建失败**,由 owner 删除这个 Benchmark 再重新创建。
+
+## 手动创建 Benchmark
+
+**开始之前**
+
+- 只有 Project owner 能手动创建 Benchmark。
+
+1. 在评估中心右上角,选择**手动创建**。
+2. 在**手动创建 Benchmark** 表单中,填写**标题**、**Benchmark id** 和**描述**。id 也是目录名,只能包含字母、数字、`_` 和 `-`。它不会随标题自动变化;点输入框旁边的**用 AI 生成**,可以从标题生成一个 kebab-case 的 id。
+3. 设置**每题运行次数**,取 1 到 1000 之间的整数。评估和优化默认把每道题运行这么多次,再取平均。
+4. 为每道题填写**目录名后缀**、**题目标题**、**题干**和**评分细则**。题干交给被测的 Agent;评分细则列出可观察的评分项,合计 100 分,永远不会交给被测的 Agent。点**添加题目**可以再加一道题。
+5. 选择**创建 Benchmark**。这个 Benchmark 的页面随即打开。
+
+手动创建时不用选择所属的 Agent。手动创建的 Benchmark 立即发布,但还没有基线分,所以优化之前,先用它[评估 Agent](#评估-agent)。
+
+## 查看 Benchmark
+
+点 Benchmark 卡片或**查看**,打开这个 Benchmark 的页面(`/benchmark/<benchmark>`)。**返回列表**回到列表页。
+
+页头在标题旁边写出 Benchmark 的目录 `benchmarks/<benchmark>`,附带**复制目录路径**按钮,另有它自己的**使用**按钮。
+
+### 题目
+
+**题目**区域列出这个 Benchmark 的所有题目。点某道题的**查看详情**即可打开它。
+
+题目对话框用和插件详情相同的文件浏览器展示题目文件:左侧是逐级展开的文件树,右侧是只读预览。文件树有两个顶层文件夹:
+
+- **任务材料**:被测的 Agent 据此作答。
+- **评分标准**:评估方据此打分。这个文件夹标注着**被测 Agent 不可见**。
+
+### 分数曲线
+
+**分数随时间变化**图表按时间画出每次评估的分数,每个**标签**一条线。标签由被测 Agent、模型 ID 和思考等级组成,所以只有可比的分数才会落在同一条线上。没有标签的记录归入灰色的**未标注**系列。
+
+标签刻意不包含 Agent State 版本:同一个 Agent 在相同模型和思考等级下的历次版本会留在同一条线上,改进正应该在这条线上显现出来。把鼠标悬停在某个点上,可以看到它测的是哪个版本。
+
+### 评估明细
+
+**评估明细**表按从新到旧的顺序列出这个 Benchmark 的评估,列依次是**时间**、**被测 Agent**、**版本**、**模型 ID**、**推理强度**、**分数**、**成本**和**耗时**。还没有评估的 Benchmark 会显示**暂无评估记录**。
+
+点一行,就在对话框里打开这次评估。对话框显示:
+
+- 标签,以及被测 Agent 和它的版本;
+- 分数、成本和耗时;
+- 这次评估的说明,标题和正文分开展示;
+- 逐题表,每行可以展开,查看每次运行的原始结果及其所在的 Session。
+
+在这张表里点一道题,题目对话框会叠在上面打开。
+
+## 就题目或评估问 AI
+
+题目对话框和评估对话框的底部都有**问 AI**。点开是一个提示词对话框,问题已经填好,还可以换成其他示例问题。默认问题就是第一个示例,试过别的问题后可以随时换回来。
+
+题目对话框中的示例:
+
+- **解释这道题考什么、怎样才算答好**(默认)
+- **评分细则在奖励什么?**
+- **为什么有的运行在这道题上分数低?**
+- **题干怎样才能更清楚?**
+
+评估对话框中的示例:
+
+- **解释这次评估的结果**(默认)
+- **为什么这次分数低?**
+- **哪些题最弱、该改什么?**
+- **与上一次评估相比变化在哪?**
+
+提示词末尾有一段固定内容,把屏幕上的事实一并交给 Agent:
+
+- 对于题目:`statement/README.md` 和 `rubric/README.md` 的路径,以及最近一次评估里各次运行在这道题上的分数。
+- 对于评估:Benchmark id 和目录、评估时间、标签、版本、评估 Runtime、总分和逐题结果、每次运行的 Session id,以及评估说明。
+
+提示词要求 Agent 读这些文件和 Trace,解释它的发现。Agent 只读取和分析,既不改 Benchmark,也不改被测的 Agent。选择**在新对话中编辑**,然后发送提示词。
+
+## 评估 Agent
+
+评估让一个 Agent 跑完 Benchmark 的每道题,并在这个 Benchmark 的记分板上新增一条带标签的分数。
+
+1. 在 Benchmark 卡片或 Benchmark 页面的页头上,选择**使用**。对话框默认打开**评估**标签页。
+2. 在**被测智能体**中,选择要评估的 Agent,默认是最近一次评估所测的 Agent。
+3. 在**执行评估的智能体**中,选择负责运行和打分的 Agent。它需要装有 `agent-evaluation` Skill,没装时对话框会提醒你。
+4. 可选:修改**评估会话使用的模型**(预设为 Project 的默认模型)或**每题运行次数**(预设为 Benchmark 配置的次数),并填写**说明**。
+5. 选择**在新对话中编辑**,检查提示词,然后发送。
+
+对话框里没有设置被测 Agent 所用模型和思考等级的字段。**评估会话使用的模型**只决定派发和汇总评测的那个会话使用什么模型。
+
+评估会话,以及它启动的每个被测会话,都归入会话列表的**评估任务**折叠夹。评估完成后,会成为这个 Benchmark **评估明细**表的最新一行。
+
+## 优化 Agent
+
+优化每次按一个假设改动 Agent,分数严格提高才保留新版本。比较的起点是这个 Agent 在当前 Benchmark 上的基线分。
+
+**开始之前**
+
+- 这个 Agent 在当前 Benchmark 上已有一次完整的评估。用 AI 创建的 Benchmark 已经为它的被测智能体测过一次;其他情况下,先[评估这个 Agent](#评估-agent)。
+
+1. 在 Benchmark 卡片或 Benchmark 页面的页头上,选择**使用**,再切到**优化**标签页。
+2. 在**被测智能体**中,选择要改进的 Agent。标签页上会显示它当前的基线分和目标分数。
+3. 在**执行优化的智能体**中,选择实际执行优化的 Agent。它需要装有 `agent-optimization` Skill,没装时对话框会提醒你。
+4. 设置**每题运行次数**、**最多轮数**(默认 3)和**目标分数**。目标分数默认是基线分向上取整后加 10,最高 100。
+5. 可选:修改**优化会话使用的模型**(预设为 Project 的默认模型),并填写**优化重点**。
+6. 选择**在新对话中编辑**,检查提示词,然后发送。
+
+达到目标分数时,优化会提前结束,否则在跑满最多轮数后结束。优化过程中的评估沿用基线记录的模型和思考等级。每个采纳的版本都会在同一条曲线上添一个点,版本号显示在**版本**列和这个点的悬停提示里。
+
+> [!WARNING]
+> 被测的 Agent 在这个 Benchmark 上还没有基线分时,标签页会提示你先到**评估**标签页取得基线分,目标分数也默认为 80。这时仍然可以发送,但 `agent-optimization` Skill 会停下来,说明它需要基线分。
+
+## 替换 Benchmark
+
+Benchmark 一经创建,题目就冻结了。Web App 和服务端接口都不能修改题干或评分细则:题目一改,记分板上已有的分数就不再可比。AI 出题过程中的难度校准发生在取得基线分之前,属于创建的一部分。
+
+想换一批题目,就新建一个 Benchmark,再删掉旧的:
+
+1. 打开一道题,选择**问 AI**,选**题干怎样才能更清楚?**,然后发送。
+2. 选择**用 AI 创建**,描述旧的 Benchmark 以及建议的修改。
+3. 新 Benchmark 发布后,[删除旧的那个](#删除-benchmark)。
+
+## 删除 Benchmark
+
+只有 Project owner 能删除 Benchmark,而且只能在列表中它的卡片上删除,Benchmark 页面上没有删除入口。
+
+1. 在 Benchmark 卡片上,选择删除图标(**删除 Benchmark**)。
+2. 阅读确认提示:它的全部题目和评估记录都将删除,无法恢复。
+3. 选择**删除**。
+
+> [!NOTE]
+> 删掉 `example-benchmark` 只是暂时的:下次加载 `default_agent` 时,它会重新写入。
+
+## 工作原理
+
+- **存储。** Benchmark 就是 Project 里与 `agents/` 平级的 `benchmarks/<benchmark>/` 目录,以 Benchmark id 命名。每道题都有 `statement/README.md` 和 `rubric/README.md`,分数记在 `scoreboard.yaml` 里。见 [Benchmark 存储](/self-improvement#benchmark-存储)。
+- **状态。** `benchmark_config.toml` 中的 `status` 决定遮罩:`draft` 显示**构建中**,`failed` 显示**创建失败**,`published` 解除遮罩。
+- **用 AI 创建。** 提示词的固定结尾把被测智能体的 id、期望的基线分和 Pilot 迭代上限交给 `benchmark-design` Skill,并要求取得基线分。
+- **手动创建。** 服务端按 Skill 读取的目录结构,把表单内容写入磁盘(`POST …/benchmarks`,仅 owner),状态为 `published`。
+- **评估。** 提示词要求通过自行派生的 `agent-evaluation` 子 Agent 跑完完整的 Case × runs 矩阵。每条结果报告的 Agent、模型和思考等级都必须一致,最后只向 `scoreboard.yaml` 追加一条带标签的评估。被测的 Agent 和 Benchmark 都保持不变。
+- **删除。** 服务端整目录删除(`DELETE …/benchmarks/:id`)。评估还在运行时删除 Benchmark,可能留下一个目录,因为运行中的评估还在往里写。这个目录没有 `benchmark_config.toml`,不会出现在列表里,可以手动删除。
+- **示例 Benchmark。** 只要 `benchmarks/example-benchmark/` 不存在,加载 `default_agent` 时就会写入 `example-benchmark`。
diff --git a/packages/docs/content/files.en.md b/packages/docs/content/files.en.md
new file mode 100644
index 00000000..d70c304c
--- /dev/null
+++ b/packages/docs/content/files.en.md
@@ -0,0 +1,171 @@
+---
+title: Files panel
+description: Browse, preview, edit, and manage the files in a conversation's Workspace.
+---
+
+The **Files** panel is one of the chat page's side panels. It shows the Workspace of the open conversation: a directory tree on the left, and a preview of the selected file on the right. Every member of the Project can browse, preview, edit, upload, rename and delete files here.
+
+- To get started, see [Open the Files panel](#open-the-files-panel).
+- To find a file, see [Search the Workspace](#search-the-workspace).
+- To change files, see [Edit a text file](#edit-a-text-file) and [Use the context menu](#use-the-context-menu).
+- To add files, see [Upload files](#upload-files).
+
+## Open the Files panel
+
+Open the panel from any of these places:
+
+- The top right of the chat toolbar: select **Right sidebar** or **Bottom panel**, then choose **Files**. If the dock already shows other panels, use its **Add panel** menu.
+- The **Shortcuts** launcher on the conversation's right edge.
+- A message: select a file chip or file card to open the panel at that file. A link in a reply that names a file in the Workspace opens it here too, instead of navigating the browser; whether the file exists is not checked first, so the panel says when it is missing.
+
+The panel is available once the conversation has started. See [Use side panels](/chat#use-side-panels).
+
+## Browse the file tree
+
+The tree lists the contents of a directory the first time you open it. File rows show the file size after the name. Point at a row to see its path, size, and modified time.
+
+The tree pane's header holds the search box, **Refresh** and **Upload**.
+
+The path row above the preview names the open file. The leading directories collapse into a single `…` first, and the file name is the last thing to go. When no file is open, the path row names the current directory. The root reads `.`, and the Workspace's absolute path lives in the Session details card.
+
+The tree and the open preview re-read when a turn finishes. The tree also re-reads when the panel comes back into view.
+
+### Move with the keyboard
+
+- Up and down move the selection.
+- Right opens a directory or steps into it.
+- Left closes a directory or steps out.
+- Home and End jump to the first or last row.
+- Enter and Space act like a click.
+
+### Hide the tree or change its width
+
+At the left end of the panel's header row, select **Hide file tree** to slide the tree out of the panel's left edge. The search box, **Refresh** and **Upload** are hidden with it. Select **Show file tree** to bring the tree back. The tree is shown by default, and the panel remembers your choice in the browser.
+
+Drag the divider between the two panes to set the tree's width. When the divider has focus, the arrow keys nudge it. The panel remembers the width too.
+
+When the panel is narrower than 480px, it falls back to a single column: the tree until you choose a file, then the preview with a **Back to list** button.
+
+## Search the Workspace
+
+The search box searches the whole Workspace on the server, not only the directories you have opened.
+
+1. In the tree pane's header, select the **Search files** box.
+2. Enter part of a file or directory name.
+
+A moment after you stop typing, the results appear as a flat list of full paths, shallowest first. While the search runs, the box shows "Searching…". Search matches entry names and ignores case.
+
+A search stops at 200 matches or 20,000 entries walked. It then shows "Too many matches — showing the first N". When nothing matches, it shows "No matches in the Workspace".
+
+Select a directory in the results to clear the search and open that directory in the tree. Press Esc or select the clear button to empty the box.
+
+## Preview a file
+
+Select a file in the tree to open it in the preview. How a file is shown depends on its type:
+
+| File type | How it is shown |
+| --- | --- |
+| Markdown and HTML | Rendered, with a **Preview / Source** toggle |
+| Text | With syntax highlighting and line numbers |
+| Images | Inline. Select the image to zoom. |
+| PDF | Embedded |
+| Anything else | Offered as a download. See [Download a file](#download-a-file). |
+
+A file whose extension says nothing about its type, such as a `Makefile` or a `LICENSE`, is read as text when its bytes look like text.
+
+A Markdown file larger than 64KB opens in the source view. You can still switch to the rendered view. In rendered Markdown, a relative link opens that Workspace file in the panel, and relative images load.
+
+An HTML file can also be opened in a new browser tab: in the preview, select **Open in new tab**.
+
+> [!NOTE]
+> When the app is reached through an address with no separate preview origin, the tab opens sandboxed, without localStorage, cookies or third-party embeds. To avoid the sandbox, reach the app over 127.0.0.1 or localhost, or set `PENGUIN_PREVIEW_ORIGIN`.
+
+A text preview reads up to 1MB. A larger file is shown truncated, with the message "File too large; preview truncated, download for the full file", and cannot be edited here. **Download** is in the preview header.
+
+Three buttons float over the top right of the file view: **Copy code**, **Wrap** and **Edit**. **Wrap** soft-wraps long lines and is on by default. The source view and the editor share the one remembered choice.
+
+## Edit a text file
+
+1. Open the file in the preview, then select **Edit** at the top right of the file view. The preview becomes an editor: the same highlighted text with line numbers, now editable. There is no rich editor.
+2. Make your changes.
+3. Select **Save** (the check mark), or press Ctrl+S / Cmd+S.
+4. In the **Save file** dialog, select **Save** to write the file back.
+
+Select **Cancel** (×) to return to the preview without saving.
+
+The panel asks before your unsaved changes are lost: when you switch to another file, close the panel's tab, or leave the page.
+
+> [!TIP]
+> Collapsing or hiding the dock loses nothing. The panel stays exactly as it was, preview, tree and draft included, and comes back untouched without asking.
+
+A draft survives switching to another Session. Open the same file again to reopen the editor on it, with a "Restored unsaved changes" notice.
+
+A save over the 14MB write limit is refused with a message.
+
+## Handle a file that changed on disk
+
+The agent writes to the same Workspace, so a file can change while you are editing it. The panel checks for changes whenever a turn finishes. Your text is never replaced. As soon as the file has changed on disk, the editor header shows **Changed on disk**.
+
+A save that would land on a changed file is refused before anything is written. The **File changed on disk** dialog asks whether to **Overwrite** the file with your version or keep editing. Your text is kept either way.
+
+## Use the context menu
+
+Right-click a tree row or the file view to open the context menu. On a touch screen, long-press. On a keyboard, press Shift+F10 or the menu key.
+
+> [!NOTE]
+> The context menu does not open inside an HTML or PDF preview, or inside the editor, where the browser's own menu is how text is pasted.
+
+| Menu item | What it does | Available for |
+| --- | --- | --- |
+| **Copy relative path** | Copies the path from the Workspace root. | Files and directories |
+| **Add to conversation** | Adds a reference to the file or directory to the composer as a chip. A directory's path ends in `/`. Nothing is sent until you send the message. | Files and directories |
+| **Add selection to conversation** | On send, the message carries the selected text as a code block headed by the file and line range, such as `@src/app.ts:12-18`. | Files, in the file view, with text selected |
+| **Upload here** | Uploads into this directory. See [Upload files](#upload-files). | Directories |
+| **Download** | Downloads the file. See [Download a file](#download-a-file). | Files |
+| **Rename or move** | Enter a **New path** relative to the Workspace root and select **Move**. Missing directories are created. An existing target is refused. | Files |
+| **Delete** | Deletes the file after a confirmation. The file does not go to a trash folder. | Files |
+
+> [!NOTE]
+> Rename, move and delete read the file's current version first. If the agent rewrote the file while the dialog was open, they change nothing.
+
+## Upload files
+
+### Upload with the button
+
+1. In the tree, open the directory the files should go into.
+2. In the tree pane's header, select **Upload**.
+3. Select one or more files.
+
+The panel uploads several files at a time into the current directory. Each file can be up to 14MB; oversize files are named and skipped before anything is read. If the target directory already contains a file with the same name, the **Overwrite existing files** dialog lists the clashes, and selecting **Upload** overwrites them. When the upload finishes, the first uploaded file opens, unless the editor holds unsaved changes.
+
+### Upload with drag and drop
+
+Drag files from your computer onto the panel. A dashed frame names the directory the files will land in ("Drop to upload into …").
+
+- Drop onto a directory row to upload into that directory. The row highlights while the drag is over it.
+- Drop onto a file row to upload into that file's directory.
+- Dropped folders are skipped with a notice.
+
+> [!NOTE]
+> Dropping files onto the conversation or the composer attaches them to your message instead of uploading them. See [Chat](/chat#drag-files-onto-the-chat).
+
+## Download a file
+
+1. Select the file in the tree to open it in the preview.
+2. In the preview header, select **Download**.
+
+In the desktop app's own window, a **Show in folder** button sits beside **Download**. Select it to open the file's directory in the system file manager. Finder and Explorer select the file; a Linux desktop opens the directory.
+
+> [!NOTE]
+> **Show in folder** appears only in the desktop app's own window. A browser signed into the same server does not get the button, even on the same machine, because the server cannot tell it from a remote one.
+
+## Limits
+
+| Limit | Value |
+| --- | --- |
+| Text preview | Up to 1MB. Larger files are shown truncated and cannot be edited here. |
+| Markdown rendering | Up to 64KB. Larger files open in the source view. |
+| Upload size | 14MB per file |
+| Save size | 14MB per file |
+| Search | Stops at 200 matches or 20,000 entries walked |
+| Panel width | Below 480px, the panel falls back to one column |
diff --git a/packages/docs/content/files.zh.md b/packages/docs/content/files.zh.md
new file mode 100644
index 00000000..85239c5d
--- /dev/null
+++ b/packages/docs/content/files.zh.md
@@ -0,0 +1,171 @@
+---
+title: 文件面板
+description: 浏览、预览、编辑和管理对话 Workspace 里的文件。
+---
+
+**文件浏览**面板是对话页的侧边面板之一,展示当前对话的 Workspace:左侧是目录树,右侧是所选文件的预览。Project 的所有成员都可以在这里浏览、预览、编辑、上传、重命名和删除文件。
+
+- 第一次使用,见[打开文件面板](#打开文件面板)。
+- 查找文件,见[搜索 Workspace](#搜索-workspace)。
+- 修改文件,见[编辑文本文件](#编辑文本文件)和[使用右键菜单](#使用右键菜单)。
+- 添加文件,见[上传文件](#上传文件)。
+
+## 打开文件面板
+
+可以从以下任一位置打开面板:
+
+- 对话工具栏右上角:选择**右侧栏**或**下侧栏**,再选择**文件浏览**。如果侧栏里已经有别的面板,就用它的**添加面板**菜单。
+- 对话区右缘的**快捷方式**悬浮球。
+- 消息里的文件小卡片或文件卡片:点击后打开面板并定位到该文件。回复里指向 Workspace 内文件的链接也在这里打开,而不是让浏览器跳转;点击前不检查文件是否存在,文件不在时由面板给出提示。
+
+对话开始后才能使用这个面板,见[使用侧边面板](/chat#使用侧边面板)。
+
+## 浏览文件树
+
+目录第一次展开时才列出其中的内容。文件行在名称后显示文件大小,鼠标指向某一行可以看到它的路径、大小和修改时间。
+
+目录树的顶栏里有搜索框、**刷新**和**上传**。
+
+预览上方的路径行显示当前打开的文件。空间不够时,前面的目录先折叠成一个 `…`,文件名最后才省略。没有打开文件时,路径行显示当前目录。根目录写作 `.`,Workspace 的绝对路径在 Session 详情卡片里查看。
+
+每轮对话结束时,目录树和打开的预览会重新读取;面板重新回到视野中时,目录树也会重新读取。
+
+### 用键盘操作
+
+- 上、下方向键移动选中行。
+- 右方向键展开目录,或进入目录。
+- 左方向键收起目录,或回到上一级。
+- Home 和 End 跳到第一行或最后一行。
+- Enter 和空格键相当于点击。
+
+### 隐藏目录树或调整宽度
+
+在面板顶栏最左侧选择**隐藏文件树**,目录树会从面板左缘滑出,搜索框、**刷新**和**上传**也一起隐藏。选择**显示文件树**即可恢复。目录树默认显示,这个选择会记在浏览器里。
+
+拖动两栏之间的分隔条可以调整目录树的宽度;分隔条获得焦点时,也可以用方向键微调。宽度同样会被记住。
+
+面板窄于 480px 时改为单栏显示:先显示目录树,选中文件后换成预览,预览里有**返回列表**按钮。
+
+## 搜索 Workspace
+
+搜索框在服务器上搜索整个 Workspace,而不只是你展开过的目录。
+
+1. 在目录树顶栏点击**搜索文件**框。
+2. 输入文件名或目录名的一部分。
+
+停止输入片刻后,结果以平铺列表显示,每项都是完整路径,层级浅的排在前面;搜索期间显示「搜索中…」。搜索只匹配条目名称,不区分大小写。
+
+匹配数达到 200 个,或遍历了 20,000 个条目时,搜索会停下并提示「匹配项过多,仅显示最靠前的 N 条」。没有匹配时显示「Workspace 中没有匹配项」。
+
+在结果中选择一个目录,会清除搜索并在目录树中打开该目录。按 Esc 或点击清除按钮可以清空搜索框。
+
+## 预览文件
+
+在目录树中选择文件即可预览。不同类型的文件显示方式不同:
+
+| 文件类型 | 显示方式 |
+| --- | --- |
+| Markdown 和 HTML | 渲染后显示,可用**预览 / 源码**切换 |
+| 文本 | 语法高亮,带行号 |
+| 图片 | 直接显示,点击可放大 |
+| PDF | 内嵌显示 |
+| 其他类型 | 提供下载,见[下载文件](#下载文件) |
+
+扩展名看不出类型的文件(例如 `Makefile`、`LICENSE`),如果内容看起来是文本,就按文本处理。
+
+超过 64KB 的 Markdown 文件默认以源码视图打开,仍可切换到渲染视图。渲染后的 Markdown 里,相对链接会在面板内打开对应的 Workspace 文件,相对路径的图片也能正常显示。
+
+HTML 文件还可以在浏览器新标签页中打开:在预览中选择**新页面打开**。
+
+> [!NOTE]
+> 如果当前访问地址没有独立的预览源,新标签页会以沙箱模式打开,localStorage、Cookie 和第三方嵌入内容都无法使用。要避开沙箱,请通过 127.0.0.1 或 localhost 访问应用,或设置 `PENGUIN_PREVIEW_ORIGIN`。
+
+文本预览最多读取 1MB。更大的文件会截断显示,提示「内容过大,预览已截断,请下载查看完整文件」,并且不能在这里编辑。**下载**按钮在预览顶栏。
+
+文件视图右上角浮着三个按钮:**复制代码**、**自动换行**和**编辑**。**自动换行**让过长的行折行显示,默认开启;源码视图和编辑器共用这一个设置,并会记住你的选择。
+
+## 编辑文本文件
+
+1. 在预览中打开文件,选择文件视图右上角的**编辑**。预览变成编辑器:依然是带高亮和行号的文本,只是可以修改了。这里没有富文本编辑器。
+2. 修改内容。
+3. 选择**保存**(对勾图标),或按 Ctrl+S / Cmd+S。
+4. 在**保存文件**对话框中选择**保存**,写回文件。
+
+选择**取消**(×)会放弃编辑,回到预览。
+
+未保存的修改有可能丢失时,面板会先询问,例如切换到其他文件、关闭面板标签页或离开页面。
+
+> [!TIP]
+> 收起或隐藏侧栏不会丢失任何内容。面板保持原样,预览、目录树和草稿都在,再次展开时直接恢复,不会询问。
+
+切换到其他 Session 后草稿依然保留:再次打开同一个文件,编辑器会带着草稿重新打开,并提示「已恢复 … 的未保存修改」。
+
+保存的内容超过 14MB 写入上限时,保存会被拒绝并给出提示。
+
+## 处理磁盘上已变更的文件
+
+Agent 也在写同一个 Workspace,所以你编辑的文件可能在此期间被改动。每轮对话结束时面板都会检查一次。你输入的文本不会被替换,但只要文件变了,编辑器顶栏就会标出**磁盘上已变更**。
+
+如果保存会覆盖一个已变更的文件,面板会在写入前拒绝,并弹出**文件在磁盘上已变更**对话框,让你选择**仍然覆盖**,或者继续编辑。无论选哪一项,你输入的文本都会保留。
+
+## 使用右键菜单
+
+在目录树的某一行或文件视图上点击右键,即可打开右键菜单。触屏设备上长按,键盘上按 Shift+F10 或菜单键。
+
+> [!NOTE]
+> HTML 或 PDF 预览内部以及编辑器里不会弹出这个菜单,在编辑器里要靠浏览器自带的右键菜单粘贴文本。
+
+| 菜单项 | 作用 | 适用于 |
+| --- | --- | --- |
+| **复制相对路径** | 复制从 Workspace 根目录开始的路径。 | 文件和目录 |
+| **添加到对话** | 把文件或目录的引用作为小卡片放进输入框,目录的路径以 `/` 结尾。发送消息前不会发出任何内容。 | 文件和目录 |
+| **将选中内容添加到对话** | 发送时,选中的文本以代码块形式随消息发出,代码块开头标明文件和行号范围,例如 `@src/app.ts:12-18`。 | 文件,需在文件视图中选中文本 |
+| **上传到此文件夹** | 把文件上传到该目录,见[上传文件](#上传文件)。 | 目录 |
+| **下载** | 下载该文件,见[下载文件](#下载文件)。 | 文件 |
+| **重命名 / 移动** | 输入相对于 Workspace 根目录的**新的路径**,再选择**移动**。路径中不存在的目录会自动创建;目标已存在时拒绝操作。 | 文件 |
+| **删除** | 确认后删除文件。文件不会进入回收站。 | 文件 |
+
+> [!NOTE]
+> 重命名、移动和删除都会先读取文件的当前版本。如果对话框打开期间 Agent 改写了该文件,这些操作不会做任何改动。
+
+## 上传文件
+
+### 用按钮上传
+
+1. 在目录树中打开要上传到的目录。
+2. 在目录树顶栏选择**上传**。
+3. 选择一个或多个文件。
+
+文件会上传到当前目录,一次可以选多个。每个文件最大 14MB,超限的文件会在读取前被点名跳过。目标目录中已有同名文件时,**覆盖同名文件**对话框会列出这些文件,选择**上传**即覆盖。上传完成后自动打开第一个上传的文件;如果编辑器里有未保存的修改,则不打开。
+
+### 拖放上传
+
+把文件从电脑拖到面板上,虚线框会标出文件将放入的目录(「松开即上传到 …」)。
+
+- 拖到目录行上松开,上传到该目录;拖动经过时该行高亮。
+- 拖到文件行上松开,上传到该文件所在的目录。
+- 拖入的文件夹会被跳过,并给出提示。
+
+> [!NOTE]
+> 把文件拖到对话区或输入框上,文件会作为附件加到消息里,不会上传到 Workspace。见[对话](/chat#把文件拖到对话区)。
+
+## 下载文件
+
+1. 在目录树中选择文件,在预览中打开。
+2. 在预览顶栏选择**下载**。
+
+在桌面应用自己的窗口里,**下载**旁边还有**在文件夹中显示**按钮,点击后会在系统文件管理器中打开文件所在的目录:Finder 和资源管理器会选中该文件,Linux 桌面则打开该目录。
+
+> [!NOTE]
+> **在文件夹中显示**只出现在桌面应用自己的窗口里。用浏览器登录同一台服务器时没有这个按钮,即使浏览器就在同一台机器上也一样,因为服务器无法把它与远程浏览器区分开。
+
+## 限制
+
+| 项目 | 限制 |
+| --- | --- |
+| 文本预览 | 最多 1MB;更大的文件截断显示,不能在这里编辑 |
+| Markdown 渲染 | 最多 64KB;更大的文件以源码视图打开 |
+| 上传大小 | 每个文件 14MB |
+| 保存大小 | 每个文件 14MB |
+| 搜索 | 达到 200 个匹配或遍历 20,000 个条目后停止 |
+| 面板宽度 | 窄于 480px 时改为单栏显示 |
diff --git a/packages/docs/content/goal-mode.en.md b/packages/docs/content/goal-mode.en.md
index 9467bad6..e2c33ec4 100644
--- a/packages/docs/content/goal-mode.en.md
+++ b/packages/docs/content/goal-mode.en.md
@@ -1,28 +1,62 @@
---
title: Goal Mode
-description: Give the Agent an objective instead of a message — the goal plugin's stop hook keeps driving Tasks on one Session until the goal is complete, blocked, or out of token budget.
+description: Give an agent an objective and let it keep working until the goal is complete, blocked, or out of Token budget.
---
-## What it is
+Goal mode lets you give an agent an objective instead of a single message. The harness keeps running Tasks on the same Session, round after round, until the goal is complete, blocked, or out of Token budget. The model cannot end a goal by simply replying: it has to claim completion, or a real impasse, through the protocol described in [How a goal runs](#how-a-goal-runs).
-A normal Task ends when the model stops calling tools and replies. Goal mode inverts the contract: you state an **objective**, and the system keeps driving Tasks on the same Session — each round re-injecting the objective and checking a goal file — until the goal reaches a terminal state. The model never decides to stop by simply going quiet; it must *claim* completion (or a genuine impasse) through the protocol below, and everything else loops.
+- To start a goal from the Web App, the CLI, or the API, see [Start a goal](#start-a-goal).
+- To see what happens in each round and how a goal ends, see [How a goal runs](#how-a-goal-runs).
+- To cap what a goal can spend, see [Token budget](#token-budget).
+- To end a goal early, see [Stop a goal](#stop-a-goal).
+- To read a goal's progress from the API, see [Check a goal's state](#check-a-goals-state).
-Goal mode is the **`goal` plugin**, a [hook package](/skills#hook-packages) preinstalled on `default_agent` and installable on any Agent from the plugin library. Its `start.mjs` — the package's [`user_prompt` hook](/agent-loop#user-prompt-hooks) — writes the goal file and answers the submitted prompt with round 1's protocol message as expansion `context`; its `stop.mjs` — a [stop hook](/agent-loop#stop-hooks) — reads the Session's Trace after every Task and answers `continue` with the next round's message, or `stop`. Nothing in the core SDK knows what a goal is; the loop that consults hooks is generic. An Agent without the plugin cannot start a goal: the Web App and the API say so (`409 goal_plugin_not_installed`) instead of running a Task that would simply end.
+## Start a goal
-Start a goal from any of the three surfaces:
+**Before you begin**
-| Surface | How |
-| --- | --- |
-| Web App | The composer's `+` menu → **Goal mode** (or type `/goal`); the chip takes an optional token budget (`500k`, `2m`, empty = unlimited). Skills selected in the composer prefix the first round's message as a `[use_skills]` block, exactly like a normal send |
-| CLI chat | `/goal[:<budget>] <objective>`, e.g. `/goal:500k make all tests pass` |
-| CLI one-shot | `penguin run --goal [budget] -m "<objective>"`; exit code 0 only when the goal completes |
-| Server API | `POST /api/sessions/:id/tasks` with `{ input, goal: { budget } }` (budget `-1` or omitted = unlimited) |
+- The agent has the `goal` plugin installed. It comes preinstalled on `default_agent`; install it on any other agent from the plugin library.
+- The agent's hooks are on: **Enable hooks** on the agent's **Hooks** tab. Hooks are on unless the Project owner switched them off.
-Under the hood the server asks the Session to run the goal package's `user_prompt` hook — the installed `agent_state/hooks/goal/start.mjs`, fed `{ hook: "user_prompt", session_id, scratchpad_dir, prompt, budget }` on stdin — and starts the goal run with your message exactly as typed followed by the `{ context }` it prints, stamped `sender: "harness"`; the stop hook takes it from there. In the SDK, a goal is therefore a plain `session.run` on an Agent with the plugin installed, started by writing the goal file the same way (`Session.runUserPromptHook("goal", …)`, or the script directly).
+Without the plugin, or with hooks off, the agent cannot start a goal. The Web App and the API report `409 goal_plugin_not_installed` instead of running a Task that would simply end.
-## The goal file: GOAL.json
+### From the Web App
-The goal's state is a file at `<agent_dir>/scratchpad/<session_id>/GOAL.json` (sibling of the model's `PLAN.md` convention), created when the goal starts and rewritten by the stop hook after every round:
+1. In the composer, open the `+` menu and select **Goal mode**, or type `/goal`.
+2. Optional: on the goal chip, select the budget (it reads **Budget unlimited**), enter a **Token budget** such as `500k` or `2m`, and select **Save budget**. Leave it blank for no limit.
+3. Write your objective as the message and send it.
+
+Skills you select in the composer are added to the first round's message as a `[use_skills]` block, exactly like a normal send. While the goal runs, a banner above the composer shows the objective, the round, the Tokens used against the budget, and the goal's status.
+
+### From CLI chat
+
+In `penguin chat`, enter:
+
+```
+/goal[:<budget>] <objective>
+```
+
+For example:
+
+```
+/goal:500k make all tests pass
+```
+
+### From a one-shot run
+
+```
+penguin run --goal [budget] -m "<objective>"
+```
+
+The command exits with code 0 only when the goal completes.
+
+### From the Server API
+
+Send `POST /api/sessions/:id/tasks` with the body `{ input, goal: { budget } }`. Omit `budget`, or set it to `-1`, for no limit.
+
+## The goal file
+
+A goal's state lives in a file at `<agent_dir>/scratchpad/<session_id>/GOAL.json`, next to the model's `PLAN.md`. The file is created when the goal starts, and the stop hook rewrites it after every round.
```json
{
@@ -34,42 +68,103 @@ The goal's state is a file at `<agent_dir>/scratchpad/<session_id>/GOAL.json` (s
}
```
-| Field | Writer | Notes |
+| Field | Written by | Meaning |
| --- | --- | --- |
-| `objective` | the start script | the text every later round re-injects |
-| `status` | model, or the hook | `complete` / `blocked` are the model's — its one mailbox back to the loop, and the only field it may touch; `active`, `wrapping_up` (the wrap-up round after the budget ran out), `budget_limited` and `aborted` are the hook's |
-| `budget` | the start script | the token budget for the whole goal; `-1` = none |
-| `round` | the hook, every round | the round in progress; on a terminal status, the rounds run |
-| `tokens_used` | the hook, every round | uncached input + output the main session consumed so far, read off the Trace |
-| `ended` | the hook, at the end | `true` once the hook has acted on a terminal status — what tells a goal this run just ended from one an earlier run ended (the hook stays silent for those) |
+| `objective` | The start script | The text every later round re-injects. |
+| `status` | The model, or the hook | `complete` and `blocked` are the model's: they are its only way to talk back to the loop, and `status` is the only field it may touch. `active`, `wrapping_up` (the wrap-up round after the budget runs out), `budget_limited` and `aborted` are the hook's. |
+| `budget` | The start script | The Token budget for the whole goal. `-1` means no limit. |
+| `round` | The hook, every round | The round in progress. Once the status is terminal, the number of rounds that ran. |
+| `tokens_used` | The hook, every round | Uncached input plus output Tokens the main Session has used so far, read from the Trace. |
+| `ended` | The hook, at the end | `true` once the hook has acted on a terminal status. This tells a goal that this run just ended apart from one an earlier run ended; the hook stays silent about the latter. |
+
+The file always holds the goal's current state, and the Web server restores the chat page's goal banner straight from it.
+
+> [!NOTE]
+> A broken file stops the goal instead of looping forever. A file that no longer parses stops the goal as `blocked` and is renamed to `GOAL.json.broken`. A `status` value outside the protocol also counts as `blocked`.
+
+## How a goal runs
+
+Each round starts with a protocol message: plain user text stamped `sender: "harness"`, with no marker block. The stamp alone marks it as sent by the harness. In the Web App it appears as a compact collapsed card, **Injected by the harness**, in the same form as background notices; expand the card to read the full text.
-The file is always the goal's current state — the Web server restores the chat page's banner straight from it. Reads are tolerant: a file that no longer parses stops the goal as `blocked` and is moved aside as `GOAL.json.broken`, and a `status` outside the protocol reads as `blocked` — a broken control channel stops the loop instead of spinning it forever.
+Round 1 sends your own message first, exactly as you wrote it, with its text, images and skill-invocation blocks. The protocol message follows it and points back at your message as the objective. Later rounds restate the objective from the goal file.
-## The loop
+The protocol message embeds the `GOAL.json` the hook has just written, including the round, the Tokens used and the budget, so the model sees exactly the file it is asked to edit. It also sets the working rules:
-Each round's protocol message is plain user text stamped `sender: "harness"` — no marker block; the stamp alone says the harness sent it, and the Web App renders it as a compact collapsed card ("Injected by the harness", the background notices' form) that expands to the full text. Round 1 sends your own message verbatim first (text and images, skill-invocation blocks and all) with the protocol message right behind it pointing back at yours as the objective; later rounds restate the objective from the goal file. The protocol message embeds the `GOAL.json` the hook has just written — round, tokens used and budget included, so the model sees exactly the file it is asked to edit — and states the working rules: evidence-based verification before claiming completion, no shrinking the objective to an easier subset, and key progress recorded in `PLAN.md` so it survives context compaction. After the Task ends, the stop hook reads the Trace and the file and decides, first match wins:
+- Verify completion against evidence before claiming it.
+- Do not shrink the objective to an easier subset.
+- Record key progress in `PLAN.md`, so it survives context compaction.
-- the file says `complete` → the goal is done; `blocked` → what the model needs from you is in its final reply. The injected rules require the **same blocking condition to persist for three consecutive rounds** before the model may claim `blocked`, so a transient obstacle doesn't end the goal;
-- the Task was cut off — an `abort` event (user stop), a last request that failed for good, or the per-Task `max_turns` notice — → `aborted`: the model never got to write the file, and re-firing would hit the same cutoff again;
-- the wrap-up round just ran → `budget_limited`;
-- 100 rounds → `aborted` (a runaway backstop for a goal with no or a huge budget whose model never writes the file);
-- the budget is reached → one wrap-up round;
-- otherwise → the next round.
+When the Task ends, the stop hook reads the Trace and the goal file, and acts on the first case that matches:
-Every answer is recorded as a `hook` event (`name: goal`) on the stream and in the Trace, with the file's state — `status`, `round`, `tokens_used`, `budget` — as its `output`. The terminal statuses are written to the file as well, so the file and the last event agree.
+1. **The file says `complete`.** The goal is done.
+2. **The file says `blocked`.** The model's final reply says what it needs from you. The rules require the same blocking condition to persist for three consecutive rounds before the model may claim `blocked`, so a passing obstacle does not end the goal.
+3. **The Task was cut off**: an `abort` event from a user stop, a last request that failed for good, or the per-Task `max_turns` notice. The goal ends as `aborted`. The model never got to write the file, and another round would hit the same cutoff.
+4. **The wrap-up round just ran.** The goal ends as `budget_limited`.
+5. **100 rounds have run.** The goal ends as `aborted`. This backstop catches a goal with no budget, or a very large one, whose model never writes the file.
+6. **The budget is used up.** One wrap-up round runs next.
+7. **Otherwise**, the next round starts.
### Images in an objective
-An objective may carry attached images: they ride round 1 as ordinary input, and the model sees them then. Later rounds re-inject the objective text only. An image cannot stand in for the text — a picture alone states no objective, so a text-less goal input is rejected; file attachments are refused, since nothing carries them across rounds.
+An objective can include images. They are sent in round 1 as ordinary input, and the model sees them then. Later rounds re-inject only the objective text.
-In the Web App the regular stop button aborts the entire goal; in the CLI, Ctrl-C does. A user's interruption outranks the hook: after a cutoff no `continue` is ever run, and the goal ends as `aborted` with the file saying so.
+An image cannot replace the text: a picture alone does not state an objective, so a goal input without text is rejected. File attachments are refused, because nothing carries them from one round to the next.
## Token budget
-The hook counts the round's usage off the Trace: **uncached input + output** (`request.total − cache_read`) of every `token_usage` record since the round's harness-injected input, added to `tokens_used`. Subagent sessions have their own Traces and are not counted. The sum is a spend estimate, not a bill: cache reads cost money too, just a small fraction of the uncached-input price, so leaving them out keeps the number an honest approximation without per-model price tables.
+The budget counts **uncached input plus output** Tokens. After each round, the hook adds that round's usage, read from the Trace, to `tokens_used`. Subagent Sessions have their own Traces and are not counted.
+
+The count estimates spend; it is not a bill. Cache reads also cost money, but only a small fraction of the uncached input price. Leaving them out keeps the number a fair approximation without per-model price tables.
+
+The budget is checked between rounds. When it runs out, the goal is not cut off mid-thought. One final wrap-up round runs instead: the model summarizes its progress, lists the remaining work, and leaves a clear next step, and it must not claim `complete` just because the budget ran out. The hook then ends the goal as `budget_limited`. A truthful `complete` written during the wrap-up round still counts.
+
+> [!NOTE]
+> A round already running is never cut short, so actual spend can exceed the budget by up to one round, plus the wrap-up round.
+
+With no budget, the goal runs until the model claims `complete` or `blocked`. That depends on the model reporting those two states honestly, with a hard stop after 100 rounds.
+
+## Stop a goal
+
+Stopping the current Task ends the whole goal:
+
+- In the Web App, use the regular stop button.
+- In the CLI, press Ctrl-C.
+
+Your interruption outranks the hook. After a cutoff, no `continue` ever runs, and the goal ends as `aborted`; the goal file records that too.
+
+## Check a goal's state
+
+Send `GET /api/sessions/:id/goal`. The server reads the Session's `GOAL.json` and returns `{ goal: { objective, status, budget, used, rounds } }`, or `{ goal: null }` when the Session has never run a goal.
+
+A goal lives only as long as its run. If the file shows a goal the hook has not ended but the Session is not running, a crash or a killed process left it behind, and it reads as `aborted`.
+
+While a goal runs, live progress arrives on the Session's SSE channel as `goal_started`, `goal_round` and `goal_finished` events.
+
+Deleting the Session deletes its scratchpad, and `GOAL.json` with it.
+
+## How it works
+
+### The goal plugin
+
+Goal mode is not built into the core. The `goal` plugin is a [hook package](/skills#hook-packages) with two scripts:
+
+- `start.mjs` is its [`user_prompt` hook](/agent-loop#user-prompt-hooks). It writes the goal file and answers the submitted prompt with round 1's protocol message as its expansion `context`.
+- `stop.mjs` is a [stop hook](/agent-loop#stop-hooks). After every Task it reads the Session's Trace and answers `continue` with the next round's message, or `stop`.
+
+Nothing in the core SDK knows what a goal is. The loop that consults hooks is generic.
+
+### Starting a goal
+
+The server asks the Session to run the goal package's `user_prompt` hook: the installed `agent_state/hooks/goal/start.mjs`, which receives `{ hook: "user_prompt", session_id, scratchpad_dir, prompt, budget }` on stdin. The server then starts the goal run with your message exactly as typed, followed by the `{ context }` the script prints, stamped `sender: "harness"`. The stop hook takes it from there.
+
+In the SDK, a goal is therefore a plain `session.run` on an agent with the plugin installed. You start it by writing the goal file the same way: call `Session.runUserPromptHook("goal", …)`, or run the script directly.
+
+### Counting and recording
+
+For each round, the hook adds `request.total − cache_read` from every `token_usage` record since the round's harness-injected input.
-The budget is checked between rounds. When it is exhausted the goal is not cut off mid-thought: one final wrap-up round is injected — summarize progress, list remaining work, leave a clear next step, and no claiming `complete` just because the money ran out — after which the hook ends the goal as `budget_limited` (a truthful `complete` written during the wrap-up still counts). Because the check runs between rounds only, a round already in flight is never cut short: actual spend can overshoot the budget by up to one round, plus the wrap-up round. With no budget set, the loop runs until `complete` or `blocked` — bounded by the model's honesty about the two terminal states, plus the hard backstop of 100 rounds.
+Every answer the stop hook gives is recorded as a `hook` event (`name: goal`) on the stream and in the Trace. Its `output` carries the file's state: `status`, `round`, `tokens_used` and `budget`. Terminal statuses are written to the file as well, so the file and the last event agree.
-## Server state and events
+### Server state
-The Web server keeps no goal table: `GET /api/sessions/:id/goal` reads the Session's `GOAL.json` (null when it never ran a goal). A goal lives only inside its run, so a file the hook has not ended while the Session is not running was left behind by a crash or a kill and reads as `aborted`. Live progress arrives as `goal_started` / `goal_round` / `goal_finished` events on the session's SSE channel, derived from the stream — the round inputs and the goal hook's events. Deleting the Session removes the scratchpad, and `GOAL.json` with it.
+The Web server keeps no goal table. The goal endpoint reads the Session's `GOAL.json` directly. The SSE events are derived from the stream: the round inputs and the goal hook's events.
diff --git a/packages/docs/content/goal-mode.zh.md b/packages/docs/content/goal-mode.zh.md
index 514e26b2..5c6c5cfa 100644
--- a/packages/docs/content/goal-mode.zh.md
+++ b/packages/docs/content/goal-mode.zh.md
@@ -1,32 +1,66 @@
---
title: 目标模式
-description: 给 Agent 一个目标而不是一条消息——goal 插件的 stop hook 在同一 Session 上持续驱动 Task,直到目标完成、受阻或 token 预算耗尽。
+description: 给 Agent 一个目标,让它持续工作,直到目标完成、受阻或 Token 预算用完。
---
-## 是什么
+在目标模式下,你交给 Agent 的是一个目标,而不是单独一条消息。harness 会在同一个 Session 上一轮接一轮地运行 Task,直到目标完成、受阻或 Token 预算用完。模型不能靠回复一句话就结束目标,必须按[目标如何运行](#目标如何运行)中的协议声明完成,或者声明确实陷入了僵局。
-普通 Task 在模型不再调用工具、给出回复时就结束了。目标模式反转了这个契约:你给出一个**目标(objective)**,系统在同一个 Session 上持续驱动 Task——每一轮重新注入目标并检查目标文件——直到目标进入终态。模型不能靠"不说话"来停下:它必须通过下述协议**声明**完成(或真正的僵局),否则循环继续。
+- 从 Web App、CLI 或 API 启动目标,见[启动目标](#启动目标)。
+- 每一轮发生了什么、目标如何结束,见[目标如何运行](#目标如何运行)。
+- 限制目标的花费,见 [Token 预算](#token-预算)。
+- 提前结束目标,见[停止目标](#停止目标)。
+- 通过 API 读取目标进度,见[查看目标状态](#查看目标状态)。
-目标模式就是 **`goal` 插件**,一个[钩子包](/skills#钩子包),`default_agent` 预装,任何 Agent 都可以从插件库安装。它的 `start.mjs`——钩子包的 [`user_prompt` hook](/agent-loop#user-prompt-hook)——写下目标文件、以第一轮协议消息作为扩展 `context` 应答提交的 Prompt;它的 `stop.mjs`——一个 [stop hook](/agent-loop#stop-hook)——在每个 Task 结束后读 Session 的 Trace,回答 `continue`(附下一轮的消息)或 `stop`。核心 SDK 不知道目标是什么;咨询钩子的循环是通用的。没装插件的 Agent 发不起目标:Web App 与 API 会直说(`409 goal_plugin_not_installed`),而不是跑一个到点就结束的普通 Task。
+## 启动目标
-三个入口都能发起目标:
+**开始之前**
-| 入口 | 用法 |
-| --- | --- |
-| Web App | 输入框的 `+` 菜单 →「目标模式」(或输入 `/goal`);chip 上可填 token 预算(`500k`、`2m`,留空不限)。输入框选中的技能以 `[use_skills]` 块前缀在第一轮消息上,与普通发送完全一致 |
-| CLI chat | `/goal[:<预算>] <目标>`,例如 `/goal:500k 让所有测试通过` |
-| CLI 单次运行 | `penguin run --goal [预算] -m "<目标>"`;仅目标完成时退出码为 0 |
-| Server API | `POST /api/sessions/:id/tasks`,body 带 `{ input, goal: { budget } }`(budget 为 `-1` 或缺省 = 不限额) |
+- Agent 已安装 `goal` 插件。`default_agent` 预装了它,其他 Agent 可以从插件库安装。
+- Agent 的钩子已开启,也就是 Agent **钩子**标签页上的**启用钩子**。除非 Project owner 把它关掉,钩子默认开启。
-底层上,服务端请 Session 运行 goal 包的 `user_prompt` hook——已安装的 `agent_state/hooks/goal/start.mjs`,stdin 收到 `{ hook: "user_prompt", session_id, scratchpad_dir, prompt, budget }`——再以你原样的消息、紧随其后它打印的 `{ context }`(标记 `sender: "harness"`)发起目标运行;之后由 stop hook 接手。因此在 SDK 里,目标就是装了插件的 Agent 上一次普通的 `session.run`,以同样的方式写下目标文件(`Session.runUserPromptHook("goal", …)`,或直接调用脚本)来发起。
+没装插件或关了钩子,Agent 就无法启动目标。Web App 和 API 会直接返回 `409 goal_plugin_not_installed`,而不是运行一个到头就结束的普通 Task。
-## 目标文件:GOAL.json
+### 在 Web App 中
-目标的状态是一个文件,位于 `<agent_dir>/scratchpad/<session_id>/GOAL.json`(与模型的 `PLAN.md` 约定同级),目标启动时创建,此后每轮结束由 stop hook 重写:
+1. 在输入框中打开 `+` 菜单,选择**目标模式**;也可以直接输入 `/goal`。
+2. 可选:点击目标模式标签上的预算(默认显示**预算不限**),在 **Token 预算**中填入 `500k`、`2m` 这样的值,然后点击**保存预算**。留空表示不限预算。
+3. 在输入框里写下目标,然后发送。
+
+输入框中选中的 Skill 会以 `[use_skills]` 块的形式加在第 1 轮消息的开头,和普通发送完全一样。目标运行期间,输入框上方有一条横幅,显示目标、当前轮次、已用 Token 与预算,以及目标状态。
+
+### 在 CLI 对话中
+
+在 `penguin chat` 中输入:
+
+```
+/goal[:<budget>] <objective>
+```
+
+例如:
+
+```
+/goal:500k make all tests pass
+```
+
+### 用单次运行
+
+```
+penguin run --goal [budget] -m "<objective>"
+```
+
+只有目标完成时,命令的退出码才是 0。
+
+### 通过 Server API
+
+发送 `POST /api/sessions/:id/tasks`,请求体为 `{ input, goal: { budget } }`。省略 `budget` 或设为 `-1`,表示不限预算。
+
+## 目标文件
+
+目标的状态保存在 `<agent_dir>/scratchpad/<session_id>/GOAL.json` 文件里,和模型的 `PLAN.md` 放在同一个目录。目标启动时创建这个文件,之后每一轮结束,stop 钩子都会重写它。
```json
{
- "objective": "让所有测试通过",
+ "objective": "make all tests pass",
"status": "active",
"budget": 500000,
"round": 3,
@@ -34,42 +68,103 @@ description: 给 Agent 一个目标而不是一条消息——goal 插件的 sto
}
```
-| 字段 | 写入方 | 说明 |
+| 字段 | 写入方 | 含义 |
| --- | --- | --- |
-| `objective` | 启动脚本 | 后续每轮重新注入的文本 |
-| `status` | 模型或钩子 | `complete` / `blocked` 是模型的——它回传循环的唯一信箱,也是它唯一可以改的字段;`active`、`wrapping_up`(预算耗尽后的收尾轮)、`budget_limited`、`aborted` 是钩子的 |
-| `budget` | 启动脚本 | 整个目标的 token 预算;`-1` = 不设 |
-| `round` | 钩子,每轮 | 进行中的轮次;到终态时即已运行的轮数 |
-| `tokens_used` | 钩子,每轮 | 主会话迄今消耗的非缓存 input + output,从 Trace 读出 |
-| `ended` | 钩子,结束时 | 钩子对终态动过手之后置 `true`——借此区分这次运行刚结束的目标与早先某次运行结束的目标(后者钩子保持沉默) |
+| `objective` | 启动脚本 | 之后每一轮重新注入的文本。 |
+| `status` | 模型或钩子 | `complete` 和 `blocked` 归模型写:这是模型向循环回话的唯一途径,`status` 也是它唯一能改的字段。`active`、`wrapping_up`(预算用完后的收尾轮)、`budget_limited` 和 `aborted` 归钩子写。 |
+| `budget` | 启动脚本 | 整个目标的 Token 预算。`-1` 表示不限预算。 |
+| `round` | 钩子,每轮 | 正在进行的轮次。进入终态后,表示实际运行的轮数。 |
+| `tokens_used` | 钩子,每轮 | 主 Session 迄今消耗的未缓存输入 Token 与输出 Token 之和,从 Trace 读出。 |
+| `ended` | 钩子,结束时 | 钩子处理完终态后置为 `true`。借此区分本次运行刚结束的目标和更早某次运行已经结束的目标,钩子对后者不再作声。 |
+
+这个文件始终反映目标的当前状态,Web 服务端直接用它恢复对话页上的目标横幅。
+
+> [!NOTE]
+> 文件坏了,目标会停下来,不会无休止地循环。文件无法解析时,目标以 `blocked` 结束,文件改名为 `GOAL.json.broken`;`status` 取了协议之外的值,也按 `blocked` 处理。
+
+## 目标如何运行
+
+每一轮都以一条协议消息开始。它是普通的用户文本,带 `sender: "harness"` 标记,不含任何标记块,单凭这个标记就能看出消息出自 harness。Web App 把它显示成一张标着**由 harness 注入**的紧凑折叠卡片,样式与后台通知相同,展开卡片可以看到全文。
-文件永远是目标的当前状态——Web 服务端直接从它恢复聊天页的 banner。读取是容错的:不再能解析的文件让目标以 `blocked` 停下并被挪到 `GOAL.json.broken`,协议外的 `status` 读作 `blocked`——控制通道坏了就停下循环,而不是无限空转。
+第 1 轮先原样发送你自己的消息,其中的文字、图片和 Skill 调用块都保留。协议消息紧随其后,指明你的消息就是目标。之后的每一轮从目标文件中复述目标。
-## 循环
+协议消息里嵌着钩子刚写好的 `GOAL.json`,轮次、已用 Token 和预算都在其中,模型看到的正是要它编辑的那份文件。消息还规定了几条工作规则:
-每一轮的协议消息就是纯文本 user 消息,带 `sender: "harness"` 标记——没有任何标记块;来源全靠这一标记说明,Web App 把它渲染为一张紧凑的折叠卡片(「由 harness 注入」,后台任务通知同款形态),展开可见全文。第一轮先原样发送你自己的消息(文本与图片、技能调用块等一并保留),协议消息紧随其后、指回你的消息作为目标;后续轮从目标文件复述目标文本。协议消息内嵌钩子刚写下的那份 `GOAL.json`(轮次、已用 token、预算都在其中,模型看到的就是它要编辑的那个文件),并附工作规则——声明完成前必须基于证据逐项核验、不许把目标缩水成更容易的子集、关键进展写入 `PLAN.md` 以跨越上下文压缩。Task 结束后 stop hook 读 Trace 与文件、按序判定,第一条命中即生效:
+- 声明完成之前,先拿证据核实。
+- 不许把目标缩小成更容易的子集。
+- 把关键进展写进 `PLAN.md`,经过上下文压缩也不会丢。
-- 文件写着 `complete` → 目标完成;`blocked` → 模型缺什么写在它最后一条回复里。注入规则要求**同一阻塞条件持续三个连续轮次**后才允许声明 `blocked`,临时性障碍不会终结目标;
-- 这一轮被掐断——`abort` 事件(用户停止)、最后一次请求彻底失败、或单 Task `max_turns` 通知——→ `aborted`:模型没来得及写文件,重发只会撞上同一次掐断;
-- 收尾轮刚跑完 → `budget_limited`;
-- 满 100 轮 → `aborted`(未设或预算极大、而模型从不写文件时的失控兜底);
-- 预算已到 → 一轮收尾轮;
-- 否则 → 下一轮。
+Task 结束后,stop 钩子读取 Trace 和目标文件,按下面的顺序逐条判断,命中第一条就照它处理:
-每个回答都以一条 `hook` 事件(`name: goal`)记在流与 Trace 里,`output` 携带文件的状态——`status`、`round`、`tokens_used`、`budget`。终态同样写进文件,文件与最后一条事件永远一致。
+1. **文件写着 `complete`。** 目标完成。
+2. **文件写着 `blocked`。** 模型需要你做什么,写在它的最后一条回复里。规则要求同一个阻塞条件连续三轮都存在,模型才能声明 `blocked`,所以暂时的障碍不会让目标结束。
+3. **Task 中途中断**:出现了用户停止产生的 `abort` 事件、最后一次请求最终失败,或者单个 Task 的 `max_turns` 提示。目标以 `aborted` 结束。模型没来得及写文件,再跑一轮也会遇到同样的中断。
+4. **刚跑完收尾轮。** 目标以 `budget_limited` 结束。
+5. **已经跑满 100 轮。** 目标以 `aborted` 结束。这是一道防失控的兜底:没设预算或预算极大的目标,如果模型始终不写文件,就会在这里停下。
+6. **预算已用完。** 下一轮是收尾轮。
+7. **其他情况**,开始下一轮。
### 目标里的图片
-目标可以附带图片:它们作为普通输入随第一轮发出,模型当时就能看到;后续轮只重新注入目标文本。图片不能替代文字——一张图说明不了目标,所以没有文字的目标输入会被拒绝;文件附件也会被拒绝,因为没有东西能把它带过后续轮次。
+目标可以带图片。图片在第 1 轮以普通输入的形式发出,模型在那一轮就能看到。之后的轮次只重新注入目标的文字。
-Web App 中常规停止按钮即中止整个目标;CLI 中是 Ctrl-C。用户的中断压过钩子:被掐断之后任何 `continue` 都不会执行,目标以 `aborted` 结束,文件也如此记录。
+图片不能代替文字:光有一张图说明不了目标,所以服务端拒绝没有文字的目标输入。文件附件也不接受,因为没有机制能把它们从一轮带到下一轮。
## Token 预算
-钩子从 Trace 上数这一轮的用量:自本轮 harness 注入的输入以来每条 `token_usage` 记录的**非缓存 input + output**(`request.total − cache_read`),累加进 `tokens_used`。子 Session 有自己的 Trace,不计入。这个累加值是**花费的估算而非账单**:缓存读取并非免费,只是单价远低于非缓存 input,忽略它既不失真,也免去了依赖各模型价目表。
+预算统计的是**未缓存输入与输出**的 Token。每一轮结束后,钩子从 Trace 读出这一轮的用量,累加到 `tokens_used`。子 Agent 的 Session 有自己的 Trace,不计入。
+
+这个数是花费的估算,不是账单。缓存读取也收费,只是价格仅为未缓存输入的一小部分。不计入它们,得到的数仍然是合理的近似,也省去了按模型维护价目表。
+
+预算在两轮之间检查。预算用完时,目标不会在思考到一半时戛然而止,而是再跑最后一轮收尾:模型总结进展、列出剩余工作、给出明确的下一步,并且不能只因为预算用完就声明 `complete`。之后钩子以 `budget_limited` 结束目标。收尾轮里如实写下的 `complete` 仍然有效。
+
+> [!NOTE]
+> 正在运行的一轮总会跑完,所以实际花费最多可能超出预算一轮的用量,再加上收尾轮。
+
+不设预算时,目标会一直运行到模型声明 `complete` 或 `blocked`。这取决于模型能否如实报告这两种状态,另有 100 轮的硬性上限兜底。
+
+## 停止目标
+
+停止当前 Task,就会结束整个目标:
+
+- 在 Web App 中,点击常规的停止按钮。
+- 在 CLI 中,按 Ctrl-C。
+
+你的中断优先于钩子:中断之后不会再执行任何 `continue`,目标以 `aborted` 结束,目标文件里也这样记录。
+
+## 查看目标状态
+
+发送 `GET /api/sessions/:id/goal`。服务端读取这个 Session 的 `GOAL.json`,返回 `{ goal: { objective, status, budget, used, rounds } }`;Session 从未运行过目标时,返回 `{ goal: null }`。
+
+目标只存在于它的那次运行之中。如果钩子还没结束文件里的目标,Session 却已经不在运行,说明它是崩溃或进程遭强制终止时遗留下来的,读出来就是 `aborted`。
+
+目标运行期间,实时进度以 `goal_started`、`goal_round` 和 `goal_finished` 事件,通过这个 Session 的 SSE 通道推送。
+
+删除 Session 会一并删除它的 scratchpad,以及其中的 `GOAL.json`。
+
+## 工作原理
+
+### goal 插件
+
+目标模式并不内置在核心里。`goal` 插件是一个[钩子包](/skills#钩子包),包含两个脚本:
+
+- `start.mjs` 是它的 [`user_prompt` 钩子](/agent-loop#user-prompt-hook):写入目标文件,并以第 1 轮的协议消息作为扩展 `context`,应答提交的 Prompt。
+- `stop.mjs` 是一个 [stop 钩子](/agent-loop#stop-hook):每个 Task 结束后读取 Session 的 Trace,应答 `continue` 并附上下一轮的消息,或者应答 `stop`。
+
+核心 SDK 完全不知道目标是什么,询问钩子的那个循环是通用的。
+
+### 启动流程
+
+服务端让 Session 运行 goal 包的 `user_prompt` 钩子,也就是已安装的 `agent_state/hooks/goal/start.mjs`,脚本从 stdin 收到 `{ hook: "user_prompt", session_id, scratchpad_dir, prompt, budget }`。随后服务端启动目标运行:先原样发送你输入的消息,再发送脚本打印的 `{ context }`,这条消息带 `sender: "harness"` 标记。之后由 stop 钩子接手。
+
+因此在 SDK 里,目标就是装了插件的 Agent 上一次普通的 `session.run`,启动时用同样的方式写好目标文件:调用 `Session.runUserPromptHook("goal", …)`,或者直接运行脚本。
+
+### 计数与记录
+
+每一轮,钩子把自本轮 harness 注入的输入以来每条 `token_usage` 记录的 `request.total − cache_read` 累加起来。
-预算在轮与轮之间检查。耗尽时不会把模型拦腰斩断:系统注入最后一个收尾轮——总结进展、列出剩余工作、给出明确的下一步,并且不许因为钱花完了就标 `complete`——之后钩子以 `budget_limited` 终局(收尾轮里如实写下的 `complete` 仍然算数)。正因为只在轮间检查,进行中的一轮不会被截断:实际花费最多可超出预算一轮,外加收尾轮。未设预算时循环一直跑到 `complete` 或 `blocked`——边界是模型对两个终态的诚实,外加 100 轮的硬性兜底上限。
+stop 钩子的每次应答都记为一条 `hook` 事件(`name: goal`),出现在流里,也写进 Trace。事件的 `output` 带着文件的状态:`status`、`round`、`tokens_used` 和 `budget`。终态也会写进文件,所以文件与最后一条事件始终一致。
-## 服务端状态与事件
+### 服务端状态
-Web 服务端不再有目标表:`GET /api/sessions/:id/goal` 直接读该 Session 的 `GOAL.json`(从未运行过目标时为 null)。目标只在它的运行跨度内活着,所以 Session 并未运行而钩子尚未结束的文件,那是崩溃或被杀留下的,读作 `aborted`。实时进度通过会话 SSE 通道的 `goal_started` / `goal_round` / `goal_finished` 事件到达,由流上的轮输入与 goal hook 事件映射而来。删除 Session 会连同 scratchpad(包括 `GOAL.json`)一起清除。
+Web 服务端不维护目标表。目标接口直接读取 Session 的 `GOAL.json`,SSE 事件则从流中派生,来源是各轮的输入和 goal 钩子的事件。
diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.md
index 19ae0aa1..a5e0fd07 100644
--- a/packages/docs/content/interfaces.en.md
+++ b/packages/docs/content/interfaces.en.md
@@ -1,11 +1,20 @@
---
title: Core Interfaces
-description: A top-down tour of the contracts — full LLMInterface and EnvironmentInterface signatures, inner types field by field, and every swappable seam.
+description: The Human, LLM and Environment contracts behind the engine, with their full signatures, inner types and extension seams.
---
-The context_engine depends on three interfaces: Human, LLM and Environment. All protocol conversion happens inside the implementations — the engine sees only [OmniMessage](/omni-message). This page goes top-down: the two big interface signatures and the Human boundary first, then each interface's inner types layer by layer. All types are exported by `@prismshadow/penguin-core`; source: `packages/core/src/interfaces/` — `llm.ts` (what the model side needs), `environment.ts` (what the Environment side needs), `shared.ts` (the vocabulary both genuinely need), and `index.ts`, the barrel behind the `@prismshadow/penguin-core/interfaces` subpath.
+The `context_engine` depends on three interfaces: Human, LLM and Environment. All protocol conversion happens inside the implementations, so the engine sees only [OmniMessage](/omni-message).
-## Overview
+This page follows a turn's control flow: [the Human boundary](#the-human-boundary), the [LLM contract](#llminterface), the [approval callback](#approvefn) and the [Environment contract](#environmentinterface). It ends with the [subagent](#subagent-interfaces) and [vision](#visiondescriberservice) services and the [extension seams](#extension-seams).
+
+All types are exported by `@prismshadow/penguin-core`. The source lives in `packages/core/src/interfaces/`:
+
+- `llm.ts`: what the model side needs.
+- `environment.ts`: what the Environment side needs.
+- `shared.ts`: the vocabulary both sides genuinely need.
+- `index.ts`: the barrel behind the `@prismshadow/penguin-core/interfaces` subpath.
+
+## The three boundaries
```text
Human (a boundary, not a class)
@@ -26,23 +35,60 @@ The context_engine depends on three interfaces: Human, LLM and Environment. All
| LLM | `LLMInterface.streamGenerate` | `GenerativeModel` (over AgentHub) |
| Environment | `EnvironmentInterface.executeTool` et al. | `Environment` + the builtin tool registry |
-Two iron rules run through every interface: **never throw into the engine** (errors converge into messages/returns carrying a `stop_reason`), and **the streaming discipline** (`start → delta → stop`, complete message immediately after).
+Every interface follows two rules:
+
+- **Never throw into the engine.** Errors become messages or return values that carry a `stop_reason`.
+- **Follow the streaming discipline.** A stream goes `start → delta → stop`, and the complete message follows immediately.
### Message plane and control plane
-The **content** crossing all three boundaries is OmniMessage and nothing else — `session.run`'s input and streamed output, `streamGenerate`'s input array and yielded stream, `executeTool`'s approved call and its output stream, a subagent round's input and its forwarded messages, and every Trace write.
+The **content** that crosses all three boundaries is OmniMessage and nothing else:
+
+- `session.run`'s input and its streamed output
+- `streamGenerate`'s input array and its yielded stream
+- `executeTool`'s approved tool call and its output stream
+- a subagent round's input and its forwarded messages
+- every Trace write
-What travels *alongside* it is the **control plane**, deliberately not message-shaped, because none of it is conversation content:
+What travels alongside it is the **control plane**. It is deliberately not message-shaped, because none of it is conversation content:
| Control-plane item | Where | Why it is not a message |
| --- | --- | --- |
| `signal: AbortSignal` | `RunOptions`, `GenerativeModelParameters`, `ToolExecutionRequest` | An interruption that had to wait its turn in a message queue would not be an interruption. |
-| `thinkingLevel` | `GenerativeModelParameters` | A per-request parameter, like a timeout — it says how to run the request, not what to say. The engine holds the live value as its own state (`ContextEngine.setThinkingLevel`, fed by the `Session.thinkingLevel` setter — the soft-limited knob); unset, the LLM object's construction default — the context's opening level — applies (`RunOptions` carries no level). |
-| `approve` and its `ApprovalDecision` | `RunOptions`, `ToolExecutionRequest` | The callback takes an OmniMessage tool call; the answer is a three-value enum the engine turns into an `approval_decision` message the moment it has it. |
-| `LLMOutcome` | `streamGenerate`'s generator return value | The request's terminal state, which the engine's retry and reconnect policy branches on. A generator's return value is statically guaranteed to exist; "the last message yielded must be a `request_end`" would only ever be a runtime convention. The engine writes that `request_end` from it. |
+| `thinkingLevel` | `GenerativeModelParameters` | A per-request parameter, like a timeout: it says how to run the request, not what to say. The engine holds the live value as its own state (`ContextEngine.setThinkingLevel`, fed by the `Session.thinkingLevel` setter, the soft-limited knob). When a request omits it, the LLM object's construction default applies, which is the context's opening level. `RunOptions` carries no level. |
+| `approve` and its `ApprovalDecision` | `RunOptions`, `ToolExecutionRequest` | The callback takes an OmniMessage tool call. The answer is a three-value enum, which the engine turns into an `approval_decision` message as soon as it has it. |
+| `LLMOutcome` | `streamGenerate`'s generator return value | The request's terminal state, which the engine's retry and reconnect policy branches on. A generator's return value is guaranteed by the type system; "the last message yielded must be a `request_end`" could only ever be a runtime convention. The engine writes that `request_end` from it. |
+
+Everything else that is not OmniMessage belongs to the Environment's management plane, described under [EnvironmentInterface](#environmentinterface).
+
+## The Human boundary
+
+Human is deliberately not an interface class. The SDK caller *is* the Human:
-Everything else that is not OmniMessage is Environment's management plane, described below.
+```ts
+const session = await agent.createSession({ workspaceDir, provider, modelId });
+
+session.run(
+ newMessages: OmniMessage[], // input: the Prompt
+ opts?: RunOptions,
+): AsyncGenerator<OmniMessage, RunCutoff | null>; // output: streamed OmniMessage; returns null when the run completed
+interface RunOptions {
+ signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
+ approve?: ApproveFn; // per-tool approval; denies everything when omitted
+ preToolUse?: PreToolUseFn; // pre-tool-use hook consult; the Session wires it from installed hook packages
+}
+
+interface RunCutoff { // how a run was cut off early
+ kind: "abort" | "llm_failure" | "compaction_failure" | "max_turns";
+ errorCode?: ErrorCode; // mirrors the terminal record's error_code (none for max_turns)
+ errorMessage?: string; // mirrors the terminal record's error_message
+}
+```
+
+The CLI wires terminal I/O onto this boundary. The Server wires HTTP requests and SSE channels onto it. Any programmatic caller that connects becomes a new Human implementation, with nothing to register.
+
+The return value tells a consumer whether the run really finished. Failures emit no abort event, only their terminal `request_end` or `compaction_end` record, so code that must not treat a cut-off run as finished reads `RunCutoff` instead of inspecting the stream.
## LLMInterface
@@ -60,32 +106,35 @@ interface GenerativeModelParameters {
}
```
-The generator yields `partial_*` fragments and complete messages, emits Token usage as `token_usage` events, and reports the terminal state via its **return value** (not a yielded message).
+The generator yields `partial_*` fragments and complete messages, and emits Token usage as `token_usage` events. It reports the terminal state through its **return value**, not a yielded message.
### LLMOutcome semantics
```ts
interface LLMOutcome {
- status: StopReason; // completed | timeout | malformed | aborted | failed | auth
- message?: string; // failure detail: on failed/auth, and on timeout/malformed when a
- // concrete error was caught — carried onto request_end so the
- // errors panel shows the real reason behind a retried request
- permanent?: boolean; // marks a failed as deterministic (client-side rejection thrown before
- // any network I/O, e.g. fast_mode on a model without a fast tier):
- // the engine aborts with the message instead of retrying
+ status: StopReason; // completed | aborted | retryable | fatal
+ errorCode?: ErrorCode; // classified cause on a non-completed failure; carried onto request_end as error_code
+ errorMessage?: string; // failure detail: on fatal, and on retryable when a concrete error was caught;
+ // carried onto request_end as error_message, so the errors panel shows
+ // the real reason behind a retried request
}
```
| status | Meaning | Engine reaction |
| --- | --- | --- |
-| `completed` | finished normally (token_usage already emitted) | proceed |
-| `timeout` | timeout / transport disconnect | auto-reconnect within the run |
-| `malformed` | response parse failure | auto-reconnect within the run |
-| `failed` | an error the classifier did not judge transient (params, …) | auto-reconnect within the run as well — the status is still reported as `failed`. Exception: with `permanent: true` (a deterministic client-side rejection, e.g. fast mode on a model without a fast tier) the run stops immediately with the message |
-| `aborted` | user interrupt | stop, hand back to the user |
-| `auth` | credentials rejected | stop, hand back to the user — the one LLM status that never retries; hosts gate input until the model's API key is updated |
+| `completed` | Finished normally (`token_usage` already emitted) | Proceed |
+| `retryable` | A failure worth retrying: transport drops, idle timeouts, 408/429/5xx, malformed or truncated responses, and anything unclassifiable | Reconnect within the run on the backoff ladder |
+| `fatal` | A failure no retry can fix: a provider 4xx rejection (408 and 429 excluded), rejected credentials, or a deterministic client-side rejection before any network I/O (for example, fast mode on a model without a fast tier) | Stop the run and surface `errorMessage` |
+| `aborted` | User interrupt | Stop and hand back to the user |
-Implementation constraints: never throw; no internal retries — reconnecting is the engine's job (see [The Agent Loop](/agent-loop)).
+The status answers one question: should this request be retried? `errorCode` says what kind of failure it was. Unclassifiable errors are `retryable` on purpose: the fatal detector is an allowlist, so a gateway that words a transient fault its own way keeps its retries.
+
+The fix for a `fatal` outcome is a configuration or credential change, then a new request. Only the model reference is fixed at Session creation. Credentials come from the current Project config, so after a key update the Session can continue.
+
+Implementation constraints:
+
+- Never throw.
+- Do no internal retries. Reconnecting is the engine's job; see [The Agent Loop](/agent-loop).
### GenerativeModelConfig
@@ -96,7 +145,7 @@ interface GenerativeModelConfig {
modelId: string;
apiKey?: string;
baseUrl?: string;
- clientType?: string; // AgentHub client protocol (openai / …); inferred from modelId when omitted
+ clientType?: string; // AgentHub client protocol (openai-chat / openai-responses / …); inferred from modelId when omitted
tools: ToolDefinition[];
systemPrompt?: string; // fully assembled system prompt, placeholders substituted
contextWindow?: number;
@@ -104,23 +153,55 @@ interface GenerativeModelConfig {
fastMode?: boolean; // per-model fast mode (AgentHub fast_mode; premium faster tier), off by default
thinkingLevel?: ThinkingLevelName; // construction default (a per-request parameter can override); "none" | "low" | "medium" | "high" | "xhigh" | "max"
requestTimeoutMs?: number; // Request idle budget: the longest wait for the next upstream event, default 300000; <=0 disables
+ sessionId?: string; // the Session's id, sent only to endpoints whose attribution header names the conversation
toolCallIds?: ToolCallIdAllocator; // Session-level tool_call_id registry (pass the same instance across compaction)
}
```
### The built-in implementation: GenerativeModel
-`GenerativeModel` (`packages/core/src/llm/generative-model.ts`) grounds the contract on the `AutoLLMClient` of the `@prismshadow/agenthub` model gateway:
+`GenerativeModel` (`packages/core/src/llm/generative-model.ts`) builds the contract on the `AutoLLMClient` of the `@prismshadow/agenthub` model gateway.
+
+**History.** The gateway keeps conversation history **statefully** and receives only the new messages each turn. Resuming a Session replays the committed history through a one-time `setHistory`.
+
+**Event translation.** An internal `EventTranslator` turns gateway stream events into `partial_*` fragments plus complete messages, and keeps each item's opaque `fidelity` payload verbatim. Segmentation mirrors the gateway's own aggregation:
+
+- A thinking block is closed by its fidelity payload.
+- A run of equal fidelity stays one block. OpenAI-compatible clients stamp every delta with the same `{ reasoning_field }`, which must not split blocks.
+- A text segment splits on a differing `fidelity.phase` and closes on a `fidelity.signature`. Fidelity keys accumulate on merge.
+- Complete messages settle in thinking → text → tool_call order.
+
+**Thought summaries.** Every request asks the gateway for thought summaries (`thinking_summary`). No provider rejects the flag: the gateway drops it for families without such a feature, and the Claude family reads it as summarized thinking. Besides letting the reader watch the model reason, it keeps events arriving during a reasoning phase.
+
+**Idle timeout.** Those events are what `requestTimeoutMs` measures. The timer runs only while awaiting the next upstream event and resets on each one. It never counts consumer-side time such as yielding, approvals or Trace writes. It bounds silence, not the length of a response.
+
+**Tool call ids.** `ToolCallIdAllocator` handles providers that use the function name as the call id: it appends `#n` inbound and strips it outbound. Its scope is the whole Session.
+
+**Provider differences.** Tool-call formats, reasoning content and streaming events are absorbed entirely inside the gateway. See [Models & Providers](/models).
+
+## ApproveFn
+
+`RunOptions` and `ToolExecutionRequest` both carry this callback type:
+
+```ts
+type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto
+type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
+```
+
+| Rule | Behavior |
+| --- | --- |
+| Call frequency | Called exactly once per complete `tool_call` |
+| Callback throws | Counts as `deny` |
+| No callback injected | The engine denies everything (the conservative default) |
+| Subagents | A subagent inherits its parent's approval callback, invoked with an `origin` tag, so the approval policy spans the whole delegation tree |
+
+`"forbidden"` is never a host's answer. `Session.run` wraps the injected callback with the [Project command policy](/configuration#command-policy), so a vetoed command gets `"forbidden"` before the host is asked at all.
-- the gateway maintains conversation history **statefully**, receiving only new messages each turn; resuming a Session replays committed history through a one-time `setHistory`;
-- an internal `EventTranslator` translates gateway stream events into `partial_*` fragments plus complete messages, preserving each item's opaque `fidelity` payload verbatim; segmentation mirrors the gateway's own aggregation — a thinking block is closed by its fidelity payload and a run of equal fidelity stays one block (OpenAI-compatible clients stamp every delta with the same `{ reasoning_field }`, which must not split blocks), while a text segment splits on a differing `fidelity.phase` and closes on a `fidelity.signature`, fidelity keys accumulating on merge; complete messages settle in thinking → text → tool_call order;
-- every request asks the gateway for thought summaries (`thinking_summary`), which no provider rejects — it is dropped where the family has no such thing, and read as "summarized thinking" by the Claude family. Besides letting the reader watch the model reason, it keeps events arriving during a reasoning phase, which is what `requestTimeoutMs` measures: the timer runs only while awaiting the next upstream event, resets on each one, and never counts consumer-side time (yielding, approvals, Trace writes), so it bounds silence rather than the length of a response;
-- `ToolCallIdAllocator` disambiguates providers that use the function name as the call id (append `#n` inbound, strip outbound), scoped to the whole Session;
-- provider differences (tool-call formats, reasoning content, streaming events) are absorbed entirely inside the gateway — see [Models & Providers](/models).
+Either denial produces one fixed `aborted` output line: "Tool call denied by user." for `"deny"`, and "Tool call denied by policy." for `"forbidden"`. The decision value itself rides the `approval_decision` event, so the Trace names the decider without an extra field. An existing callback that returns only `"allow"` or `"deny"` needs no change.
## EnvironmentInterface
-The complete tool-execution contract:
+The core of the tool-execution contract:
```ts
interface EnvironmentInterface {
@@ -131,12 +212,28 @@ interface EnvironmentInterface {
}
```
-This interface carries two planes, and only the first one belongs to the agent loop:
+The interface carries two planes, and only the first belongs to the agent loop:
+
+- **The message plane** is `executeTool`, the only method `context_engine` calls here. An OmniMessage tool call goes in; a stream of OmniMessage comes out.
+- **The management plane** is `listTools`, `toolPermission`, `dispose` and the optional members below. None of them pass through the engine. They serve Session assembly and a host's own UI, such as the Web App's process and subagents panels or an approval mode's permission lookup. They are ordinary method calls that return ordinary data, which is why they are not message-shaped: making them messages would not make the engine's boundary any purer.
+
+| Optional management member | Purpose |
+| --- | --- |
+| `listBackgroundCommands()`, `killBackgroundCommand(processId)` | List the background command processes; kill one by id (the whole process group) |
+| `probeBackgroundCommandServices()` | Refresh the listen-port probe behind a command's detected service URL |
+| `detachToolCall(toolCallId)` | Ask one running call to continue as a background task (the Web App's per-card button); answers `detached`, `not_running` or `not_detachable` |
+| `listBackgroundSubagents()`, `hasRunningBackgroundSubagents()` | List the live child sessions; report whether a background child is mid-round |
+| `sendToBackgroundSubagent(childSessionId, messages, opts?)` | Steer a running child, start a follow-up round on an idle one, or revive a released one (`opts.resume`); answers `steered`, `started`, `resumed`, `busy` or `gone` |
+| `abortBackgroundSubagentRun(childSessionId)` | Stop a child's current run; the session survives |
+| `setBackgroundSubagentThinkingLevel(childSessionId, level)` | Pin a live child's thinking level |
+| `setSubagentApprovalFallback(approve)` | Attach the host's session-lifetime fallback approval sink for child sessions |
+| `setSubagentStateListener`, `setBackgroundStateListener`, `setBackgroundTaskListener`, `setBackgroundMessageListener` | Attach the single listener for subagent run-state changes, background-task state changes, completion reports and live background-subagent messages |
+
+`executeTool` yields `partial_tool_call_output` fragments and ends with exactly one complete `tool_call_output`. Nested messages tagged with `origin`, such as those `run_subagent` forwards, pass through unchanged.
-- the **message plane** — `executeTool`, the one method `context_engine` ever calls here: an OmniMessage tool call in, a stream of OmniMessage out;
-- the **management plane** — `listTools` and `toolPermission`, plus the optional background-command and subagent members (the listings, `killBackgroundCommand`, `sendToBackgroundSubagent`, `abortBackgroundSubagentRun`, the listener attachments and `dispose`). None of these pass through the engine: they serve Session assembly and a host's own UI — the Web App's process and subagents panels, an approval mode's permission lookup — and are ordinary method calls returning ordinary data. That is why they are not message-shaped, and why widening them would not make the engine's boundary any purer.
+The built-in Environment can keep truncated text in the Session scratchpad without exposing storage lifecycle hooks through this public interface. The recovery path it shows the model is a plain absolute path. On Windows the path uses forward slashes, which Node's fs APIs and the package's (Git) Bash tool shell both accept, so the same spelling works as a `read_file` argument and inside shell commands.
-`executeTool` yields `partial_tool_call_output` fragments and ends with exactly one complete `tool_call_output`; `origin`-tagged nested messages (e.g. forwarded by `run_subagent`) pass through unchanged. The built-in Environment can keep truncated text in the Session scratchpad without exposing storage lifecycle hooks through this public interface. Its model-visible recovery path is a plain absolute path; on Windows it is written with forward slashes, which Node's fs APIs and the package's (Git) Bash tool shell both accept, so the same spelling works as a `read_file` argument and inside shell commands. Rendering is explicitly not this interface's concern — streaming rendering belongs to the CLI / Web front ends.
+Rendering is not this interface's concern. Streaming rendering belongs to the CLI and Web front ends.
### ToolExecutionRequest and EnvironmentConfig
@@ -154,6 +251,11 @@ interface EnvironmentConfig {
services?: EnvironmentServices; // runtime services injected into individual tools
vault?: Record<string, string>; // Vault env vars, injected into exec_command / input_command subprocesses
proxyEnv?: () => ProxyEnvPolicy | null; // command-subprocess proxy policy; re-read per spawn, absent or null = pass through
+ controlEnv?: () => Record<string, string>; // host control variables (API address, token, Session coordinates); re-read per
+ // spawn; override vault entries, never the hardened ones
+ pathPrepend?: () => string[]; // directories put at the front of PATH for command subprocesses; re-read per spawn
+ confineSpawn?: () => SpawnConfiner | null; // sandbox confinement for command subprocesses; re-read per spawn,
+ // absent or null = commands spawn unconfined
}
// "strip" removes HTTP(S)_PROXY/ALL_PROXY (NO_PROXY kept); "inject" forces the explicit
@@ -161,6 +263,13 @@ interface EnvironmentConfig {
// (supplied pre-merged by the caller), inherited ALL_PROXY removed. Vault entries still win.
type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string; noProxy: string };
+// Rewrites the exact argv a command is about to spawn so it runs confined. Fail-closed: a
+// confiner that cannot enforce its policy throws, and the command fails to spawn.
+type SpawnConfiner = (
+ argv: readonly string[],
+ opts: { cwd: string; workspaceDir: string },
+) => readonly string[];
+
interface EnvironmentServices {
subagentRunner?: SubagentRunner; // needed by run_subagent
visionDescriber?: VisionDescriberService; // injected for text-only models only: read_file describes images through it
@@ -178,9 +287,7 @@ interface MCPServerConfig {
}
```
-`Agent.createSession()` and `resumeSession()` pass the Session scratchpad directory
-automatically. A standalone embedder that owns a stable per-Session directory opts in by
-supplying it — no archive-specific type is exposed:
+`Agent.createSession()` and `resumeSession()` pass the Session scratchpad directory automatically. A standalone embedder that owns a stable per-Session directory opts in by supplying it. No archive-specific type is exposed:
```ts
const environment = new Environment({
@@ -192,15 +299,16 @@ const environment = new Environment({
### The inner tool contract: BuiltinTool
-Inside the Environment, an individual tool follows a deliberately narrower contract ("loose tool, strict framework"):
+Inside the Environment, each tool follows a deliberately narrower contract ("loose tool, strict framework"):
```ts
interface BuiltinTool {
name: string;
definition: ToolDefinitionConfig;
+ detachable?: boolean; // has a background form a running call can be moved to
execute(
args: Record<string, unknown>,
- ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, approve? }
+ ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, detachSignal?, approve? }
): AsyncGenerator<OmniMessage, ToolResult | void>;
}
@@ -212,75 +320,53 @@ interface ToolDefinitionConfig {
forModel?: "vision" | "text-only"; // assembled per session-model class (unset by the built-in entries)
timeoutMs?: number; // default 120000; <=0 disables
maxOutputLength?: number; // default 16000, head-kept truncation; <=0 disables
+ call_description?: boolean; // false filters the `description` call argument out of the schema; missing = kept
}
```
-A tool emits only content deltas; framing, timeouts, truncation, `stop_reason` priority and errors-to-messages are all handled centrally by the Environment — it is close to impossible for a tool author to break the protocol. Extension is registration: add one `name → factory` entry to `BUILTIN_TOOL_FACTORIES` (`packages/core/src/environment/tools/registry.ts`). Per-tool parameters and behavior: [Tools & Approval](/tools).
-
-## The Human boundary
-
-Human is deliberately not an interface class. The SDK caller *is* the Human:
+A tool emits only content deltas. The Environment handles framing, timeouts, truncation, `stop_reason` priority and turning errors into messages centrally, so a tool author can hardly break the protocol.
-```ts
-const session = await agent.createSession({ workspaceDir, provider, modelId });
-
-session.run(
- newMessages: OmniMessage[], // input: the Prompt
- opts?: RunOptions,
-): AsyncGenerator<OmniMessage>; // output: streamed OmniMessage
-
-interface RunOptions {
- signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
- approve?: ApproveFn; // per-tool approval; denies everything when omitted
-}
-```
-
-The CLI wires terminal I/O onto this boundary; the Server wires HTTP requests and SSE channels onto it. Any programmatic caller that connects becomes a new Human implementation — nothing to register.
-
-## ApproveFn
-
-```ts
-type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto
-type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
-```
-
-Constraints: called exactly once per complete `tool_call`; a throwing callback counts as `deny`; when none is injected the engine denies everything (conservative default). A Subagent inherits its parent's approval callback (invoked with an `origin` tag), so the approval policy spans the whole delegation tree.
-
-`"forbidden"` is never a host's answer: `Session.run` wraps the injected callback with the [Project command policy](/configuration#command-policy), and a vetoed command answers `"forbidden"` before the host is asked at all. The denial output is one fixed `aborted` line either way — "Tool call denied by user." for `"deny"`, "Tool call denied by policy." for `"forbidden"` — and the decision value itself rides the `approval_decision` event, so the Trace names the decider with no extra field. An existing callback returning `"allow"` / `"deny"` needs no change.
+Adding a tool is registration: add one `name → factory` entry to `BUILTIN_TOOL_FACTORIES` (`packages/core/src/environment/tools/registry.ts`). For each tool's parameters and behavior, see [Tools & Approval](/tools).
## Subagent interfaces
-Subagent creation is injected at the `createAgent` composition layer, so the Environment never back-depends on the layers above it:
+Subagent creation is injected at the `createAgent` composition layer, so the Environment never depends on the layers above it:
```ts
interface SubagentRunner {
- // Precheck errors (depth limit, unknown agent) are thrown — Environment collapses them to failed
+ // Precheck errors (depth limit, unknown agent) are thrown — Environment collapses them to a fatal result
spawn(input: {
agentId?: string; // defaults to the current Agent (self-spawn)
modelId?: string; // paired with provider; both omitted = inherit the parent Session's model
provider?: string; // required whenever modelId is given (a model reference is the pair)
thinkingLevel?: ThinkingLevelName; // omitted = inherit the parent Session's effective level
}): Promise<SubagentHandle>;
+ resume?(input: { agentId?: string; sessionId: string }): Promise<SubagentHandle>; // revive a released child Session
}
interface SubagentHandle {
sessionId: string; // the child Session id: the origin hop; subagent_id derives from its tail
+ takeMeta?(): OmniMessage | null; // one-shot take of the child's session_meta (a background launch forwards it upfront)
run(input: {
messages: OmniMessage[]; // the round's input, the shape Session.run takes a Prompt in
signal?: AbortSignal;
approve?: ApproveFn; // the parent's approval callback — forwarding is inheritance
- }): AsyncGenerator<OmniMessage>;
+ }): AsyncGenerator<OmniMessage, RunCutoff | null>; // returns null when the round completed
+ steer?(messages: OmniMessage[]): boolean; // queue a steering message for a running round; false when none is running
+ setThinkingLevel?(level: ThinkingLevelName): void; // pin the child's thinking level from its next request
dispose(): void; // release the child Session's runtime resources; idempotent
}
```
-Spawning and running are separate, so the same child Session can accept a follow-up Prompt after a turn ends (a long-running Subagent, driven via `input_subagent`). Child Sessions run in the same Workspace with their own Trace; nesting depth is currently capped at 1.
+Spawning and running are separate, so the same child Session can accept a follow-up Prompt after a round ends. This is how `input_subagent` drives a long-running subagent. A released child Session can be revived with `resume`, which restores its own history, model and Workspace. Child Sessions run in the same Workspace, each with its own Trace. Nesting depth is currently capped at 1.
+
+A round reports a cut-off through its return value, so the parent reports that round as failed instead of handing the model half an answer.
-A round's input is an OmniMessage list — the same shape `steer` takes, and the same shape `EnvironmentInterface.sendToBackgroundSubagent` takes from a host — so both ways into a child session speak one vocabulary. The caller owns each message's `sender`: the model's own dispatch (`run_subagent`, `input_subagent`) stamps `parent_agent`, while a human's message from a host panel carries none, and the child's Trace records who actually spoke.
+A round's input is an OmniMessage list: the same shape `steer` takes, and the same shape a host passes to `EnvironmentInterface.sendToBackgroundSubagent`. Both ways into a child session speak one vocabulary. The caller owns each message's `sender`. The model's own dispatch (`run_subagent`, `input_subagent`) stamps `parent_agent`, while a human's message from a host panel carries none, so the child's Trace records who actually spoke.
## VisionDescriberService
-The image proxy-reading service for text-only models (needed by `read_file` when the Session model cannot view images — its presence is how the tool knows):
+The image proxy-reading service for text-only models. `read_file` needs it when the Session model cannot view images, and its presence is how the tool knows:
```ts
interface VisionDescriberService {
@@ -293,8 +379,9 @@ interface VisionDescriberService {
| To … | Do … |
| --- | --- |
-| Swap or customize model access | implement `LLMInterface` (or just set `client_type` for OpenAI-compatible endpoints) |
-| Swap the execution sandbox | implement `EnvironmentInterface` |
-| Add a tool | implement `BuiltinTool` + register a factory; or declare it under `tools.builtin` in `system_config.yaml` |
-| Customize approval policy | inject an `ApproveFn` (the CLI/Web modes are wrappers over it) |
-| Change an Agent's behavior | edit its Agent State: `system_config.yaml`, `AGENTS.md`, Skills — see the [Configuration Reference](/configuration) |
+| Swap or customize model access | Implement `LLMInterface` (or just set `client_type` for OpenAI-compatible endpoints) |
+| Swap the execution sandbox | Implement `EnvironmentInterface` |
+| Confine the commands an agent runs | Supply `confineSpawn` with a `SpawnConfiner` |
+| Add a tool | Implement `BuiltinTool`, register a factory, and list the tool under `tools.builtin` in `system_config.yaml` (entries without a registered factory are skipped); or connect an MCP server under `tools.mcpServers` |
+| Customize approval policy | Inject an `ApproveFn` (the CLI and Web approval modes are wrappers over it) |
+| Change an agent's behavior | Edit its Agent State (`system_config.yaml`, `AGENTS.md`, Skills); see the [Configuration Reference](/configuration) |
diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.md
index 1c17ee05..f1a57d3c 100644
--- a/packages/docs/content/interfaces.zh.md
+++ b/packages/docs/content/interfaces.zh.md
@@ -1,48 +1,94 @@
---
-title: 接口契约
-description: 自顶向下的接口全览:LLMInterface 与 EnvironmentInterface 的完整签名、内层类型逐字段定义,以及每一处可替换的扩展点。
+title: 核心接口
+description: 引擎背后的 Human、LLM 与 Environment 契约,附完整签名、内部类型与扩展点。
---
-context_engine 依赖三个接口:Human、LLM、Environment。协议转换全部发生在接口实现内部——引擎只见 [OmniMessage](/omni-message)。本页自顶向下:先给出两大接口的完整签名与 Human 边界,再逐层展开每个接口的内部类型。类型全部由 `@prismshadow/penguin-core` 导出,源码见 `packages/core/src/interfaces/`——`llm.ts`(模型侧所需)、`environment.ts`(Environment 侧所需)、`shared.ts`(两侧确实共用的词汇),以及 `index.ts`:`@prismshadow/penguin-core/interfaces` 子路径背后的 barrel。
+`context_engine` 依赖三个接口:Human、LLM 和 Environment。协议转换全部发生在实现内部,引擎能看到的只有 [OmniMessage](/omni-message)。
-## 总览
+本页沿一轮运行的控制流展开:[Human 边界](#human-边界)、[LLM 契约](#llminterface)、[审批回调](#approvefn)和 [Environment 契约](#environmentinterface)。结尾介绍[子 Agent](#子-agent-接口) 和[视觉](#visiondescriberservice)服务,以及[扩展点](#扩展点)。
+
+所有类型都从 `@prismshadow/penguin-core` 导出。源码位于 `packages/core/src/interfaces/`:
+
+- `llm.ts`:模型侧需要的类型。
+- `environment.ts`:Environment 侧需要的类型。
+- `shared.ts`:两侧真正共用的词汇。
+- `index.ts`:`@prismshadow/penguin-core/interfaces` 子路径背后的聚合导出入口。
+
+## 三条边界
```text
- Human(边界,非接口类)
+ Human (a boundary, not a class)
session.run(newMessages, { approve, signal })
│ ▲
- ▼ │ 流式 OmniMessage
+ ▼ │ streamed OmniMessage
context_engine
│ │
LLMInterface │ │ EnvironmentInterface
▼ ▼
GenerativeModel Environment
- └─ AgentHub 网关 └─ BuiltinTool 注册表(exec_command …)
+ └─ AgentHub gateway └─ BuiltinTool registry (exec_command …)
```
| 接口 | 契约 | 内置实现 |
| --- | --- | --- |
-| Human | `session.run` 的入参与流式出参 | CLI、Server(SSE) |
-| LLM | `LLMInterface.streamGenerate` | `GenerativeModel`(基于 AgentHub) |
-| Environment | `EnvironmentInterface.executeTool` 等 | `Environment` + 内置工具注册表 |
+| Human | `session.run` 的输入与流式输出 | CLI、Server(SSE) |
+| LLM | `LLMInterface.streamGenerate` | `GenerativeModel`(经由 AgentHub) |
+| Environment | `EnvironmentInterface.executeTool` 等 | `Environment` 与内置工具注册表 |
-两条铁律贯穿所有接口:**从不向引擎抛异常**(错误收敛为带 `stop_reason` 的消息/返回值),**流式纪律**(`start → delta → stop`,随后立即产出完整消息)。
+每个接口都遵守两条规则:
+
+- **绝不向引擎抛异常。** 错误会转化成携带 `stop_reason` 的消息或返回值。
+- **遵守流式纪律。** 流按 `start → delta → stop` 推进,完整消息紧随其后。
### 消息面与控制面
-三条边界上流动的**内容**只有 OmniMessage,没有别的——`session.run` 的输入与流式输出、`streamGenerate` 的输入数组与产出流、`executeTool` 的已批准调用与其输出流、子会话一轮的输入与被转发的消息,以及每一次 Trace 写入。
+穿过三条边界的**内容**有且只有 OmniMessage:
+
+- `session.run` 的输入与流式输出
+- `streamGenerate` 的输入数组与产出的流
+- `executeTool` 收到的已批准工具调用与输出流
+- 子 Agent 一轮的输入与转发回来的消息
+- 每次 Trace 写入
-与之**并行**流动的是**控制面**,刻意不做成消息形态——它们都不是对话内容:
+与这些内容并行的部分构成**控制面**。控制面刻意不做成消息形态,因为它们都不是对话内容:
-| 控制面项 | 位置 | 为什么不是消息 |
+| 控制面项目 | 所在位置 | 为什么不是消息 |
| --- | --- | --- |
-| `signal: AbortSignal` | `RunOptions`、`GenerativeModelParameters`、`ToolExecutionRequest` | 要在消息队列里排队才生效的打断,就不叫打断了。 |
-| `thinkingLevel` | `GenerativeModelParameters` | 逐次请求参数,与超时同类——它说的是这次请求怎么跑,而不是说了什么。实时值是引擎自有状态(`ContextEngine.setThinkingLevel`,由 `Session.thinkingLevel` 赋值转发,软限制旋钮);未设置时用 LLM 对象的构造默认值——即上下文开启时的等级(`RunOptions` 不带等级)。 |
-| `approve` 及其 `ApprovalDecision` | `RunOptions`、`ToolExecutionRequest` | 回调的入参是 OmniMessage 工具调用;答案是三值枚举,引擎拿到后立刻转写为 `approval_decision` 消息。 |
-| `LLMOutcome` | `streamGenerate` generator 的返回值 | 本次 Request 的结束态,引擎的重试与重连策略全部据此分支。generator 的返回值由类型强制存在;「最后产出的消息必须是 `request_end`」只能是运行期约定。引擎正是据它写出那条 `request_end`。 |
+| `signal: AbortSignal` | `RunOptions`、`GenerativeModelParameters`、`ToolExecutionRequest` | 中断若要在消息队列里排队等候,就不再是中断。 |
+| `thinkingLevel` | `GenerativeModelParameters` | 逐请求参数,与超时同类:它说明请求怎么执行,而不是要说什么。引擎把当前生效的值保存在自己的状态里(`ContextEngine.setThinkingLevel`,由 `Session.thinkingLevel` setter 供值,一个带软限制的旋钮)。请求未携带时,套用 LLM 对象的构造默认值,也就是上下文的起始等级。`RunOptions` 不携带等级。 |
+| `approve` 及其 `ApprovalDecision` | `RunOptions`、`ToolExecutionRequest` | 回调接收一个 OmniMessage 工具调用,返回三值枚举;引擎一拿到结果,立即写成一条 `approval_decision` 消息。 |
+| `LLMOutcome` | `streamGenerate` 生成器的返回值 | 请求的终态,引擎的重试与重连策略以此为分支依据。生成器返回值由类型系统保证;「最后产出的消息必须是 `request_end`」只能是运行时约定。引擎据此写出那条 `request_end`。 |
+
+其余不属于 OmniMessage 的内容都归 Environment 的管理面,在 [EnvironmentInterface](#environmentinterface) 一节说明。
+
+## Human 边界
+
+Human 刻意不定义成接口类。SDK 调用方*就是* Human:
+
+```ts
+const session = await agent.createSession({ workspaceDir, provider, modelId });
+
+session.run(
+ newMessages: OmniMessage[], // input: the Prompt
+ opts?: RunOptions,
+): AsyncGenerator<OmniMessage, RunCutoff | null>; // output: streamed OmniMessage; returns null when the run completed
+
+interface RunOptions {
+ signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
+ approve?: ApproveFn; // per-tool approval; denies everything when omitted
+ preToolUse?: PreToolUseFn; // pre-tool-use hook consult; the Session wires it from installed hook packages
+}
-除此之外仍非 OmniMessage 的部分,属于 Environment 的管理面,见下。
+interface RunCutoff { // how a run was cut off early
+ kind: "abort" | "llm_failure" | "compaction_failure" | "max_turns";
+ errorCode?: ErrorCode; // mirrors the terminal record's error_code (none for max_turns)
+ errorMessage?: string; // mirrors the terminal record's error_message
+}
+```
+CLI 把终端 I/O 接到这条边界上,Server 把 HTTP 请求和 SSE 通道接上去。任何以编程方式接入的调用方都成为新的 Human 实现,无需注册任何东西。
+
+返回值说明这次运行是否真正跑完。失败不会发出 abort 事件,只会留下终态的 `request_end` 或 `compaction_end` 记录。所以,不能把被切断的运行当作已完成的代码,应当读取 `RunCutoff`,而不是从流里推断。
## LLMInterface
@@ -54,151 +100,215 @@ interface LLMInterface {
}
interface GenerativeModelParameters {
- newMessages: OmniMessage[]; // 仅本轮新增消息(实现自行维护历史,多 role 不接受)
+ newMessages: OmniMessage[]; // only this turn's new messages (the impl owns history; mixed roles rejected)
signal?: AbortSignal;
- thinkingLevel?: ThinkingLevelName; // 本次请求的思考等级覆盖;缺省用构造默认值
+ thinkingLevel?: ThinkingLevelName; // per-request override; omitted = the construction default
}
```
-生成器逐条产出 `partial_*` 分片与完整消息,Token 用量以 `token_usage` 事件产出;终态经**返回值**(而非产出消息)给出。
+生成器产出 `partial_*` 片段和完整消息,并通过 `token_usage` 事件上报 Token 用量。终态通过**返回值**报告,而不是通过某条产出的消息。
### LLMOutcome 语义
```ts
interface LLMOutcome {
- status: StopReason; // completed | timeout | malformed | aborted | failed | auth
- message?: string; // 失败详情:failed/auth 时携带;timeout/malformed 捕获到具体
- // 错误时也携带——透传到 request_end,错误面板据此展示被重试
- // 请求背后的真实原因
- permanent?: boolean; // 标记该 failed 为确定性失败(发起网络请求前在客户端就被拒绝,
- // 如在没有 fast 档位的模型上启用 fast_mode):引擎直接带消息
- // 终止,不再重试
+ status: StopReason; // completed | aborted | retryable | fatal
+ errorCode?: ErrorCode; // classified cause on a non-completed failure; carried onto request_end as error_code
+ errorMessage?: string; // failure detail: on fatal, and on retryable when a concrete error was caught;
+ // carried onto request_end as error_message, so the errors panel shows
+ // the real reason behind a retried request
}
```
-| status | 含义 | 引擎的反应 |
+| status | 含义 | 引擎反应 |
| --- | --- | --- |
-| `completed` | 正常完成(已产出 token_usage) | 继续下一步 |
-| `timeout` | 超时/传输层断连 | 同一 run 内自动重连 |
-| `malformed` | 响应解析失败 | 同一 run 内自动重连 |
-| `failed` | 分类器未判定为瞬时的错误(参数等) | 同样在同一 run 内自动重连——状态本身仍如实上报为 `failed`。例外:携带 `permanent: true`(确定性的客户端拒绝,如在没有 fast 档位的模型上启用快速模式)时立即带消息停止 |
-| `aborted` | 用户中断 | 停止交还用户 |
-| `auth` | 凭据被拒绝 | 停止交还用户——唯一从不重试的 LLM 终态;宿主据此禁用输入,直到该模型的 API key 被更新 |
+| `completed` | 正常完成(`token_usage` 已经发出) | 继续执行 |
+| `retryable` | 值得重试的失败:传输中断、空闲超时、408/429/5xx、格式错误或截断的响应,以及一切无法归类的错误 | 在本次运行内按退避阶梯重连 |
+| `fatal` | 重试救不回来的失败:供应商 4xx 拒绝(408 和 429 除外)、凭证被拒,或发起任何网络 I/O 之前就能确定的客户端拒绝(例如给没有快速档位的模型开启快速模式) | 停止运行并呈现 `errorMessage` |
+| `aborted` | 用户中断 | 停止,把控制权交还用户 |
+
+status 只回答一个问题:这个请求要不要重试?errorCode 则说明失败属于哪一类。无法归类的错误有意归为 `retryable`:fatal 的判定采用白名单,网关即使用自己的措辞描述瞬时故障,也照样保留重试。
-实现约束:从不抛异常;不做内部重试(重连是引擎的职责,见 [Agent 运行循环](/agent-loop))。
+`fatal` 结果的补救办法是修改配置或凭证,然后重新发起请求。Session 创建时只有模型引用固定下来;凭证来自当前 Project 配置,所以更新 API key 后 Session 可以继续。
+
+实现约束:
+
+- 绝不抛异常。
+- 不做内部重试。重连是引擎的职责,见 [Agent 运行循环](/agent-loop)。
### GenerativeModelConfig
-内置实现的初始化配置,逐字段:
+内置实现的初始化配置,逐字段说明:
```ts
interface GenerativeModelConfig {
modelId: string;
apiKey?: string;
baseUrl?: string;
- clientType?: string; // AgentHub 客户端协议(openai / …);缺省按 modelId 推断
+ clientType?: string; // AgentHub client protocol (openai-chat / openai-responses / …); inferred from modelId when omitted
tools: ToolDefinition[];
- systemPrompt?: string; // 占位符替换完成后的完整系统提示词
+ systemPrompt?: string; // fully assembled system prompt, placeholders substituted
contextWindow?: number;
maxTokens?: number;
- fastMode?: boolean; // 单模型快速模式(AgentHub fast_mode;溢价快速档位),默认关闭
- thinkingLevel?: ThinkingLevelName; // 构造期默认档位(逐请求参数可覆盖);"none" | "low" | "medium" | "high" | "xhigh" | "max"
- requestTimeoutMs?: number; // Request 的空闲超时:等待上游下一个事件的上限,默认 300000;<=0 关闭
- toolCallIds?: ToolCallIdAllocator; // Session 级 tool_call_id 唯一性登记表(压缩重建时传同一实例)
+ fastMode?: boolean; // per-model fast mode (AgentHub fast_mode; premium faster tier), off by default
+ thinkingLevel?: ThinkingLevelName; // construction default (a per-request parameter can override); "none" | "low" | "medium" | "high" | "xhigh" | "max"
+ requestTimeoutMs?: number; // Request idle budget: the longest wait for the next upstream event, default 300000; <=0 disables
+ sessionId?: string; // the Session's id, sent only to endpoints whose attribution header names the conversation
+ toolCallIds?: ToolCallIdAllocator; // Session-level tool_call_id registry (pass the same instance across compaction)
}
```
### 内置实现:GenerativeModel
-`GenerativeModel`(`packages/core/src/llm/generative-model.ts`)把契约落到模型网关 `@prismshadow/agenthub` 的 `AutoLLMClient` 上:
+`GenerativeModel`(`packages/core/src/llm/generative-model.ts`)基于 `@prismshadow/agenthub` 模型网关的 `AutoLLMClient` 实现这份契约。
+
+**历史。** 网关**有状态地**维护对话历史,每轮只接收新消息。恢复 Session 时,通过一次性的 `setHistory` 重放已提交的历史。
+
+**事件转换。** 内部的 `EventTranslator` 把网关流事件转换成 `partial_*` 片段和完整消息,并逐字保留每一项的不透明 `fidelity` 负载。分块方式与网关自身的聚合规则一致:
+
+- thinking 块由自己的 fidelity 负载收尾。
+- fidelity 相同的连续内容保持在同一个块里。OpenAI 兼容客户端会给每个 delta 打上相同的 `{ reasoning_field }`,不能因此把块切开。
+- 文本段在 `fidelity.phase` 出现差异时拆分,出现 `fidelity.signature` 时结束。合并时 fidelity 键会累积。
+- 完整消息按 thinking → text → tool_call 的顺序落定。
+
+**思考摘要。** 每次请求都会向网关索取思考摘要(`thinking_summary`)。没有供应商会拒绝这个标记:对没有这项能力的模型家族,网关直接丢弃它;Claude 家族则把它理解为摘要式思考。除了让读者看到模型如何推理,它还能让推理阶段持续有事件到达。
+
+**空闲超时。** `requestTimeoutMs` 度量的正是这些事件。计时器只在等待下一个上游事件时运行,每收到一个事件就重置一次。产出、审批、Trace 写入这些消费侧耗时一律不计。它限制的是静默时长,不是响应长度。
+
+**工具调用 id。** `ToolCallIdAllocator` 用来应对把函数名当作调用 id 的供应商:入站时追加 `#n`,出站时再去掉。作用范围是整个 Session。
+
+**供应商差异。** 工具调用格式、推理内容和流式事件的差异全部在网关内部吸收。见[模型与供应商](/models)。
+
+## ApproveFn
+
+`RunOptions` 和 `ToolExecutionRequest` 都携带这个回调类型:
-- 网关**有状态**地维护会话历史,每轮只接收新消息;恢复 Session 时经一次性的 `setHistory` 重放已提交历史;
-- 内部的 `EventTranslator` 把网关流式事件翻译为 `partial_*` 分片 + 完整消息,逐条原样保留不透明的 `fidelity` 保真负载;分段与网关自身的聚合一致——thinking 块由其 fidelity 负载闭合,连续相同的 fidelity 归为同一块(OpenAI 兼容客户端给每条增量盖同一个 `{ reasoning_field }`,不能因此切块),text 段遇到不同的 `fidelity.phase` 即切分、遇到 `fidelity.signature` 即闭合,合并时 fidelity 键累积;完整消息按 thinking → text → tool_call 顺序落盘;
-- 每次请求都向网关索取思考摘要(`thinking_summary`),没有 Provider 会因此报错——没有对应能力的家族由网关丢弃该字段,Claude 系则据此把思考切为摘要展示。它除了让读者看得见模型在想什么,也让推理阶段持续有事件到达,而这正是 `requestTimeoutMs` 计的东西:计时只在等待上游下一个事件时进行、收到任一事件即归零,消费侧的时间(向前端产出、等待审批、写 Trace)一概不计——它约束的是沉默,不是回复的长度;
-- `ToolCallIdAllocator` 处理个别 Provider 用函数名充当调用 id 的情况(入站追加 `#n`、出站剥离),作用域覆盖整个 Session;
-- Provider 协议差异(工具调用格式、思考内容、流式事件)全部在网关内抹平,见[模型与 Provider](/models)。
+```ts
+type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto
+type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
+```
+
+| 规则 | 行为 |
+| --- | --- |
+| 调用频率 | 每个完整的 `tool_call` 恰好调用一次 |
+| 回调抛出异常 | 按 `deny` 处理 |
+| 未注入回调 | 引擎拒绝一切(保守默认) |
+| 子 Agent | 子 Agent 继承父级的审批回调,调用时会带上 `origin` 标记,审批策略因此覆盖整棵委托树 |
+
+`"forbidden"` 永远不是宿主给出的答案。`Session.run` 会用 [Project 命令策略](/configuration#命令策略)包装注入的回调,命中策略的命令不会问到宿主,直接得到 `"forbidden"`。
+
+两种拒绝都只产生一行固定的 `aborted` 输出:`"deny"` 对应「Tool call denied by user.」,`"forbidden"` 对应「Tool call denied by policy.」。决定值本身随 `approval_decision` 事件传递,Trace 不用额外字段就能记录决策者。已有回调如果只返回 `"allow"` 或 `"deny"`,无需任何改动。
## EnvironmentInterface
-工具执行侧的完整契约:
+工具执行契约的核心:
```ts
interface EnvironmentInterface {
listTools(): Promise<ToolDefinition[]>;
executeTool(request: ToolExecutionRequest): AsyncGenerator<OmniMessage>;
- toolPermission(name: string): "r" | "rw" | undefined; // 供前端审批模式判定
- dispose?(): void; // 释放运行时资源,幂等
+ toolPermission(name: string): "r" | "rw" | undefined; // for frontend approval-mode decisions
+ dispose?(): void; // release runtime resources; idempotent
}
```
-本接口承载两条面,只有第一条属于 Agent 循环:
+这个接口承载两个面,只有第一个属于 Agent 循环:
-- **消息面**——`executeTool`,`context_engine` 在此唯一调用的方法:进去一条 OmniMessage 工具调用,出来一串 OmniMessage;
-- **管理面**——`listTools` 与 `toolPermission`,以及可选的后台命令与子会话成员(各类列举、`killBackgroundCommand`、`sendToBackgroundSubagent`、`abortBackgroundSubagentRun`、监听器挂载与 `dispose`)。它们都不经过引擎:服务于 Session 装配与宿主自己的 UI——Web App 的进程面板与子会话面板、审批模式的权限查询——是返回普通数据的普通方法调用。这正是它们不做成消息形态的原因,也是把它们消息化并不会让引擎边界更纯的原因。
+- **消息面**是 `executeTool`,`context_engine` 在这里调用的唯一方法。进去一个 OmniMessage 工具调用,出来一条 OmniMessage 流。
+- **管理面**是 `listTools`、`toolPermission`、`dispose` 和下面的可选成员。它们都不经过引擎,服务于 Session 组装和宿主自己的 UI,比如 Web App 的进程面板和子 Agent 面板,或者审批模式的权限查询。这些都是返回普通数据的普通方法调用,所以不做成消息形态:把它们改成消息,引擎的边界也不会更纯粹。
+
+| 可选管理成员 | 用途 |
+| --- | --- |
+| `listBackgroundCommands()`、`killBackgroundCommand(processId)` | 列出后台命令进程;按 id 杀掉其中一个(整个进程组) |
+| `probeBackgroundCommandServices()` | 重新探测命令的监听端口,更新检测到的服务 URL |
+| `detachToolCall(toolCallId)` | 请求把一个运行中的调用转入后台任务继续执行(Web App 卡片上的按钮);返回 `detached`、`not_running` 或 `not_detachable` |
+| `listBackgroundSubagents()`、`hasRunningBackgroundSubagents()` | 列出存活的子 Session;报告后台子 Agent 是否正处于某轮运行中 |
+| `sendToBackgroundSubagent(childSessionId, messages, opts?)` | 给运行中的子 Agent 发插话消息、让空闲的子 Agent 开启后续一轮,或者复活已释放的子 Agent(`opts.resume`);返回 `steered`、`started`、`resumed`、`busy` 或 `gone` |
+| `abortBackgroundSubagentRun(childSessionId)` | 停止子 Agent 当前这轮运行;Session 本身继续存活 |
+| `setBackgroundSubagentThinkingLevel(childSessionId, level)` | 固定一个存活子 Agent 的思考等级 |
+| `setSubagentApprovalFallback(approve)` | 挂上宿主的兜底审批出口,处理子 Session 的审批请求;它与 Session 同生命周期 |
+| `setSubagentStateListener`、`setBackgroundStateListener`、`setBackgroundTaskListener`、`setBackgroundMessageListener` | 为子 Agent 运行状态变化、后台任务状态变化、完成报告和后台子 Agent 实时消息各挂上唯一的监听器 |
-`executeTool` 逐条产出 `partial_tool_call_output`,并以恰好一条完整 `tool_call_output` 收尾;带 `origin` 的嵌套消息(如 `run_subagent` 转发的子 Session 消息)原样透传。内置 Environment 可以把被截断文本保存在 Session scratchpad 中,无需在此公共接口暴露存储生命周期钩子。其模型可见 recovery 路径是普通绝对路径;Windows 上统一写成正斜杠——Node 的 fs API 与包内 (Git) Bash 工具 Shell 都接受这种写法,同一拼写既可直接作 `read_file` 参数、也可用于 Shell 命令。渲染不是本接口的职责——流式渲染由 CLI / Web 前端完成。
+`executeTool` 产出 `partial_tool_call_output` 片段,最后恰好以一条完整的 `tool_call_output` 收尾。带 `origin` 标记的嵌套消息(例如 `run_subagent` 转发的那些)原样通过。
+
+内置 Environment 可以把截断的文本保存在 Session scratchpad 里,而不必通过这个公开接口暴露存储生命周期钩子。展示给模型的恢复路径是普通的绝对路径。Windows 上路径使用正斜杠,Node 的 fs API 和包内工具所用的 Git Bash 都接受这种写法,所以同一个写法既能直接用作 `read_file` 的参数,也能直接写进 shell 命令。
+
+渲染不在这个接口的职责范围内。流式渲染属于 CLI 和 Web 前端。
### ToolExecutionRequest 与 EnvironmentConfig
```ts
interface ToolExecutionRequest {
- toolCall: OmniMessage<ToolCallPayload>; // 已通过审批的调用
+ toolCall: OmniMessage<ToolCallPayload>; // an approved call
signal?: AbortSignal;
- approve?: ApproveFn; // 转发给需要派生子 Session 的工具,实现审批继承
+ approve?: ApproveFn; // forwarded to tools that spawn child Sessions (approval inheritance)
}
interface EnvironmentConfig {
workspaceDir: string;
toolConfig: ToolConfig; // { customTools: ToolDefinitionConfig[]; mcpServers: MCPServerConfig[] }
- sessionScratchpadDir?: string; // 本 Session 的 scratchpad(scratchpad/<sessionId>),提供后启用截断输出恢复
- services?: EnvironmentServices; // 注入给个别工具的运行时服务
- vault?: Record<string, string>; // Vault 环境变量,注入 exec_command / input_command 子进程
- proxyEnv?: () => ProxyEnvPolicy | null; // 命令子进程代理策略;每次 spawn 重读,缺省或 null 即原样透传
+ sessionScratchpadDir?: string; // this Session's scratchpad (scratchpad/<sessionId>); enables truncated-output recovery
+ services?: EnvironmentServices; // runtime services injected into individual tools
+ vault?: Record<string, string>; // Vault env vars, injected into exec_command / input_command subprocesses
+ proxyEnv?: () => ProxyEnvPolicy | null; // command-subprocess proxy policy; re-read per spawn, absent or null = pass through
+ controlEnv?: () => Record<string, string>; // host control variables (API address, token, Session coordinates); re-read per
+ // spawn; override vault entries, never the hardened ones
+ pathPrepend?: () => string[]; // directories put at the front of PATH for command subprocesses; re-read per spawn
+ confineSpawn?: () => SpawnConfiner | null; // sandbox confinement for command subprocesses; re-read per spawn,
+ // absent or null = commands spawn unconfined
}
-// "strip" 剥除 HTTP(S)_PROXY/ALL_PROXY(保留 NO_PROXY);"inject" 以显式代理覆盖继承环境:
-// HTTP(S)_PROXY(含小写拼写)= url、NO_PROXY = noProxy(由调用方预先合并),继承的 ALL_PROXY
-// 一并移除。Vault 条目仍然优先。
+// "strip" removes HTTP(S)_PROXY/ALL_PROXY (NO_PROXY kept); "inject" forces the explicit
+// proxy over the inherited env: HTTP(S)_PROXY (+ lowercase twins) = url, NO_PROXY = noProxy
+// (supplied pre-merged by the caller), inherited ALL_PROXY removed. Vault entries still win.
type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string; noProxy: string };
+// Rewrites the exact argv a command is about to spawn so it runs confined. Fail-closed: a
+// confiner that cannot enforce its policy throws, and the command fails to spawn.
+type SpawnConfiner = (
+ argv: readonly string[],
+ opts: { cwd: string; workspaceDir: string },
+) => readonly string[];
+
interface EnvironmentServices {
- subagentRunner?: SubagentRunner; // run_subagent 所需
- visionDescriber?: VisionDescriberService; // 仅注入 text-only 模型的 Session:read_file 经它代读图片
- commandSessions?: CommandSessionManager; // 长驻命令会话登记表(Environment 内部构造)
- subagentSessions?: SubagentSessionManager;// 后台 Subagent 会话登记表(同上)
- backgroundDone?: (event: BackgroundTaskDoneEvent) => void; // run_in_background 完成回报的汇聚点(同上)
- backgroundForward?: (msg: OmniMessage) => void; // 后台 Subagent 消息的实时转发出口(同上)
+ subagentRunner?: SubagentRunner; // needed by run_subagent
+ visionDescriber?: VisionDescriberService; // injected for text-only models only: read_file describes images through it
+ commandSessions?: CommandSessionManager; // long-running command session registry (built by Environment)
+ subagentSessions?: SubagentSessionManager;// background subagent session registry (likewise)
+ backgroundDone?: (event: BackgroundTaskDoneEvent) => void; // completion-report sink for run_in_background launches (likewise)
+ backgroundForward?: (msg: OmniMessage) => void; // live message tap of a background subagent (likewise)
}
interface MCPServerConfig {
- name: string; // 工具名前缀:发现的工具以 mcp__<name>__<tool> 暴露
- config: Record<string, unknown>; // 接口层保持开放对象;装配期由 environment/mcp 校验成
- // transport 描述(stdio / http / sse),见 /tools § MCP Server
+ name: string; // tool-name prefix: discovered tools appear as mcp__<name>__<tool>
+ config: Record<string, unknown>; // stays an open object at this seam; typed at assembly time by
+ // environment/mcp into a transport description (stdio / http / sse),
+ // see /tools § MCP Servers
}
```
-`Agent.createSession()` 与 `resumeSession()` 会自动传入 Session scratchpad 目录。自行管理稳定
-per-Session 目录的独立 embedder 只需提供该目录即可启用,不暴露归档专用类型:
+`Agent.createSession()` 和 `resumeSession()` 会自动传入 Session scratchpad 目录。自行管理稳定的逐 Session 目录的独立嵌入方,传入这个目录即可启用,不需要任何归档专用的类型:
```ts
const environment = new Environment({
workspaceDir,
toolConfig,
- sessionScratchpadDir, // 例如 <dataRoot>/<project>/agents/<agent>/scratchpad/<sessionId>
+ sessionScratchpadDir, // e.g. <dataRoot>/<project>/agents/<agent>/scratchpad/<sessionId>
});
```
### 内层工具契约:BuiltinTool
-Environment 之内,单个工具遵循更窄的契约(「松工具、紧框架」):
+在 Environment 内部,每个工具都遵循一份刻意更窄的契约(「工具宽松,框架严格」):
```ts
interface BuiltinTool {
name: string;
definition: ToolDefinitionConfig;
+ detachable?: boolean; // has a background form a running call can be moved to
execute(
args: Record<string, unknown>,
- ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, approve? }
+ ctx: ToolExecutionContext, // { workspaceDir, toolCallId, signal?, detachSignal?, approve? }
): AsyncGenerator<OmniMessage, ToolResult | void>;
}
@@ -207,92 +317,71 @@ interface ToolDefinitionConfig {
description: string;
parameters?: Record<string, unknown>; // JSON Schema
permission?: "r" | "rw";
- forModel?: "vision" | "text-only"; // 按 Session 模型类别装配(内置条目不设)
- timeoutMs?: number; // 默认 120000;<=0 关闭
- maxOutputLength?: number; // 默认 16000,头部保留截断;<=0 关闭
-}
-```
-
-工具只产出内容增量;封帧、超时、截断、`stop_reason` 优先级、错误转消息全部由 Environment 统一处理——工具作者几乎不可能写出破坏协议的工具。注册即扩展:向 `BUILTIN_TOOL_FACTORIES`(`packages/core/src/environment/tools/registry.ts`)添加一个 `名称 → 工厂` 条目即可。逐工具的参数与行为见[工具与审批](/tools)。
-
-## Human 边界
-
-Human 刻意不设计为接口类。SDK 的调用方就是 Human:
-
-```ts
-const session = await agent.createSession({ workspaceDir, provider, modelId });
-
-session.run(
- newMessages: OmniMessage[], // 输入:Prompt
- opts?: RunOptions,
-): AsyncGenerator<OmniMessage>; // 输出:流式 OmniMessage
-
-interface RunOptions {
- signal?: AbortSignal; // 中断信号(如 Ctrl-C)
- approve?: ApproveFn; // 逐工具审批;未注入时默认全部拒绝
+ forModel?: "vision" | "text-only"; // assembled per session-model class (unset by the built-in entries)
+ timeoutMs?: number; // default 120000; <=0 disables
+ maxOutputLength?: number; // default 16000, head-kept truncation; <=0 disables
+ call_description?: boolean; // false filters the `description` call argument out of the schema; missing = kept
}
```
-CLI 把终端输入输出接到这个边界上;Server 把 HTTP 请求与 SSE 通道接上来。任何程序化调用方接上来就是一种新的 Human 实现,无需注册。
+工具只发出内容 delta。分帧、超时、截断、`stop_reason` 优先级,以及把错误转成消息,全部由 Environment 集中处理,工具作者几乎不可能破坏协议。
-## ApproveFn
-
-```ts
-type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = 命令策略的拦截
-type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
-```
-
-约束:每个完整 `tool_call` 恰好被调用一次;回调抛出异常按 `deny` 处理;未注入时引擎默认全部拒绝(保守策略)。Subagent 继承父级的审批回调(调用时带 `origin` 标记),审批策略天然贯穿整个委托树。
+添加工具就是注册:在 `BUILTIN_TOOL_FACTORIES`(`packages/core/src/environment/tools/registry.ts`)里加一条 `name → factory` 条目。各工具的参数和行为见[工具与审批](/tools)。
-`"forbidden"` 从不出自宿主之手:`Session.run` 用 [Project 命令策略](/configuration#沙箱安全策略)包装注入进来的回调,命中的命令在宿主被问到之前就以 `"forbidden"` 作答。两种拒绝的工具输出都是固定的 `aborted` 一句——`"deny"` 为 `Tool call denied by user.`,`"forbidden"` 为 `Tool call denied by policy.`——决定值本身随 `approval_decision` 事件落 Trace,无需额外字段即可分辨决定者。返回 `"allow"` / `"deny"` 的既有回调无需改动。
+## 子 Agent 接口
-## Subagent 接口
-
-Subagent 的创建能力在 `createAgent` 组装层注入,避免 Environment 反向依赖上层:
+子 Agent 的创建能力在 `createAgent` 组装层注入,因此 Environment 不会反向依赖上层:
```ts
interface SubagentRunner {
- // 深度超限、目标 Agent 不存在等前置错误以抛出表达(由 Environment 收敛为 failed)
+ // Precheck errors (depth limit, unknown agent) are thrown — Environment collapses them to a fatal result
spawn(input: {
- agentId?: string; // 缺省复用当前 Agent(自派生)
- modelId?: string; // 与 provider 成对给出;两者都缺省时继承父 Session 的模型
- provider?: string; // 给出 modelId 时必填(模型引用即二元组)
- thinkingLevel?: ThinkingLevelName; // 缺省继承父 Session 的有效思考等级
+ agentId?: string; // defaults to the current Agent (self-spawn)
+ modelId?: string; // paired with provider; both omitted = inherit the parent Session's model
+ provider?: string; // required whenever modelId is given (a model reference is the pair)
+ thinkingLevel?: ThinkingLevelName; // omitted = inherit the parent Session's effective level
}): Promise<SubagentHandle>;
+ resume?(input: { agentId?: string; sessionId: string }): Promise<SubagentHandle>; // revive a released child Session
}
interface SubagentHandle {
- sessionId: string; // 子 Session id:消息 origin 的一跳,subagent_id 由其尾部派生
+ sessionId: string; // the child Session id: the origin hop; subagent_id derives from its tail
+ takeMeta?(): OmniMessage | null; // one-shot take of the child's session_meta (a background launch forwards it upfront)
run(input: {
- messages: OmniMessage[]; // 本轮输入,与 Session.run 接收 Prompt 的形状一致
+ messages: OmniMessage[]; // the round's input, the shape Session.run takes a Prompt in
signal?: AbortSignal;
- approve?: ApproveFn; // 父级审批回调,转发即继承
- }): AsyncGenerator<OmniMessage>;
- dispose(): void; // 释放子 Session 运行时资源,幂等
+ approve?: ApproveFn; // the parent's approval callback — forwarding is inheritance
+ }): AsyncGenerator<OmniMessage, RunCutoff | null>; // returns null when the round completed
+ steer?(messages: OmniMessage[]): boolean; // queue a steering message for a running round; false when none is running
+ setThinkingLevel?(level: ThinkingLevelName): void; // pin the child's thinking level from its next request
+ dispose(): void; // release the child Session's runtime resources; idempotent
}
```
-派生(spawn)与运行(run)分离,同一子 Session 可以在一轮结束后接受追加 Prompt 继续运行(长驻 Subagent,经 `input_subagent` 驱动)。子 Session 在同一 Workspace 中运行、拥有独立 Trace;嵌套深度当前限制为 1。
+创建与运行是分开的两步,所以一轮结束后,同一个子 Session 还能继续接收后续 Prompt。`input_subagent` 就是这样驱动长期运行的子 Agent 的。已释放的子 Session 可以用 `resume` 复活,恢复它自己的历史、模型和 Workspace。子 Session 运行在同一个 Workspace 里,各自拥有独立的 Trace。嵌套深度目前上限为 1。
+
+某一轮中途被切断时,返回值会说明这一点,父级据此把这一轮报告为失败,而不是把半截答案交给模型。
-一轮的输入是 OmniMessage 数组——与 `steer` 相同的形状,也与宿主调用 `EnvironmentInterface.sendToBackgroundSubagent` 时相同的形状——通往子会话的两条路径由此说同一套词汇。每条消息的 `sender` 由调用方决定:模型自己派发(`run_subagent`、`input_subagent`)标记 `parent_agent`,宿主面板上真人发出的消息不带 sender,子会话的 Trace 因此记录的是真正说话的人。
+一轮的输入是一个 OmniMessage 列表:和 `steer` 接受的形状相同,也是宿主传给 `EnvironmentInterface.sendToBackgroundSubagent` 的形状。进入子 Session 的两条途径使用同一套词汇。每条消息的 `sender` 由调用方负责。模型自己发起的派发(`run_subagent`、`input_subagent`)会打上 `parent_agent`,宿主面板里来自人的消息则不带标记,子 Agent 的 Trace 由此能记录到底是谁在说话。
## VisionDescriberService
-text-only 模型的图像代读服务(`read_file` 读图所需——它的存在即工具判定 Session 模型不能看图的依据):
+为纯文本模型代读图像的服务。Session 模型无法查看图像时,`read_file` 需要这个服务;工具正是靠它是否存在来判断这一点:
```ts
interface VisionDescriberService {
- modelId: string | null; // Project 未配置 vision_model 时为 null,工具以 failed 说明收尾
- createLLM?: () => LLMInterface; // 构造该视觉模型的一次性 LLM(无工具、无系统提示词)
+ modelId: string | null; // null when the Project has no vision_model — the tool ends with a failed explanation
+ createLLM?: () => LLMInterface; // one-shot LLM for the vision model (no tools, no system prompt)
}
```
-## 扩展点一览
+## 扩展点
-| 想要 | 做法 |
+| 目标 | 做法 |
| --- | --- |
-| 更换/自定义模型接入 | 实现 `LLMInterface`(或仅配置 `client_type` 走 OpenAI 兼容协议) |
+| 更换或自定义模型访问 | 实现 `LLMInterface`(或者只为 OpenAI 兼容端点设置 `client_type`) |
| 更换执行沙箱 | 实现 `EnvironmentInterface` |
-| 新增工具 | 实现 `BuiltinTool` + 注册工厂;或在 `system_config.yaml` 的 `tools.builtin` 中声明 |
-| 定制审批策略 | 注入 `ApproveFn`(CLI/Web 的四种模式即其封装) |
-| 改变 Agent 行为 | 编辑 Agent State:`system_config.yaml`、`AGENTS.md`、Skills,见[配置参考](/configuration) |
+| 约束 Agent 执行的命令 | 给 `confineSpawn` 提供一个 `SpawnConfiner` |
+| 添加工具 | 实现 `BuiltinTool` 并注册工厂,然后在 `system_config.yaml` 的 `tools.builtin` 下列出这个工具(没有注册工厂的条目直接跳过);或者在 `tools.mcpServers` 下接入 MCP 服务器 |
+| 自定义审批策略 | 注入一个 `ApproveFn`(CLI 和 Web 的审批模式都是对它的封装) |
+| 修改 Agent 的行为 | 编辑它的 Agent State(`system_config.yaml`、`AGENTS.md`、Skill);见[配置参考](/configuration) |
diff --git a/packages/docs/content/introduction.en.md b/packages/docs/content/introduction.en.md
index 54d7aa7a..dab55367 100644
--- a/packages/docs/content/introduction.en.md
+++ b/packages/docs/content/introduction.en.md
@@ -1,49 +1,57 @@
---
title: Introduction
-description: What PenguinHarness is, what ships in the box, and the design tenets behind it.
+description: What PenguinHarness is, what ships in the box, and where to start.
---
-PenguinHarness is an open-source AI Agent harness — a complete TypeScript stack built for constructing and evolving agents. It deploys fully locally (your data never leaves the machine), runs on as little as a single CPU, and reaches 1000+ online and local models through one unified model gateway.
+Welcome to the PenguinHarness documentation. PenguinHarness is an open-source agent harness for building, running, evaluating and improving AI agents, built as one TypeScript stack. It deploys fully locally, so everything it stores stays on your machine; it runs on as little as a single CPU, and one unified model gateway reaches 1000+ online and local models.
-In one line: **Efficient Self-Improving Harness for Everyone.**
+## Get started
-## The three pillars
+Work through these pages in order:
-PenguinHarness is organized around three radiating concepts — the message protocol, the SDK, and the skill library — each carrying one pillar:
-
-| Pillar | Meaning |
-| --- | --- |
-| **Simplest Is the Best** | A deliberately minimal toolset over clean low-level interfaces: fewer tool calls, fewer Tokens, complex tasks done efficiently. |
-| **Harness for Building Agents** | With the PenguinHarness SDK, an Agent builds complete Agent applications for you — autonomously, from scratch. |
-| **Harness for Recursive Self-Improvement** | With PenguinHarness Skills, an Agent evaluates and optimizes itself, improving recursively over time. |
+1. [Quickstart](/quickstart): install PenguinHarness with the desktop app, the CLI, Docker or the SDK, and run your first Task.
+2. [Key concepts](/concepts): learn the terms these docs use, such as Project, Session, Task and Workspace.
+3. [Conversations](/chat): work with an agent in a conversation and follow what it does.
+4. [Agents](/agents): create agents and configure their prompts, Skills, memory and tools.
+5. [Evaluation Center](/evaluation-center): measure an agent against a Benchmark and improve it.
## What ships in the box
-One install gives you four layers that share a single data directory and a single message protocol:
+PenguinHarness is made of these components. They share one data root and one message protocol, so you can mix them freely.
| Component | Package | Description |
| --- | --- | --- |
-| SDK | `@prismshadow/penguin-core` | The core engine: ReAct loop, the [OmniMessage protocol](/omni-message), the LLM and Environment [interface contracts](/interfaces), Agent State and Trace. |
-| CLI | `@prismshadow/penguin-cli` | The `penguin` command: interactive REPL, one-shot task runs, model and Vault configuration. |
-| Server | `@prismshadow/penguin-server` | The Web backend: HTTP [API and SSE streaming](/server-api), multi-user auth, Project authorization, usage statistics. |
-| Web App | `@prismshadow/penguin-web` | The browser UI: multi-session chat, Agent management, skill library, model configuration, Trace observability and the evaluation center. |
+| SDK | `@prismshadow/penguin-core` | The core engine: the ReAct loop, the [OmniMessage protocol](/omni-message), the LLM and Environment [interface contracts](/interfaces), Agent State and Trace. |
+| CLI | `@prismshadow/penguin-cli` | The `penguin` command: an interactive REPL, one-shot Task runs, and model and Vault configuration. |
+| Server | `@prismshadow/penguin-server` | The Web backend: the HTTP [API and SSE streaming](/server-api), multi-user auth, Project authorization and usage statistics. |
+| Web App | `@prismshadow/penguin-web` | The browser UI: multi-session chat, agent management, the plugin library, model configuration, Trace observability and the Evaluation Center. |
+| Desktop app | `@prismshadow/penguin-desktop` | The Web App as a standalone application for macOS, Windows and Linux. It embeds the server and installs the `penguin` command. |
+
+## The three pillars
+
+PenguinHarness is summed up in one line, **Efficient Self-Improving Harness for Everyone**, and organized around three concepts: the message protocol, the SDK and the skill library. Each concept carries one pillar:
+
+| Pillar | Meaning |
+| --- | --- |
+| **Simplest Is the Best** | A deliberately minimal toolset over clean low-level interfaces: fewer tool calls, fewer Tokens, and complex tasks done efficiently. |
+| **Harness for Building Agents** | With the PenguinHarness SDK, an agent builds complete agent applications for you, autonomously and from scratch. |
+| **Harness for Recursive Self-Improvement** | With PenguinHarness Skills, an agent evaluates and optimizes itself, improving recursively over time. |
## Design tenets
-These principles run through every component; the design pages keep coming back to them:
+These principles run through every component, and the design pages keep coming back to them:
-- **A minimal toolset**: dedicated file tools (`read_file` / `edit_file` / `write_file`) for precise reading and editing, with the shell (`exec_command`) as the general-purpose fallback for everything else. See [Tools & Approval](/tools).
-- **Agents are editable data**: prompts, Skills and config are editable files on disk, not hardcoded constants — what you can see, an Agent can improve. See the [Configuration Reference](/configuration).
-- **Everything observable**: every request, tool call and approval decision is appended to the [Trace](/sessions-and-traces); a Session restores fully from it.
-- **Errors converge into messages**: model and tool failures never throw — they become messages the model can react to. See [The Agent Loop](/agent-loop).
-- **Streaming first**: text streams token by token; tool calls and results appear live.
-- **Model ↔ Agent decoupling**: an Agent never binds to a model; you pick one per Session. See [Models & Providers](/models).
+- **A minimal toolset**: dedicated file tools (`read_file` / `edit_file` / `write_file`) handle precise reading and editing, and the shell (`exec_command`) is the general-purpose fallback for everything else. See [Tools & Approval](/tools).
+- **Agents are editable data**: prompts, Skills and config are editable files on disk, not hardcoded constants. What you can see, an agent can improve. See the [Configuration Reference](/configuration).
+- **Everything is observable**: every request, tool call and approval decision is appended to the [Trace](/sessions-and-traces), and a Session restores fully from it.
+- **Errors converge into messages**: model and tool failures never throw. They become messages the model can react to. See [The Agent Loop](/agent-loop).
+- **Streaming first**: text streams token by token, and tool calls and results appear live.
+- **Models and agents are decoupled**: an agent never binds to a model; you pick one per Session. See [Models & Providers](/models).
## A note on naming
-The unified message protocol is called **OmniMessage** in technical writing (marketing materials also call it Penguin Message). This documentation uses OmniMessage throughout.
+The unified message protocol is called **OmniMessage** in technical writing, and marketing materials also call it Penguin Message. This documentation uses OmniMessage throughout.
-## Next steps
+## Learn how it works
-- Follow the [Quickstart](/quickstart): install PenguinHarness by whichever route fits you — desktop app, CLI, Docker, or SDK — and run your first Task.
-- Start the design docs at the [Architecture](/architecture) overview to see how the pieces fit together.
+To see how the pieces fit together, start the design pages at the [Architecture](/architecture) overview.
diff --git a/packages/docs/content/introduction.zh.md b/packages/docs/content/introduction.zh.md
index 6768c402..b6931993 100644
--- a/packages/docs/content/introduction.zh.md
+++ b/packages/docs/content/introduction.zh.md
@@ -1,49 +1,57 @@
---
title: 产品介绍
-description: PenguinHarness 是什么,它由哪些部分组成,以及它的设计信条。
+description: PenguinHarness 是什么,它由哪些部分组成,以及从哪里开始。
---
-PenguinHarness 是一个开源的 AI Agent Harness——为「构建 Agent」与「进化 Agent」而生的一整套 TypeScript 基础设施。它完全本地部署,数据不出机器,最低一颗 CPU 即可运行;通过统一的模型网关可接入 1000+ 在线与本地模型。
+欢迎阅读 PenguinHarness 文档。PenguinHarness 是一个开源的 Agent Harness,用来构建、运行、评估和持续改进 AI Agent,整体是一套 TypeScript 技术栈。它完全本地部署,存储的一切都留在你的机器上;最低一颗 CPU 即可运行,通过统一的模型网关可以接入 1000+ 在线与本地模型。
-一句话概括:**Efficient Self-Improving Harness for Everyone.**
+## 开始使用
-## 三大支柱
-
-PenguinHarness 的能力围绕三个递进的概念展开——消息协议、SDK、技能库,分别支撑三个支柱:
+建议按顺序阅读下面这些页面:
-| 支柱 | 含义 |
-| --- | --- |
-| **Simplest Is the Best** | 在干净的底层接口之上刻意保持极简的工具集:更少的工具调用、更少的 Token,高效完成复杂任务。 |
-| **Harness for Building Agents** | 基于 PenguinHarness SDK,由一个 Agent 从零开始为你自主构建完整的 Agent 应用。 |
-| **Harness for Recursive Self-Improvement** | 基于 PenguinHarness Skills,Agent 评估并优化自己,随时间递归进化。 |
+1. [快速开始](/quickstart):用桌面应用、CLI、Docker 或 SDK 安装 PenguinHarness,跑通第一个 Task。
+2. [核心概念](/concepts):了解文档里用到的术语,例如 Project、Session、Task 和 Workspace。
+3. [对话](/chat):在对话中与 Agent 协作,随时看到它在做什么。
+4. [Agent](/agents):创建 Agent,配置它的提示词、Skill、记忆和工具。
+5. [评估中心](/evaluation-center):用 Benchmark 衡量 Agent 的表现,并加以改进。
## 产品组成
-一次安装即获得完整的四层交付物,它们共享同一套数据目录与同一个消息协议:
+PenguinHarness 由下面这些组件构成。它们共用同一个数据目录和同一套消息协议,因此可以自由混用。
| 组件 | 包名 | 说明 |
| --- | --- | --- |
-| SDK | `@prismshadow/penguin-core` | 核心引擎:ReAct 循环、[OmniMessage 协议](/omni-message)、LLM 与 Environment [接口契约](/interfaces)、Agent State 与 Trace。 |
-| CLI | `@prismshadow/penguin-cli` | 命令行 `penguin`:交互式 REPL、单次任务运行、模型与 Vault 配置。 |
-| Server | `@prismshadow/penguin-server` | Web 服务端:HTTP [API 与 SSE 流式通道](/server-api)、多用户认证、Project 授权、用量统计。 |
-| Web App | `@prismshadow/penguin-web` | 浏览器界面:多 Session 对话、Agent 管理、技能库、模型配置、Trace 观测与评估中心。 |
+| SDK | `@prismshadow/penguin-core` | 核心引擎:ReAct 循环、[OmniMessage 协议](/omni-message)、LLM 与 Environment 的[接口契约](/interfaces)、Agent State 与 Trace。 |
+| CLI | `@prismshadow/penguin-cli` | `penguin` 命令:交互式 REPL、单次 Task 运行,以及模型与 Vault 配置。 |
+| Server | `@prismshadow/penguin-server` | Web 服务端:HTTP [API 与 SSE 流式通道](/server-api)、多用户认证、Project 授权和用量统计。 |
+| Web App | `@prismshadow/penguin-web` | 浏览器界面:多会话对话、Agent 管理、插件库、模型配置、Trace 观测和评估中心。 |
+| 桌面应用 | `@prismshadow/penguin-desktop` | 把 Web App 做成独立应用,支持 macOS、Windows 和 Linux。它内嵌服务端,并会装好 `penguin` 命令。 |
+
+## 三大支柱
+
+PenguinHarness 可以用一句话概括:**Efficient Self-Improving Harness for Everyone**。它围绕三个概念展开,即消息协议、SDK 和技能库,每个概念支撑一个支柱:
+
+| 支柱 | 含义 |
+| --- | --- |
+| **Simplest Is the Best** | 在干净的底层接口之上刻意保持极简的工具集:更少的工具调用、更少的 Token,高效完成复杂任务。 |
+| **Harness for Building Agents** | 借助 PenguinHarness SDK,由 Agent 从零开始为你自主构建完整的 Agent 应用。 |
+| **Harness for Recursive Self-Improvement** | 借助 PenguinHarness Skills,Agent 评估并优化自己,随着时间递归进化。 |
## 设计信条
-这些原则贯穿所有组件,后续每一页设计文档都会反复引用:
+这些原则贯穿所有组件,设计文档也会反复提到它们:
-- **极简工具集**:专门的文件工具(`read_file` / `edit_file` / `write_file`)负责精确读写,shell(`exec_command`)作为通用兜底接口负责其余一切,见[工具与审批](/tools)。
-- **Agent 是可编辑的数据**:Prompt、Skill、配置都是磁盘上的可编辑文件,而非硬编码——你能看到的,Agent 就能改进,见[配置参考](/configuration)。
-- **全量可观测**:每一次请求、工具调用与审批决策都以追加方式写入 [Trace](/sessions-and-traces),Session 可从 Trace 完整恢复。
-- **错误收敛为消息**:模型与工具的错误不抛异常,而是变成模型可以继续处理的消息,见 [Agent 运行循环](/agent-loop)。
-- **流式优先**:文本逐 Token 流出,工具调用与结果实时可见。
-- **模型与 Agent 解耦**:Agent 不绑定模型,每个 Session 创建时自由选择,见[模型与 Provider](/models)。
+- **极简工具集**:专门的文件工具(`read_file` / `edit_file` / `write_file`)负责精确读写,其余一切由 shell(`exec_command`)兜底。见[工具与审批](/tools)。
+- **Agent 是可编辑的数据**:提示词、Skill 和配置都是磁盘上可编辑的文件,而不是硬编码的常量。你能看到的,Agent 就能改进。见[配置参考](/configuration)。
+- **一切可观测**:每一次请求、工具调用和审批决定都会追加写入 [Trace](/sessions-and-traces),Session 可以从 Trace 完整恢复。
+- **错误收敛为消息**:模型和工具的失败从不抛出异常,而是变成模型可以继续处理的消息。见 [Agent 运行循环](/agent-loop)。
+- **流式优先**:文本逐 Token 流出,工具调用和结果实时可见。
+- **模型与 Agent 解耦**:Agent 从不绑定模型,每个 Session 由你选择模型。见[模型与 Provider](/models)。
## 命名说明
-统一消息协议在技术文档中称为 **OmniMessage**(产品宣传中也叫 Penguin Message)。本文档站一律使用 OmniMessage。
+统一消息协议在技术文档中称为 **OmniMessage**,产品宣传中也叫 Penguin Message。本文档一律使用 OmniMessage。
-## 下一步
+## 了解工作原理
-- 跟随[快速开始](/quickstart):桌面端、命令行、Docker、SDK 任选一条路线装好 PenguinHarness,跑通第一个 Task。
-- 从[架构总览](/architecture)进入设计文档,理解各组件如何协作。
+想了解各个部分如何协作,可以从[架构总览](/architecture)开始阅读设计文档。
diff --git a/packages/docs/content/message-flow.en.md b/packages/docs/content/message-flow.en.md
index e4cb4f8a..10fbcbbc 100644
--- a/packages/docs/content/message-flow.en.md
+++ b/packages/docs/content/message-flow.en.md
@@ -1,13 +1,13 @@
---
title: Message Flow & Ordering
-description: How messages travel between Human, engine, LLM, Environment and Trace — every ordering guarantee and non-guarantee, and why stream order differs from context order.
+description: How messages travel between the five actors of a turn, which orderings are guaranteed and which are not, and why stream order differs from context order.
---
-[The OmniMessage Protocol](/omni-message) defines what messages *are*; this page explains how they *move* and in what order they become visible: the delivery paths, the merge mechanism, the observable timeline within a turn, which orderings are guaranteed, which are not, and why "order on the stream" and "order in the model context" are two different things. Source of truth: `packages/core/src/engine/context-engine.ts`.
+[The OmniMessage Protocol](/omni-message) defines what messages are. This page explains how they move and in what order they become visible: the delivery paths within a turn, the merge mechanism behind them, and the observable timeline of a turn. It then states which orderings are guaranteed and which are not, and why order on the stream and order in the model context are two different things. Source: `packages/core/src/engine/context-engine.ts`.
## Delivery paths within a turn
-Five actors: Human (the SDK caller), engine (context_engine), LLM, Environment, Trace. Within one turn:
+Five actors take part in a turn: Human (the SDK caller), engine (`context_engine`), LLM, Environment, and Trace. Within one turn:
```text
Human ──run(newMessages)──► engine
@@ -22,26 +22,31 @@ Human ──run(newMessages)──► engine
engine ──approval_decision──► Human and Trace
allow ──► Environment.executeTool (concurrent, never blocks the LLM stream)
Environment ──partial_tool_call_output──► Human, and (complete) ──► Trace
- LLM stream ends: token_usage is its last message, request_end follows at once
+ LLM stream ends: token_usage (completed requests only) is its last message, request_end follows at once
still-running tools keep streaming output (possibly after request_end)
all outputs settled ──► reordered to original call order as the next turn's LLM input
```
-Key point: **every message is written to the Trace at the same moment it enters the output stream**, so stream order and Trace order agree (the Trace merely skips partials and `origin`-tagged messages — see [Sessions & Traces](/sessions-and-traces)).
+> [!NOTE]
+> Every message is written to the Trace at the same moment it enters the output stream. Stream order and Trace order therefore agree; the Trace merely skips partials and `origin`-tagged messages. See [Sessions & Traces](/sessions-and-traces).
+
+Several of these paths run concurrently. [The merge point: MergeQueue](#the-merge-point-mergequeue) explains how their output becomes one ordered stream.
## The merge point: MergeQueue
-A turn has several concurrent producers: the driver task consuming the LLM stream, plus N concurrently executing tools. All of them push into one merge queue, and a **single consumer** (the `run` generator) yields messages one at a time in **arrival order**; the turn ends only when every producer has finished and the queue is drained. The same pump delivers a context opener's records — the first run's bootstrap and a compaction's `openNextContext` publish their connect pair and toolset record through it, so those stream live too.
+A turn has several concurrent producers: the driver task consuming the LLM stream, plus N concurrently executing tools. All of them push into one merge queue. A single consumer, the `run` generator, yields messages one at a time in **arrival order**. The turn ends only when every producer has finished and the queue is drained.
+
+The same pump also delivers a context opener's records. The first run's bootstrap and a compaction's `openNextContext` publish their connect pair and toolset record through it, so those records stream live too.
This one mechanism fixes three basic properties of message delivery:
-1. the consumer sees a single **totally ordered** stream — no client-side multiplexing needed;
-2. messages from different producers interleave by arrival time — tool outputs arrive in **completion order**, unrelated to call order;
-3. order *within* one producer is preserved (the LLM stream is internally ordered; a single tool's fragments are ordered).
+- The consumer sees a single **totally ordered** stream. No client-side multiplexing is needed.
+- Messages from different producers interleave by arrival time. Tool outputs arrive in **completion order**, unrelated to call order.
+- Order within one producer is preserved. The LLM stream is internally ordered, and a single tool's fragments are ordered.
## The observable order within a turn
-A turn with two tool calls, as the consumer observes it (annotated):
+The timeline below shows a turn with two tool calls, as the consumer observes it:
```text
1 event request_begin
@@ -64,23 +69,37 @@ A turn with two tool calls, as the consumer observes it (annotated):
(A and B settled → re-fed in A, B original order → next request_begin)
```
-If a `tool_call` is denied, line 8 carries `deny` and a synthetic `aborted` `tool_call_output` ("Tool call denied by user.") follows immediately — nothing is dispatched.
+### Denials and vetoes
+
+When a `tool_call` is refused, line 8 carries the refusal and a synthetic `aborted` `tool_call_output` follows immediately; nothing is dispatched. The decision and the output text name who refused:
+
+| Refused by | `approval_decision` | Synthetic output |
+| --- | --- | --- |
+| The approval callback | `deny` | "Tool call denied by user." |
+| The command policy | `forbidden` | "Tool call denied by policy." |
+| A `pre_tool_use` hook | `deny` | "Tool call denied by the <name> hook: <reason>." |
+
+A hook that answers is recorded as a `hook` event right before the `approval_decision`.
## Guarantees and non-guarantees
-**Guaranteed:**
+The two tables below separate what a consumer may rely on from what it may not.
+
+### Guarantees
| Guarantee | Meaning |
| --- | --- |
| Streaming discipline | every segment goes strictly `start → delta* → stop`, complete message right after; concatenated deltas ≡ the complete message |
| Approval position | `approval_decision` comes after its `tool_call` and before any output of that tool |
| Pairing | every committed `tool_call` gets exactly one complete `tool_call_output` (a denial gets the synthetic one) |
-| LLM stream tail | `token_usage` is the LLM stream's last message, `request_end` follows immediately |
+| LLM stream tail | on a completed request, `token_usage` is the LLM stream's last message and `request_end` follows immediately; a request that did not complete produces no `token_usage` |
| Commit criterion | `request_end.status === "completed"` ⇔ the turn was committed by the gateway (replay keeps or drops on this) |
| Stream order = Trace order | written as streamed; the Trace only filters partials and `origin` messages |
| Transport ordering | SSE delivers per channel with monotonic ids; reconnects replay from `Last-Event-ID` or get `resync_required` — see [Server API](/server-api) |
-**Not guaranteed (renderers must not rely on these):**
+### Non-guarantees
+
+Renderers must not rely on any of the following:
| Non-guarantee | Meaning |
| --- | --- |
@@ -90,28 +109,38 @@ If a `tool_call` is denied, line 8 carries `deny` and a synthetic `aborted` `too
## Stream order vs context order
-The same batch of tool outputs exists in two orders, serving two different consumers:
+The same batch of tool outputs exists in two orders, one for each consumer:
-- **stream order (completion order)** — for the Human: whoever finishes first is visible first, for real-time rendering;
-- **context order (original call order)** — for the model: before entering the next turn's input, outputs are reordered to the original `tool_call` order, matching provider pairing rules.
+- **Stream order** (completion order) is for the Human. Whoever finishes first becomes visible first, for real-time rendering.
+- **Context order** (original call order) is for the model. Before outputs enter the next turn's input, they are reordered to the original `tool_call` order, matching provider pairing rules.
-Therefore **a renderer must never reconstruct the context from arrival order** — hang each output onto its call via `tool_call_id`; the engine owns context ordering.
+> [!WARNING]
+> A renderer must never reconstruct the context from arrival order. Attach each output to its call via `tool_call_id`; the engine owns context ordering.
## Edge-case timelines
+The cases below change the observable order on the stream:
+
| Case | Observable order on the stream |
| --- | --- |
-| User interrupt | (messages produced so far) → the `abort` event — the last message before `run` returns; carry-over goes to the model context only, never streamed, never written to Trace |
-| Automatic reconnect | `request_end(failed \| timeout \| malformed)` → a fresh `request_begin` (up to 5 times, exponential backoff with a 30s ceiling; only `auth` skips the ladder); the `[turn_retried]` block is model-visible only |
-| Compaction | `compaction_begin` → the compaction request runs against the old context (its raw messages are written to Trace only, except the summary text being generated, which is forwarded as ordinary `partial_text`/`text` inside the span) → that request's `token_usage` → `compaction_end(status)` |
-| max_turns reached | a length notice → the run ends; unsubmitted input is kept as carry-over |
+| User interrupt | (messages produced so far) → the `abort` event — the engine's last message of the run (only `hook` events from stop hooks can follow it); carry-over goes to the model context only, never streamed, never written to Trace |
+| Automatic reconnect | `request_end(retryable)` carrying `retry_in_ms` → a fresh `request_begin` (up to 5 consecutive fruitless retries, exponential backoff with a 30s ceiling); the `[turn_retried]` block is model-visible only |
+| LLM failure that ends the run | `request_end(fatal)`, or a `request_end(retryable)` without `retry_in_ms` once the retries run out, is the engine's last message of the run (only `hook` events from stop hooks can follow it); no `abort` event follows, because `abort` marks only a user interruption |
+| Compaction | `compaction_begin` → the compaction request runs against the old context (its raw messages are written to Trace only, except each attempt's `token_usage` and the thinking and summary being generated, which are forwarded as ordinary `partial_thinking`/`partial_text` or `thinking`/`text` inside the span) → `compaction_end(status)` |
+| max_turns reached | a length notice (`[reached max turns (N); stopping]`) → the run ends; unsubmitted input is kept as carry-over |
| The Prompt itself | written to Trace, not echoed back onto the stream (the caller already has it) |
-| session_meta | never emitted on the main Session's stream (it lives in the Trace and the history API); a Subagent child stream's **first** message is the child's `session_meta` |
+| `session_meta` | never emitted on the main Session's stream (it lives in the Trace and the history API); a Subagent child stream's first message is the child's `session_meta` |
## Across Sessions: the origin chain
-A child Session spawned by `run_subagent` has its own complete stream. When forwarded to the parent, each child message gets one child-Session-id hop prepended to `origin`, and it interleaves with the parent's own messages **by arrival time**; renderers route by `origin` into the nested card. Child messages are not written to the parent Trace — the parent keeps only the `subagent` pointer event, while the child's stream order is recorded in its own Trace.
+A child Session spawned by `run_subagent` has its own complete stream. When a child message is forwarded to the parent, it gets one child-Session-id hop prepended to `origin`, and it interleaves with the parent's own messages by arrival time. Renderers route by `origin` into the nested card.
+
+Child messages are not written to the parent Trace. The parent keeps only the `subagent` pointer event, while the child's stream order is recorded in its own Trace.
## Transport ordering (SSE)
-The Server pushes this exact output stream verbatim (single-line JSON) onto the per-Session SSE channel: monotonically increasing event ids, a bounded replay buffer for reconnects, `resync_required` when the replay window is gone. Event order: on reconnect the replayed gap (or `resync_required`) comes first, then the authoritative `task_state` snapshot and pending approvals; a fresh connection skips replay, so `task_state` is its first event. Details — including the bundled Web App's connect-first + dedup consumption pattern — are on the [Server API](/server-api) page.
+The Server pushes this exact output stream, verbatim as single-line JSON, onto the per-Session SSE channel. Event ids increase monotonically. A bounded replay buffer serves reconnects; if the replay window is gone, the Server sends `resync_required`.
+
+On reconnect, the replayed gap (or `resync_required`) arrives first, then the authoritative `task_state` snapshot and pending approvals. A fresh connection skips replay, so `task_state` is its first event.
+
+Details, including the bundled Web App's connect-first + dedup consumption pattern, are on the [Server API](/server-api) page.
diff --git a/packages/docs/content/message-flow.zh.md b/packages/docs/content/message-flow.zh.md
index dbbc25d5..0441fcf4 100644
--- a/packages/docs/content/message-flow.zh.md
+++ b/packages/docs/content/message-flow.zh.md
@@ -1,116 +1,146 @@
---
title: 消息流转与时序
-description: 消息在 Human、engine、LLM、Environment 与 Trace 之间的传递机制,每一处顺序保证与非保证,以及流序与上下文序的区别。
+description: 消息如何在一轮的五个参与者之间传递,哪些顺序有保证、哪些没有,以及流序为何不同于上下文序。
---
-[OmniMessage 协议](/omni-message)定义了消息**是什么**,本页讲清消息**怎么传、以什么顺序可见**:传递路径、汇流机制、一轮内的可见时序、哪些顺序有保证、哪些没有,以及"流上的顺序"与"模型上下文的顺序"为何是两回事。源码依据:`packages/core/src/engine/context-engine.ts`。
+[OmniMessage 协议](/omni-message)定义了消息是什么,本页讲消息怎么传、以什么顺序可见:一轮内的传递路径、背后的汇流机制和一轮内的可见时序。随后说明哪些顺序有保证、哪些没有,以及「流上的顺序」与「模型上下文的顺序」为何是两回事。源码:`packages/core/src/engine/context-engine.ts`。
## 一轮的传递路径
-五个参与者:Human(SDK 调用方)、engine(context_engine)、LLM、Environment、Trace。一轮之内:
+一轮有五个参与者:Human(SDK 调用方)、engine(`context_engine`)、LLM、Environment 和 Trace。一轮之内:
```text
Human ──run(newMessages)──► engine
- engine ──写 Prompt──────────────────────► Trace
- engine ──request_begin──► Human 与 Trace
- engine ──streamGenerate(新消息)──► LLM
- ┌───────────────── LLM 流式返回 partial_* 与完整消息 ────────┐
- │ engine 逐条转发:每条同时 ──► Human(yield)与 ──► Trace(写) │
- └─────────────────────────────────────────────────────────────┘
- 完整 tool_call ──► engine:await approve(tc)(逐个)
- engine ──approval_decision──► Human 与 Trace
- allow ──► Environment.executeTool(并发,不阻塞 LLM 流)
- Environment ──partial_tool_call_output──► Human 与(完整时)Trace
- LLM 流结束:最后一条 token_usage,随即 request_end ──► Human 与 Trace
- 仍在执行的工具继续流出输出(可晚于 request_end)
- 全部输出齐 ──► 按原始调用顺序重排,作为下一轮 LLM 输入
+ engine ──write Prompt──────────────────► Trace
+ engine ──request_begin──► Human and Trace
+ engine ──streamGenerate(new messages)──► LLM
+ ┌──────────── LLM streams partial_* and complete messages ────────┐
+ │ engine forwards each: simultaneously ──► Human (yield) │
+ │ and ──► Trace (write) │
+ └──────────────────────────────────────────────────────────────────┘
+ complete tool_call ──► engine: await approve(tc) (one at a time)
+ engine ──approval_decision──► Human and Trace
+ allow ──► Environment.executeTool (concurrent, never blocks the LLM stream)
+ Environment ──partial_tool_call_output──► Human, and (complete) ──► Trace
+ LLM stream ends: token_usage (completed requests only) is its last message, request_end follows at once
+ still-running tools keep streaming output (possibly after request_end)
+ all outputs settled ──► reordered to original call order as the next turn's LLM input
```
-要点:**每条消息在进入输出流的同时写入 Trace**,因此流序与 Trace 序一致(Trace 跳过分片与带 `origin` 的消息,见 [Session 与 Trace](/sessions-and-traces))。
+> [!NOTE]
+> 每条消息在进入输出流的同时写入 Trace,因此流序与 Trace 序一致;Trace 只是跳过分片和带 `origin` 的消息,见 [Session 与 Trace](/sessions-and-traces)。
+
+其中几条路径是并发的,它们的输出如何汇成一条有序的流,见[单一汇流点:MergeQueue](#单一汇流点mergequeue)。
## 单一汇流点:MergeQueue
-一轮内存在多个并发生产者:消费 LLM 流的驱动任务,加上 N 个并发执行的工具。它们全部 push 进同一个合并队列,由**单一消费者**(`run` 生成器)按**到达顺序**逐条 yield;生产者全部完成且队列排空,这一轮才结束。上下文开启的记录走同一个泵:首次运行的 bootstrap 与压缩后的 `openNextContext` 都经它发布连接事件对与工具集记录,因此同样实时流出。
+一轮内有多个并发生产者:消费 LLM 流的驱动任务,加上 N 个并发执行的工具。它们全部推入同一个合并队列,由唯一的消费者(`run` 生成器)按**到达顺序**逐条产出。所有生产者都结束且队列排空,这一轮才结束。
+
+开启上下文时产生的记录也走同一个泵:首次运行的 bootstrap 和压缩后的 `openNextContext` 都经它发布连接事件对与工具集记录,因此这些记录同样实时流出。
这一机制决定了消息传递的三条基本性质:
-1. 消费方看到的是一条**全序**的消息流,不需要自己做多路归并;
-2. 不同生产者的消息按到达时刻交错——工具输出的先后是**完成顺序**,与调用顺序无关;
-3. 同一生产者内部的顺序被保留(LLM 流内部有序;单个工具的分片有序)。
+- 消费方看到的是一条**全序**的消息流,不需要自己做多路归并。
+- 不同生产者的消息按到达时刻交错:工具输出的先后是**完成顺序**,与调用顺序无关。
+- 同一生产者内部的顺序保持不变:LLM 流内部有序,单个工具的分片也有序。
## 一轮内的可见顺序
-一个带两次工具调用的轮,消费方按序观察到(标注示例):
+一个带两次工具调用的轮次,消费方按序观察到:
```text
1 event request_begin
2 partial partial_thinking(start → delta… → stop)
- 3 complete thinking ← stop 后立即跟完整消息
+ 3 complete thinking ← the complete message right after stop
4 partial partial_text(start → delta… → stop)
5 complete text
6 partial partial_tool_call A(start → delta… → stop)
7 complete tool_call A
- 8 event approval_decision(allow, A) ← 审批逐个,决策即产出;A 开始并发执行
- 9 partial partial_tool_call B(…) ← LLM 流继续,不等 A
+ 8 event approval_decision(allow, A) ← approvals are sequential; A starts executing
+ 9 partial partial_tool_call B(…) ← the LLM stream continues, not waiting for A
10 complete tool_call B
11 event approval_decision(allow, B)
-12 partial partial_tool_call_output B(…) ← B 先有输出:完成顺序,非调用顺序
+12 partial partial_tool_call_output B(…) ← B produces output first: completion order
13 complete tool_call_output B
-14 event token_usage ← LLM 流的最后一条
-15 event request_end(completed) ← LLM 流结束即产出,不等工具
-16 partial partial_tool_call_output A(…) ← 迟到输出出现在 request_end 之后
+14 event token_usage ← the LLM stream's last message
+15 event request_end(completed) ← emitted when the LLM stream ends, not waiting for tools
+16 partial partial_tool_call_output A(…) ← late output lands after request_end
17 complete tool_call_output A
- (A、B 输出齐 → 按 A、B 原始顺序进入下一轮输入 → 下一个 request_begin)
+ (A and B settled → re-fed in A, B original order → next request_begin)
```
-若某条 `tool_call` 被拒绝,第 8 行的决策为 `deny`,随即产出一条合成的 `aborted` `tool_call_output`(内容 `Tool call denied by user.`),不派发执行。
+### 拒绝与否决
+
+某个 `tool_call` 遭拒时,第 8 行记录拒绝决策,随即产出一条合成的 `aborted` `tool_call_output`,不派发执行。决策和输出文本都写明是谁拒绝的:
+
+| 拒绝方 | `approval_decision` | 合成输出 |
+| --- | --- | --- |
+| 审批回调 | `deny` | "Tool call denied by user." |
+| 命令策略 | `forbidden` | "Tool call denied by policy." |
+| `pre_tool_use` 钩子 | `deny` | "Tool call denied by the <name> hook: <reason>." |
+
+钩子作答时,`approval_decision` 之前会紧挨着记录一条 `hook` 事件。
## 顺序保证与非保证
-**有保证:**
+下面两张表分别列出消费方可以依赖和不可依赖的顺序。
+
+### 有保证
-| 保证 | 说明 |
+| 保证 | 含义 |
| --- | --- |
| 分片纪律 | 每段严格 `start → delta* → stop`,完整消息紧随其后;全部 delta 拼接 ≡ 完整消息 |
-| 审批位次 | `approval_decision` 在其 `tool_call` 之后、该工具任何输出之前 |
-| 配对完整 | 每个已提交的 `tool_call` 恰好对应一条完整 `tool_call_output`(拒绝为合成输出) |
-| LLM 流收尾 | `token_usage` 是 LLM 流的最后一条,`request_end` 紧随其后 |
-| 提交判据 | `request_end.status === "completed"` ⇔ 该轮已被网关提交(回放据此取舍) |
-| 流序 = Trace 序 | 逐条"边流边写";Trace 只是滤掉分片与 `origin` 消息 |
-| 传输有序 | SSE 按通道单调 id 投递,断线按 `Last-Event-ID` 补发或 `resync_required`,见 [Server API](/server-api) |
+| 审批位次 | `approval_decision` 在其 `tool_call` 之后、该工具的任何输出之前 |
+| 配对完整 | 每个已提交的 `tool_call` 恰好对应一条完整的 `tool_call_output`(被拒绝的是合成输出) |
+| LLM 流收尾 | 请求正常完成时,`token_usage` 是 LLM 流的最后一条,`request_end` 紧随其后;未完成的请求不产出 `token_usage` |
+| 提交判据 | `request_end.status === "completed"` ⇔ 该轮已被网关提交(回放据此取舍) |
+| 流序 = Trace 序 | 边流边写;Trace 只滤掉分片与 `origin` 消息 |
+| 传输有序 | SSE 按通道投递,事件 id 单调递增;断线重连时从 `Last-Event-ID` 补发,或收到 `resync_required`,见 [Server API](/server-api) |
-**无保证(渲染层不得依赖):**
+### 无保证
-| 非保证 | 说明 |
+渲染层不得依赖以下顺序:
+
+| 非保证 | 含义 |
| --- | --- |
-| 工具输出顺序 | 到达顺序是完成顺序;多工具的分片可交错,须按 `tool_call_id` 归属 |
-| `request_end` ≠ 轮结束 | 仍在执行的工具输出可出现在 `request_end` 之后、下一个 `request_begin` 之前 |
-| 事件与内容的相对间隔 | `approval_decision` 与首条工具输出之间可能插入 LLM 流的后续消息 |
+| 工具输出顺序 | 到达顺序是完成顺序;多个工具的分片会交错,须按 `tool_call_id` 归属 |
+| `request_end` ≠ 轮结束 | 仍在执行的工具输出可以出现在 `request_end` 之后、下一个 `request_begin` 之前 |
+| 事件与内容的相对间隔 | `approval_decision` 与该工具首条输出之间可能插入 LLM 流的后续消息 |
## 流序与上下文序
同一批工具输出存在两种顺序,服务两个不同的消费者:
-- **流序(完成顺序)**——面向 Human:谁先完成谁先可见,保证实时性;
-- **上下文序(原始调用顺序)**——面向模型:进入下一轮输入前按 `tool_call` 的原始顺序重排,保证与 Provider 的配对约定一致。
+- **流序**(完成顺序)面向 Human:谁先完成谁先可见,保证实时渲染。
+- **上下文序**(原始调用顺序)面向模型:进入下一轮输入之前,输出按 `tool_call` 的原始顺序重排,符合供应商的配对规则。
-因此**渲染层不得用到达顺序重建上下文**——按 `tool_call_id` 把输出挂回对应调用即可;上下文顺序由 engine 负责。
+> [!WARNING]
+> 渲染层不得按到达顺序重建上下文。按 `tool_call_id` 把每条输出挂回对应的调用即可,上下文顺序由 engine 负责。
## 边界情形的时序
+以下情形在流上可见的顺序:
+
| 情形 | 流上可见的顺序 |
| --- | --- |
-| 用户中断 | (已产出的消息)→ `abort` 事件——`run` 返回前的最后一条;补发内容只进模型上下文,不上流、不进 Trace |
-| 自动重连 | `request_end(failed \| timeout \| malformed)` → 新的 `request_begin`(至多 5 次,指数退避、上限 30s;只有 `auth` 不走梯度);`[turn_retried]` 块仅模型可见 |
-| 上下文压缩 | `compaction_begin` → 压缩请求在旧上下文中执行(原始消息只写 Trace,唯一例外是正在生成的摘要文本——以普通 `partial_text`/`text` 在区间内上行)→ 该请求的 `token_usage` → `compaction_end(status)` |
-| 达到 max_turns | 长度提示消息 → 结束;未提交的输入按补发保留 |
-| Prompt 本身 | 写入 Trace,但不回流(输入方已有) |
-| session_meta | 主 Session 的输出流不产出它(存在于 Trace 与历史接口中);Subagent 子流的**第一条**是子 Session 的 `session_meta` |
+| 用户中断 | (已产出的消息)→ `abort` 事件,这是本次运行中 engine 的最后一条消息(其后只可能出现 stop 钩子的 `hook` 事件);补发内容只进模型上下文,不上流、不进 Trace |
+| 自动重连 | 携带 `retry_in_ms` 的 `request_end(retryable)` → 新的 `request_begin`(最多连续 5 次无进展的重试,指数退避、上限 30 秒);`[turn_retried]` 块仅模型可见 |
+| LLM 失败导致运行结束 | `request_end(fatal)`,或重试耗尽后不带 `retry_in_ms` 的 `request_end(retryable)`,是本次运行中 engine 的最后一条消息(其后只可能出现 stop 钩子的 `hook` 事件);不会再有 `abort` 事件,因为 `abort` 只标记用户中断 |
+| 上下文压缩 | `compaction_begin` → 压缩请求在旧上下文中执行(压缩请求的原始消息只写 Trace,例外是每次尝试的 `token_usage`,以及正在生成的思考与摘要,它们以普通的 `partial_thinking`/`partial_text` 或 `thinking`/`text` 在区间内转发)→ `compaction_end(status)` |
+| 达到 max_turns | 长度提示(`[reached max turns (N); stopping]`)→ 运行结束;未提交的输入按补发保留 |
+| Prompt 本身 | 写入 Trace,但不回流(调用方已经有了) |
+| `session_meta` | 主 Session 的输出流不产出它(它在 Trace 与历史接口中);子 Agent 子流的第一条消息是子 Session 的 `session_meta` |
+
+## 跨 Session:origin 链
+
+`run_subagent` 派生的子 Session 有自己完整的消息流。转发给父级时,每条子消息的 `origin` 前插一跳子 Session id,并与父级自己的消息按到达时刻交错;渲染层按 `origin` 把消息归入对应的嵌套卡片。
+
+子消息不写入父 Trace:父 Trace 只保留 `subagent` 指针事件,子 Session 的流序记录在它自己的 Trace 里。
-## 跨 Session:origin 链
+## 传输层顺序(SSE)
-`run_subagent` 派生的子 Session 有自己的完整消息流。转发给父级时,每条子消息的 `origin` 前插一跳子 Session id,与父级本地消息**按到达时刻交错**;渲染层按 `origin` 归入对应子会话卡片。子消息不写父 Trace——父 Trace 只保留 `subagent` 指针事件,子 Session 的流序记录在它自己的 Trace 里。
+Server 把上述输出流原样(单行 JSON)推入每个 Session 的 SSE 通道。事件 id 单调递增,有界缓冲区支持断线补发;重放窗口已失效时,Server 发送 `resync_required`。
-## 传输层顺序(SSE)
+重连时,补发的缺口(或 `resync_required`)在前,随后才是权威的 `task_state` 快照与未决审批;全新连接不重放,首个事件就是 `task_state`。
-Server 把上述输出流原样(单行 JSON)推入 per-Session SSE 通道:事件 id 单调递增,有界缓冲支持断线补发,重放窗口失效时以 `resync_required` 通知客户端重拉历史。事件次序:重连时补发的缺口(或 `resync_required`)在前,随后才是权威的 `task_state` 快照与未决审批;全新连接不重放缓冲,首条即为 `task_state` 快照。细节见 [Server API](/server-api) 的流式接口一节;自带 Web App 的"连接先行 + 去重"消费模式亦在该页。
+细节见 [Server API](/server-api),自带 Web App 的「连接先行 + 去重」消费模式也在该页。
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index 49078298..1b1bf59e 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -1,174 +1,329 @@
---
title: Models & Providers
-description: Model access through the single AgentHub gateway, (provider, model_id) identity, the per-Project model table, credentials and thinking levels.
+description: Add models to a Project, set API keys and the default model, and choose thinking levels and fast mode.
---
-## One gateway
+Each Project has its own model table: the models its conversations can use, grouped by provider, with their credentials, limits, and prices. You manage the table on the **Models** page. An agent is never tied to a model; the model is chosen when a conversation starts.
-All model access goes through one gateway library: `@prismshadow/agenthub` (AutoLLMClient). Core defines only a thin `LLMInterface` (see [Interfaces](/interfaces)); per-provider protocol adaptation happens inside AgentHub, so 1000+ online and local models are reachable, including any OpenAI-compatible endpoint. The protocol translation lives in `packages/core/src/llm/generative-model.ts`.
+- To find your way around, see [The Models page](#the-models-page).
+- To add models, see [Add a model group](#add-a-model-group), [Add a model](#add-a-model), or [Create a model group with AI](#create-a-model-group-with-ai).
+- To give models credentials, see [Set API keys](#set-api-keys).
+- To choose which model new conversations use, see [Set the default model](#set-the-default-model).
+- To tune requests, see [Thinking levels](#thinking-levels) and [Fast mode](#fast-mode).
+- For the full list of built-in providers and the file format, see [Built-in provider groups](#built-in-provider-groups) and [The per-Project model table](#the-per-project-model-table).
-## Model identity
+## The Models page
-A model's identity is always the `(provider, model_id)` pair: `provider` is a config group name, `model_id` the upstream request id sent to AgentHub unchanged. The two are independent fields — concatenating them into one string is forbidden anywhere in the pipeline.
+In the sidebar, select **Models**. Models are listed in groups, one per provider.
-Every interface that names a model takes the complete pair: the CLI, the HTTP API, and the SDK all reject half a reference instead of completing it. The provider is never inferred from the model id and has no default, because gateways resell vendor models under their upstream ids — a guessed group would send the entry's credential to a vendor nobody named. Where a model reference is optional at all (`penguin run` / `chat`, Session creation, Schedules), the choice is between the whole pair and nothing: omit both halves to take the Project's default model.
+- **Groups.** Built-in groups follow the order in [Built-in provider groups](#built-in-provider-groups). Groups you create follow them, sorted by name. A built-in group with no models is hidden; **Custom** is always shown. The **TokenDance** group carries a **Recommended** tag.
+- **Open and close groups.** Select a group's header to open or close it. On your first visit only the TokenDance group is open. The browser remembers which groups you opened, per Project.
+- **Reorder groups.** Drag a group's header to move it. The order is saved in this browser, per Project, and the model picker in the chat uses the same order. Dragging is not available on touch screens or while searching.
+- **Search.** Type in **Search models: id / name / provider** to show only the matching models. While you search, every matching group is open.
-## The per-Project model table
-
-Each Project's available models are recorded in the hidden `.project_config.toml`, maintained via the CLI (`penguin config model add / default / list`, see [CLI Reference](/cli)) or the Web UI — never hand-edited. `ModelEntry` fields:
+Each model card shows the model's display name, tags, context window, prices, key status, and the Tokens the model has used so far.
-| Field | Meaning |
+| Tag | Meaning |
| --- | --- |
-| `provider` | Config group name; paired with `model_id` it forms the unique key |
-| `model_id` | Upstream request id |
-| `context_window` | Context window (tokens). Load-bearing, not just display: each request's effective output cap and the compaction threshold are derived from it, so requests never ask for more output than the window still fits. Unset (or implausibly small, under 4096): the output clamp turns off and compaction derives from an assumed 128000 — set the real value for models with smaller windows. The Web dialog prefills 1,000,000 when a custom or user-group model leaves the field blank (a hand-added entry is a known model, not an unknown window); narrow it when the endpoint serves less. `penguin config model add` writes no default at all when `--context-window` is omitted |
-| `max_tokens` | Optional per-model output cap (max output tokens per request). When set it overrides the Agent's `model.max_tokens`; unset inherits it. The cap is a ceiling, not the literal wire value: each request sends `min(max_tokens, context_window − estimated input − safety margin)`, so small-window models work without hand-tuning it. Omitting the field on a Web full-table save clears it |
-| `client_type` | Protocol hint (`openai-chat` for Chat Completions, `openai-responses` for the Responses API, `ant-messages` for Anthropic Messages, …); inferred by AgentHub from the model id when omitted. Custom endpoints use one of those three generic protocol clients, and the Web dialog can detect which one a base URL serves. The pre-0.4.2 spelling `openai` is a deprecated alias and is normalized to `openai-chat` when the config is read |
-| `display_name` | Display name |
-| `vision` | Whether image input is supported, default true |
-| `fast_mode` | Optional fast mode (off by default): opts the model's session requests into the provider's faster serving tier at premium pricing. Only `true` is ever persisted — omitting the field on a Web full-table save clears it. Models without a fast tier reject requests carrying it (see [Fast mode](#fast-mode)) |
-| `pricing` | Three price buckets (unit `usd_per_mtok`, USD per million tokens): `cache_read` / `cache_write` / `output` |
-| `api_key` / `base_url` | Inlined credentials, both optional; when blank, AgentHub falls back to environment variables |
+| **Default** | The Project's default model |
+| **Vision** | The model accepts images |
+| **Proxy vision** | The model reads images for models without vision |
+| **Fast** | Fast mode is on |
+| **Free** | All three prices are 0 |
+| **N% off** | A promotion or an off-peak rate currently applies; see [Prices and promotions](#prices-and-promotions) |
-A fresh Project defaults to deepseek-flash (DeepSeek V4.1 Flash), which reads images itself. A `vision_model` entry can additionally designate the proxy model through which `read_file` reads images for text-only session models (see [Tools & Approval](/tools)); it is unset by default.
+Prices are shown per million Tokens, in the order cache read / cache write / output. The currency is the one chosen under **Currency** in the settings: **USD $** or **CNY ¥**, converted at a fixed rate of 7.
-File shape (illustrative):
+Select a card to open **Model settings**. Links next to a group open the provider's key console (**Manage keys**). The model dialog links to the provider's model list (**Get model IDs**) and to the model's own page (**Model page**).
-```toml
-default_model = { provider = "deepseek", model_id = "deepseek-flash" }
-vision_model = { provider = "google", model_id = "gemini-3.1-pro-preview" }
+Only the Project owner can change models and credentials. Members can search, open and close groups, reorder them in their own browser, and open **Model settings** read-only.
-[[models]]
-provider = "deepseek"
-model_id = "deepseek-flash"
-context_window = 1000000
-client_type = "deepseek-v4"
-base_url = "https://api.deepseek.com"
+## Add a model group
-[[models]]
-provider = "custom"
-model_id = "my-model"
-client_type = "openai-chat"
-base_url = "https://llm.example.com/v1"
-api_key = "sk-..."
-```
+A group you create works like the **Custom** group: its models use one of the generic protocols, and each carries its own base URL.
-For a model tagged `vision = false` (e.g. `deepseek-v4-pro`, the text-only member of the DeepSeek group), images from conversation input are saved to the Session scratchpad and handed over as a file path spliced into the text, and `read_file` hands an image to the `vision_model` for description instead of returning it.
+1. On the **Models** page, select **Create manually**, or select **Add group** (+) below the last group. The **Add group** dialog opens.
+2. In **Group name**, enter a name. The name:
+ - starts with a lowercase letter or digit;
+ - uses only lowercase letters, digits, `-` and `_`;
+ - is at most 32 characters long;
+ - cannot match a built-in group or an existing group.
+3. Choose **Create only** or **Import models**, then follow the section below for your choice.
-## Built-in provider groups
+### Create an empty group
-Built-in groups and their env-var fallbacks (catalog source: `packages/core/src/state/model-catalog.ts`); each group also has a `_BASE_URL` variant (e.g. `ANTHROPIC_BASE_URL`). The models page lists the groups in this order by default and opens the first one; drag a group header to arrange them yourself, and that arrangement is stored per Project and is what you see from then on.
+1. Select **Create only**, then select **Confirm**. The **Add model** dialog opens for the new group.
+2. Add the first model; see [Add a model](#add-a-model).
-| Provider | API key env var | Notes |
-| --- | --- | --- |
-| tokendance | `OPENAI_API_KEY` | The recommended vendor group. OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates, several of them currently discounted |
-| penguin-go | `PENGUIN_GO_API_KEY` | Preset relay group with fixed base URL `https://token.penguin.ooo/api`; its header can authorize a key automatically or set one manually |
-| deepseek | `DEEPSEEK_API_KEY` | Group of the default model |
-| openrouter | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://openrouter.ai/api/v1` |
-| fireworks | `OPENAI_API_KEY` | Fireworks AI (OpenAI-compatible), preset base URL `https://api.fireworks.ai/inference/v1`; API model ids look like `accounts/fireworks/models/<slug>` |
-| google | `GEMINI_API_KEY` | |
-| openai | `OPENAI_API_KEY` | |
-| anthropic | `ANTHROPIC_API_KEY` | |
-| siliconflow | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://api.siliconflow.cn/v1` |
-| zhipu | `ZAI_API_KEY` | |
-| moonshot | `MOONSHOT_API_KEY` | |
-| minimax | `MINIMAX_API_KEY` | Direct MiniMax M3 Responses client (`client_type = "minimax-m3"`): `MiniMax-M3` with a 1,000,000-token context window and vision; preset base URL `https://api.minimax.io/v1`; accepts a Token Plan Subscription Key or pay-as-you-go API key |
-| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen pay-as-you-go (DashScope's OpenAI-compatible endpoint), preset base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`; resold third-party models keep vendor-prefixed ids (e.g. `kimi/kimi-k3`) |
-| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan subscription gateway, preset base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`; pricing from each model page's official list price (the preview model has only a quota-multiplier promo, no list price) |
-| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint; ships one preset, Atria Dawn Preview (Anthropic Messages API at `api.atria-asi.ai`, credential from `ANTHROPIC_API_KEY` when the entry has none, 256K window, priced at $0 until the vendor publishes prices) |
+The group appears in the list once its first model is saved.
-The gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan) go through AgentHub's generic OpenAI-protocol clients, so with blank credentials they read `OPENAI_API_KEY` — not a gateway-specific variable. The OpenRouter group uses the Responses client (`client_type = "openai-responses"`) throughout — its presets and any model you add to the group alike — because OpenRouter serves the Responses API at that same base URL for every model it resells; the other gateway presets pin the Chat Completions client (`client_type = "openai-chat"`). Both clients read the same `OPENAI_*` variables, so the credential rules are identical either way. The direct MiniMax M3 client reads `MINIMAX_API_KEY`. The built-in MiniMax preset pins `https://api.minimax.io/v1`; `MINIMAX_BASE_URL` is consulted only for entries without an inline `base_url`. M3 pricing records MiniMax's standard pay-as-you-go tier at 512K input tokens or below; every rate doubles above that and the priority tier is 1.5x, so long-context and priority usage is underestimated — the same base-tier convention already used for OpenAI (>272K) and Gemini 3.1 Pro (>200K).
+### Import models from an endpoint
-The preset catalog also carries OpenRouter's free tier: the `:free` model variant `nvidia/nemotron-3-ultra-550b-a55b:free` and the `openrouter/free` unified Free Models Router. They cost nothing, but are subject to OpenRouter's free-tier rate limits and data policy.
+**Import models** fills a new group with every model an OpenAI-compatible or Anthropic-compatible endpoint lists.
-Some models in the preset catalog: deepseek-flash / deepseek-v4-pro (`deepseek-flash` is V4.1 Flash and reads images; `deepseek-v4-pro` is the V4 Pro 0813 release and is text-only. DeepSeek still accepts the retired `deepseek-v4-flash` and `deepseek-v4-flash-vision-exp` names and serves them from V4.1 Flash. They are no longer presets, but the catalog keeps them — and TokenDance's `deepseek-v4-flash-vision-exp` — as retired rows: a Project that still has one keeps its name, **Sync presets** keeps its price current but never adds it to a Project without it, and it is priced on its off-peak schedule whenever it stores the catalog price. Send an image to `deepseek-flash`), MiniMax-M3, gemini-3.8-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-6-astra / gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, qwen3.8-max / qwen3.8-flash, seed-2.1-pro / seed-2.1-turbo / seed-evolving, dots-3-note-preview (free on TokenDance, 512K context) (not exhaustive). Penguin Go's DeepSeek rows follow DeepSeek's current lineup and carry only `deepseek-flash` and `deepseek-v4-pro`. The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group rows record the official peak tier and declare its off-peak schedule: outside Beijing weekday 9:00–12:00 and 14:00–18:00 every bucket is halved, which the models page marks with a `50% off` badge and the cost center bills at. Two resold rows follow the same schedule, because their sellers pass DeepSeek's own windows through: TokenDance's `deepseek-v4.1-flash` and OpenRouter's `deepseek/deepseek-v4.1-flash`. Qwen bills the DeepSeek models it sells on a schedule of its own — half price from 22:00 to 8:00 Beijing time, every day — so `deepseek-v4.1-flash` in both Qwen groups and the Token Plan's `deepseek-v4-pro-0813` declare that one instead, and the badge's tooltip names the windows of whichever schedule the row follows. The stored price is always the peak one, so what is on disk does not depend on the hour a Project was created or re-synced in. GLM-5.3 Flash appears five times — directly as `glm-5.3-flash`, under the same id on TokenDance, and as OpenRouter's `z-ai/glm-5.3-flash`, Fireworks AI's `accounts/fireworks/models/glm-5p3-flash` and Qwen Pay-As-You-Go's `ZHIPU/GLM-5.3-Flash` — and every row accepts images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the gateway rows go through the generic OpenAI-compatible clients, which carry them for any id. What the rows do not share is the price: each records what its own seller charges, so they disagree while a promotion is running.
+1. Select **Import models**.
+2. In **API key**, enter the key. Leave it empty to use the protocol's `OPENAI_*` or `ANTHROPIC_*` environment variables.
+3. In **Custom base URL**, enter the endpoint's base URL.
+4. Select **Detect** at the top-right of the field, or pick the protocol from the menu at the right edge of the field. See [Detect a custom model's protocol](#detect-a-custom-models-protocol).
+5. Select **Import all models**. PenguinHarness asks the endpoint for its model list and saves every model into the new group, in the endpoint's order.
-TokenDance rows record the gateway's list price and, where a promotion is running, the rate off it. Nine models are discounted today — `kimi-k3` at 40% off, `deepseek-v4-flash-0731`, `deepseek-v4-pro-0813`, `glm-5.3`, `glm-5.3-flash` and `qwen3.8-max` at 10%, and the three Doubao Seed rows (`seed-2.1-pro`, `seed-2.1-turbo`, `seed-evolving`) at 50%. One further row, `deepseek-v4.1-flash`, carries no flat discount and instead follows DeepSeek's own off-peak schedule, described above. Their model cards show the price being billed right now, with the rate as a badge. A Project is preset with the **list** price: the server stores the promotion beside it (in `web.db`, not in `.project_config.toml`) and takes it off when usage is priced, so the cost center charges what the gateway charges. Editing a row's price yourself cancels its promotion and keeps any off-peak decoration off the card: the figure is then yours, not the gateway's.
+Each imported model gets the base URL, the protocol, and the key you entered. Only the model id comes from the endpoint: prices, context window, and display name stay empty, and vision stays off until you detect it or turn it on. That is the same starting point as a model you add by hand.
-## App attribution
+Some ids are skipped, and the result says how many: "Imported {added} models, skipped {skipped} entries". An id is skipped when it is empty, longer than 200 characters, contains control characters, or is already taken.
-Some gateways read a request header that files a call under the app that made it, feeding their own app rankings and usage reports. The catalog decides those headers by **endpoint host**, not by the entry's provider group: an entry filed under custom whose base URL points at such a gateway carries the same headers. Only the entry's own `base_url` is consulted — an endpoint supplied through `OPENAI_BASE_URL` is resolved inside AgentHub, is not visible on this side, and is therefore not attributed.
+If the protocol cannot list models ("This protocol cannot list models — add them manually") or the list is empty, nothing is saved and the dialog stays open. A failed detection only turns the protocol suffix amber; you can still pick the protocol by hand or switch back to **Create only**.
-| Endpoint | Header | Value |
-| --- | --- | --- |
-| `openrouter.ai` | `HTTP-Referer` | `https://penguin.ooo/` |
-| `openrouter.ai` | `X-OpenRouter-Title` | `PenguinHarness` |
-| `openrouter.ai` | `X-OpenRouter-Categories` | `cli-agent,personal-agent` |
-| `tokendance.space` | `X-App-URL` | `https://penguin.ooo/` |
+The listing uses `POST /api/projects/:id/models/list` (owner only), which calls AgentHub's `listModels()` on that protocol's client with a 20-second limit.
+
+### Delete a group
+
+1. On the header of a group you created, select **Delete group**.
+2. Confirm the deletion.
+
+All of the group's models and their API keys are removed. Built-in groups cannot be deleted.
+
+## Add a model
-Every other endpoint — every direct vendor, and every gateway that reads no such header — receives no extra headers at all. The headers state the app's identity only; they carry nothing about the user, the Agent or the Session.
+1. On the group's header, select **Add model**.
+2. In **Model ID**, enter the model id exactly as the provider's API expects it, for example `gpt-5.5`. **Get model IDs** opens the provider's model list.
+3. Optional: in **Display name**, enter a display name. An empty display name shows the model id.
+4. Fill in the credentials and endpoint:
+ - **API key**: leave it empty to use the provider's environment variable. The field names the variable when it is set on the server.
+ - **Custom base URL**: required in **Custom** and in groups you created. In gateway groups it is filled in for you.
+5. Optional: fill in the limits and prices:
+ - **Context window**: the model's context window in Tokens. For a model that is not in the built-in catalog, an empty field saves as 1000000.
+ - **Max output tokens**: the most output Tokens per request. Leave it empty to use the agent's setting; lower it for models with a small context.
+ - **Cache read price**, **Cache write price**, and **Output price**: per million Tokens, in the display currency; they are stored in USD. Fill in all three or none.
+6. Optional: turn on **Vision support** if the model accepts images, or select **Detect**; see [Detect vision support](#detect-vision-support). New models in **Custom** and in groups you created start with vision off; models you add to other groups start with it on.
+7. Optional: turn on **Fast mode**; see [Fast mode](#fast-mode).
+8. Select **Confirm**.
-## Penguin Go preset group
+Which protocol a new model uses depends on its group:
-`penguin-go` is a built-in model group, like TokenDance. New Projects contain the group's catalog models immediately; existing Projects add them through **Sync presets** on the Models page. The built-in rows provide a stable initial route to `https://token.penguin.ooo/api`, while the platform catalog returned during authorization or **Sync** can add model ids that are missing locally, together with their protocol, endpoint, display name, context window, vision capability, and platform price. Like every built-in group, synchronized models leave the user-owned `max_tokens` override unset and inherit the Agent setting. Existing rows refresh their three platform price buckets and client protocol; their endpoint and other Project-owned configuration are not overwritten, and rows are never deleted. Pure embedding rows are excluded. As in every other group, `.project_config.toml` holds the list price, and a flat promotion the platform runs is stored by the server in `web.db`, taken off when usage is priced, and shown as the model card's badge. These promotions come only from the platform: **Sync presets** does not set them, and each authorization or Sync replaces them. If that record is lost, usage is priced at the list price until the next authorization or Sync writes it back. The platform reports peak rates in USD per million tokens. The current built-in Penguin Go DeepSeek rows declare the same Beijing off-peak schedule as the direct DeepSeek group, so their model cards and cost records use half price outside weekday 9:00–12:00 and 14:00–18:00.
+- **Vendor groups** (DeepSeek, Google Gemini, OpenAI, Anthropic, Z.AI, Moonshot, MiniMax) support only the vendor's own API. If a model id cannot be routed that way, the dialog warns you and offers **Move to Custom**. Use Custom for OpenAI-compatible endpoints.
+- **OpenRouter** always uses `openai-responses`, and **vLLM** always uses `openai-chat-vllm-adapter`.
+- **Other gateway groups** use OpenAI Chat Completions.
+- **Custom** and groups you created: pick the protocol from the base URL field, or detect it. See [Detect a custom model's protocol](#detect-a-custom-models-protocol).
-Before the group has a platform key, its **Authorize key** action creates a one-time request only after the user clicks it, then opens Penguin Go in a new tab while the local server polls. The browser receives only an authorization URL and local flow id; the device secret and delivered API key remain server-side. On success PenguinHarness validates `connection.apiKey`, the endpoints, and the model catalog. It writes the key to every existing group model, adds newly advertised models with their recommended protocol, endpoint, name, context window, vision capability, and list price, refreshes existing platform-model prices and client protocols, then replaces the group's promotions with the platform's. Synchronization preserves existing endpoints and other Project-owned configuration and never deletes models. Account and balance data are neither saved nor displayed.
+### Edit or delete a model
-After a platform key is configured, a separate **Sync** action appears immediately before **Add model**. **Authorize key** remains available so the owner can replace the key with one from another platform account. Sync uses the stored key to request the latest catalog, adds new models, refreshes existing platform-owned metadata, and leaves the config file untouched when the catalog produces no changes. If the platform reports that the key is invalid or revoked, the Models page automatically opens authorization again. Penguin Go's browser session and API key are separate: an expired browser session does not prevent a valid key from synchronizing; reauthorization is needed only when the key itself is invalid.
+Select the model's card to open **Model settings**. Change the fields, select **Confirm**, and confirm the save. From the same dialog you can **Test connection**, **Set as default model**, **Set as proxy vision model**, or **Delete model**.
-## Authorizing a new API key
+Changing **Model ID** or **Group** renames the entry; its credential and its default or proxy vision role move with it. **Delete model** removes the model's configuration and API key.
-A provider that supports automatic key authorization puts an extra action on its group header in the Models page: **Authorize key**. TokenDance and Penguin Go both do. A successful flow writes the new key to every model in that group, replacing whatever key those entries carry. After Penguin Go authorization succeeds, a separate **Sync** action incrementally discovers models the platform later makes available while authorization remains available for switching accounts.
+## Create a model group with AI
-Pressing it opens the provider's authorization page in a new tab, while the dialog in the Models page waits for and reports the result. TokenDance uses a PKCE callback and exchange; Penguin Go uses device authorization start and poll endpoints. That protocol difference stays server-side, so the user interaction and group-key result are the same.
+**Create with AI** covers what an import cannot read: a model listing page that is not an OpenAI-compatible `/models` endpoint, a service described in words, or vendor models to add to an existing group.
-The exchange runs entirely on the server: neither a PKCE verifier nor a device secret reaches the browser, and the minted key goes straight into the model table. An authorization delivers one key and expires at the deadline returned by the provider; PenguinHarness never keeps a local flow for longer than ten minutes.
+> [!TIP]
+> For an OpenAI-compatible endpoint that lists its own models, **Import models** in the **Add group** dialog is faster.
-TokenDance supports entering a one-time code when its redirect cannot return. Penguin Go is polled by the Models page and therefore has no manual-code mode.
+1. On the **Models** page, select **Create with AI**. The **Add a model group with AI** dialog opens.
+2. Paste the address of a model listing page or describe the service, or pick an example under **Try an example**.
+3. Select **Edit in a new conversation**. A new conversation with the Project's default agent opens with the prompt filled in.
+4. Send the prompt.
-Only the Project owner can start authorization. The full key never returns to the Web app. If writing a Penguin Go key locally fails, the server keeps that single delivery briefly so the write can be retried without authorizing again.
+The fixed instructions tell the agent to use the `penguin-config` Skill and to:
-## Local / self-hosted OpenAI-compatible endpoints (e.g. vLLM)
+- run `penguin config model add --provider <group> --model-id <upstream id> --project-id <project> --root <data root>` once per model, adding `--client-type openai --base-url <endpoint>` for an OpenAI-compatible endpoint. The data root is named because a command's environment does not carry it;
+- when the source is a web page, fetch it first and add the models you named, or the most popular ones, about ten at most;
+- ask once for a missing API key, or leave it empty for you to fill in on the **Models** page;
+- never read or edit `.project_config.toml`;
+- finish with `penguin config model list`.
-A local inference server is just a `custom` entry: `client_type = "openai-chat"`, `base_url` pointing at the server (e.g. `http://127.0.0.1:8000/v1`), and the served model name as `model_id` (`openai-chat` is also what the protocol detection below settles on for such servers, and what the base URL field's suffix menu selects by hand). Two settings make it run smoothly:
+The **Models** page reloads the table on every visit, so the new group is there when you come back from the conversation.
-- **Enable tool calling server-side.** For vLLM, start the server with `--enable-auto-tool-choice` and the `--tool-call-parser` matching your model (e.g. `hermes` for Qwen, `llama3_json` for Llama 3.x); without them tool calls arrive as plain text and the agent loop cannot execute anything.
-- **Set the entry's `context_window` to the server's real window** — for vLLM, the `--max-model-len` value (e.g. `32768`). The per-request output cap and the compaction threshold both derive from this window automatically: requests clamp `max_tokens` to what the window still fits, and compaction fires before the window overflows, so no hand-tuned `max_tokens` is needed. Left unset, the per-request output clamp is off and compaction assumes a 128000 window, so a smaller real window will reject requests.
+## Detect a custom model's protocol
-## Protocol detection for custom models
+Models in **Custom** and in groups you created speak one of AgentHub's generic protocols, and the dialog can find out which one a base URL serves. A new custom model starts with no protocol selected: the suffix at the right edge of the base URL field reads **Select protocol**.
-Custom and user-defined groups speak AgentHub's generic protocol clients, and the Web dialog detects which one a base URL serves. A new custom model starts with **no protocol selected**: the suffix at the right edge of the base URL field reads "Select protocol" rather than a path, and no row in its menu is checked. **Detect** sits at the top-right of that field, next to its label, and is always available — no API key is needed to press it. Pressing it has the server probe the URL with three cheap requests in fixed order — `openai-responses` (`POST {base}/responses`, OpenAI Responses API) first, then `ant-messages` (`POST {base}/v1/messages`, Anthropic Messages API), then `openai-chat` (`POST {base}/chat/completions`) — and the first protocol the endpoint actually serves is applied to the entry's `client_type`, confirmed by a toast naming what was found. Nothing about a result is written into the form itself — where the protocol ended up is visible in the suffix, which is what actually holds it.
+To detect the protocol, select **Detect** at the top-right of the base URL field. It is always available, and no API key is needed. The server probes the URL with three cheap requests, in this order, and applies the first protocol the endpoint serves:
-Detection tolerates the ways a base URL is usually mistyped: one `/v1` too many (`https://host/v1/v1`), one too few (`https://host` for an API served under `https://host/v1`), or a whole endpoint URL pasted from a provider's documentation (`/chat/completions`, `/responses`, `/messages`). It probes the normalized base first, then its neighbouring form — the trailing `/v1` removed when it has one, added when it has not — taking the three protocols in the usual order for each (six short probes at most), and the base URL field is rewritten to the form that actually answered, so what you save is the URL the protocol is really served at.
+1. `openai-responses`: `POST {base}/responses` (OpenAI Responses API)
+2. `ant-messages`: `POST {base}/v1/messages` (Anthropic Messages API)
+3. `openai-chat`: `POST {base}/chat/completions`
-Saving is the backstop: confirm the dialog while the protocol is still unset and detection runs first, then the save continues with what it found (the button reads "Detecting…" for the round-trip). A hit there is not announced — the save you asked for simply proceeds. If the probe finds nothing the model is **not** saved: the failure pops up and the dialog stays open, so you can pick a protocol by hand or correct the URL. This matters because AgentHub resolves an unmatched client type by raising, not by defaulting: an entry persisted with no protocol would be a model that cannot start.
+A message names the protocol found, for example "Detected {name}; applied". The result lives only in the suffix, which shows the protocol path.
-Probes are minimal invalid requests (`{}` bodies): they cost no tokens and need no valid model id — an error in the protocol's own shape already proves the route exists, while a `404`/`405` means the path isn't served and HTML or gateway junk counts for nothing. The probed URLs and auth headers are exactly what the AgentHub client would use after saving (`Authorization: Bearer` for the OpenAI protocols; `x-api-key` plus `Authorization: Bearer` and `anthropic-version` for `ant-messages`), so a detected protocol is one that will really work.
+Detection tolerates common base URL mistakes:
-The probe credential is resolved server-side in three layers: the API key typed in the dialog, else the key already stored for this entry, else the environment variable belonging to the protocol **that probe** speaks — `ANTHROPIC_API_KEY` for `ant-messages`, `OPENAI_API_KEY` for the two OpenAI protocols, the same variables the saved model would read. Resolution happens per probe precisely because the protocol is the thing being determined. None of these values are ever sent to the browser or echoed in the response. Detection still works with no credential anywhere — a protocol-shaped `401` identifies the route perfectly well — but an authenticated probe is far likelier to draw that protocol-shaped answer than the generic `401` or gateway HTML an anonymous request often gets.
+- one `/v1` too many (`https://host/v1/v1`);
+- one too few (`https://host` for an API served under `https://host/v1`);
+- a whole endpoint URL pasted from a provider's documentation (`/chat/completions`, `/responses`, `/messages`).
-The manual override is the protocol path shown inside the right edge of the base URL field (`/responses`, `/v1/messages`, `/chat/completions`) — the path the client appends to your URL, which is one-to-one with the protocol. Clicking it opens a menu of the three protocols with the path each one appends, and picking one wins over detection — so an endpoint you already know the protocol of never has to be probed at all. Whenever detection fails — unreachable, timed out, non-API answers, or none of the three paths served — the suffix turns amber and one toast says the same thing: the protocol could not be detected, check the API key and the base URL. The per-protocol probe outcomes are still reported by the endpoint for debugging. Entries from before this feature keep `client_type = "openai"` — still an alias of `openai-chat` — and are only rewritten when you pick a protocol or a detection run applies. Detection is exposed as `POST /api/projects/:id/models/detect` (owner only, see [Server API](/server-api)).
+It probes the cleaned-up base first, then its neighbouring form: the trailing `/v1` is removed if the URL has one, added if it does not. Each form is tried against the three protocols in order, six short probes at most. The base URL field is then rewritten to the form that answered: "Detected {protocol}; base URL normalized to {url}".
-Nothing is inferred from the model id in these groups. Typing `claude-sonnet-5` into a custom group does not imply the Anthropic client or its `ANTHROPIC_*` key — custom and user-defined groups always fall back to the compatible client (`openai-chat`), and that is what the API-key hint reflects. Detection is an accuracy improvement on top, never a gate: if it comes back empty the model still saves, on `openai-chat`, with a toast saying so. Vendor and gateway groups are unaffected — their ids are catalog-known, so they keep routing by id or by their preset pin.
+To set the protocol by hand, select the suffix. The menu lists **OpenAI Responses** (`/responses`), **Anthropic Messages** (`/v1/messages`), and **OpenAI Chat Completions** (`/chat/completions`), each with the path the client appends to your URL. A protocol you pick wins over detection, so an endpoint whose protocol you know never has to be probed.
-The add-group dialog offers two modes under the name field. **Create only** is the light path: a valid name hands off to that group's add-model dialog. **Import models** fills the brand-new group from its endpoint, in the add-model dialog's field rhythm — API key first, then the base URL with **Detect** at its top-right and the in-field protocol picker as manual override. Once a protocol is determined (detected or picked), **Import all models** appears: it asks the endpoint for every model id it serves (`POST /api/projects/:id/models/list`, owner only — AgentHub's `listModels()` on that protocol client, bounded at 20s) and saves them all as entries of the new group in one table write — base URL, protocol, and the typed key inline on each — in the endpoint's own order. An id the config cannot hold (empty, over 200 characters, or carrying control characters) or one already taken is skipped and counted in the toast, so a single bad entry never sinks the import. Only the id is taken from the endpoint: pricing, context window and display name stay empty, and an imported model claims no vision support until you probe it or switch it on — the same start a model added to the group by hand gets. An empty key follows the same per-protocol environment fallback as everywhere else. A failed detection turns the suffix amber and blocks nothing — pick the protocol by hand or switch back to create-only; listing failures (a protocol with no models endpoint, an empty listing) stay inside the dialog and persist nothing.
+If detection finds nothing, the suffix turns amber and a message says "Could not detect the protocol. Please check the API key and the base URL." This happens when the endpoint is unreachable, timed out, answered with something that is not an API, or serves none of the three paths. The endpoint still reports each probe's outcome for debugging.
-The header's **Create with AI** (owner only) covers what the import cannot read: a listing page that is not an OpenAI-compatible `/models` endpoint, a service described in words, or a vendor model to add to an existing group. The prompt goes to the Project's default agent with a fixed tail that has it use the `penguin-config` skill — one `penguin config model add --provider <group> --model-id <upstream id> --project-id <project> --root <data root>` per model (`--client-type openai --base-url <endpoint>` for OpenAI-compatible endpoints; the root is named because a command's environment does not carry it), a web page fetched first with the models you named picked (else the most popular, about ten at most), a missing API key asked for once or left empty for you to fill in on the Models page, `.project_config.toml` never touched, and `penguin config model list` at the end. The page reloads its table on every visit, so the new group is there when you come back from the conversation.
+Detection never blocks a save. If you select **Confirm** while the protocol is still unset, detection runs first and the button reads **Detecting…**. A hit is saved without a message. If nothing is found, the model is still saved, on OpenAI Chat Completions, with the message "Protocol not detected; saved as OpenAI Chat Completions".
-### Vision detection
+### How probing works
-"Supports vision" can be left off and asked of the model instead: **Detect** next to the switch sends one 1x1 PNG with a one-word prompt and turns the switch on if the model answers. A model that answers specifically that it will not take an image turns the switch off — that is a real answer, not an error — while a probe that fails on auth or the network leaves the switch exactly as you had it and shows the usual "check the API key and the base URL".
+- Probes are minimal invalid requests with `{}` bodies. They cost no Tokens and need no valid model id: an error in the protocol's own shape proves the route exists, a `404` or `405` means the path is not served, and HTML or gateway noise counts for nothing.
+- The probed URLs and auth headers are exactly what the AgentHub client uses after saving: `Authorization: Bearer` for the OpenAI protocols, and `x-api-key` plus `Authorization: Bearer` and `anthropic-version` for `ant-messages`. A detected protocol is one that will really work.
+- The server picks the probe credential in three steps: the API key typed in the dialog, else the key already stored for the entry, else the environment variable of the protocol that probe speaks (`ANTHROPIC_API_KEY` for `ant-messages`, `OPENAI_API_KEY` for the two OpenAI protocols). The choice is made per probe, because the protocol is what is being determined. None of these values reach the browser or the response.
+- Detection works with no credential at all, since a protocol-shaped `401` identifies the route. An authenticated probe is still far more likely to get that answer than the generic `401` or gateway HTML an anonymous request often gets.
+- Nothing is inferred from the model id in these groups. Typing `claude-sonnet-5` into a custom group does not select the Anthropic client or its `ANTHROPIC_*` key: custom groups fall back to `openai-chat`, and the API key hint follows that. Vendor and gateway groups are not affected; their ids are known to the catalog, so they route by id or by the group's preset.
+- Entries created before detection existed keep `client_type = "openai"`, which is still an alias of `openai-chat`. They are rewritten only when you pick a protocol or a detection applies. An older, non-standard protocol value is shown read-only: "Protocol: {t} (kept as configured; not editable)".
+- Detection is available as `POST /api/projects/:id/models/detect` (owner only); see [Server API](/server-api).
-Unlike protocol detection, **this probe is a real, billed completion**: an image request cannot be shaped to cost nothing the way the protocol probes are. It therefore runs only when you press the control, never on its own and never on save. The credential chain is the connectivity test's — the key typed in the dialog, else the stored one, else the protocol's environment variable, all resolved server-side. New custom models start with vision off; models added from a vendor or gateway group keep their catalog-known capability.
+## Detect vision support
+**Vision support** can stay off until you ask the model. Select **Detect** next to the switch: PenguinHarness sends the model one 1x1 PNG with a one-word prompt.
+
+- If the model answers, the switch turns on: "This model accepts images; vision turned on".
+- If the model says it does not take images, the switch turns off. That is a real answer, not an error.
+- If the probe fails on authentication or the network, the switch stays as it was, and the message asks you to check the API key and the base URL.
+
+> [!NOTE]
+> Unlike protocol detection, this probe is a real, billed request: an image request cannot be made free the way the protocol probes are. It runs only when you select **Detect**, never on its own and never on save.
+
+The credential comes from the same chain as the connection test: the key typed in the dialog, else the stored key, else the protocol's environment variable, all resolved on the server. **Vision support** appears only for models that are not in the built-in catalog; catalog models already declare whether they accept images.
+
+## Set API keys
+
+Each model carries its own API key, or none.
+
+- **One model.** In **Model settings**, enter the key in **API key**. Once saved, the key is shown masked; leave the field empty to keep it, or select **Clear stored API key** to remove it.
+- **A whole group.** On a group's header, select **Set key** and enter the key. It applies to every model in the group.
+- **No key.** A model without a key uses the provider's environment variable on the server; see [Built-in provider groups](#built-in-provider-groups). The card and the dialog show when a key is read from an environment variable.
+
+A key you type is stored in the hidden Project config file, which has mode 0600. The Web App always masks it.
+
+### Authorize a new API key
+
+A provider that supports automatic key authorization adds **Authorize key** to its group header. Two built-in groups do: TokenDance and Penguin Go. The key is written to every model in the group, replacing the key those models use now.
+
+1. On the group's header, select **Authorize key**.
+2. Select **Open authorization page**. The provider's authorization page opens in a new tab.
+3. Authorize there. The dialog, which shows "Waiting for the authorization to finish in the other tab…", reports the result on its own.
+
+TokenDance creates a **new** key on your account; it does not read a key you already have. The provider sends the browser back to PenguinHarness, which exchanges the one-time code and saves the key. If the page cannot redirect back, for example because the browser cannot reach the server at the address it was given, select **Page can't redirect back? Enter the code by hand**. The authorization page then shows a one-time code instead of redirecting.
+
+1. Paste the code into **Authorization code**.
+2. Select **Submit code**.
+
+Penguin Go differs in four ways:
+
+- The server polls Penguin Go for the result, so this group has no manual-code mode.
+- Once the group has a key, a **Sync** action sits on the header just before **Add model** and reads the platform's catalog again; see [The Penguin Go group](#the-penguin-go-group). **Authorize key** stays available, so you can switch to another platform account.
+- A key the platform reports as invalid or revoked reopens authorization on the **Models** page.
+- If writing the delivered key locally fails, the server keeps that one delivery for a short while, so the write can be retried without authorizing again.
+
+Keep in mind:
+
+- Only the Project owner can start an authorization. With TokenDance, only their own signed-in session can finish it, which in practice is the tab the dialog is open in. The redirect itself is received without a session, because the browser the provider sends back is not always the one you started in, but it only hands the code over: nothing is exchanged and no key is saved until the dialog asks for the result.
+- The whole exchange runs on the server. Neither TokenDance's PKCE verifier nor Penguin Go's device secret ever reaches the browser, and the new key goes straight into the model table without passing through it.
+- An authorization delivers one key and expires at the provider's own deadline, and never later than ten minutes.
+- TokenDance hands over the new key only once. If saving it fails, authorize again and delete the unused key in the provider's console.
+- A TokenDance key carries PenguinHarness's app URL from the [App attribution](#app-attribution) table, so calls made with it stay attributed even from another tool.
+
+## Set the default model
+
+New conversations use the Project's default model unless you pick another one. A new Project's default is `deepseek-flash` (DeepSeek V4.1 Flash), which reads images itself.
+
+1. Select the model's card to open **Model settings**.
+2. Select **Set as default model** and confirm.
+
+The first model added to a table without a default becomes the default automatically. Setting the default also saves any unsaved changes in the dialog.
+
+### Set the proxy vision model
+
+A model without vision cannot see images. When it reads an image with `read_file`, a proxy vision model describes the image for it. There is none by default.
+
+1. Open **Model settings** for a model with **Vision support** on.
+2. Select **Set as proxy vision model** and confirm.
+
+The proxy vision role is cleared when that model is deleted or its vision is turned off. For a model with `vision = false`, such as `deepseek-v4-pro`, the text-only member of the DeepSeek group, images from the conversation are saved to the Session scratchpad and handed over as a file path in the text. `read_file` passes an image to the proxy vision model for a description instead of returning it. See [Tools & Approval](/tools).
+
+## Test a connection
+
+In **Model settings**, select **Test connection** (owner only). The test uses what is in the dialog right now, including a key you typed, the base URL, the protocol, and the **Fast mode** switch, so problems show up before you save. The result reads "Connected ({ms} ms)" or "Failed: {msg}".
+
+### Measure speed
+
+To compare the models in a group:
+
+1. On the group's header, select **Speed test**.
+2. Select **Start**.
+
+PenguinHarness sends one real request to each model in turn, which uses a small amount of your API quota, and shows on each card:
+
+- the time to first token, in milliseconds: green under 1000, yellow up to 3000, red above;
+- the output rate, in Tokens per second: green at 40 or more, yellow at 15 or more, red below.
+
+Results stay only on the page and are gone after a reload.
+
+## Sync preset models
+
+PenguinHarness updates can change the built-in catalog of preset models. When they do, the Project owner sees:
+
+- a red dot on **Models** in the sidebar;
+- a notice on the page, "Changes detected: {added} new, {updated} to upgrade", with **Update now** and **Dismiss**;
+- a **Sync presets** button in the header.
+
+**Update now** lists the models it will touch; confirm with **Sync presets**. The **Sync presets** button in the header syncs right away, without the list.
+
+Syncing:
+
+- adds catalog models the Project does not have, retired rows excepted: one the Project already has is kept current, but a Project without it never gets it (see [Preset models](#preset-models));
+- resets each existing catalog model's vision flag, context window, protocol, prices, and base URL to the catalog's values;
+- fills in an empty display name, but never overwrites one;
+- never touches API keys, **Max output tokens**, fast mode, or models and groups you added yourself.
+
+**Dismiss** hides the notice until a later catalog change.
## Thinking levels
-For MiniMax M3, `none` maps directly to `reasoning.effort = "none"`.
+The thinking level sets how much the model reasons before it answers. There are six levels: `none | low | medium | high | xhigh | max`. Each agent has a default, `model.thinking_level` in `system_config.yaml` (see [Agent config](/configuration#agent-config)). A new agent starts at `medium`.
-DeepSeek V4 accepts `low`/`high`/`max` and folds `medium` and `xhigh` onto `high` server-side. AgentHub 0.4.4 aligned the client with that vocabulary, so on DeepSeek models `low` now sends `low` (it previously sent `high`) and `xhigh` now sends `high` (it previously sent `max`): a Session left on `low` reasons less — and costs less — than before, and one on `xhigh` reasons less deeply. Pick `max` to get DeepSeek's deepest effort.
+The pickers offer `low` and above. Many models cannot turn thinking off, but a stored `none` is still valid and still displays. Every level is labeled with the value it sends, so the label names exactly what goes on the request.
-Six levels: `none | low | medium | high | xhigh | max`, configured per Agent as `model.thinking_level` in `system_config.yaml`, default medium. The Web pickers offer `low` and above only (many models cannot disable thinking; `none` stays a valid stored value and still displays). Every level is labelled with the wire value it sends, so the label names exactly what goes on the request. `max` is the deepest tier: each client maps it onto the deepest effort its vendor accepts and degrades silently where there is no such tier, so picking it never fails — on Gemini and MiniMax M3 it lands on the same effort as `xhigh`. The chat draft view offers a quick picker next to the model selector: a picked level is written back to the selected Agent's setting immediately (the switched-to level becomes that Agent's new default and applies from the next session). Inside an active session the thinking level is a **per-turn parameter**: the composer's picker lists only the levels and starts out showing the Agent config's level — while the user hasn't picked one it auto-follows the config (sends omit the level, so config edits keep taking effect); once picked, the level sticks for that session and rides on every subsequent send (it applies to that session's subsequent Tasks only and never writes back to the Agent config). See [Configuration](/configuration).
+- `max` is the deepest tier. Each client maps it to the deepest effort its vendor accepts and falls back silently where there is no such tier, so picking it never fails. On Gemini and MiniMax M3 it lands on the same effort as `xhigh`.
+- For MiniMax M3, `none` maps directly to `reasoning.effort = "none"`.
+- DeepSeek V4 accepts `low`, `high` and `max`, and folds `medium` and `xhigh` into `high` on its side. Pick `max` for DeepSeek's deepest effort.
+
+### In a new chat
+
+The picker next to the model selector changes the selected agent's default right away. It applies from that agent's next conversation.
+
+### In a conversation
+
+The picker shows the level this conversation uses, which starts as the agent's default.
+
+- A level you pick is saved on the conversation and applies from the model's next request. It never changes the agent's default.
+- Changing the level mid-conversation invalidates the model's cached context, which raises cost.
+- If the conversation has history, a **Switch thinking level** dialog offers **Compact, then switch**, which is cheaper, or **Switch anyway**. Compacting first is not available while the conversation is still working.
+
+To change an agent's default in its settings, see [Runtime tab](/agents#runtime-tab).
## Fast mode
-Each model entry can opt into the provider's faster serving tier ("Fast mode" toggle in the Web model dialog, `--fast-mode` / `--no-fast-mode` on `penguin config model add`, `fast_mode = true` in the entry). Off by default; existing configs are unaffected. Switching it on asks for confirmation first, because it changes what the model costs.
+Fast mode sends a model's conversation requests to the provider's faster serving tier, at premium prices. It is off by default, and existing configs are not affected.
+
+Turn fast mode on or off per model in one of three ways:
-When enabled, session requests carry AgentHub's `fast_mode` flag: OpenAI-protocol clients send `service_tier: "priority"`, Anthropic-protocol clients send `speed: "fast"` with the fast-mode beta header. Fast tiers are billed at the provider's premium price list (MiniMax charges 1.5x its standard rate; OpenAI and Anthropic publish separate premium rates), and the recorded per-token pricing does not adjust for it — costs shown for fast-mode usage are underestimated unless you raise the entry's price buckets.
+- The **Fast mode** switch in the model dialog
+- `--fast-mode` / `--no-fast-mode` on `penguin config model add`
+- `fast_mode = true` in the entry
+
+Turning it on asks for confirmation first, because it changes what the model costs. A model with fast mode on shows the **Fast** tag.
+
+With fast mode on, conversation requests carry AgentHub's `fast_mode` flag:
+
+- OpenAI-protocol clients send `service_tier: "priority"`.
+- Anthropic-protocol clients send `speed: "fast"` with the fast-mode beta header.
+
+Fast tiers are billed at the provider's premium prices: MiniMax charges 1.5x its standard rate, and OpenAI and Anthropic publish separate premium rates.
+
+> [!WARNING]
+> The recorded per-Token prices do not change, so costs shown for fast-mode usage are underestimated unless you raise the entry's prices.
### Which models offer it
-Whether a fast tier exists is decided by the AgentHub client a model routes to, not by the model entry, so the toggle appears only where that client actually sends the parameter:
+Whether a fast tier exists depends on the AgentHub client a model routes to, not on the model entry. The switch appears only where that client actually sends the parameter:
| Routed client | Fast mode |
| --- | --- |
@@ -177,27 +332,225 @@ Whether a fast tier exists is decided by the AgentHub client a model routes to,
| Gemini, GLM, Kimi, DeepSeek, OpenAI embeddings | rejected — no toggle |
| Claude on Bedrock, or a Claude 4.6 id | rejected — no toggle |
-Routing follows the entry's `client_type`, or its `model_id` when none is set, so the same upstream id can land in different places: a Kimi model added under a gateway group (`client_type = "openai"`) can serve fast mode, while the same id routed to Kimi's own client cannot. A custom model behind your own base URL keeps the toggle — it speaks the OpenAI protocol and may well be OpenAI — but a third-party server is free to accept the parameter and serve the standard tier anyway.
+Routing follows the entry's `client_type`, or its `model_id` when none is set, so the same upstream id can land in different places. A Kimi model added under a gateway group (`client_type = "openai"`) can use fast mode, while the same id routed to Kimi's own client cannot. A custom model behind your own base URL keeps the switch: it speaks the OpenAI protocol and may well be OpenAI, but a third-party server is free to accept the parameter and serve the standard tier anyway.
+
+Two things the switch cannot check for you:
+
+- Anthropic's fast mode is a limited research preview. Until your organization is granted access, requests return a 429 rate-limit error. The confirmation says so for Anthropic-protocol models.
+- `CLIENT_TYPE` and `ANTHROPIC_BASE_URL` in the server's environment override the entry, and can route a model somewhere the switch did not anticipate.
+
+> [!NOTE]
+> If a request still reaches a client that rejects `fast_mode`, AgentHub refuses it before any network request. The conversation ends that turn immediately with the provider's message and a pointer to the setting. A rejection that will always repeat is never retried.
+
+An entry that stores `fast_mode = true` on a model that cannot serve it keeps its switch in the dialog, marked unsupported, so you can always turn it off.
+
+The connection test sends the dialog's current fast-mode state, so **Test connection** shows a fast-mode rejection before you save. Background requests, such as Session title generation and `read_file`'s proxy vision reads, never use fast mode. Only the conversation's own requests do.
+
+## Connect a local or self-hosted endpoint
+
+A local inference server can join a Project in two ways.
+
+### Add the model to the vLLM group
+
+Add the model to the **vLLM** group. The protocol is fixed to `openai-chat-vllm-adapter`, and the group has no preset base URL, so set **Custom base URL** to your server.
+
+The group ships eight preset models at a price of 0:
+
+- `Qwen/Qwen3.8-Flash-Next`
+- `Qwen/Qwen3.8-27B`
+- `Qwen/Qwen3.6-35B-A3B`
+- `Qwen/Qwen3.5-0.8B`
+- `Qwen/Qwen3.5-9B`
+- `deepseek-ai/DeepSeek-V4-Pro`
+- `deepseek-ai/DeepSeek-V4-Flash`
+- `deepseek-ai/DeepSeek-V4-Flash-Vision-Exp`
+
+Their context windows are each model's native length: 262,144 for the Qwen models, 1,000,000 for the DeepSeek V4 models.
+
+### Add a custom entry
+
+Add a `custom` model with:
+
+- `client_type = "openai-chat"`
+- `base_url` pointing at the server, for example `http://127.0.0.1:8000/v1`
+- the served model name as `model_id`
+
+Protocol detection settles on `openai-chat` for such servers, and the base URL field's suffix menu selects it by hand.
+
+### Make a local server run smoothly
+
+Whichever way you add the model, check two settings:
+
+- **Enable tool calling on the server.** For vLLM, start the server with `--enable-auto-tool-choice` and the `--tool-call-parser` for your model, for example `hermes` for Qwen or `llama3_json` for Llama 3.x. Without them, tool calls arrive as plain text and the agent loop cannot run anything.
+- **Set the entry's `context_window` to the server's real window.** For vLLM, that is the `--max-model-len` value, for example `32768`.
+
+The per-request output limit and the compaction threshold both follow this window. Requests limit `max_tokens` to what the window still fits, and compaction runs before the window overflows, so you do not need to tune `max_tokens` by hand.
+
+> [!NOTE]
+> If the field is left unset, the per-request output limit is off and compaction assumes a 128000 window, so a server with a smaller real window rejects requests.
+
+## Built-in provider groups
+
+The table below lists the built-in groups and the environment variables their models fall back to when an entry has no key. The catalog source is `packages/core/src/state/model-catalog.ts`. Each group also has a `_BASE_URL` variant, for example `ANTHROPIC_BASE_URL`. The **Models** page lists the groups in this order, followed by the groups you create.
+
+| Provider | API key env var | Notes |
+| --- | --- | --- |
+| tokendance | `OPENAI_API_KEY` | The recommended group. OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates, several of them currently discounted |
+| penguin-go | `PENGUIN_GO_API_KEY` | Preset relay group, fixed base URL `https://token.penguin.ooo/api`; its header authorizes a key for you or takes one you set by hand. See [The Penguin Go group](#the-penguin-go-group) |
+| deepseek | `DEEPSEEK_API_KEY` | Group of the default model |
+| openrouter | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://openrouter.ai/api/v1` |
+| fireworks | `OPENAI_API_KEY` | Fireworks AI (OpenAI-compatible), preset base URL `https://api.fireworks.ai/inference/v1`; API model ids look like `accounts/fireworks/models/<slug>` |
+| google | `GEMINI_API_KEY` | |
+| openai | `OPENAI_API_KEY` | |
+| anthropic | `ANTHROPIC_API_KEY` | |
+| siliconflow | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://api.siliconflow.cn/v1` |
+| zhipu | `ZAI_API_KEY` | |
+| moonshot | `MOONSHOT_API_KEY` | |
+| minimax | `MINIMAX_API_KEY` | Direct MiniMax M3 Responses client (`client_type = "minimax-m3"`): `MiniMax-M3` with a 1,000,000-token context window and vision; preset base URL `https://api.minimax.io/v1`; accepts a Token Plan Subscription Key or pay-as-you-go API key |
+| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen pay-as-you-go (DashScope's OpenAI-compatible endpoint), preset base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`; resold third-party models keep vendor-prefixed ids (e.g. `kimi/kimi-k3`) |
+| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan subscription gateway, preset base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`; pricing from each model page's official list price (the preview model has only a quota-multiplier promo, no list price) |
+| vllm | `OPENAI_API_KEY` | Self-hosted vLLM servers: protocol fixed to `openai-chat-vllm-adapter`, no preset base URL, eight preset models priced at 0 (see [Connect a local or self-hosted endpoint](#connect-a-local-or-self-hosted-endpoint)) |
+| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint; ships one preset, Atria Dawn Preview (Anthropic Messages API at `api.atria-asi.ai`, credential from `ANTHROPIC_API_KEY` when the entry has none, 256K window, priced at $0 until the vendor publishes prices) |
+
+The gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan) go through AgentHub's generic OpenAI-protocol clients, so with blank credentials they read `OPENAI_API_KEY`, not a gateway-specific variable.
+
+- The OpenRouter group uses the Responses client (`client_type = "openai-responses"`) for its presets and for any model you add to it, because OpenRouter serves the Responses API at that same base URL for every model it resells.
+- The other gateway presets use the Chat Completions client (`client_type = "openai-chat"`).
+- Both clients read the same `OPENAI_*` variables, so the credential rules are identical either way.
+
+The direct MiniMax M3 client reads `MINIMAX_API_KEY`. The built-in MiniMax preset uses `https://api.minimax.io/v1`. `MINIMAX_BASE_URL` is read only for entries without their own `base_url`.
+
+### The Penguin Go group
+
+`penguin-go` is a built-in group like TokenDance: a relay behind the fixed base URL `https://token.penguin.ooo/api`. A new Project gets the group's catalog models right away; a Project created before the group adds them with **Sync presets**.
+
+The group's key comes from its header; see [Authorize a new API key](#authorize-a-new-api-key). Authorization, and the **Sync** action that follows it, also read the platform's own model catalog:
+
+- Models the platform offers and the Project does not have are added, with their protocol, endpoint, display name, context window, vision flag and list price. Pure embedding models are left out.
+- Models the Project already has keep their endpoint and everything else you configured. Only their three prices and their client protocol are refreshed, `max_tokens` stays unset so the agent's setting applies, and nothing is ever deleted.
+- The platform's promotions replace the ones stored for this group. As in every other group, `.project_config.toml` holds the list price and the promotion lives in the server's database; **Sync presets** never sets one, and each authorization or **Sync** replaces them. If that record is lost, usage is priced at the list price until the next one writes it back.
+
+The platform quotes peak rates in USD per million Tokens. The group's DeepSeek rows follow DeepSeek's current line-up, `deepseek-flash` and `deepseek-v4-pro`, and declare the same off-peak schedule as the direct DeepSeek group, so their cards and cost records use half price outside Beijing weekday 9:00–12:00 and 14:00–18:00.
+
+### Preset models
+
+The preset catalog includes, among others:
+
+- `deepseek-flash` / `deepseek-v4-pro`
+- `MiniMax-M3`
+- `gemini-3.8-flash`
+- `claude-opus-5` / `claude-opus-4-8` / `claude-sonnet-5`
+- `gpt-6-astra` / `gpt-5.6` / `gpt-5.5`
+- `glm-5.3` / `glm-5.3-flash`
+- `kimi-k3`
+- `qwen3.8-max` / `qwen3.8-flash`
+- `seed-2.1-pro` / `seed-2.1-turbo` / `seed-evolving`
+- `dots-3-note-preview` (free on TokenDance, 512K context)
+
+The list is not exhaustive.
+
+- **DeepSeek images.** `deepseek-flash` is V4.1 Flash and reads images; `deepseek-v4-pro` is the V4 Pro 0813 release and is text-only. To send an image, use `deepseek-flash`.
+- **Retired rows.** DeepSeek still accepts `deepseek-v4-flash` and `deepseek-v4-flash-vision-exp`, and serves both from V4.1 Flash. They are no longer presets, but the catalog keeps them, together with TokenDance's `deepseek-v4-flash-vision-exp`, as retired rows: a Project that still carries one keeps its display name, and **Sync presets** keeps its price current. A retired row is never added to a Project that does not have it, and a new Project never gets one.
+- **OpenAI twice.** The whole OpenAI line-up is listed twice: directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions).
+- **GLM-5.3 Flash five times.** It appears directly as `glm-5.3-flash`, under the same id on TokenDance, and as OpenRouter's `z-ai/glm-5.3-flash`, Fireworks AI's `accounts/fireworks/models/glm-5p3-flash` and Qwen pay-as-you-go's `ZHIPU/GLM-5.3-Flash`. Every row accepts images: AgentHub's GLM client forwards image parts for this one GLM id, every other GLM id refuses them, and the gateway rows go through the generic OpenAI-compatible clients, which carry images for any id. What the rows do not share is the price: each records what its own seller charges, so they disagree while a promotion runs.
+- **OpenRouter free tier.** The catalog carries the `:free` model variant `nvidia/nemotron-3-ultra-550b-a55b:free` and the `openrouter/free` unified Free Models Router. They cost nothing, but OpenRouter's free-tier rate limits and data policy apply.
+
+### Prices and promotions
+
+- **Three price buckets.** Each model records `cache_read`, `cache_write` and `output` prices in USD per million Tokens. The cost center bills usage against them.
+- **Base tier only.** Where a vendor's prices step up with input size, the catalog records the base tier. MiniMax M3 records MiniMax's standard pay-as-you-go tier at 512K input tokens or below; above that, every rate doubles, and the priority tier is 1.5x, so long-context and priority usage is underestimated. OpenAI (above 272K) and Gemini 3.1 Pro (above 200K) follow the same convention.
+- **DeepSeek off-peak.** The direct DeepSeek rows record the official peak prices and declare DeepSeek's off-peak schedule: outside Beijing time 9:00–12:00 and 14:00–18:00 on weekdays, every bucket is halved. The **Models** page shows a `50% off` tag during those hours, and the cost center bills at that rate.
+ - Four resold rows follow the same schedule because their sellers pass DeepSeek's windows through: TokenDance's `deepseek-v4.1-flash`, OpenRouter's `deepseek/deepseek-v4.1-flash`, and Penguin Go's `deepseek-flash` and `deepseek-v4-pro`.
+ - Qwen bills the DeepSeek models it resells on a schedule of its own, half price from 22:00 to 8:00 Beijing time every day. `deepseek-v4.1-flash` in both Qwen groups, and the Token Plan's `deepseek-v4-pro-0813`, declare that one instead, and the tag's tooltip names the windows of whichever schedule the row follows.
+ - The stored price is always the peak price, so what is on disk does not depend on the hour a Project was created or synced.
+- **Flat promotions.** Nine TokenDance models are discounted today:
+ - `kimi-k3` at 40% off
+ - `deepseek-v4-flash-0731`, `deepseek-v4-pro-0813`, `glm-5.3`, `glm-5.3-flash` and `qwen3.8-max` at 10%
+ - the three Doubao Seed rows (`seed-2.1-pro`, `seed-2.1-turbo`, `seed-evolving`) at 50%
+
+ Gemini 3.8 Flash, 3.7 Flash and 3.6 Flash are also 50% off, both in the google group and on OpenRouter (`google/gemini-3.8-flash`, `google/gemini-3.7-flash`, `google/gemini-3.6-flash`), because Google halves them through 2026-12-31. A Project is preset with the **list** price: the server keeps the promotion beside it, in its own database rather than in `.project_config.toml`, and takes it off when usage is priced, so the cost center charges what the seller charges. The model card shows the rate being billed right now as a tag, and the model dialog says **These are list prices. A running promotion takes N% off them; changing a price cancels it**.
+- **Your own prices.** Editing a row's price cancels its promotion and takes the discount tag off the card: the figure is then yours, not the seller's.
+
+## The per-Project model table
+
+Each Project's models are recorded in the hidden `.project_config.toml`. Maintain it through the **Models** page or the CLI (`penguin config model add / default / list`, see [CLI Reference](/cli)).
+
+> [!WARNING]
+> Do not edit `.project_config.toml` by hand.
+
+Each `ModelEntry` has these fields:
+
+| Field | Meaning |
+| --- | --- |
+| `provider` | Config group name; paired with `model_id` it forms the unique key |
+| `model_id` | Upstream request id |
+| `context_window` | Context window (tokens). Load-bearing, not just display: each request's effective output cap and the compaction threshold are derived from it, so requests never ask for more output than the window still fits. Unset (or implausibly small, under 4096): the output clamp turns off and compaction derives from an assumed 128000 — set the real value for models with smaller windows. The Web dialog writes 1,000,000 when a model that is not in the catalog leaves the field blank (a hand-added entry is a known model, not an unknown window); narrow it when the endpoint serves less. `penguin config model add` writes no default at all when `--context-window` is omitted |
+| `max_tokens` | Optional per-model output cap (max output tokens per request). When set it overrides the agent's `model.max_tokens`; unset inherits it. The cap is a ceiling, not the literal wire value: each request sends `min(max_tokens, context_window − estimated input − safety margin)`, so small-window models work without hand-tuning it. Omitting the field on a Web full-table save clears it |
+| `client_type` | Protocol hint (`openai-chat` for Chat Completions, `openai-responses` for the Responses API, `ant-messages` for Anthropic Messages, …); inferred by AgentHub from the model id when omitted. Custom endpoints use one of those three generic protocol clients, and the Web dialog can detect which one a base URL serves. The pre-0.4.2 spelling `openai` is a deprecated alias and is normalized to `openai-chat` when the config is read |
+| `display_name` | Display name |
+| `vision` | Whether image input is supported, default true |
+| `fast_mode` | Optional fast mode (off by default): opts the model's Session requests into the provider's faster serving tier at premium pricing. Only `true` is ever persisted — omitting the field on a Web full-table save clears it. Models without a fast tier reject requests carrying it (see [Fast mode](#fast-mode)) |
+| `pricing` | Three price buckets (unit `usd_per_mtok`, USD per million tokens): `cache_read` / `cache_write` / `output` |
+| `api_key` / `base_url` | Inlined credentials, both optional; when blank, AgentHub falls back to environment variables |
+
+The file also holds `default_model`, and optionally `vision_model`, the proxy vision model. File shape (illustrative):
+
+```toml
+default_model = { provider = "deepseek", model_id = "deepseek-flash" }
+vision_model = { provider = "google", model_id = "gemini-3.1-pro-preview" }
+
+[[models]]
+provider = "deepseek"
+model_id = "deepseek-flash"
+context_window = 1000000
+client_type = "deepseek-v4"
+base_url = "https://api.deepseek.com"
+
+[[models]]
+provider = "custom"
+model_id = "my-model"
+client_type = "openai-chat"
+base_url = "https://llm.example.com/v1"
+api_key = "sk-..."
+```
+
+## App attribution
+
+Some gateways read a request header that files a call under the app that made it, for their own app rankings, usage reports or routing.
+
+The catalog decides these headers by **endpoint host**, not by the entry's provider group. An entry filed under custom whose base URL points at such a gateway carries the same headers. Only the entry's own `base_url` counts: an endpoint supplied through `OPENAI_BASE_URL` is resolved inside AgentHub, is not visible on this side, and is therefore not attributed.
+
+| Endpoint | Header | Value |
+| --- | --- | --- |
+| `openrouter.ai` | `HTTP-Referer` | `https://penguin.ooo/` |
+| `openrouter.ai` | `X-OpenRouter-Title` | `PenguinHarness` |
+| `openrouter.ai` | `X-OpenRouter-Categories` | `cli-agent,personal-agent` |
+| `tokendance.space` | `X-App-URL` | `https://penguin.ooo/` |
+| `opencode.ai` | `x-opencode-session` | The Session id, sent only when a Session id is known |
+
+Every other endpoint, including every direct vendor and every gateway that reads no such header, receives no extra headers. The OpenRouter and TokenDance headers state the app's identity only. The OpenCode header names the conversation, because that gateway routes each conversation by it; no header carries anything about the user or the agent.
+
+## How it works
+
+### One gateway
-Two things the toggle cannot check for you:
+All model access goes through one gateway library, `@prismshadow/agenthub` (AutoLLMClient). The core defines only a thin `LLMInterface` (see [Interfaces](/interfaces)). Per-provider protocol adaptation happens inside AgentHub, so 1000+ online and local models are reachable, including any OpenAI-compatible endpoint. The protocol translation lives in `packages/core/src/llm/generative-model.ts`.
-- Anthropic's fast mode is a limited research preview: until your organization is granted access, requests return a 429 rate-limit error. The confirmation says so for Anthropic-protocol models.
-- `CLIENT_TYPE` and `ANTHROPIC_BASE_URL` in the server's environment override the entry, and can route a model somewhere the toggle did not anticipate.
+### Model identity
-If a request does reach a client that rejects `fast_mode`, AgentHub refuses it **before any network request**: the session ends that turn immediately with the provider's message plus a pointer to the setting, and a deterministic rejection is never retried. An entry that stores `fast_mode = true` on a model that cannot serve it keeps its toggle in the dialog, marked unsupported, so it can always be switched off.
+A model's identity is always the `(provider, model_id)` pair. `provider` is a config group name, and `model_id` is the upstream request id, sent to AgentHub unchanged. The two are independent fields, and joining them into one string is forbidden anywhere in the pipeline.
-The connectivity test sends the dialog's current toggle state, so "Test connection" surfaces a fast-mode rejection before saving. Background requests (session title generation, `read_file`'s vision-model proxy reads) never carry fast mode — only the session's own requests do.
+Every interface that names a model takes the complete pair: the CLI, the HTTP API and the SDK all reject half a reference instead of completing it. The provider is never inferred from the model id and has no default, because gateways resell vendor models under their upstream ids; a guessed group would send the entry's credential to a vendor nobody named.
-## Models decoupled from Agents
+Where a model reference is optional (`penguin run` / `chat`, Session creation, scheduled tasks), the choice is between the whole pair and nothing. Omit both halves to use the Project's default model.
-An Agent never binds a model: the model is chosen when a Session is created and stays locked for that Session; the same Agent can run different Sessions on different models. The in-session `/model` command changes models handoff-style: it opens a new session for the same Agent on the new model, keeping the current Workspace, whose first message carries a `[model_switch_from]` source block (the source session id and its Trace file path) — the history is not injected into the new context (some models require thinking payloads and `fidelity` on history replay, which cannot cross models); the model reads the Trace file itself when it needs it, and the source session stays untouched. The three `pricing` buckets feed the usage/cost center's per-Token accounting.
+### Models and agents
-Credential handling:
+An agent never binds a model. The model is chosen when a Session is created and stays fixed for that Session, so the same agent can run different Sessions on different models.
-- an inline `api_key` is stored in the hidden Project config file with mode 0600;
-- the Web UI masks it on display;
-- blank credentials fall back to the provider's environment variables.
+The in-session `/model` command switches models by handoff:
-## Connectivity test
+1. It opens a new Session for the same agent on the new model, in the current Workspace.
+2. The new Session's first message carries a `[model_switch_from]` block with the source Session's id and its Trace file path.
-The Web Models page offers a per-model connectivity test (owner only).
+The history is not injected into the new context. Some models require thinking payloads and `fidelity` when history is replayed, and these cannot cross models. The model reads the Trace file itself when it needs to, and the source Session stays untouched.
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 47fbe8f3..45ef7bfc 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -1,203 +1,556 @@
---
-title: 模型与 Provider
-description: 经 AgentHub 单一网关接入模型,以 (provider, model_id) 成对标识,Project 级模型表、凭证与思考等级配置。
+title: 模型与供应商
+description: 为 Project 添加模型,设置 API key 和默认模型,选择思考等级和快速模式。
---
-## 单一网关
+每个 Project 都有一张自己的模型表:里面是它的对话可以使用的模型,按供应商分组,并附有凭证、限制和价格。你在**模型库**页面管理这张表。Agent 不会绑定到任何模型;对话开始时才选定模型。
-所有模型访问都经由一个网关库:`@prismshadow/agenthub`(AutoLLMClient)。core 只定义一层很薄的 `LLMInterface`(见 [接口契约](/interfaces)),各 Provider 的协议适配全部由 AgentHub 完成,因此可以接入 1000+ 在线或本地模型,包括任意 OpenAI 兼容端点。协议翻译实现在 `packages/core/src/llm/generative-model.ts`。
+- 要了解页面布局,见[模型库页面](#模型库页面)。
+- 要添加模型,见[新增模型分组](#新增模型分组)、[添加模型](#添加模型)或[用 AI 创建模型分组](#用-ai-创建模型分组)。
+- 要为模型提供凭证,见[设置 API key](#设置-api-key)。
+- 要选择新对话使用的模型,见[设置默认模型](#设置默认模型)。
+- 要调整请求,见[思考等级](#思考等级)和[快速模式](#快速模式)。
+- 内置供应商的完整列表和文件格式,见[内置供应商分组](#内置供应商分组)和 [Project 模型表](#project-模型表)。
-## 模型标识
+## 模型库页面
-模型身份永远是 `(provider, model_id)` 成对表示:`provider` 是配置分组名,`model_id` 是原样发给上游的请求 id。二者是两个独立字段,任何环节都不允许拼接成一个字符串。
+在侧边栏选择**模型库**。模型按分组列出,每个供应商一个分组。
-所有涉及模型的接口都要求完整的二元组:CLI、HTTP API 与 SDK 都会拒绝半个引用,而不会替你补全。provider 绝不由模型 id 推断,也没有缺省值——网关会以上游 id 转售厂商模型,猜出来的分组会把该条目的凭据发往无人指定的厂商。凡是模型引用本身可省略之处(`penguin run` / `chat`、创建 Session、定时任务),可选的是整对:两半都省略即使用 Project 默认模型。
+- **分组**:内置分组按[内置供应商分组](#内置供应商分组)里的顺序排列;你创建的分组排在后面,按名称排序。没有模型的内置分组会隐藏;**Custom** 始终显示。**TokenDance** 分组带有**官方推荐**标签。
+- **展开和收起分组**:点击分组标题即可展开或收起。首次访问时只有 TokenDance 分组是展开的。浏览器会记住你展开过哪些分组,按 Project 分别记录。
+- **调整分组顺序**:拖动分组标题即可移动分组。顺序保存在当前浏览器里,按 Project 分别记录;对话中的模型选择器也用同样的顺序。触摸屏上或搜索时不能拖动。
+- **搜索**:在**搜索模型:id / 名称 / 厂商**里输入,就只显示匹配的模型。搜索期间,所有包含匹配模型的分组都会展开。
-## Project 模型表
-
-每个 Project 的可用模型记录在隐藏文件 `.project_config.toml` 中,由 CLI(`penguin config model add / default / list`,见 [CLI 参考](/cli))或 Web 界面维护,不手工编辑。`ModelEntry` 字段:
+每张模型卡片显示模型的显示名、标签、上下文窗口、价格、密钥状态,以及模型至今已使用的 Token 量。
-| 字段 | 说明 |
+| 标签 | 含义 |
| --- | --- |
-| `provider` | 配置分组名,与 `model_id` 成对构成唯一键 |
-| `model_id` | 上游请求 id |
-| `context_window` | 上下文窗口(Token 数)。不只用于展示:每次请求的实际输出上限与压缩阈值都由它推导,请求不会索要超出窗口剩余空间的输出。缺省(或小于 4096 的非常规值)时输出收敛关闭、压缩按 128000 假定推导——窗口更小的模型务必填真实值。Web 的模型弹窗在自定义 / 自建分组模型留空该字段时按 1000000 写入(手动新增的条目是已知模型,不是未知窗口),上游窗口更小时自行调低;`penguin config model add` 省略 `--context-window` 时不写入任何缺省值 |
-| `max_tokens` | 可选的按模型输出上限(单次请求最大输出 Token 数)。设置后覆盖 Agent 的 `model.max_tokens`,缺省沿用。该值是天花板而非逐字上线值:每次请求实际发送 `min(max_tokens, context_window − 估算输入 − 安全余量)`,小窗口模型无需手工调低。Web 整表保存时省略该字段即清除 |
-| `client_type` | 协议提示(`openai-chat` 对应 Chat Completions、`openai-responses` 对应 Responses API、`ant-messages` 对应 Anthropic Messages 等);缺省由 AgentHub 按 model id 推断。自定义端点使用这三种通用协议客户端之一,Web 对话框可按 base URL 检测其中哪一种。0.4.2 之前的旧写法 `openai` 为已废弃别名,读取配置时归一化为 `openai-chat` |
-| `display_name` | 显示名 |
-| `vision` | 是否支持图像输入,默认 true |
-| `fast_mode` | 可选的快速模式(默认关闭):让该模型的会话请求进入厂商的快速推理档位,按溢价计费。只会持久化 `true`——Web 整表保存时省略该字段即清除。没有 fast 档位的模型会拒绝携带该参数的请求(见 [快速模式](#快速模式)) |
-| `pricing` | 三档价格(单位 `usd_per_mtok`,USD 每百万 Token):`cache_read` / `cache_write` / `output` |
-| `api_key` / `base_url` | 内联凭证,可留空;留空时 AgentHub 回退读环境变量 |
+| **默认** | Project 的默认模型 |
+| **视觉** | 模型可以接收图片 |
+| **视觉代理** | 模型代替不支持视觉的模型读取图片 |
+| **快速** | 已开启快速模式 |
+| **免费** | 三项价格都是 0 |
+| **省 N%** | 当前有促销价或空闲时段价生效;见[价格与促销](#价格与促销) |
-新建 Project 的默认模型是 deepseek-flash(DeepSeek V4.1 Flash),它自己就能读图。另可配置一条 `vision_model`,作为 text-only 模型用 `read_file` 读图时的代读模型(见 [工具与审批](/tools));默认不配置。
+价格按每百万 Token 显示,顺序为缓存命中 / 缓存未命中 / 输出。币种在设置里**币种**下选择:**美元 $** 或 **人民币 ¥**,按固定汇率 7 换算。
-文件形态(示意):
+点击卡片即可打开**模型配置**。分组旁边的链接会打开供应商的密钥控制台(**前往密钥管理**)。模型弹窗里还有两个链接,分别打开供应商的模型列表(**获取模型 id**)和模型的主页(**模型主页**)。
-```toml
-default_model = { provider = "deepseek", model_id = "deepseek-flash" }
-vision_model = { provider = "google", model_id = "gemini-3.1-pro-preview" }
+只有 Project owner 能修改模型和凭证。成员可以搜索、展开和收起分组,在自己浏览器里调整顺序,也能以只读方式打开**模型配置**。
-[[models]]
-provider = "deepseek"
-model_id = "deepseek-flash"
-context_window = 1000000
-client_type = "deepseek-v4"
-base_url = "https://api.deepseek.com"
+## 新增模型分组
-[[models]]
-provider = "custom"
-model_id = "my-model"
-client_type = "openai-chat"
-base_url = "https://llm.example.com/v1"
-api_key = "sk-..."
-```
+你创建的分组和 **Custom** 分组一样:里面的模型使用某种通用协议,每个模型各带一个 base URL。
-对标注 `vision = false` 的模型(如 `deepseek-v4-pro`,即 DeepSeek 分组中的纯文本条目):对话输入中的图片会保存到 Session scratchpad,以文件路径形式拼入文本;`read_file` 读图时改为交给 `vision_model` 代读、不再返回图片。
+1. 在**模型库**页面,点击**手动创建**,或者点击最后一个分组下方的**新增分组**(+)。**新增分组**弹窗会打开。
+2. 在**分组名**里输入名称。名称要求:
+ - 以小写字母或数字开头;
+ - 只包含小写字母、数字、`-` 和 `_`;
+ - 长度最多 32 个字符;
+ - 不能与内置分组或已有分组重名。
+3. 选择**仅新增分组**或**导入模型**,然后按下面与你选择对应的小节操作。
-## 内置 Provider 分组
+### 创建空分组
-内置分组及其环境变量回退(目录源:`packages/core/src/state/model-catalog.ts`);每个分组同时存在 `_BASE_URL` 变体(如 `ANTHROPIC_BASE_URL`)。模型页默认按此顺序排列分组并展开第一个;拖动分组标题即可自行调整,该排列按 Project 保存,此后一直生效。
+1. 点击**仅新增分组**,再点击**确认**。这时会为新分组打开**添加模型**弹窗。
+2. 添加第一个模型,见[添加模型](#添加模型)。
-| Provider | API Key 环境变量 | 说明 |
-| --- | --- | --- |
-| tokendance | `OPENAI_API_KEY` | 官方推荐的厂商分组。OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为不带厂商前缀的裸 id(如 `glm-5.3`、`kimi-k3`);价格取该网关自己的 CNY 牌价,其中若干条目当前处于折扣中 |
-| penguin-go | `PENGUIN_GO_API_KEY` | 预置中转站分组,固定 base URL `https://token.penguin.ooo/api`;未授权时可自动获取密钥,授权后可同步平台新增模型,也可以手动统一设置 |
-| deepseek | `DEEPSEEK_API_KEY` | 默认模型所在分组 |
-| openrouter | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://openrouter.ai/api/v1` |
-| fireworks | `OPENAI_API_KEY` | Fireworks AI(OpenAI 兼容),预置 base URL `https://api.fireworks.ai/inference/v1`;API 模型 id 形如 `accounts/fireworks/models/<slug>` |
-| google | `GEMINI_API_KEY` | |
-| openai | `OPENAI_API_KEY` | |
-| anthropic | `ANTHROPIC_API_KEY` | |
-| siliconflow | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://api.siliconflow.cn/v1` |
-| zhipu | `ZAI_API_KEY` | |
-| moonshot | `MOONSHOT_API_KEY` | |
-| minimax | `MINIMAX_API_KEY` | 直连 MiniMax M3 Responses 客户端(`client_type = "minimax-m3"`):`MiniMax-M3` 支持 1,000,000 Token 上下文和视觉输入;预置 base URL `https://api.minimax.io/v1`;接受 Token Plan Subscription Key 或按量付费 API Key |
-| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen 按量付费(DashScope OpenAI 兼容端),预置 base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`;转售第三方模型保留厂商前缀 id(如 `kimi/kimi-k3`) |
-| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan 订阅网关,预置 base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`;定价取各模型页官方牌价(预览模型仅配额倍率促销、无牌价) |
-| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点;自带一条预置:Atria Dawn Preview(`api.atria-asi.ai` 的 Anthropic Messages API,条目未填 key 时读 `ANTHROPIC_API_KEY`,256K 窗口,厂商未公布价格前暂记 0) |
+保存第一个模型后,分组才会出现在列表里。
-网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)经 AgentHub 的通用 OpenAI 协议客户端请求,因此凭证留空时读取的是 `OPENAI_API_KEY`,而非网关自己的变量名。OpenRouter 分组整体使用 Responses 客户端(`client_type = "openai-responses"`)——预置条目与你自行添加进该分组的模型都是——因为 OpenRouter 为其转售的每一个模型都在同一 base URL 上提供 Responses API;其余网关预置则固定 Chat Completions 客户端(`client_type = "openai-chat"`)。两种客户端读取相同的 `OPENAI_*` 变量,凭证规则完全一致。直连 MiniMax M3 客户端读取 `MINIMAX_API_KEY`。内置 MiniMax 预设固定使用 `https://api.minimax.io/v1`;仅当模型条目未内联 `base_url` 时才读取 `MINIMAX_BASE_URL`。M3 价格取 MiniMax 按量付费的标准档、输入不超过 512K Token 的牌价;超过 512K 后各档价格翻倍,priority 档另为 1.5 倍,因此长上下文与 priority 用量会被低估——与 OpenAI(>272K)、Gemini 3.1 Pro(>200K)沿用的基准档口径一致。
+### 从端点导入模型
-预置目录还收录了 OpenRouter 的免费档:`:free` 模型变体 `nvidia/nemotron-3-ultra-550b-a55b:free` 与统一路由 `openrouter/free`(Free Models Router),零成本可用,但受 OpenRouter 免费档速率限制与数据政策约束。
+**导入模型**会把一个 OpenAI 兼容或 Anthropic 兼容端点列出的所有模型填进新分组。
-预置目录中的部分模型:deepseek-flash / deepseek-v4-pro(`deepseek-flash` 即 V4.1 Flash,支持图像输入;`deepseek-v4-pro` 是 V4 Pro 0813 版本,为纯文本。退役的 `deepseek-v4-flash` 与 `deepseek-v4-flash-vision-exp` 仍被 DeepSeek 接受、由 V4.1 Flash 承接。它们不再是预置条目,但目录把它们连同 TokenDance 的 `deepseek-v4-flash-vision-exp` 作为退役条目保留:仍带着这些模型的 Project 照旧显示其名称,「同步预置」会继续更新其价格、但不会把它们补进没有它们的 Project,行上存的是目录价时按空闲时段计价。要发图请用 `deepseek-flash`)、MiniMax-M3、gemini-3.8-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-6-astra / gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash、seed-2.1-pro / seed-2.1-turbo / seed-evolving、dots-3-note-preview(TokenDance 上免费,512K 上下文)等(非完整清单)。Penguin Go 分组的 DeepSeek 条目跟随 DeepSeek 当前的模型阵容,只收录 `deepseek-flash` 与 `deepseek-v4-pro`。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的条目记录官方高峰档,并声明其空闲时段规则:在北京时间周一至周五 9:00–12:00、14:00–18:00 之外,各档价格减半——模型页以「省 50%」徽标标记,成本中心按此计价。另有两条转售条目沿用同一套时段,因为卖家原样传递了 DeepSeek 自己的窗口:TokenDance 的 `deepseek-v4.1-flash` 与 OpenRouter 的 `deepseek/deepseek-v4.1-flash`。Qwen 转售的 DeepSeek 模型则按它自己的时段计费——北京时间每天 22:00 至次日 8:00 半价——因此两个 Qwen 分组的 `deepseek-v4.1-flash` 与 Token Plan 的 `deepseek-v4-pro-0813` 声明的是这一套,折扣徽标的悬停说明写的也是该条目所遵循时段的窗口。存盘的始终是高峰价,因此磁盘上的数字不会随 Project 创建或同步预置的时刻而变。GLM-5.3 Flash 收录了五份——直连的 `glm-5.3-flash`、TokenDance 分组的同名条目,以及 OpenRouter 的 `z-ai/glm-5.3-flash`、Fireworks AI 的 `accounts/fireworks/models/glm-5p3-flash` 与 Qwen 按量付费的 `ZHIPU/GLM-5.3-Flash`——每一条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而各网关条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。各条不一致的是价格:每一条都记录各自卖家的收费,因此促销期间彼此不同。
+1. 点击**导入模型**。
+2. 在 **API key** 里输入密钥。留空则使用协议的 `OPENAI_*` 或 `ANTHROPIC_*` 环境变量。
+3. 在**自定义 base URL** 里输入端点的 base URL。
+4. 点击字段右上角的**检测协议**,或者在字段最右侧的菜单里选择协议。见[检测自定义模型的协议](#检测自定义模型的协议)。
+5. 点击**批量导入模型**。PenguinHarness 会向端点请求模型列表,然后按端点返回的顺序把所有模型保存到新分组。
-TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折扣率。当前有九个模型处于折扣中——`kimi-k3` 六折,`deepseek-v4-flash-0731`、`deepseek-v4-pro-0813`、`glm-5.3`、`glm-5.3-flash` 与 `qwen3.8-max` 九折,三条 Doubao Seed 条目(`seed-2.1-pro`、`seed-2.1-turbo`、`seed-evolving`)五折。另有一条 `deepseek-v4.1-flash` 不走固定折扣,而是沿用上文所述 DeepSeek 自己的空闲时段规则。它们的模型卡片显示当前实际计费的那个价格,并以徽标标出折扣率。新建 Project 预置的是**牌价**:折扣率由服务端另行保存(存于 `web.db`,不写入 `.project_config.toml`),计算成本时再从牌价中扣除,因此成本中心按网关实际收费计价。自行修改条目的价格会取消其促销,也不再显示空闲时段折扣标记:此时那个数字属于你,而不是网关。
+每个导入的模型都会带上你填写的 base URL、协议和密钥。端点只提供模型 id:价格、上下文窗口和显示名都留空,视觉保持关闭,直到你检测或手动开启。这和手动添加的模型起点相同。
-## 应用归因
+有些 id 不会导入,结果里会说明跳过的数量:「已导入 {added} 个模型,跳过 {skipped} 个条目」。跳过的情形包括:id 为空、超过 200 个字符、包含控制字符,或者已被占用。
-部分网关会读取一个请求头,把调用归到发起它的应用名下,用于自己的应用榜单与用量报告。这类请求头由目录按**端点主机名**决定,与条目所在的 Provider 分组无关:一个填在 custom 分组、但 base URL 指向该网关的条目,同样会带上归因头。判断只看条目自己的 `base_url`——从 `OPENAI_BASE_URL` 读到的端点在 AgentHub 内部解析,这一侧看不到,因此不会归因。
+如果协议无法列出模型(「该协议不支持列出模型,请手动添加」),或者列表为空,什么都不会保存,弹窗保持打开。检测失败只会把协议后缀变成琥珀色;你仍然可以手动选择协议,或者改回**仅新增分组**。
-| 端点 | 请求头 | 取值 |
-| --- | --- | --- |
-| `openrouter.ai` | `HTTP-Referer` | `https://penguin.ooo/` |
-| `openrouter.ai` | `X-OpenRouter-Title` | `PenguinHarness` |
-| `openrouter.ai` | `X-OpenRouter-Categories` | `cli-agent,personal-agent` |
-| `tokendance.space` | `X-App-URL` | `https://penguin.ooo/` |
+列出模型走的是 `POST /api/projects/:id/models/list`(仅 owner 可用),它会以 20 秒为限,在该协议对应的客户端上调用 AgentHub 的 `listModels()`。
+
+### 删除分组
+
+1. 在你创建的分组标题上,点击**删除分组**。
+2. 确认删除。
+
+分组里的所有模型和对应的 API key 都会一并删除。内置分组无法删除。
+
+## 添加模型
+
+1. 在分组标题上,点击**添加模型**。
+2. 在**模型 ID** 里输入模型 id,必须与供应商 API 要求的完全一致,例如 `gpt-5.5`。**获取模型 id** 会打开供应商的模型列表。
+3. 可选:在**模型名称**里输入显示名。显示名为空时直接显示模型 id。
+4. 填写凭证和端点:
+ - **API key**:留空则使用供应商的环境变量。如果服务端设置了这个变量,输入框会显示变量名。
+ - **自定义 base URL**:在 **Custom** 分组和你创建的分组里必填。网关分组会自动填好。
+5. 可选:填写限制和价格:
+ - **上下文窗口**:模型的上下文窗口大小,单位是 Token。模型不在内置模型目录里时,留空会保存为 1000000。
+ - **最大输出长度**:每次请求最多输出的 Token 数。留空则使用 Agent 的设置;上下文较小的模型建议调低这个值。
+ - **缓存命中价格**、**缓存未命中价格**和**输出价格**:按每百万 Token 填写,用页面上显示的币种;存储时统一换算成美元。三项要么全填,要么全不填。
+6. 可选:如果模型能接收图片,打开**支持视觉**,或者点击**检测**;见[检测视觉支持](#检测视觉支持)。在 **Custom** 分组和你创建的分组里,新添加的模型默认关闭视觉;加到其他分组的模型默认开启视觉。
+7. 可选:打开**快速模式**;见[快速模式](#快速模式)。
+8. 点击**确认**。
+
+新模型使用哪种协议,取决于所在的分组:
+
+- **厂商分组**(DeepSeek、Google Gemini、OpenAI、Anthropic、Z.AI、Moonshot、MiniMax)只支持厂商自己的 API。如果模型 id 无法按这种方式路由,弹窗会警告你,并提供**转为自定义模型**。OpenAI 兼容的端点请放进 **Custom** 分组。
+- **OpenRouter** 总是使用 `openai-responses`,**vLLM** 总是使用 `openai-chat-vllm-adapter`。
+- **其他网关分组**使用 OpenAI Chat Completions。
+- **Custom** 和你创建的分组:在 base URL 字段里选择协议,或者检测协议。见[检测自定义模型的协议](#检测自定义模型的协议)。
+
+### 编辑或删除模型
+
+点击模型卡片,打开**模型配置**。修改字段,点击**确认**,再确认保存。在同一个弹窗里,你还可以**测试连通性**、**设为默认模型**、**设为视觉代理模型**或**删除模型**。
+
+修改**模型 ID** 或**分组**会重命名这条记录;凭证以及默认模型、视觉代理的角色都会跟着迁移。**删除模型**会删除模型的配置和 API key。
+
+## 用 AI 创建模型分组
-其余端点(所有直连厂商,以及不读归因头的网关)不会收到任何额外请求头。归因头只声明应用身份,不携带用户、Agent 或会话信息。
+**用 AI 创建**用来处理导入读不了的情况:模型列表页面不是 OpenAI 兼容的 `/models` 端点、只有文字描述的服务,或者要把厂商模型加进已有分组。
-## Penguin Go 预置分组
+> [!TIP]
+> 如果 OpenAI 兼容端点能自己列出模型,**新增分组**弹窗里的**导入模型**更快。
-`penguin-go` 与 TokenDance 一样是内置模型分组。新建 Project 会直接带上该分组在目录中的模型;已有 Project 通过模型页的「同步预置」补入。内置条目提供指向 `https://token.penguin.ooo/api` 的稳定初始路由;授权或「同步」时返回的平台模型清单还可以把本地缺失的模型 id 连同协议、端点、显示名称、上下文窗口、视觉能力和平台价格一起补入。与其他内置分组一样,同步新增的模型不会设置由用户管理的 `max_tokens` 覆盖值,而是沿用 Agent 设置。对已有条目会刷新三档平台价格和客户端协议;端点及其他由 Project 管理的配置不被覆盖,条目也不会被删除;纯 Embedding 条目不加入。与其他分组一样,`.project_config.toml` 记录的是牌价;平台的固定促销折扣由服务端存入 `web.db`,计算成本时从牌价中扣除,并显示为模型卡片的折扣标识。这些折扣只来自平台:「同步预置」不会写入,每次授权或「同步」都会整体替换。折扣记录丢失时按牌价计价,直到下一次授权或「同步」写回。平台返回的是 USD 每百万 Token 的峰值价格。当前内置的 Penguin Go DeepSeek 条目声明了与 DeepSeek 直连分组相同的北京时间空闲时段规则,因此模型卡片和成本记录会在工作日 9:00–12:00、14:00–18:00 之外按半价计算。
+1. 在**模型库**页面,点击**用 AI 创建**。**让 AI 添加模型分组**弹窗会打开。
+2. 粘贴模型列表页面的地址,或者用文字描述这个服务,也可以在**试试这些示例**里挑一个示例。
+3. 点击**在新对话中编辑**。会打开一个新对话,使用 Project 的默认 Agent,并已填好 Prompt。
+4. 发送 Prompt。
-分组尚未配置平台 Key 时,「自动获取密钥」会在用户点击授权后创建一次性请求,并在新标签页打开 Penguin Go 授权页,由本地服务端完成轮询。浏览器只拿到授权 URL 和本地 flow id;设备密钥与交付的 API Key 都留在服务端。授权成功后会校验 `connection.apiKey`、端点和模型清单:Key 写入该分组全部既有模型,平台新增模型则连同推荐协议、端点、名称、上下文窗口、视觉能力和牌价一起加入,已有平台模型的价格和客户端协议同步为平台返回值,随后用平台返回的折扣整体替换该分组的促销折扣。同步会保留既有端点和其他由 Project 管理的配置,也不会删除模型;账户和余额不保存也不展示。
+固定指令会让 Agent 使用 `penguin-config` Skill,并执行以下操作:
-配置过平台 Key 后,分组会在「添加模型」左侧显示独立的「同步」动作,「自动获取密钥」仍然保留,方便改用另一个平台账户的 Key。「同步」使用已保存的 Key 请求平台最新模型清单,并补充新增模型、刷新已有模型的平台元数据;模型清单没有产生变化时保持配置文件不变。若平台返回 Key 已失效或被撤销,模型页会自动重新打开授权流程。Penguin Go 的网页登录会话和 API Key 是两套状态:网页登录过期不会阻止有效 Key 继续同步,只有 Key 本身无效时才需要重新授权。
+- 每个模型运行一次 `penguin config model add --provider <group> --model-id <upstream id> --project-id <project> --root <data root>`;如果是 OpenAI 兼容端点,再加 `--client-type openai --base-url <endpoint>`。之所以要写明 data root,是因为命令的运行环境里不带这个信息;
+- 来源是网页时,先抓取网页,然后添加你点名的模型,或者最流行的模型,最多十个左右;
+- 缺少 API key 时只询问一次,或者留空,让你稍后在**模型库**页面填写;
+- 绝不读取或编辑 `.project_config.toml`;
+- 最后运行 `penguin config model list`。
-## 授权新建 API key
+**模型库**页面每次打开都会重新加载模型表,所以从对话回来时,新分组已经在页面上了。
-若某个供应商提供自动授权取 Key,模型页的该分组头部会多出一个动作:**自动获取密钥**。内置分组中 TokenDance 与 Penguin Go 都提供,成功后都会把新 Key 写入该分组下每一个模型,覆盖这些条目当前的 Key。Penguin Go 授权成功后还会显示独立的「同步」动作,用于增量获取平台后来开放的模型;原授权动作仍可用于更换账户。
+## 检测自定义模型的协议
-点击后会在新标签页打开供应商的授权页,发起操作的模型页对话框会等待并报告结果。TokenDance 使用 PKCE 回调与兑换;Penguin Go 使用设备授权的 start / poll 接口。协议差异只存在于服务端,前端交互与写入分组 Key 的结果一致。
+**Custom** 分组和你自己创建的分组里的模型,使用的都是 AgentHub 的某一种通用协议,弹窗可以检测出一个 base URL 到底支持哪一种。新建的自定义模型一开始没有选择协议:base URL 输入框右端的后缀显示为**选择协议**。
-整个过程都在服务端进行:PKCE verifier 或设备密钥从不进入浏览器,新建出的 Key 直接写入模型表。一次授权只能交付一个 Key,并按供应商返回的截止时间过期;PenguinHarness 本地流程最长保留十分钟。
+要检测协议,点击 base URL 输入框右上角的**检测协议**。这个按钮始终可用,也不需要 API key。服务端会按下面的顺序向 URL 发出三个轻量请求,并采用端点支持的第一个协议:
-TokenDance 在跳转回不来时支持手动填写一次性授权码;Penguin Go 由模型页轮询平台状态,不需要也不提供手动授权码入口。
+1. `openai-responses`:`POST {base}/responses`(OpenAI Responses API)
+2. `ant-messages`:`POST {base}/v1/messages`(Anthropic Messages API)
+3. `openai-chat`:`POST {base}/chat/completions`
-只有 Project owner 能发起授权。完整 Key 不会回传 Web 前端;若 Penguin Go 的本地写入失败,服务端会短暂保留这次单次交付,允许直接重试写入而不再次授权。
+检测到协议时会出现一条消息,例如「检测到 {name} 协议,已应用」。检测结果只体现在后缀里,后缀显示的就是协议路径。
-## 本地 / 自建 OpenAI 兼容端点(如 vLLM)
+检测能容忍常见的 base URL 错误:
-本地推理服务就是一条 `custom` 条目:`client_type = "openai-chat"`、`base_url` 指向服务地址(如 `http://127.0.0.1:8000/v1`)、`model_id` 填服务端的模型名(下文的协议检测对这类服务同样会落到该协议,也可直接用 base URL 输入框右端的后缀菜单手动选它)。两处设置决定运行是否顺畅:
+- 多写了一个 `/v1`(`https://host/v1/v1`);
+- 少写了一个 `/v1`(API 实际在 `https://host/v1` 下,却只填了 `https://host`);
+- 直接粘贴了供应商文档里的完整端点 URL(`/chat/completions`、`/responses`、`/messages`)。
-- **服务端要开启工具调用。** vLLM 需以 `--enable-auto-tool-choice` 启动,并按模型选择对应的 `--tool-call-parser`(如 Qwen 用 `hermes`、Llama 3.x 用 `llama3_json`);不开启时工具调用会以纯文本返回,Agent 循环无法执行任何工具。
-- **条目的 `context_window` 填服务端的真实窗口**——vLLM 即 `--max-model-len` 的值(如 `32768`)。每次请求的输出上限与压缩阈值都会由该窗口自动推导:请求把 `max_tokens` 收敛到窗口剩余空间以内,压缩也会在撞上窗口硬限制之前触发,无需手工调低 `max_tokens`。不填时不做逐请求输出收敛、压缩按 128000 假定,真实窗口更小会导致请求被拒。
+检测会先探测清理后的 base,再探测它的相邻形式:URL 末尾有 `/v1` 就去掉,没有就加上。每种形式依次尝试三种协议,最多发出六个短探测。base URL 输入框随后会改写为应答的那个形式,并提示「已检测为 {protocol},base URL 已整理为 {url}」。
-## 自定义模型的协议检测
+要手动设置协议,点击这个后缀。菜单里列出 **OpenAI Responses**(`/responses`)、**Anthropic Messages**(`/v1/messages`)和 **OpenAI Chat Completions**(`/chat/completions`),每一项都标注了客户端会追加到你 URL 末尾的路径。手动选择的协议优先于检测,已经知道端点协议时,根本不必探测。
-Custom 与自建分组走 AgentHub 的通用协议客户端,Web 对话框会检测 base URL 实际提供的是哪一种。新建自定义模型时**默认不选择任何协议**:base URL 输入框右端的后缀显示「选择协议」而不是某条路径,其菜单中也没有任何一项被勾选。「检测协议」按钮位于该输入框右上角、与标签同一行,始终可点击——不需要先填 API Key。点击它,服务端按固定顺序向该 URL 发三个轻量探测请求——先 `openai-responses`(`POST {base}/responses`,OpenAI Responses API),再 `ant-messages`(`POST {base}/v1/messages`,Anthropic Messages API),最后 `openai-chat`(`POST {base}/chat/completions`)——第一个真正被端点提供的协议写入条目的 `client_type`,并以 toast 提示检测到的是哪一种。表单里不会留下任何结果文字——协议最终落在哪,看后缀即可,那才是真正承载它的地方。
+如果检测不出结果,后缀会变成琥珀色,并提示「无法检测接口协议,请检查 API Key 与 base URL。」原因可能是端点不可访问、请求超时、返回的内容不是 API,或者三个路径都不支持。端点仍会报告每次探测的结果,方便调试。
-检测容忍多写一个 `/v1`、少写一个 `/v1`、或整段端点 URL(`/chat/completions`、`/responses`、`/messages`)粘进来的情况:先按整理后的 base 探测,再试它的相邻形式(带 `/v1` 的去掉、不带的补上),每种都按原有协议顺序试(最多六次短探测),命中后把 base URL 字段改写成实际应答的那个形式。
+检测从不阻塞保存。协议还没确定时就点击**确认**,会先执行检测,按钮显示**检测中…**。检测到协议就直接保存,不再提示。检测不到时模型照样保存,协议定为 OpenAI Chat Completions,并提示「未检测到协议,已按 OpenAI Chat Completions 保存」。
-保存是兜底环节:若确认对话框时协议仍为空,会先自动检测,再带着检测结果继续保存(这段往返期间按钮显示「检测中…」)。此处检测成功不额外提示——你要的保存直接继续。若这次探测什么都没找到,模型**不会**被保存:toast 说明原因,对话框保持打开,你可以手动选协议或修正 URL。这一步是必要的:AgentHub 遇到无法匹配的 client type 会直接抛错而不是回退默认值,协议为空的条目就是一个根本起不来的模型。
+### 探测原理
-探测请求是刻意构造的最小非法请求(`{}` 请求体):不消耗 Token、不需要有效的模型 id——按协议自身形态返回的错误即证明路由存在;`404`/`405` 则说明该路径未提供,HTML 或网关杂讯一概不算数。探测的 URL 与鉴权头和保存后 AgentHub 客户端实际使用的完全一致(OpenAI 系协议用 `Authorization: Bearer`;`ant-messages` 同时带 `x-api-key`、`Authorization: Bearer` 与 `anthropic-version`),因此检测出的协议就是真正能跑通的协议。
+- 探测请求是请求体为 `{}` 的最小无效请求,不消耗 Token,也不需要有效的模型 id:返回的错误若符合协议自身的格式,就证明路由存在;返回 `404` 或 `405`,说明路径没有提供服务;HTML 或网关杂讯一律不算数。
+- 探测用的 URL 和认证头,与保存后 AgentHub 客户端实际使用的完全一致:OpenAI 系协议用 `Authorization: Bearer`,`ant-messages` 用 `x-api-key` 加 `Authorization: Bearer` 和 `anthropic-version`。所以检测出的协议一定真实可用。
+- 服务端按三步选取探测凭据:优先用弹窗里填写的 API key,其次用这个条目已保存的 key,最后用探测目标协议对应的环境变量(`ant-messages` 用 `ANTHROPIC_API_KEY`,两个 OpenAI 协议用 `OPENAI_API_KEY`)。每发一次探测都会重新选择,因为此刻要确定的就是协议。这些值不会传到浏览器,也不会出现在响应里。
+- 完全没有凭据也能检测,因为协议格式的 `401` 同样能识别路由。不过相比匿名请求经常得到的笼统 `401` 或网关 HTML,带凭据的探测得到这个明确答案的可能性大得多。
+- 在这些分组里,不会从模型 id 推断任何东西。在自定义分组里输入 `claude-sonnet-5`,不会因此选用 Anthropic 客户端或它的 `ANTHROPIC_*` key:自定义分组一律回退到 `openai-chat`,API key 提示也照此显示。供应商分组和网关分组不受影响;模型目录认识它们的 id,所以按 id 或按分组的预置来路由。
+- 在检测功能出现之前创建的条目,保留 `client_type = "openai"`,它至今仍是 `openai-chat` 的别名。只有手动选择协议、或某次检测生效时,才会改写这个值。旧的非标准协议值以只读方式显示:「协议:{t}(沿用原配置,不可修改)」。
+- 检测也可以通过 `POST /api/projects/:id/models/detect` 调用(仅 owner 可用),参见 [Server API](/server-api)。
-探测所用凭据在服务端按三层依次解析:对话框里填的 API Key,其次该条目已保存的密钥,最后是**当前这个探测**所用协议对应的环境变量——`ant-messages` 读 `ANTHROPIC_API_KEY`,两个 OpenAI 协议读 `OPENAI_API_KEY`,与保存后模型实际读取的是同一批变量。之所以逐个探测分别解析,正是因为协议本身还没确定。这些值都不会回传浏览器,也不会出现在响应里。完全没有凭据时检测同样可用——协议形态的 `401` 足以认出路由——但带上鉴权的探测,远比匿名请求更容易拿到那种协议形态的应答,而不是笼统的 `401` 或网关 HTML。
+## 检测视觉支持
-手动覆盖入口是 base URL 输入框右端内嵌的那段协议路径(`/responses`、`/v1/messages`、`/chat/completions`)——客户端会追加到你填的 URL 之后,与协议一一对应。点开它即列出三种协议及各自追加的路径,手动选择优先于检测结果——已经知道协议的端点根本不必探测。只要检测失败——连不上、超时、返回的不是 API 响应、三条路径都没提供——该后缀就转为琥珀色,并统一以 toast 提示同一句话:无法检测接口协议,请检查 API Key 与 base URL。逐个协议的探测结果仍由该接口返回,便于排查。此前创建的条目保留 `client_type = "openai"`(仍是 `openai-chat` 的别名),只有手动选择或检测生效时才会改写。检测能力以 `POST /api/projects/:id/models/detect` 暴露(仅 owner,见 [Server API](/server-api))。
+**支持视觉**开关可以一直关着,等你需要时再去问模型。点击开关旁的**检测**:PenguinHarness 会向模型发送一张 1x1 的 PNG,配一句只有一个词的提示。
-这些分组不会从 model id 推断任何东西。在自定义分组里填 `claude-sonnet-5` 不代表就走 Anthropic 客户端、读 `ANTHROPIC_*`——Custom 与自建分组一律回退到兼容客户端(`openai-chat`),API Key 提示也据此显示。检测只是锦上添花,不是关卡:若检测无结果,模型仍会按 `openai-chat` 保存,并以 toast 说明。厂商与网关分组不受影响——它们的 id 在内置目录里,仍按 id 路由或沿用预设。
+- 模型能回答,开关就打开:提示「该模型接受图片输入,已开启视觉」。
+- 模型表示自己不接受图片,开关就关闭。这是真实的回答,不是错误。
+- 探测因认证或网络问题失败时,开关保持原样,提示会请你检查 API key 和 base URL。
-「新增分组」对话框在分组名下方提供两种模式。**仅新增分组**是轻量路径:名称合法即进入该分组的新增模型对话框。**导入模型**按端点填满全新分组,沿用新增模型对话框的字段节奏——先填 API key,再填 base URL,其右上方是「检测协议」,输入框内嵌的协议菜单可手动改选。协议确定后(检测命中或手动选定)出现**「批量导入模型」**:向端点询问它服务的全部模型 id(`POST /api/projects/:id/models/list`,仅 owner——在该协议客户端上调用 AgentHub 的 `listModels()`,限时 20s),并在一次整表写入中把它们全部存为新分组的条目——base URL、协议与所填 key 内联在每条上——顺序保持端点返回的顺序。配置无法承载的 id(为空、超过 200 字符、含控制字符)以及已被占用的 id 会被跳过并计入 toast,因此单个坏条目不会让整次导入失败。端点那边只取 id:价格、上下文窗口与显示名一律留空;导入的模型在你探测或手动打开之前不声明视觉能力——与手动往该分组添加模型的起点完全一致。key 留空时沿用各处一致的按协议环境变量回退。检测失败只把后缀转为琥珀色、不阻塞任何操作——可手动选协议继续,或切回仅新增分组;列表失败(协议不支持列出模型、列表为空)只在对话框内呈现且不落盘。
+> [!NOTE]
+> 和协议检测不同,这一探测是真实、计费的请求:图片请求无法像协议探测那样做到免费。它只在你点击**检测**时执行,绝不会自动运行,也不会在保存时运行。
-页头的**用 AI 创建**(仅 owner)补上导入读不到的那些:模型列表页不是 OpenAI 兼容的 `/models` 端点、只能用文字描述的服务,或要加进既有分组的厂商模型。提示词发给 Project 的默认 Agent,固定尾巴要求它用 `penguin-config` 技能——每个模型执行一次 `penguin config model add --provider <分组> --model-id <上游 id> --project-id <Project> --root <数据根目录>`(OpenAI 兼容端点加 `--client-type openai --base-url <端点>`;数据根目录要写明,因为命令的环境里没有它),来源是网页时先抓取并优先加你点名的模型(否则取最常用的、至多十个左右),缺 API key 只问一次、不给则留空由你到模型库页补填,不读写 `.project_config.toml`,最后 `penguin config model list`。页面每次进入都重新加载模型表,从对话回来即能看到新分组。
+凭据来源和连通性测试是同一条链路:先用弹窗里填写的 key,其次用已保存的 key,最后用协议对应的环境变量,全部在服务端解析。**支持视觉**只对不在内置模型目录里的模型显示;目录里的模型本身就声明了是否接受图片。
-### 视觉能力检测
+## 设置 API key
-「支持视觉」可以先不开,交给模型自己回答:开关旁边的「检测」会发送一张 1x1 的 PNG 和一句一个词的提示,模型能正常作答就把开关打开。若模型明确回答不接受图片,则关闭开关——这是一个真实答案,不是错误;而因鉴权或网络失败的探测则什么都不改动,只显示那句「请检查 API Key 与 base URL」。
+每个模型都可以配自己的 API key,也可以不配。
-与协议检测不同,**这次探测是一次真实计费的补全**:图片请求无法像协议探测那样构造成零成本。因此它只在你主动点击时运行,不会自行触发,保存时也不会。凭据链与连通性测试一致——对话框里填的 Key,其次已保存的 Key,最后是该协议的环境变量,全部在服务端解析。新建的自定义模型默认关闭视觉;从厂商或网关分组添加的模型沿用内置目录已知的能力。
+- **单个模型。** 在**模型配置**里,把 key 填入 **API key**。保存后 key 会打码显示;输入框留空即保留原 key,点击**清除已存 API key** 可删除它。
+- **整个分组。** 在分组标题栏上点击**手动设置密钥**并输入 key,组内所有模型都会使用它。
+- **不配 key。** 没配 key 的模型使用服务端上供应商的环境变量;参见[内置供应商分组](#内置供应商分组)。key 来自环境变量时,卡片和弹窗都会显示这一点。
+你填写的 key 存在 Project 的隐藏配置文件里,文件权限为 0600。Web App 里它始终打码显示。
+
+### 授权获取新 API key
+
+支持自动授权取 key 的供应商,会在分组标题栏上加上**自动获取密钥**。内置分组里有两个提供了这个流程:TokenDance 和 Penguin Go。取得的 key 会写入分组里的每个模型,替换它们现在使用的 key。
+
+1. 在分组的标题栏上,点击**自动获取密钥**。
+2. 点击**打开授权页**。供应商的授权页会在新标签页中打开。
+3. 在授权页完成授权。弹窗显示「等待在新标签页中完成授权…」,并自动报告结果。
+
+TokenDance 会为你的账号创建一把**新** key,不会读取你已有的 key。供应商会把浏览器带回 PenguinHarness,由 PenguinHarness 用一次性授权码换取并保存 key。如果授权页跳不回来,比如浏览器无法访问重定向给出的服务器地址,点击**授权页跳不回来?改为手动填写授权码**。授权页随后不再重定向,改为直接显示一次性授权码。
+
+1. 把授权码粘贴进**授权码**输入框。
+2. 点击**提交授权码**。
+
+Penguin Go 有四处不同:
+
+- 结果由服务端向 Penguin Go 轮询获取,因此这个分组没有手动填写授权码的方式。
+- 分组有 key 之后,标题栏上**添加模型**之前会出现**同步**,用它再次读取平台的模型目录,见 [Penguin Go 分组](#penguin-go-分组)。**自动获取密钥**依然保留,可以换成另一个平台账号的 key。
+- 平台报告 key 失效或被吊销时,**模型库**页面会重新打开授权。
+- 取到的 key 写入本地失败时,服务端会把这一次交付短暂保留,可以直接重试写入,不必再次授权。
+
+注意事项:
+
+- 只有 Project owner 能发起授权。TokenDance 还要求由他本人已登录的会话完成授权,实际上就是打开着弹窗的那个标签页。重定向本身不要求会话就能接收,因为供应商带回的浏览器未必是你发起授权时用的那个;但它只交回授权码:在弹窗来取结果之前,不会发生任何换取,也不会保存任何 key。
+- 整个换取过程都在服务端完成。TokenDance 的 PKCE verifier 和 Penguin Go 的设备密钥都不会进入浏览器;新 key 直接写入模型表,同样不经过浏览器。
+- 一次授权只交付一把 key,有效期取供应商给出的截止时间,且不超过十分钟。
+- TokenDance 只交付一次新 key。如果保存失败,请重新授权,并到供应商的控制台删除没用上的那把 key。
+- TokenDance 的 key 携带[应用归因](#应用归因)表中 PenguinHarness 的应用 URL,所以即使用其他工具发起调用,用量也仍会归到 PenguinHarness 名下。
+
+## 设置默认模型
+
+新对话使用 Project 的默认模型,除非你选了别的。新建 Project 的默认模型是 `deepseek-flash`(DeepSeek V4.1 Flash),它自己就能读图。
+
+1. 点击模型的卡片,打开**模型配置**。
+2. 点击**设为默认模型**并确认。
+
+模型表还没有默认模型时,第一个添加进来的模型会自动成为默认模型。设置默认模型的同时,也会保存弹窗里未保存的修改。
+
+### 设置视觉代理模型
+
+没有视觉的模型看不到图片。它用 `read_file` 读图时,由视觉代理模型替它描述图片。默认没有视觉代理模型。
+
+1. 找一个开启**支持视觉**的模型,打开它的**模型配置**。
+2. 点击**设为视觉代理模型**并确认。
+
+删除这个模型或关闭它的视觉后,视觉代理角色随之取消。对于 `vision = false` 的模型,比如 DeepSeek 分组里纯文本的 `deepseek-v4-pro`,对话中的图片会存到 Session 暂存区,并在文本里以文件路径的形式交给模型。`read_file` 读到图片时,会把图片交给视觉代理模型描述,而不是直接返回。参见[工具与审批](/tools)。
+
+## 测试连通性
+
+在**模型配置**里点击**测试连通性**(仅 owner 可用)。测试用的是弹窗里当前的内容,包括你填写的 key、base URL、协议和**快速模式**开关,所以保存之前就能发现问题。结果显示为「连通正常({ms} ms)」或「连通失败:{msg}」。
+
+### 测速
+
+要比较一个分组里的模型:
+
+1. 在分组标题栏上点击**测速**。
+2. 点击**开始测速**。
+
+PenguinHarness 依次向每个模型发送一个真实请求,这会消耗少量 API 配额,然后在每张卡片上显示:
+
+- 首个 Token 的延迟,单位毫秒:低于 1000 显示绿色,1000 到 3000 显示黄色,3000 以上显示红色;
+- 输出速率,单位 Token/秒:40 及以上显示绿色,15 及以上显示黄色,15 以下显示红色。
+
+结果只留在当前页面,刷新后就消失。
+
+## 同步预置模型
+
+PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Project owner 会看到:
+
+- 侧边栏**模型库**上出现红点;
+- 页面上出现通知「检测到变更:{added} 个新增,{updated} 个可升级」,附带**现在升级**和**忽略**按钮;
+- 页头出现**同步预置**按钮。
+
+**现在升级**会列出将要改动的模型,再用**同步预置**确认。页头的**同步预置**按钮则立即同步,不显示列表。
+
+同步时会:
+
+- 添加 Project 还没有的目录模型,退役条目除外:Project 已有的退役条目照常更新,没有它的 Project 则不会被补上(见[预置模型](#预置模型));
+- 把已有目录模型的视觉标记、上下文窗口、协议、价格和 base URL 重置为目录里的值;
+- 模型名称为空时自动补全,但绝不覆盖已有名称;
+- 绝不动 API key、**最大输出长度**、快速模式,以及你自己添加的模型和分组。
+
+点击**忽略**后,通知会隐藏,直到目录再次变化才重新出现。
## 思考等级
-对于 MiniMax M3,`none` 会直接映射为 `reasoning.effort = "none"`。
+思考等级决定模型在回答前思考多少。共有六级:`none | low | medium | high | xhigh | max`。每个 Agent 都有默认等级,即 `system_config.yaml` 里的 `model.thinking_level`(参见 [Agent 配置](/configuration#agent-配置))。新建 Agent 的默认等级是 `medium`。
+
+等级选择器只提供 `low` 及以上。很多模型无法关闭思考,但已保存的 `none` 依然有效,也依然会显示。每个等级都标注它实际发送的值,标签上写的就是请求里发的内容。
+
+- `max` 是最深的档位。各客户端会把它映射到供应商支持的最深推理档位,没有这个档位时静默回退,所以选它不会失败。在 Gemini 和 MiniMax M3 上,它的档位和 `xhigh` 相同。
+- 对 MiniMax M3,`none` 直接映射为 `reasoning.effort = "none"`。
+- DeepSeek V4 接受 `low`、`high` 和 `max`,`medium` 和 `xhigh` 会在它那边归并为 `high`。要 DeepSeek 最深的推理,请选 `max`。
-DeepSeek V4 只接受 `low`/`high`/`max`,服务端会把 `medium` 与 `xhigh` 都折算成 `high`。AgentHub 0.4.4 让 client 与这套取值对齐,因此在 DeepSeek 模型上,`low` 现在发送 `low`(此前发送 `high`),`xhigh` 现在发送 `high`(此前发送 `max`):停在 `low` 的会话思考更浅、花费也更少,停在 `xhigh` 的会话思考深度有所下降。想要 DeepSeek 最深的思考档位,请选 `max`。
+### 在新对话中
-思考等级共六档:`none | low | medium | high | xhigh | max`,按 Agent 在 `system_config.yaml` 的 `model.thinking_level` 配置,默认 medium。Web 拾取器只提供 `low` 及以上档位(多数模型不支持关闭思考;`none` 仍是合法的已存值,能正常显示)。每个档位都以实际发送的取值标注,标签即请求上真正带的值。`max` 是最深的一档:各 client 会把它映射到对应厂商能接受的最深档位,厂商没有这一档时静默降级,因此选它不会失败——在 Gemini 与 MiniMax M3 上它与 `xhigh` 落到同一档。对话草稿页在模型选择器旁提供快捷拾取器:选定档位立即写回所选 Agent 的该项配置(切换后的档位即成为该 Agent 的新默认,自下一个 Session 生效)。进行中的会话里,思考等级是**逐轮参数**:输入区拾取器只列出各档位,初始即显示 Agent 配置的档位——用户未手动选择时自动跟随配置下发(请求不携带档位,配置的修改持续生效);选定某档后即固定为该会话的档位,随之后每次发送携带(仅作用于该会话的后续 Task,不写回 Agent 配置)。见 [配置参考](/configuration)。
+模型选择器旁边的等级选择器,会立即修改所选 Agent 的默认等级,从它的下一个对话开始生效。
+
+### 在对话中
+
+选择器显示当前对话使用的等级,初始值是 Agent 的默认等级。
+
+- 你选的等级会保存在这个对话上,从模型的下一次请求开始生效,从不改动 Agent 的默认等级。
+- 对话中途改等级,会让模型的缓存上下文失效,成本随之升高。
+- 如果对话已有历史记录,会弹出**切换思考等级**弹窗,提供**压缩后切换**(更便宜)或**仍要切换**两个选项。对话还在运行时,无法先压缩。
+
+要在 Agent 设置里修改默认等级,参见[运行参数标签页](/agents#运行参数标签页)。
## 快速模式
-每个模型条目都可以选择进入厂商的快速推理档位(Web 模型弹窗中的「快速模式」开关、`penguin config model add` 的 `--fast-mode` / `--no-fast-mode`,或条目里的 `fast_mode = true`)。默认关闭;既有配置不受影响。打开开关会先弹出确认提示,因为它会改变该模型的计费。
+快速模式会把模型的对话请求发往供应商更快速的服务层级,并按溢价计费。默认关闭,已有配置不受影响。
+
+有三种方式可以按模型开关快速模式:
+
+- 模型弹窗里的**快速模式**开关
+- `penguin config model add` 的 `--fast-mode` / `--no-fast-mode` 参数
+- 条目里的 `fast_mode = true`
-开启后,会话请求携带 AgentHub 的 `fast_mode` 参数:OpenAI 协议 client 发送 `service_tier: "priority"`,Anthropic 协议 client 发送 `speed: "fast"` 并附带 fast-mode beta 请求头。快速档位按厂商的溢价价目计费(MiniMax 为标准价的 1.5 倍,OpenAI 与 Anthropic 另有溢价价目表),而条目记录的按 Token 单价不会随之调整——不上调三档价格的话,快速模式用量的成本统计会偏低。
+开启前会先要求确认,因为这会改变模型的成本。开启快速模式的模型会显示**快速**标签。
-### 哪些模型会出现该开关
+开启快速模式后,对话请求会带上 AgentHub 的 `fast_mode` 标志:
-是否存在快速档位,由该模型路由到的 AgentHub client 决定,而不是由模型条目决定,因此开关只在该 client 确实会发送这个参数时才出现:
+- OpenAI 协议客户端发送 `service_tier: "priority"`。
+- Anthropic 协议客户端发送 `speed: "fast"`,并附带 fast-mode beta 请求头。
-| 路由到的 client | 快速模式 |
+快速层级按供应商的溢价价格计费:MiniMax 收标准费率的 1.5 倍,OpenAI 和 Anthropic 则各自公布单独的溢价费率。
+
+> [!WARNING]
+> 记录的每 Token 价格不会随之改变,所以除非你调高条目里的价格,快速模式用量显示的成本会偏低。
+
+### 哪些模型支持快速模式
+
+存不存在快速层级,取决于模型路由到的 AgentHub 客户端,而不是模型条目。只有客户端确实会发送这个参数时,开关才会出现:
+
+| 路由到的客户端 | 快速模式 |
| --- | --- |
-| OpenAI 协议(`openai_chat`、`openai_responses`、`gpt6`、`minimax_m3`) | 发送 `service_tier: "priority"` |
-| Anthropic 协议(`ant_messages`、`claude5`) | 发送 `speed: "fast"` 并附带 beta 请求头 |
-| Gemini、GLM、Kimi、DeepSeek、OpenAI embedding | 拒绝——不提供开关 |
-| Bedrock 上的 Claude,或 Claude 4.6 系列 id | 拒绝——不提供开关 |
+| OpenAI 协议(`openai_chat`、`openai_responses`、`gpt6`、`minimax_m3`) | 以 `service_tier: "priority"` 发送 |
+| Anthropic 协议(`ant_messages`、`claude5`) | 以 `speed: "fast"` 发送,外加 beta 请求头 |
+| Gemini、GLM、Kimi、DeepSeek、OpenAI embeddings | 拒绝,不显示开关 |
+| Bedrock 上的 Claude,或 Claude 4.6 id | 拒绝,不显示开关 |
+
+路由跟随条目的 `client_type`;没有设置时,按 `model_id` 判断,所以同一个上游 id 可能落到不同的客户端。添加在网关分组下的 Kimi 模型(`client_type = "openai"`)可以使用快速模式,同一个 id 路由到 Kimi 自己的客户端就不行。你自己 base URL 背后的 custom 模型会保留开关:它走 OpenAI 协议,背后很可能就是 OpenAI,但第三方服务器完全可以接受这个参数,然后照常按标准层级提供服务。
+
+开关无法替你确认两件事:
+
+- Anthropic 的快速模式目前是限量研究预览。在你的组织获得访问权限之前,请求会返回 429 限流错误。对 Anthropic 协议的模型,确认提示里会说明这一点。
+- 服务端环境变量里的 `CLIENT_TYPE` 和 `ANTHROPIC_BASE_URL` 会覆盖条目设置,可能把模型路由到开关没有预料到的地方。
+
+> [!NOTE]
+> 如果请求仍然落到拒绝 `fast_mode` 的客户端,AgentHub 会在发出任何网络请求之前直接拒绝。这一轮对话会立即结束,并给出供应商的消息和指向设置的提示。必定重复出现的拒绝不会重试。
+
+如果条目在不支持快速模式的模型上保存了 `fast_mode = true`,弹窗里的开关仍然保留,并标记为不支持,你随时可以关掉它。
+
+连通性测试会带上弹窗当前的快速模式状态,所以在保存之前,**测试连通性**就能显示快速模式的拒绝结果。后台请求(例如 Session 标题生成、`read_file` 的视觉代理读取)从不使用快速模式,只有对话本身的请求才会用。
+
+## 连接本地或自托管端点
+
+本地推理服务器可以通过两种方式加入 Project。
+
+### 把模型添加到 vLLM 分组
+
+把模型添加到 **vLLM** 分组。协议固定为 `openai-chat-vllm-adapter`,分组没有预置 base URL,所以要把**自定义 base URL** 设置为你的服务器地址。
+
+分组自带八个预置模型,价格均为 0:
+
+- `Qwen/Qwen3.8-Flash-Next`
+- `Qwen/Qwen3.8-27B`
+- `Qwen/Qwen3.6-35B-A3B`
+- `Qwen/Qwen3.5-0.8B`
+- `Qwen/Qwen3.5-9B`
+- `deepseek-ai/DeepSeek-V4-Pro`
+- `deepseek-ai/DeepSeek-V4-Flash`
+- `deepseek-ai/DeepSeek-V4-Flash-Vision-Exp`
+
+上下文窗口均为各模型的原生长度:Qwen 系列为 262,144,DeepSeek V4 系列为 1,000,000。
+
+### 添加 custom 条目
+
+添加一个 `custom` 模型,并设置:
+
+- `client_type = "openai-chat"`
+- `base_url` 指向服务器,例如 `http://127.0.0.1:8000/v1`
+- `model_id` 填服务器实际提供的模型名称
+
+对这类服务器,协议检测会判定为 `openai-chat`;也可以通过 base URL 字段的后缀菜单手动选定。
+
+### 让本地服务器顺畅运行
+
+无论用哪种方式添加模型,都要检查两项设置:
+
+- **在服务器上启用工具调用。** 对 vLLM,启动服务器时加上 `--enable-auto-tool-choice`,以及你的模型对应的 `--tool-call-parser`,例如 Qwen 用 `hermes`,Llama 3.x 用 `llama3_json`。缺少这些参数时,工具调用会以纯文本形式到达,Agent 循环无法执行任何操作。
+- **把条目的 `context_window` 设为服务器的真实窗口。** 对 vLLM 来说就是 `--max-model-len` 的值,例如 `32768`。
+
+单次请求的输出上限和压缩阈值都跟随这个窗口。请求会把 `max_tokens` 限制在窗口剩余空间内,压缩也会在窗口溢出之前运行,所以你不需要手动调整 `max_tokens`。
+
+> [!NOTE]
+> 如果这个字段留空,单次请求的输出上限不会生效,压缩会按 128000 的窗口计算,真实窗口更小的服务器会拒绝请求。
+
+## 内置供应商分组
+
+下表列出了各个内置分组,以及条目没有 key 时模型回退使用的环境变量。模型目录的源码位于 `packages/core/src/state/model-catalog.ts`。每个分组还有一个 `_BASE_URL` 变体,例如 `ANTHROPIC_BASE_URL`。**模型库**页面按这个顺序列出分组,你创建的分组排在后面。
+
+| 供应商 | API key 环境变量 | 说明 |
+| --- | --- | --- |
+| tokendance | `OPENAI_API_KEY` | 推荐分组。OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为裸名称,不带供应商前缀(如 `glm-5.3`、`kimi-k3`);价格采用网关自己的人民币费率,目前有几项在打折 |
+| penguin-go | `PENGUIN_GO_API_KEY` | 预置的中转分组,固定 base URL `https://token.penguin.ooo/api`;分组标题栏可以为你自动授权一把 key,也可以手动设置。见 [Penguin Go 分组](#penguin-go-分组) |
+| deepseek | `DEEPSEEK_API_KEY` | 默认模型所在的分组 |
+| openrouter | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://openrouter.ai/api/v1` |
+| fireworks | `OPENAI_API_KEY` | Fireworks AI(OpenAI 兼容),预置 base URL `https://api.fireworks.ai/inference/v1`;API 模型 id 形如 `accounts/fireworks/models/<slug>` |
+| google | `GEMINI_API_KEY` | |
+| openai | `OPENAI_API_KEY` | |
+| anthropic | `ANTHROPIC_API_KEY` | |
+| siliconflow | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://api.siliconflow.cn/v1` |
+| zhipu | `ZAI_API_KEY` | |
+| moonshot | `MOONSHOT_API_KEY` | |
+| minimax | `MINIMAX_API_KEY` | 直连 MiniMax M3 的 Responses 客户端(`client_type = "minimax-m3"`):`MiniMax-M3`,上下文窗口 1,000,000 Token,支持视觉;预置 base URL `https://api.minimax.io/v1`;接受 Token Plan 订阅密钥或按量付费 API key |
+| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen 按量付费(DashScope 的 OpenAI 兼容端点),预置 base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`;转售的第三方模型保留供应商前缀 id(如 `kimi/kimi-k3`) |
+| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan 订阅网关,预置 base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`;价格取自各模型页面的官方牌价(预览模型只有配额倍率优惠,没有牌价) |
+| vllm | `OPENAI_API_KEY` | 自托管 vLLM 服务器:协议固定为 `openai-chat-vllm-adapter`,无预置 base URL,八个预置模型价格均为 0(见[连接本地或自托管端点](#连接本地或自托管端点)) |
+| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点;自带一个预置模型 Atria Dawn Preview(Anthropic Messages API,地址 `api.atria-asi.ai`,条目没有凭据时使用 `ANTHROPIC_API_KEY`,上下文窗口 256K,供应商公布价格之前定价 $0) |
+
+网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)走的是 AgentHub 通用的 OpenAI 协议客户端,凭据留空时读取 `OPENAI_API_KEY`,而不是某个网关专属的变量。
+
+- OpenRouter 分组的预置模型,以及你添加到该分组的任何模型,都使用 Responses 客户端(`client_type = "openai-responses"`),因为 OpenRouter 在同一个 base URL 上为它转售的每一个模型提供 Responses API。
+- 其他网关的预置模型使用 Chat Completions 客户端(`client_type = "openai-chat"`)。
+- 两种客户端读取相同的 `OPENAI_*` 变量,所以无论哪种方式,凭据规则完全一致。
+
+直连 MiniMax M3 的客户端读取 `MINIMAX_API_KEY`。内置的 MiniMax 预置模型使用 `https://api.minimax.io/v1`。只有条目没有自己的 `base_url` 时,才会读取 `MINIMAX_BASE_URL`。
+
+### Penguin Go 分组
+
+`penguin-go` 和 TokenDance 一样是内置分组:一个中转服务,base URL 固定为 `https://token.penguin.ooo/api`。新建的 Project 立即带上这个分组的目录模型;在该分组之前创建的 Project,用**同步预置**把它们补上。
+
+分组的 key 从标题栏取得,见[授权获取新 API key](#授权获取新-api-key)。授权以及随后的**同步**还会读取平台自己的模型目录:
+
+- 平台提供而 Project 没有的模型会被添加进来,连同协议、端点、显示名、上下文窗口、视觉能力和牌价。纯向量(embedding)模型不收录。
+- Project 已有的模型保留自己的端点和你配置过的其他内容。只刷新三项价格和客户端协议,`max_tokens` 保持未设置,沿用 Agent 的设定;任何模型都不会被删除。
+- 平台的促销会替换这个分组已存的促销。和其他分组一样,`.project_config.toml` 里存的是牌价,促销存在服务端的数据库里;**同步预置**从不设置促销,每次授权或**同步**都会整体替换它们。这条记录丢失后,用量按牌价计价,直到下一次授权或同步把它写回来。
+
+平台报的是高峰档费率,单位是每百万 Token 多少美元。分组里的 DeepSeek 条目跟随 DeepSeek 当前的模型阵容,只有 `deepseek-flash` 和 `deepseek-v4-pro`,并声明与直连 DeepSeek 分组相同的空闲时段,因此在北京时间工作日 9:00–12:00、14:00–18:00 之外,卡片和成本记录都按半价计算。
+
+### 预置模型
+
+预置模型目录包含以下模型:
+
+- `deepseek-flash` / `deepseek-v4-pro`
+- `MiniMax-M3`
+- `gemini-3.8-flash`
+- `claude-opus-5` / `claude-opus-4-8` / `claude-sonnet-5`
+- `gpt-6-astra` / `gpt-5.6` / `gpt-5.5`
+- `glm-5.3` / `glm-5.3-flash`
+- `kimi-k3`
+- `qwen3.8-max` / `qwen3.8-flash`
+- `seed-2.1-pro` / `seed-2.1-turbo` / `seed-evolving`
+- `dots-3-note-preview`(TokenDance 上免费,512K 上下文)
+
+列表并未穷尽所有模型。
+
+- **DeepSeek 图像能力。** `deepseek-flash` 就是 V4.1 Flash,支持读图;`deepseek-v4-pro` 是 V4 Pro 0813 版本,仅支持文本。要发送图像,请使用 `deepseek-flash`。
+- **退役条目。** DeepSeek 仍然接受 `deepseek-v4-flash` 和 `deepseek-v4-flash-vision-exp`,并都由 V4.1 Flash 承接。它们不再是预置条目,但目录把它们连同 TokenDance 的 `deepseek-v4-flash-vision-exp` 作为退役条目保留:仍带着其中某条的 Project 照旧显示它的名称,**同步预置**也会继续更新它的价格。退役条目不会被补进没有它的 Project,新建的 Project 也不会拿到。
+- **OpenAI 出现两次。** OpenAI 全系模型出现了两遍:一次直连(用你自己的 OpenAI key,官方牌价),一次在 OpenRouter 上以 `openai/<id>` 形式(网关费率,随其当前促销活动浮动)。
+- **GLM-5.3 Flash 出现五次。** 分别是直连的 `glm-5.3-flash`、TokenDance 上的同名条目,以及 OpenRouter 的 `z-ai/glm-5.3-flash`、Fireworks AI 的 `accounts/fireworks/models/glm-5p3-flash` 和 Qwen 按量付费的 `ZHIPU/GLM-5.3-Flash`。每一条都接受图像:AgentHub 的 GLM 客户端只对这一个 GLM id 转发图像内容,其他所有 GLM id 都拒收图像;各网关条目走通用的 OpenAI 兼容客户端,对任何 id 都会携带图像。各条不一致的是价格:每条记录的都是自己卖家收取的价格,所以促销期间彼此不同。
+- **OpenRouter 免费档。** 目录收录了 `:free` 变体 `nvidia/nemotron-3-ultra-550b-a55b:free`,以及 `openrouter/free` 这个统一的免费模型路由(Free Models Router)。它们不花钱,但 OpenRouter 免费档的限流和数据政策仍然适用。
+
+### 价格与促销
+
+- **三类价格。** 每个模型都记录 `cache_read`、`cache_write` 和 `output` 三项价格,单位是每百万 Token 多少美元。成本中心按这些价格结算用量。
+- **仅记录基础档。** 供应商的价格随输入规模上调时,目录只记录基础档。MiniMax M3 记录的是 MiniMax 标准按量付费档在 512K 输入 Token 及以下的价格;超过后每项费率翻倍,priority 档为 1.5 倍,所以长上下文和 priority 用量的成本估算会偏低。OpenAI(272K 以上)和 Gemini 3.1 Pro(200K 以上)遵循同样的约定。
+- **DeepSeek 空闲时段。** 直连 DeepSeek 的条目记录官方高峰价格,并声明 DeepSeek 的空闲时段规则:工作日北京时间 9:00–12:00 和 14:00–18:00 以外的时段,三项价格全部减半。**模型库**页面在这些时段显示 `省 50%` 标签,成本中心也按这个费率计费。
+ - 四条转售条目遵循同样的时段,因为各自的卖家沿用了 DeepSeek 的时间窗口:TokenDance 的 `deepseek-v4.1-flash`、OpenRouter 的 `deepseek/deepseek-v4.1-flash`,以及 Penguin Go 的 `deepseek-flash` 和 `deepseek-v4-pro`。
+ - Qwen 转售的 DeepSeek 模型按它自己的时段计费:北京时间每天 22:00 至次日 8:00 半价。两个 Qwen 分组的 `deepseek-v4.1-flash` 和 Token Plan 的 `deepseek-v4-pro-0813` 声明的是这一套,折扣标签的悬停说明写的也是该条目所遵循时段的窗口。
+ - 存储的价格始终是高峰价格,所以磁盘上的数值与 Project 创建或同步的时间无关。
+- **固定折扣。** 目前有九个 TokenDance 模型在打折:
+ - `kimi-k3` 打 6 折
+ - `deepseek-v4-flash-0731`、`deepseek-v4-pro-0813`、`glm-5.3`、`glm-5.3-flash` 和 `qwen3.8-max` 打 9 折
+ - 三条 Doubao Seed 条目(`seed-2.1-pro`、`seed-2.1-turbo`、`seed-evolving`)打 5 折
+
+ Gemini 3.8 Flash、3.7 Flash 和 3.6 Flash 也打 5 折,google 分组和 OpenRouter 上(`google/gemini-3.8-flash`、`google/gemini-3.7-flash`、`google/gemini-3.6-flash`)都是如此,因为 Google 在 2026-12-31 之前对它们一律减半。Project 预置的是**牌价**:折扣率由服务端另行保存,存在它自己的数据库里,而不写入 `.project_config.toml`,计算成本时再从牌价中扣除,因此成本中心按卖家实际收取的价格计费。模型卡片用标签标出当前实际计费的费率,模型弹窗则写明**此处为牌价,当前促销在此基础上省 N%;修改价格会取消促销**。
+- **你自己的价格。** 修改条目的价格会取消它的促销,卡片上的折扣标签也随之消失:此后这个数字由你自己定,不再代表卖家。
+
+## Project 模型表
+
+每个 Project 的模型都记录在隐藏文件 `.project_config.toml` 里。通过**模型库**页面或 CLI(`penguin config model add / default / list`,参见 [CLI 参考](/cli))维护这个文件。
+
+> [!WARNING]
+> 不要手动编辑 `.project_config.toml`。
+
+每个 `ModelEntry` 包含以下字段:
+
+| 字段 | 含义 |
+| --- | --- |
+| `provider` | 配置分组名;与 `model_id` 一起构成唯一键 |
+| `model_id` | 上游请求 id |
+| `context_window` | 上下文窗口(Token)。不只是展示,而是实际参与运算:每个请求的有效输出上限和压缩阈值都由它推导,因此请求要求的输出永远不会超过窗口的剩余空间。未设置(或数值小得不合理,低于 4096)时,输出限制关闭,压缩按假定的 128000 计算;窗口较小的模型请填写真实值。在 Web 弹窗中,模型不在模型目录里且这个字段留空时,会写入 1,000,000(手动添加的条目按已知模型处理,而不是当作窗口未知);如果端点实际支持的窗口更小,就把它调小。`penguin config model add` 省略 `--context-window` 时不写任何默认值 |
+| `max_tokens` | 可选的单模型输出上限(每次请求最多输出的 Token 数)。设置后会覆盖 Agent 的 `model.max_tokens`;未设置就继承这个值。这个上限只是封顶值,不是实际发出的数值:每个请求实际发送 `min(max_tokens, context_window − estimated input − safety margin)`,所以小窗口模型不用手动调整也能正常工作。在 Web 端整表保存时省略这个字段会把它清空 |
+| `client_type` | 协议提示(`openai-chat` 对应 Chat Completions,`openai-responses` 对应 Responses API,`ant-messages` 对应 Anthropic Messages 等);省略时由 AgentHub 根据模型 id 推断。自定义端点使用这三种通用协议客户端之一,Web 弹窗可以检测一个 base URL 对应哪一种。`openai` 是 0.4.2 之前的旧写法,已弃用,读取配置时会归一化为 `openai-chat` |
+| `display_name` | 展示名称 |
+| `vision` | 是否支持图像输入,默认 true |
+| `fast_mode` | 可选的快速模式(默认关闭):开启后,这个模型的 Session 请求会改走供应商更快的服务层级,价格更高。持久化保存的值只有 `true`;在 Web 端整表保存时省略这个字段会把它清空。没有快速层级的模型会拒绝携带这个设置的请求(参见[快速模式](#快速模式)) |
+| `pricing` | 三档价格(单位 `usd_per_mtok`,即每百万 Token 的美元价格):`cache_read` / `cache_write` / `output` |
+| `api_key` / `base_url` | 内联的凭证,两项都可选;留空时 AgentHub 回退到环境变量 |
+
+文件里还保存着 `default_model`,以及可选的 `vision_model`,也就是视觉代理模型。文件结构(示例):
+
+```toml
+default_model = { provider = "deepseek", model_id = "deepseek-flash" }
+vision_model = { provider = "google", model_id = "gemini-3.1-pro-preview" }
+
+[[models]]
+provider = "deepseek"
+model_id = "deepseek-flash"
+context_window = 1000000
+client_type = "deepseek-v4"
+base_url = "https://api.deepseek.com"
+
+[[models]]
+provider = "custom"
+model_id = "my-model"
+client_type = "openai-chat"
+base_url = "https://llm.example.com/v1"
+api_key = "sk-..."
+```
+
+## 应用归因
+
+有些网关会读取一个请求头,把调用记到发起调用的应用名下,用于自己的应用排行、用量报告或路由。
+
+模型目录按**端点主机**决定这些请求头,而不是按条目所属的供应商分组。归在 custom 下的条目,只要 base URL 指向这类网关,就会带上同样的请求头。只看条目自己的 `base_url`:通过 `OPENAI_BASE_URL` 提供的端点在 AgentHub 内部解析,条目这一侧看不到,因此不会归因。
+
+| 端点 | 请求头 | 值 |
+| --- | --- | --- |
+| `openrouter.ai` | `HTTP-Referer` | `https://penguin.ooo/` |
+| `openrouter.ai` | `X-OpenRouter-Title` | `PenguinHarness` |
+| `openrouter.ai` | `X-OpenRouter-Categories` | `cli-agent,personal-agent` |
+| `tokendance.space` | `X-App-URL` | `https://penguin.ooo/` |
+| `opencode.ai` | `x-opencode-session` | Session id,仅在已知 Session id 时发送 |
+
+其他端点,包括所有直连厂商和不读取这类请求头的网关,都不会收到额外的请求头。OpenRouter 和 TokenDance 的请求头只表明应用身份。OpenCode 的请求头标明对话,因为那个网关靠它来路由每段对话;没有任何请求头携带用户或 Agent 的信息。
+
+## 工作原理
-路由按条目的 `client_type` 判定,未设置时按 `model_id` 判定,所以同一个上游 id 可能落到不同 client:在网关分组下添加的 Kimi 模型(`client_type = "openai"`)可以使用快速模式,同一个 id 路由到 Kimi 自己的 client 时则不行。自建 base URL 的自定义模型仍然保留开关——它走 OpenAI 协议,背后也可能就是 OpenAI——但第三方服务端完全可能接受该参数却仍按标准档位处理。
+### 统一网关
-有两件事开关无法替你检查:
+所有模型访问都走同一个网关库:`@prismshadow/agenthub`(AutoLLMClient)。核心只定义了一个轻量的 `LLMInterface`(参见[接口契约](/interfaces))。按供应商做协议适配的工作放在 AgentHub 内部完成,因此 1000 多个在线和本地模型都能接入,包括任何 OpenAI 兼容端点。协议转换的代码在 `packages/core/src/llm/generative-model.ts`。
-- Anthropic 的快速模式是限量的 research preview:在你的组织获得授权之前,请求会返回 429 限流错误。Anthropic 协议的模型在确认弹窗里会给出这条提示。
-- 服务端环境变量 `CLIENT_TYPE` 与 `ANTHROPIC_BASE_URL` 会覆盖条目的配置,可能把模型路由到开关未曾预期的地方。
+### 模型标识
-如果请求最终仍到达了拒绝 `fast_mode` 的 client,AgentHub 会在**发起网络请求之前**拒绝:该轮会话立即结束,错误信息带上厂商原文与设置入口指引,确定性的拒绝不会重试。若某个条目在不支持的模型上存有 `fast_mode = true`,弹窗仍会显示该开关并标注不支持,以便随时关闭。
+模型的标识永远是 `(provider, model_id)` 这一对。`provider` 是配置分组名,`model_id` 是上游请求 id,原样发给 AgentHub。两者是独立的字段,流水线中的任何环节都禁止把它们拼成一个字符串。
-连通性测试会携带弹窗当前的开关状态,因此「测试连通性」能在保存前暴露快速模式被拒的问题。后台请求(会话标题生成、`read_file` 的视觉模型代读)不携带快速模式——只有会话自身的请求携带。
+凡是要指定模型的接口,都要求给出完整的一对值:CLI、HTTP API 和 SDK 遇到只写一半的引用会直接拒绝,而不是替你补全。供应商不会从模型 id 推断,也没有默认值,因为网关会按上游 id 转售厂商模型;一旦猜错分组,条目的凭证就可能发给一个没人指定的厂商。
-## 模型与 Agent 解耦
+在模型引用可选的地方(`penguin run` / `chat`、创建 Session、定时任务),选择只有两种:给完整的两个字段,或者都不给。两个字段都省略时,使用 Project 的默认模型。
-Agent 从不绑定模型:模型在创建 Session 时选定,并在该 Session 内锁定不变;同一个 Agent 可以在不同 Session 用不同模型运行。会话内的 `/model` 命令按 handoff 方式换模型:在同一 Agent 下新建一个使用新模型、沿用当前 Workspace 的会话,首条消息携带 `[model_switch_from]` 源块(源会话 id 与其 Trace 文件路径)——历史不注入新上下文(部分模型回放历史时必须携带 thinking 与 `fidelity`,不能跨模型),模型需要时按路径自行读取;原会话保持不变。`pricing` 三档价格供用量/成本中心按 Token 计费。
+### 模型与 Agent
-凭证处理:
+Agent 从不绑定模型。模型在创建 Session 时确定,之后在整个 Session 期间保持不变,所以同一个 Agent 可以用不同模型运行不同的 Session。
-- 内联 `api_key` 存放在权限 0600 的隐藏 Project 配置文件中;
-- Web 界面展示时打码;
-- 凭证留空时回退到对应 Provider 的环境变量。
+Session 内的 `/model` 命令通过交接来切换模型:
-## 连通性测试
+1. 为同一个 Agent 在新模型上新建一个 Session,仍在当前 Workspace 里。
+2. 新 Session 的第一条消息会带一个 `[model_switch_from]` 块,包含源 Session 的 id 和它的 Trace 文件路径。
-Web 的模型页为每个模型提供连通性测试(仅 owner 可用)。
+历史不会注入新的上下文。有些模型在重放历史时需要 thinking 载荷和 `fidelity`,而这些内容无法跨模型使用。模型需要时会自己去读 Trace 文件,源 Session 保持不变。
diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.md
index ef7899ad..511de66d 100644
--- a/packages/docs/content/omni-message.en.md
+++ b/packages/docs/content/omni-message.en.md
@@ -1,15 +1,15 @@
---
title: The OmniMessage Protocol
-description: One envelope, three message types, a six-value stop_reason — the unified protocol behind the SDK, the Trace and SSE, field by field.
+description: OmniMessage is the unified message protocol that the SDK yields, the Trace stores, and the Server streams verbatim over SSE.
---
-OmniMessage is PenguinHarness's unified message protocol: the SDK yields it, the Trace stores it line by line, and the Server pushes it verbatim over SSE. What streams, what is stored and what the model sees are one structure — there is no second format between front end, back end and storage.
+OmniMessage is PenguinHarness's unified message protocol. The SDK yields OmniMessage objects, the Trace stores them line by line, and the Server pushes them verbatim over SSE. What streams, what is stored, and what the model sees are one structure: there is no second format between front end, back end, and storage.
-This page goes top-down: the envelope and the three message types first, then every payload field by field, then the protocol-wide semantics (streaming discipline, stop_reason, origin, fidelity fields). Type source: `packages/core/src/omnimessage/types.ts`.
+This page starts with the envelope and its three message types, then lists every payload field by field, and ends with the rules that span the whole protocol: the streaming discipline, `stop_reason`, `origin` and provider fidelity. The type definitions live in `packages/core/src/omnimessage/types.ts`.
## The envelope
-Every message shares one envelope; only the `payload` varies:
+Every message shares one envelope. Only the `payload` varies:
```ts
interface OmniMessage<P extends OmniPayload = OmniPayload> {
@@ -20,7 +20,7 @@ interface OmniMessage<P extends OmniPayload = OmniPayload> {
}
```
-What each message type carries:
+Each `type` carries different content:
| type | Meaning | Volume |
| --- | --- | --- |
@@ -28,8 +28,12 @@ What each message type carries:
| `model_msg` | Content inside the model context (text, thinking, tool calls and results) | the bulk |
| `event_msg` | Runtime events outside the context (approvals, usage, compaction, aborts, hook answers) | alongside |
+The optional `origin` field routes Subagent messages. See [origin: the Subagent chain](#origin-the-subagent-chain).
+
## session_meta
+A `session_meta` message describes **one model context**:
+
```ts
interface SessionMetaPayload {
session_id: string;
@@ -39,17 +43,26 @@ interface SessionMetaPayload {
system_prompt: string; // fully assembled, placeholders substituted
agent_state: string; // absolute path of the Agent State
workspace: string; // absolute path of the Workspace
- source?: "subagent" | "schedule"; // session origin; absent = user-created
+ source?: "subagent" | "schedule" | "benchmark"; // spawned by a subagent / a scheduled task / a Benchmark run; absent = user-created
}
```
-session_meta describes **one model context**: the model and the Workspace are immutable for the Session's lifetime, while the system prompt is fixed per context — the file a compaction's rotation opens starts with a `session_meta` carrying the prompt assembled for the new context from the Agent State as it is then (see [Compaction](/agent-loop)); on resume, the engine takes the latest file's line as the runtime config. See [Sessions & Traces](/sessions-and-traces). The thinking level is not here: it is a per-request parameter — the Session pin (soft-limited, applying from the next request, mid-context), else the Agent config default read at context open — and nothing records it; a `thinking_level` field found in older Traces is displayed but never read back.
+The model and the Workspace are fixed for the Session's lifetime. The system prompt is fixed per context.
+
+Every Trace file opens with a `session_meta`. When a compaction opens a new context, the new file's `session_meta` carries the system prompt assembled for that context from the Agent State as it stands at that moment (see [Compaction](/agent-loop#compaction)). On resume, the engine takes the latest file's `session_meta` as the runtime configuration. See [Sessions & Traces](/sessions-and-traces).
+
+The thinking level is not part of the meta. It is a per-request parameter: each request takes the Session's pinned level, which can change mid-context and applies from the next request, or, without a pin, the agent config default read when the context opened. Nothing records the level. A `thinking_level` field found in older Traces is displayed but never read back.
-The tool schema is **not in the meta**: the toolset is only known after MCP Servers connect, and the meta must not wait for that — the full tool definitions arrive as a standalone `tool_list_ready` event at the first run and, for every context a compaction opens, right after that context's `session_meta` at the head of its Trace file (see event_msg). Pre-split Traces embedded a `tools` field here; that field is explicitly no longer read (their tool record is not displayed).
+The tool schema is **not in the meta** either. The toolset is only known after the MCP Servers connect, and the meta must not wait for that. The full tool definitions arrive as a standalone `tool_list_ready` event (see [event_msg](#eventmsg)):
+
+- at the first run;
+- for every context a compaction opens, right after that context's `session_meta` at the head of its Trace file.
+
+Traces written before this split embedded a `tools` field in the meta. That field is no longer read, and the tool record of those Traces is not displayed.
## model_msg: complete payloads
-Seven content payloads, discriminated by `payload.type`. Shared optional fields: `stop_reason` (marks an abnormal terminal state) and `fidelity` (an opaque provider-fidelity payload, see below):
+There are seven content payloads, discriminated by `payload.type`. Two optional fields are shared: `stop_reason` marks an abnormal terminal state (see [stop_reason](#stopreason)), and `fidelity` is an opaque provider-fidelity payload (see [Provider-fidelity fields](#provider-fidelity-fields)):
```ts
type Fidelity = Record<string, unknown>; // opaque provider-fidelity payload (see below)
@@ -74,7 +87,7 @@ interface ThinkingPayload {
interface InlineThinkingPayload {
type: "inline_thinking";
role: "assistant";
- data: string; // reasoning content in binary form
+ data: string; // reasoning content as base64-encoded bytes
mime_type: string;
fidelity?: Fidelity;
stop_reason?: StopReason;
@@ -109,18 +122,20 @@ interface ImageUrlPayload {
interface InlineDataPayload {
type: "inline_data";
role: "user" | "assistant";
- data: string; // other binary content
+ data: string; // other binary content, base64-encoded
mime_type: string;
fidelity?: Fidelity;
stop_reason?: StopReason;
}
```
-`tool_call` and `tool_call_output` pair strictly via `tool_call_id`; a turn's calls form one batch, and outputs are re-fed in the original call order (see [The Agent Loop](/agent-loop)).
+`sender` separates the human user (`user`) from the parent agent driving a subagent (`parent_agent`), the harness's automatic injections such as background-task completion reports and hook continues (`harness`), and the server's own triggers such as scheduled tasks (`server`). It is never sent to the provider.
+
+`tool_call` and `tool_call_output` pair strictly via `tool_call_id`. The calls of a turn form one batch, and outputs are re-fed in the original call order (see [The Agent Loop](/agent-loop)).
## model_msg: streaming partials
-Four `partial_*` payloads mirror their complete counterparts, carrying an `event_type` phase marker:
+Four `partial_*` payloads mirror their complete counterparts. Each carries an `event_type` phase marker:
```ts
type StreamEventType = "start" | "delta" | "stop";
@@ -164,7 +179,7 @@ interface PartialToolCallOutputPayload {
### The streaming discipline
-Every streamed segment follows one timing rule, with the complete message immediately after the `stop`:
+Every streamed segment follows one timing rule, and the complete message arrives immediately after the `stop`:
```text
partial_text(start) → partial_text(delta) → … → partial_text(stop) → text (complete)
@@ -172,13 +187,46 @@ partial_text(start) → partial_text(delta) → … → partial_text(stop) → t
(truncation applies to both alike)
```
-Renderers can therefore paint deltas incrementally and swap in the complete message in place; the Trace records only complete messages, never fragments. Interface implementations close their structures internally and never leak an unclosed fragment upward. `PartialAggregator` (`aggregate.ts`) ships a ready-made aggregator.
+Renderers can therefore paint deltas as they arrive and swap in the complete message in place. The Trace records only complete messages, never fragments. Interface implementations close their structures internally and never leak an unclosed fragment upward. `PartialAggregator` (`aggregate.ts`) is a ready-made aggregator.
## event_msg
-Twelve event payloads, all listed field by field:
+Twelve event payloads record the runtime events outside the model context:
+
+| Event `type` | What it records |
+| --- | --- |
+| `tool_list_ready` | The complete tool schema sent to the model |
+| `mcp_connect_begin` | The MCP Servers being contacted |
+| `mcp_connect_end` | The overall connect status and the per-server results |
+| `request_begin` | The start of a model request |
+| `request_end` | The request's terminal status, plus the retry detail block (`error_code`, `error_message`, `attempt`, `retry_in_ms`) |
+| `approval_decision` | An approval decision, paired with its `tool_call_id` |
+| `token_usage` | Session-cumulative and per-request Token counts |
+| `compaction_begin` | The trigger reason and mode, with the context tokens and turn count at trigger time |
+| `compaction_end` | The reason, mode and terminal status of a compaction, plus the retry detail block |
+| `abort` | A user interruption and its cause code |
+| `subagent` | A pointer in the parent Trace to a direct child Session |
+| `hook` | A hook's answer: the hook point, name, decision and the hook's own record |
+
+Every payload that reports a failure carries the same error pair: `error_code`, a stable machine-readable cause that render layers localize from, and `error_message`, the raw text of the failure, shown verbatim. The complete listing:
```ts
+type ErrorCode =
+ // abort causes (a user interruption, the only thing an abort event marks)
+ | "user_abort"
+ | "backoff_interrupted"
+ | "compaction_interrupted"
+ // LLM request failures (request_end / compaction_end)
+ | "timeout" // idle timeout / connection went silent
+ | "network" // transport drops, provider 429/5xx, and anything unclassifiable
+ | "malformed" // response failed parsing/validation, or the stream was truncated
+ | "auth" // the provider rejected the credentials
+ | "rejected" // a definitive provider 4xx rejection (params, quota; 408/429 excluded)
+ | "unsupported" // a deterministic client-side rejection (fast mode without a fast tier)
+ | "invalid_input" // the input failed to assemble into a request
+ // MCP connect failures
+ | "connect_failed";
+
interface ToolListReadyPayload {
type: "tool_list_ready";
tools: ToolDefinition[]; // the complete tool schema sent to the model; emitted once
@@ -200,29 +248,30 @@ interface McpConnectBeginPayload {
// mcpServers is configured — frontends show a connecting status
}
-type McpConnectStatus = "completed" | "failed" | "aborted";
-
interface McpConnectEndPayload {
type: "mcp_connect_end";
- status: McpConnectStatus; // overall terminal status (compaction_end-style): completed
- // (all connected) / failed (some server failed) / aborted
- // (user interrupted — the attempt is cancelled and the next
- // run reconnects from scratch)
+ status: StopReason; // overall terminal status: completed (all connected) / fatal
+ // (some server failed; nothing retries it within the run) /
+ // aborted (user interrupted — the attempt is cancelled and
+ // the next run reconnects from scratch)
results: McpServerConnectResult[];
// the phase's total wall time is the end/begin messages'
// timestamp difference (messages carry their own timestamps;
// the payload holds no duplicate duration); empty on aborted
+ error_code?: ErrorCode;
+ error_message?: string;
}
interface McpServerConnectResult {
server: string;
transport: "stdio" | "http" | "sse";
- status: McpConnectStatus; // per-server and non-fatal: a failed server is skipped and
- // the run continues
+ status: StopReason; // completed / fatal / aborted — per-server and non-fatal to
+ // the run: a failed server is skipped and the run continues
duration_ms: number; // this server's own connect + discovery time (no per-server
// messages exist to derive it from)
tools?: number; // tools discovered (on completed)
- error?: string; // failure detail (on failed)
+ error_code?: ErrorCode; // failure cause and detail (on fatal)
+ error_message?: string;
}
interface RequestBeginPayload {
@@ -233,8 +282,8 @@ interface RequestEndPayload {
type: "request_end";
status: StopReason; // "completed" is the mechanical commit criterion for replay
// The unified RetryDetail block below is stamped in one place by the builders; every
- // field is additive — old Traces replay unchanged. compaction_end reuses the same
- // block (attempt = final attempt ordinal, error_message = the last failure's detail).
+ // field is additive — old Traces replay unchanged. compaction_end reuses the same block.
+ error_code?: ErrorCode; // classified cause, non-completed only
error_message?: string; // error detail (LLMOutcome.errorMessage internally — one
// name across the stack), non-completed only: the real
// reason behind a retried/failed Request (e.g. a provider
@@ -243,7 +292,8 @@ interface RequestEndPayload {
// authoritative retry count): stamped on failures and on a
// completion that needed retries; absent on a clean first try
retry_in_ms?: number; // planned reconnect wait (ms), present only when the engine
- // will retry in-run — the Web App renders it as a countdown
+ // will retry in-run — the Web App renders it as a countdown;
+ // a failed request_end without it is the run's terminal record
}
interface ApprovalDecisionPayload {
@@ -281,17 +331,27 @@ interface CompactionEndPayload {
type: "compaction_end";
reason: CompactionReason;
mode: CompactionMode;
- status: StopReason;
+ status: StopReason; // completed / retryable (abandoned after the retries ran out;
+ // the standing trigger makes it up) / fatal (a failure no
+ // retry can fix) / aborted (user interrupted); any status
+ // but completed keeps the original context
+ attempt?: number; // the final attempt's ordinal, failed attempts included
+ error_code?: ErrorCode; // the last failure's cause and detail
+ error_message?: string;
}
interface AbortPayload {
type: "abort";
- reason?: string | null;
+ error_code?: ErrorCode; // user_abort / backoff_interrupted / compaction_interrupted
+ error_message?: string;
+ reason?: string | null; // legacy: older Traces carry the cause as English prose here;
+ // the engine no longer writes it
}
interface SubagentPayload {
type: "subagent";
session_id: string; // pointer in the parent Trace to a direct child Session
+ // (written to the Trace, not streamed)
}
interface HookPayload {
@@ -303,33 +363,38 @@ interface HookPayload {
reason?: string; // one line for people
output?: Record<string, string | number | boolean>;
// the hook's own record — the goal hook writes status /
- // round / tokens_used / budget; a continue's injected input
- // is NOT here: it is the user message that follows
+ // round / tokens_used / budget, the continual-learning hook
+ // session_id / turns; a continue's injected input is NOT
+ // here: it is the user message that follows
}
```
+`compaction_end` never carries `retry_in_ms`: compaction retries are announced on the compaction request's own `request_end`, which stays in the Trace. Older Traces may still spell an MCP connect failure or an abandoned compaction as `failed`, and carry a per-server `error` field instead of the error pair.
+
## stop_reason
-A six-value enum used across messages and interface results (`LLMOutcome.status` uses the same set — see [Core Interfaces](/interfaces)):
+A four-value enum shared by every record that carries a stop reason: model messages, tool results, and request, compaction and MCP-connect terminals. `LLMOutcome.status` uses the same set (see [Core Interfaces](/interfaces)):
```ts
-type StopReason = "completed" | "failed" | "aborted" | "timeout" | "malformed" | "auth";
+type StopReason = "completed" | "aborted" | "retryable" | "fatal";
```
+A stop reason answers one question: should this be retried? The kind of failure rides on `error_code`, and its detail on `error_message`.
+
| Value | Meaning | Engine reaction |
| --- | --- | --- |
| `completed` | finished normally | continue |
-| `aborted` | user interrupt | stop, hand back to the user |
-| `timeout` | LLM timeout / transport disconnect | LLM side only: auto-reconnect within the run |
-| `malformed` | parse failure / truncated stream | LLM side only: auto-reconnect within the run |
-| `failed` | an error the classifier did not judge transient (LLM); a tool error (Environment) | LLM side: auto-reconnect within the run as well — the status is still reported as `failed`. Environment side: the error is fed back to the model, never retried |
-| `auth` | the provider rejected the credentials | stop, hand back to the user — the one LLM status that never retries; hosts gate input until the model's API key is updated (credentials come from the current Project config) |
+| `aborted` | user interruption or cancellation | stop, emit an `abort` event, hand back to the user |
+| `retryable` | a failure worth retrying: transport drops, idle timeouts, 408/429/5xx, malformed or truncated responses, and anything unclassifiable | LLM side: reconnect within the run on the backoff ladder |
+| `fatal` | a failure no retry can fix. LLM side: a definitive provider 4xx rejection (parameters, quota), rejected credentials, or a deterministic client-side rejection. Environment side: a tool error or timeout | LLM side: stop the run and hand back to the user; no `abort` event follows, and the `request_end` is the terminal record. Environment side: the error is fed back to the model, never retried |
+
+Tools rarely end `retryable`: a tool error or timeout is definitive for that call, and nothing in the harness retries a tool. Older Traces may still carry the retired values `failed`, `timeout`, `malformed` and `auth`. Replay only ever compares against `completed`, and renderers still display the old spellings.
-Errors never cross an interface boundary as exceptions — they *are* messages. See [The Agent Loop](/agent-loop).
+Errors never cross an interface boundary as exceptions. They *are* messages (see [The Agent Loop](/agent-loop)).
## origin: the Subagent chain
-`origin` serves Subagents: when a child Session's messages are forwarded to the parent, each hop prepends one child Session id (outer→inner), and renderers route messages into the right nested card by the chain:
+`origin` serves Subagents. When a child Session's messages are forwarded to the parent, each hop prepends one child Session id, ordered outer to inner. Renderers read the chain to route each message into the right nested card:
```ts
// message from the main Session: no origin
@@ -339,11 +404,16 @@ Errors never cross an interface boundary as exceptions — they *are* messages.
{ timestamp: "…", type: "model_msg", origin: ["session-2026-07-18-…-a1b2c3d4"], payload: { … } }
```
-`origin`-tagged messages are not written to the parent Trace — the child Session has its own Trace, and the parent keeps only the `subagent` pointer event.
+Messages tagged with `origin` are not written to the parent Trace. The child Session has its own Trace, and the parent keeps only the `subagent` pointer event.
## Provider-fidelity fields
-Provider-specific wire data travels in a single optional field, `fidelity` — an arbitrary JSON object the LLM client records to reproduce the original message on replay: thinking signatures, `phase` segment labels, GPT-5 encrypted reasoning, the OpenAI-compatible upstream reasoning field name:
+Provider-specific wire data travels in a single optional field, `fidelity`. It is an arbitrary JSON object that the LLM client records so the original message can be reproduced on replay, for example:
+
+- thinking signatures;
+- `phase` segment labels;
+- GPT-5 encrypted reasoning;
+- the OpenAI-compatible upstream reasoning field name.
```ts
// Claude: a thinking block closed by its signature
@@ -356,9 +426,9 @@ Provider-specific wire data travels in a single optional field, `fidelity` — a
{ type: "thinking", thinking: "…", fidelity: { reasoning_field: "reasoning_content" } }
```
-The payload is opaque to PenguinHarness: it passes through and persists verbatim end to end — some models require it byte-for-byte when history is replayed, and any rewriting (or loss) would break compatibility. This is one of the preconditions for lossless Session recovery from the Trace.
+The payload is opaque to PenguinHarness: it passes through and persists verbatim end to end. Some models require it byte for byte when history is replayed, so any rewriting or loss breaks compatibility. This is one of the preconditions for lossless Session recovery from the Trace.
-## Three jobs, one protocol
+## Surfaces and their message subsets
| Surface | Subset used |
| --- | --- |
@@ -366,11 +436,14 @@ The payload is opaque to PenguinHarness: it passes through and persists verbatim
| Trace on disk | `session_meta` + complete `model_msg` + all `event_msg` (no partials, no `origin`-tagged messages) |
| Server SSE stream | same as the SDK boundary, verbatim single-line JSON — see [Server API](/server-api) |
-How messages travel along these surfaces — and every ordering guarantee — is covered on [Message Flow & Ordering](/message-flow).
+How messages travel along these surfaces, and every ordering guarantee, is covered on [Message Flow & Ordering](/message-flow).
## Builders and guards
-`@prismshadow/penguin-core` exports all types, a builder per message kind (`builders.ts`: `userText`, `assistantText`, `toolCall`, `toolCallOutput`, `partialText`, `tokenUsage`, `withOrigin`, `emptyTokenCounts`, `addTokenCounts`, …) and runtime guards (`isCompleteModelMessage`, `isPartialPayload`, `isModelMessage`, `isEventMessage`, `isSessionMeta`):
+`@prismshadow/penguin-core` exports all protocol types, plus:
+
+- a builder per message kind in `builders.ts`: `userText`, `assistantText`, `toolCall`, `toolCallOutput`, `partialText`, `tokenUsage`, `withOrigin`, `emptyTokenCounts`, `addTokenCounts`, and more;
+- runtime guards: `isCompleteModelMessage`, `isPartialPayload`, `isModelMessage`, `isEventMessage`, `isSessionMeta`.
```ts
import { userText, isCompleteModelMessage } from "@prismshadow/penguin-core";
diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.md
index 25542a5f..2ac10dd1 100644
--- a/packages/docs/content/omni-message.zh.md
+++ b/packages/docs/content/omni-message.zh.md
@@ -1,65 +1,78 @@
---
title: OmniMessage 协议
-description: 一个信封、三类消息、六值 stop_reason——贯穿 SDK、Trace 与 SSE 的统一消息协议,逐字段定义。
+description: OmniMessage 是统一的消息协议:SDK 产出它,Trace 存储它,Server 经 SSE 原样推送它。
---
-OmniMessage 是 PenguinHarness 的统一消息协议:SDK 对外产出它,Trace 逐行存储它,Server 经 SSE 原样推送它。「流出去的」「存下来的」「模型看到的」是同一种结构,前后端与存储之间不存在第二套格式。
+OmniMessage 是 PenguinHarness 的统一消息协议。SDK 产出 OmniMessage 对象,Trace 逐行存储,Server 经 SSE 原样推送。流出去的、存下来的和模型看到的是同一种结构,前端、后端与存储之间没有第二套格式。
-本页自顶向下:先定义信封与三类消息,再逐字段展开每一种 payload,最后是贯穿全协议的语义(流式纪律、stop_reason、origin、保真字段)。类型源码:`packages/core/src/omnimessage/types.ts`。
+本页先讲信封和三类消息,再逐字段列出全部 payload,最后是贯穿整个协议的规则:流式纪律、`stop_reason`、`origin` 与保真字段。类型定义见 `packages/core/src/omnimessage/types.ts`。
## 信封
-所有消息共享同一个信封,仅 `payload` 不同:
+每条消息共用同一个信封,只有 `payload` 不同:
```ts
interface OmniMessage<P extends OmniPayload = OmniPayload> {
timestamp: string; // ISO 8601 UTC
type: "session_meta" | "model_msg" | "event_msg";
payload: P;
- origin?: string[]; // 子 Session 链(由外到内);缺省表示主 Session
+ origin?: string[]; // child-Session chain (outer→inner); absent = main Session
}
```
-三类消息的分工:
+三类消息各自承载的内容:
-| type | 含义 | 数量级 |
+| type | 含义 | 数量 |
| --- | --- | --- |
-| `session_meta` | 一个模型上下文的完整运行配置 | 每个上下文恰好一条 |
-| `model_msg` | 模型上下文中的内容消息(文本、思考、工具调用与结果) | 主体 |
-| `event_msg` | 上下文之外的运行事件(审批、用量、压缩、中断、hook 回答) | 伴随 |
+| `session_meta` | 一个模型上下文的完整运行时配置 | 每个上下文恰好一条 |
+| `model_msg` | 模型上下文内的内容(文本、思考、工具调用和结果) | 主体 |
+| `event_msg` | 上下文之外的运行时事件(审批、用量、压缩、中断、钩子回答) | 伴随出现 |
+
+可选的 `origin` 字段用来路由子 Agent 的消息,见 [origin:子 Session 链](#origin子-session-链)。
## session_meta
+一条 `session_meta` 消息描述**一个模型上下文**:
+
```ts
interface SessionMetaPayload {
session_id: string;
- provider: string; // 模型身份二元组之一
- model_id: string; // 发给 AgentHub 的上游请求 id
+ provider: string; // one half of the model-identity pair
+ model_id: string; // the upstream request id sent to AgentHub
model_context_window: number | string;
- system_prompt: string; // 占位符替换完成后的完整系统提示词
- agent_state: string; // Agent State 绝对路径
- workspace: string; // Workspace 绝对路径
- source?: "subagent" | "schedule"; // Session 来源;缺省 = 用户创建
+ system_prompt: string; // fully assembled, placeholders substituted
+ agent_state: string; // absolute path of the Agent State
+ workspace: string; // absolute path of the Workspace
+ source?: "subagent" | "schedule" | "benchmark"; // spawned by a subagent / a scheduled task / a Benchmark run; absent = user-created
}
```
-session_meta 描述**一个模型上下文**:模型与 Workspace 在 Session 生命周期内不可变,系统提示词则按上下文固定——压缩轮转出的新文件以携带新上下文提示词的 `session_meta` 开头——该提示词按当时的 Agent State 装配(见[上下文压缩](/agent-loop));恢复 Session 时引擎直接以最新文件中的这条消息为运行时配置,见 [Session 与 Trace](/sessions-and-traces)。思考等级不在此列:它是每请求参数——Session 钉住值(软限制,自下一次请求生效、允许中途更换),未钉住取上下文开启时读到的 Agent 配置缺省——不作任何记录;旧 Trace 中出现的 `thinking_level` 字段仅作展示,不再读取。
+模型与 Workspace 在整个 Session 生命周期内不变,系统提示词则按上下文固定。
+
+每个 Trace 文件都以一条 `session_meta` 开头。压缩开启新上下文时,新文件的 `session_meta` 记录的系统提示词,按当时的 Agent State 为这个上下文重新装配(见[上下文压缩](/agent-loop#上下文压缩))。恢复 Session 时,引擎以最新文件里的 `session_meta` 作为运行时配置,见 [Session 与 Trace](/sessions-and-traces)。
+
+思考等级不在 meta 里,它是逐请求的参数:每次请求取 Session 钉住的等级,这个等级可以在上下文中途更换,从下一次请求起生效;没有钉住时,取上下文开启时读到的 Agent 配置缺省值。思考等级不作任何记录。旧 Trace 里出现的 `thinking_level` 字段只用于展示,不会被读回。
-工具 schema **不在 meta 里**:工具集要等 MCP Server 连接完成才可知,而 meta 不应等待——完整工具定义在首次 run 时以独立的 `tool_list_ready` 事件下发,压缩开启的每个上下文则在其 Trace 文件头部、紧随该上下文的 `session_meta` 之后再发一次(见 event_msg)。拆分前的旧版 Trace 在 meta 里内嵌 `tools` 字段,该字段已明确不再读取(旧 Trace 的工具记录不再展示)。
+工具 schema 同样**不在 meta 里**。工具集要等 MCP Server 连接完成才能确定,而 meta 不应等待。完整的工具定义以独立的 `tool_list_ready` 事件下发(见 [event_msg](#eventmsg)):
+
+- 首次运行时下发一次;
+- 压缩开启的每个上下文,在其 Trace 文件开头、紧随 `session_meta` 之后再发一次。
+
+拆分之前写入的 Trace 在 meta 里内嵌了 `tools` 字段。这个字段已不再读取,这些 Trace 的工具记录也不再展示。
## model_msg:完整消息
-七种内容 payload,以 `payload.type` 判别。公共可选字段:`stop_reason`(非正常收尾时标注终态)与 `fidelity`(不透明的 Provider 保真负载,见下文):
+内容 payload 共七种,以 `payload.type` 区分。两个可选字段各类共用:`stop_reason` 标注非正常收尾的终态(见 [stop_reason](#stopreason)),`fidelity` 是不透明的供应商保真负载(见[保真字段](#保真字段)):
```ts
-type Fidelity = Record<string, unknown>; // 不透明的 Provider 保真负载(见下文)
+type Fidelity = Record<string, unknown>; // opaque provider-fidelity payload (see below)
interface TextPayload {
type: "text";
role: "user" | "assistant";
text: string;
- sender?: "user" | "parent_agent" | "harness" | "server"; // user 角色文本的来源;缺省 = 真人用户
- fidelity?: Fidelity; // 如 { phase } 分段标记(GPT-5)、{ signature }
+ sender?: "user" | "parent_agent" | "harness" | "server"; // who produced a user-role text; absent = the human user
+ fidelity?: Fidelity; // e.g. { phase } segment marker (GPT-5), { signature }
stop_reason?: StopReason;
}
@@ -67,14 +80,14 @@ interface ThinkingPayload {
type: "thinking";
role: "assistant";
thinking: string;
- fidelity?: Fidelity; // 部分模型历史回放所必需
+ fidelity?: Fidelity; // required by some models to replay history
stop_reason?: StopReason;
}
interface InlineThinkingPayload {
type: "inline_thinking";
role: "assistant";
- data: string; // 二进制形态的思考内容
+ data: string; // reasoning content as base64-encoded bytes
mime_type: string;
fidelity?: Fidelity;
stop_reason?: StopReason;
@@ -84,7 +97,7 @@ interface ToolCallPayload {
type: "tool_call";
role: "assistant";
name: string;
- arguments: string; // 参数 JSON 字符串
+ arguments: string; // arguments as a JSON string
tool_call_id: string;
fidelity?: Fidelity;
stop_reason?: StopReason;
@@ -94,7 +107,7 @@ interface ToolCallOutputPayload {
type: "tool_call_output";
role: "user";
output: string;
- images?: string[]; // data:<mime>;base64,… 列表(如 read_file 读图的结果)
+ images?: string[]; // data:<mime>;base64,… URLs (e.g. read_file's image results)
tool_call_id: string;
stop_reason?: StopReason;
}
@@ -102,25 +115,27 @@ interface ToolCallOutputPayload {
interface ImageUrlPayload {
type: "image_url";
role: "user";
- image_url: string; // 网络 URL 或 base64 data URL
+ image_url: string; // web URL or base64 data URL
stop_reason?: StopReason;
}
interface InlineDataPayload {
type: "inline_data";
role: "user" | "assistant";
- data: string; // 其他二进制内容
+ data: string; // other binary content, base64-encoded
mime_type: string;
fidelity?: Fidelity;
stop_reason?: StopReason;
}
```
-`tool_call` 与 `tool_call_output` 通过 `tool_call_id` 严格配对;一轮内的多个调用是一个批次,输出按原始调用顺序回填(见 [Agent 运行循环](/agent-loop))。
+`sender` 区分 user 角色文本的来源:真人用户(`user`)、驱动子 Agent 的父 Agent(`parent_agent`)、harness 的自动注入(`harness`,例如后台任务的完成回报和钩子 `continue` 注入的输入),以及 Server 自己的触发(`server`,例如定时任务)。这个字段不会发给供应商。
+
+`tool_call` 与 `tool_call_output` 通过 `tool_call_id` 严格配对。一轮内的调用构成一个批次,输出按原始调用顺序回填(见 [Agent 运行循环](/agent-loop))。
## model_msg:流式分片
-四种 `partial_*` payload 与完整消息一一对应,携带 `event_type` 标记分片阶段:
+四种 `partial_*` payload 与完整消息一一对应,并携带 `event_type` 标记分片阶段:
```ts
type StreamEventType = "start" | "delta" | "stop";
@@ -129,7 +144,7 @@ interface PartialTextPayload {
type: "partial_text";
role: "assistant";
event_type: StreamEventType;
- text: string; // 本条分片新增的文本
+ text: string; // the text added by this fragment
stop_reason?: StopReason;
}
@@ -146,7 +161,7 @@ interface PartialToolCallPayload {
role: "assistant";
event_type: StreamEventType;
name: string;
- arguments: string; // 参数 JSON 的增量片段
+ arguments: string; // incremental fragment of the arguments JSON
tool_call_id: string;
stop_reason?: StopReason;
}
@@ -156,7 +171,7 @@ interface PartialToolCallOutputPayload {
role: "user";
event_type: StreamEventType;
output: string;
- images?: string[]; // 图像不增量,由单条 delta 整体携带
+ images?: string[]; // images are not incremental — one delta carries the whole set
tool_call_id: string;
stop_reason?: StopReason;
}
@@ -164,25 +179,61 @@ interface PartialToolCallOutputPayload {
### 流式纪律
-每段流式内容严格遵守同一时序,`stop` 之后立即跟随对应的完整消息:
+每段流式内容都遵守同一条时序规则,`stop` 之后紧跟对应的完整消息:
```text
-partial_text(start) → partial_text(delta) → … → partial_text(stop) → text(完整)
- └── 全部 delta 拼接 ≡ 完整消息内容(截断也两侧同步) ──┘
+partial_text(start) → partial_text(delta) → … → partial_text(stop) → text (complete)
+ └── concatenation of all deltas ≡ the complete message ──┘
+ (truncation applies to both alike)
```
-因此渲染层可以先增量渲染、收到完整消息后原地替换;Trace 只记录完整消息,不存分片。接口实现方在内部把结构闭合完毕,永远不向上层泄漏未闭合的分片。`PartialAggregator`(`aggregate.ts`)提供现成的分片聚合实现。
+因此渲染层可以边收 delta 边绘制,收到完整消息后原地替换。Trace 只记录完整消息,不存分片。接口实现在内部把结构闭合好,从不向上层泄漏未闭合的分片。`PartialAggregator`(`aggregate.ts`)提供了现成的分片聚合器。
## event_msg
-十二种事件 payload,全部逐字段列出:
+十二种事件 payload 记录模型上下文之外的运行时事件:
+
+| 事件 `type` | 记录的内容 |
+| --- | --- |
+| `tool_list_ready` | 发送给模型的完整工具 schema |
+| `mcp_connect_begin` | 正在连接的 MCP Server |
+| `mcp_connect_end` | 总体连接状态与逐个 Server 的结果 |
+| `request_begin` | 一次模型请求的开始 |
+| `request_end` | 请求的终态,以及重试详情块(`error_code`、`error_message`、`attempt`、`retry_in_ms`) |
+| `approval_decision` | 一次审批决策,与对应的 `tool_call_id` 配对 |
+| `token_usage` | Session 累计与本次请求的 Token 计数 |
+| `compaction_begin` | 触发原因与模式,以及触发时的上下文 Token 数和累计轮数 |
+| `compaction_end` | 压缩的原因、模式与终态,以及重试详情块 |
+| `abort` | 一次用户中断及其原因码 |
+| `subagent` | 父 Trace 中指向直接子 Session 的指针 |
+| `hook` | 一次钩子回答:钩子点、名称、决策,以及钩子自己的记录 |
+
+凡是报告失败的 payload 都带同一对错误字段:`error_code` 是稳定、机器可读的原因码,渲染层据此做本地化;`error_message` 是失败的原始文本,原样展示。完整定义如下:
```ts
+type ErrorCode =
+ // abort causes (a user interruption, the only thing an abort event marks)
+ | "user_abort"
+ | "backoff_interrupted"
+ | "compaction_interrupted"
+ // LLM request failures (request_end / compaction_end)
+ | "timeout" // idle timeout / connection went silent
+ | "network" // transport drops, provider 429/5xx, and anything unclassifiable
+ | "malformed" // response failed parsing/validation, or the stream was truncated
+ | "auth" // the provider rejected the credentials
+ | "rejected" // a definitive provider 4xx rejection (params, quota; 408/429 excluded)
+ | "unsupported" // a deterministic client-side rejection (fast mode without a fast tier)
+ | "invalid_input" // the input failed to assemble into a request
+ // MCP connect failures
+ | "connect_failed";
+
interface ToolListReadyPayload {
type: "tool_list_ready";
- tools: ToolDefinition[]; // 发给模型的完整工具 schema;首次 run 时发出一次(MCP 发现
- // 完成后),Trace 中写在本轮输入之后(归属新轮次),压缩分卷时
- // 随 session_meta 一并重写到新 Trace 文件
+ tools: ToolDefinition[]; // the complete tool schema sent to the model; emitted once
+ // at the first run (after MCP discovery), written to the
+ // Trace right after the run's input (it belongs to the new
+ // turn), and rewritten with session_meta at the head of
+ // each post-compaction Trace file
}
interface ToolDefinition {
@@ -193,29 +244,34 @@ interface ToolDefinition {
interface McpConnectBeginPayload {
type: "mcp_connect_begin";
- servers: string[]; // 正在连接的 MCP Server;仅配置了 mcpServers 时发出,
- // 前端据此显示连接状态
+ servers: string[]; // the MCP Servers being contacted; emitted only when
+ // mcpServers is configured — frontends show a connecting status
}
-type McpConnectStatus = "completed" | "failed" | "aborted";
-
interface McpConnectEndPayload {
type: "mcp_connect_end";
- status: McpConnectStatus; // 总体终态(与 compaction_end.status 同风格):completed 全部
- // 连上 / failed 有 Server 失败 / aborted 用户打断——打断即
- // 取消本次连接,下次 run 重新连接
+ status: StopReason; // overall terminal status: completed (all connected) / fatal
+ // (some server failed; nothing retries it within the run) /
+ // aborted (user interrupted — the attempt is cancelled and
+ // the next run reconnects from scratch)
results: McpServerConnectResult[];
- // 阶段总耗时 = end 与 begin 两条消息的 timestamp 之差
- // (消息自带时间戳,payload 不重复记录);aborted 时为空
+ // the phase's total wall time is the end/begin messages'
+ // timestamp difference (messages carry their own timestamps;
+ // the payload holds no duplicate duration); empty on aborted
+ error_code?: ErrorCode;
+ error_message?: string;
}
interface McpServerConnectResult {
server: string;
transport: "stdio" | "http" | "sse";
- status: McpConnectStatus; // 失败逐 Server 且不致命:该 Server 被跳过,run 继续
- duration_ms: number; // 该 Server 自身的连接+发现耗时(无独立消息可推导)
- tools?: number; // 发现的工具数(completed 时)
- error?: string; // 失败详情(failed 时)
+ status: StopReason; // completed / fatal / aborted — per-server and non-fatal to
+ // the run: a failed server is skipped and the run continues
+ duration_ms: number; // this server's own connect + discovery time (no per-server
+ // messages exist to derive it from)
+ tools?: number; // tools discovered (on completed)
+ error_code?: ErrorCode; // failure cause and detail (on fatal)
+ error_message?: string;
}
interface RequestBeginPayload {
@@ -224,29 +280,33 @@ interface RequestBeginPayload {
interface RequestEndPayload {
type: "request_end";
- status: StopReason; // completed 是回放判定「该轮已提交」的机械标准
- // 以下为统一的重试详情块 RetryDetail(由 builder 一处盖章;均为增量字段,旧 Trace 回放
- // 不受影响;compaction_end 复用同一块——attempt 为最终尝试序号,error_message 为失败详情)
- error_message?: string; // 错误详情(内部 LLMOutcome.errorMessage,内外同名),仅非
- // completed 携带:被重试/失败的 Request 背后的真实原因
- // (如供应商错误码),供成本中心错误面板读取
- attempt?: number; // 本次重试序列内的第几次请求(1 起,权威计数):失败请求
- // 与经重试后成功的请求携带;首发即成功不携带
- retry_in_ms?: number; // 计划中的重连等待(毫秒),仅当引擎将在本轮内重试时携带,
- // Web App 据此渲染倒计时
+ status: StopReason; // "completed" is the mechanical commit criterion for replay
+ // The unified RetryDetail block below is stamped in one place by the builders; every
+ // field is additive — old Traces replay unchanged. compaction_end reuses the same block.
+ error_code?: ErrorCode; // classified cause, non-completed only
+ error_message?: string; // error detail (LLMOutcome.errorMessage internally — one
+ // name across the stack), non-completed only: the real
+ // reason behind a retried/failed Request (e.g. a provider
+ // error code) — read by the Cost center's errors panel
+ attempt?: number; // 1-based ordinal of this request within its retry run (the
+ // authoritative retry count): stamped on failures and on a
+ // completion that needed retries; absent on a clean first try
+ retry_in_ms?: number; // planned reconnect wait (ms), present only when the engine
+ // will retry in-run — the Web App renders it as a countdown;
+ // a failed request_end without it is the run's terminal record
}
interface ApprovalDecisionPayload {
type: "approval_decision";
- decision: "allow" | "deny" | "forbidden"; // "forbidden" = 命令策略的拦截,从未征询人——
- // 记录自身即可说明是谁拒绝的
- tool_call_id: string; // 与被审批的 tool_call 配对,构成审计记录
+ decision: "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto,
+ // never asked of a human — the record itself names the decider
+ tool_call_id: string; // pairs with the approved tool_call — the audit record
}
interface TokenUsagePayload {
type: "token_usage";
- session: TokenCounts; // Session 累计——由引擎统一累计盖章(LLM 只报 `request`)
- request: TokenCounts; // 本次 Request
+ session: TokenCounts; // Session cumulative — authored by the engine (the LLM reports `request` only)
+ request: TokenCounts; // this Request
}
interface TokenCounts {
@@ -263,108 +323,131 @@ interface CompactionBeginPayload {
type: "compaction_begin";
reason: CompactionReason;
mode: CompactionMode;
- context: number; // 触发时的上下文 Token 数
- turns: number; // 触发时的累计轮数
+ context: number; // context tokens at trigger time
+ turns: number; // cumulative turns at trigger time
}
interface CompactionEndPayload {
type: "compaction_end";
reason: CompactionReason;
mode: CompactionMode;
- status: StopReason;
+ status: StopReason; // completed / retryable (abandoned after the retries ran out;
+ // the standing trigger makes it up) / fatal (a failure no
+ // retry can fix) / aborted (user interrupted); any status
+ // but completed keeps the original context
+ attempt?: number; // the final attempt's ordinal, failed attempts included
+ error_code?: ErrorCode; // the last failure's cause and detail
+ error_message?: string;
}
interface AbortPayload {
type: "abort";
- reason?: string | null;
+ error_code?: ErrorCode; // user_abort / backoff_interrupted / compaction_interrupted
+ error_message?: string;
+ reason?: string | null; // legacy: older Traces carry the cause as English prose here;
+ // the engine no longer writes it
}
interface SubagentPayload {
type: "subagent";
- session_id: string; // 父 Trace 中指向直接子 Session 的指针
+ session_id: string; // pointer in the parent Trace to a direct child Session
+ // (written to the Trace, not streamed)
}
interface HookPayload {
type: "hook";
- hook: "stop" | "pre_tool_use"; // 触发的 hook 点(见运行循环的 hook 两节)
- name: string; // hook 名:"goal"、"continual-learning"……
- decision?: "continue" | "stop" // stop 点
- | "allow" | "deny"; // pre_tool_use 点;只留记录时缺省
- reason?: string; // 一行给人看的说明
+ hook: "stop" | "pre_tool_use"; // the hook point that fired (see the agent loop's hooks)
+ name: string; // the hook's name: "goal", "continual-learning", …
+ decision?: "continue" | "stop" // stop point
+ | "allow" | "deny"; // pre_tool_use point; absent when the hook only left a record
+ reason?: string; // one line for people
output?: Record<string, string | number | boolean>;
- // hook 自己的记录——goal hook 写 status / round /
- // tokens_used / budget;continue 注入的输入不在这里,
- // 它是紧随其后的那条 user 消息
+ // the hook's own record — the goal hook writes status /
+ // round / tokens_used / budget, the continual-learning hook
+ // session_id / turns; a continue's injected input is NOT
+ // here: it is the user message that follows
}
```
+`compaction_end` 从不携带 `retry_in_ms`:压缩的重试由压缩请求自己的 `request_end` 宣告,而这条记录只写入 Trace。旧 Trace 可能仍把 MCP 连接失败或被放弃的压缩记为 `failed`,逐个 Server 的结果里也可能是 `error` 字段,而不是这对错误字段。
+
## stop_reason
-六值枚举,贯穿消息与接口返回(`LLMOutcome.status` 使用同一集合,见[接口契约](/interfaces)):
+四值枚举,所有带终止原因的记录共用:模型消息、工具结果,以及请求、压缩和 MCP 连接的终态。`LLMOutcome.status` 使用同一组取值(见[核心接口](/interfaces)):
```ts
-type StopReason = "completed" | "failed" | "aborted" | "timeout" | "malformed" | "auth";
+type StopReason = "completed" | "aborted" | "retryable" | "fatal";
```
-| 值 | 语义 | 引擎的反应 |
+终止原因只回答一个问题:要不要重试。失败属于哪一类看 `error_code`,具体细节看 `error_message`。
+
+| 取值 | 含义 | 引擎反应 |
| --- | --- | --- |
| `completed` | 正常完成 | 继续 |
-| `aborted` | 用户中断 | 停止并交还用户 |
-| `timeout` | LLM 超时/传输层断连 | 仅 LLM 侧:同一 run 内自动重连 |
-| `malformed` | 响应解析失败/流截断 | 仅 LLM 侧:同一 run 内自动重连 |
-| `failed` | 分类器未判定为瞬时的错误(LLM 侧);工具执行出错(Environment 侧) | LLM 侧:同样在同一 run 内自动重连——该状态本身仍如实上报为 `failed`。Environment 侧:错误回灌给模型,从不重试 |
-| `auth` | 供应商拒绝了凭据 | 停止并交还用户——唯一从不重试的 LLM 终态;宿主据此禁用输入,直到该模型的 API key 被更新(凭据取自当前 Project 配置) |
+| `aborted` | 用户中断或取消 | 停止,产出 `abort` 事件,交还用户 |
+| `retryable` | 值得重试的失败:传输中断、空闲超时、408/429/5xx、解析失败或被截断的响应,以及一切无法归类的错误 | LLM 侧:同一次运行内按退避阶梯自动重连 |
+| `fatal` | 重试也无法修复的失败。LLM 侧:供应商确定性的 4xx 拒绝(参数、配额)、凭据被拒,或确定性的客户端拒绝;Environment 侧:工具出错或超时 | LLM 侧:停止本次运行,交还用户;不产出 `abort` 事件,`request_end` 即终局记录。Environment 侧:错误回灌给模型,从不重试 |
+
+工具很少以 `retryable` 收尾:工具出错或超时对这次调用是确定的结果,harness 也不会重试任何工具。旧 Trace 里可能还有已废弃的 `failed`、`timeout`、`malformed` 和 `auth`;回放只与 `completed` 比较,渲染层照常展示这些旧取值。
-错误从不以异常形式穿过接口边界——它们就是消息,见 [Agent 运行循环](/agent-loop)。
+错误从不以异常形式穿过接口边界,错误本身*就是*消息(见 [Agent 运行循环](/agent-loop))。
## origin:子 Session 链
-`origin` 服务于 Subagent:子 Session 的消息转发给父级时,每经过一层就在数组前端添加一个子 Session id(由外到内),渲染层据此把消息归入对应的子会话卡片:
+`origin` 服务于子 Agent。子 Session 的消息转发给父级时,每经过一层就在链首加上一个子 Session id,顺序由外到内。渲染层按这条链把消息归入对应的嵌套卡片:
```ts
-// 主 Session 的消息:无 origin
+// message from the main Session: no origin
{ timestamp: "…", type: "model_msg", payload: { type: "text", … } }
-// 一层 Subagent 的消息:origin = [子 Session id]
+// message from a one-level Subagent: origin = [child Session id]
{ timestamp: "…", type: "model_msg", origin: ["session-2026-07-18-…-a1b2c3d4"], payload: { … } }
```
-带 `origin` 的消息不写入父 Trace——子 Session 拥有自己的 Trace,父 Trace 只保留 `subagent` 指针事件。
+带 `origin` 的消息不写入父 Trace:子 Session 有自己的 Trace,父 Trace 只保留 `subagent` 指针事件。
## 保真字段
-Provider 专有的线上数据统一收拢在一个可选字段 `fidelity` 中——LLM 客户端为历史回放记录的任意 JSON 对象:思考签名、`phase` 分段标记、GPT-5 加密推理、OpenAI 兼容上游的推理字段名:
+供应商特有的传输层数据统一放在一个可选字段 `fidelity` 里。它是 LLM 客户端记录的任意 JSON 对象,用于在回放时复原原始消息,例如:
+
+- 思考签名;
+- `phase` 分段标签;
+- GPT-5 的加密推理;
+- OpenAI 兼容上游的推理字段名。
```ts
-// Claude:由签名闭合的 thinking 块
+// Claude: a thinking block closed by its signature
{ type: "thinking", thinking: "…", fidelity: { signature: "EqQBCkYIBxgCKkB…" } }
-// GPT-5:加密推理(thinking 文本为空,仅有 fidelity)
+// GPT-5: encrypted reasoning (empty thinking text, fidelity only)
{ type: "thinking", thinking: "", fidelity: { id: "rs_0d3…", encrypted_content: "gAAAA…" } }
-// OpenAI 兼容:思考内容来自上游哪个字段
+// OpenAI-compatible: the upstream field the reasoning text came from
{ type: "thinking", thinking: "…", fidelity: { reasoning_field: "reasoning_content" } }
```
-该负载对 PenguinHarness 完全不透明:在整条链路上原样透传、原样存储——部分模型在历史回放时要求逐字一致,任何转写或丢失都会破坏兼容性。这是 Trace 能够无损恢复 Session 的前提之一。
+这个负载对 PenguinHarness 完全不透明:全链路原样透传、原样存储。部分模型回放历史时要求它逐字节一致,任何改写或丢失都会破坏兼容性。这也是 Trace 能无损恢复 Session 的前提之一。
-## 协议的三种职责
+## 各通道的消息子集
-| 场景 | 使用的子集 |
+| 通道 | 使用的子集 |
| --- | --- |
-| SDK 边界(`session.run` 输出) | 完整 `model_msg` + 流式 `partial_*` + 全部 `event_msg` |
-| Trace 落盘 | `session_meta` + 完整 `model_msg` + 全部 `event_msg`(不存分片与 `origin` 消息) |
-| Server SSE 推送 | 与 SDK 边界一致,原样单行 JSON,见 [Server API](/server-api) |
+| SDK 边界(`session.run` 的输出) | 完整 `model_msg` + 流式 `partial_*` + 全部 `event_msg` |
+| 落盘的 Trace | `session_meta` + 完整 `model_msg` + 全部 `event_msg`(不存分片,也不存带 `origin` 的消息) |
+| Server 的 SSE 推送 | 与 SDK 边界相同,原样的单行 JSON,见 [Server API](/server-api) |
-消息沿这些通道传递的机制与顺序保证,见[消息流转与时序](/message-flow)。
+消息沿这些通道传递的机制与各项顺序保证,见[消息流转与时序](/message-flow)。
## 构造与判别
-`@prismshadow/penguin-core` 导出全部类型、每种消息的构造函数(`builders.ts`:`userText`、`assistantText`、`toolCall`、`toolCallOutput`、`partialText`、`tokenUsage`、`withOrigin`、`emptyTokenCounts`、`addTokenCounts` 等)与运行时判别函数(`isCompleteModelMessage`、`isPartialPayload`、`isModelMessage`、`isEventMessage`、`isSessionMeta`):
+`@prismshadow/penguin-core` 导出全部协议类型,此外还有:
+
+- `builders.ts` 里每种消息的构造函数:`userText`、`assistantText`、`toolCall`、`toolCallOutput`、`partialText`、`tokenUsage`、`withOrigin`、`emptyTokenCounts`、`addTokenCounts` 等;
+- 运行时判别函数:`isCompleteModelMessage`、`isPartialPayload`、`isModelMessage`、`isEventMessage`、`isSessionMeta`。
```ts
import { userText, isCompleteModelMessage } from "@prismshadow/penguin-core";
-const prompt = userText("列出当前目录的文件");
+const prompt = userText("List the files in the current directory");
// { timestamp: "…", type: "model_msg", payload: { type: "text", role: "user", text: "…" } }
```
diff --git a/packages/docs/content/quickstart-cli.en.md b/packages/docs/content/quickstart-cli.en.md
index 8dd5ab04..e76984a4 100644
--- a/packages/docs/content/quickstart-cli.en.md
+++ b/packages/docs/content/quickstart-cli.en.md
@@ -1,13 +1,19 @@
---
title: CLI and Web App
-description: One line installs penguin; configure a model and open the browser interface with penguin web — with the full installation reference.
+description: Install the penguin command, configure a model, open the Web App, and run your first Task from the terminal or the browser.
---
-One line installs `penguin`; `penguin web` then opens the same interface as the [desktop app](/quickstart-desktop) in your browser. The online installers bundle an official Node.js runtime — unpack and run, no local Node needed.
+Install the `penguin` command with one line, configure a model, and run your first Task from the terminal or the browser. `penguin web` opens the same interface as the [desktop app](/quickstart-desktop), in your browser.
-## Install
+## Before you begin
-Pick your platform. The first two bundle their own Node.js runtime; the npm route needs Node.js >= 24 already installed.
+- Linux or macOS (x64 or arm64), or Windows 10 or later (x64) with PowerShell 5.1 or later. The installers for these platforms bundle an official Node.js runtime, so you don't need Node.js on the machine.
+- Node.js >= 24, if you install with npm, build from source, or use another platform.
+- An API key for one model provider.
+
+## Install the CLI
+
+Run the installer for your platform. The Linux / macOS and Windows installers bundle their own Node.js runtime; the npm route needs Node.js >= 24 already installed.
```bash tab="Linux / macOS"
curl -fsSL https://penguin.ooo/install.sh | sh
@@ -21,24 +27,28 @@ irm https://penguin.ooo/install.ps1 | iex
npm install -g @prismshadow/penguin-cli
```
-Verify the install:
+Check the install:
```bash
penguin -v
```
-Offline installs, installing from source, install locations, version pinning and Windows specifics are all in the [installation reference](#installation-reference) at the end of this page.
+The command prints the version you installed.
+
+For offline installs, building from source, install locations, version pinning and Windows details, see the [Installation reference](#installation-reference) at the end of this page.
## Configure a model
-Use the Models page in the Web UI, or the CLI:
+PenguinHarness ships with no model credentials, so add a model before your first Task. This command adds DeepSeek's `deepseek-flash` and makes it the default:
```bash
penguin config model add --provider deepseek --model-id deepseek-flash --api-key sk-... --set-default
```
-- A model is always referenced as a `(provider, model_id)` pair, so `--provider` and `--model-id` are both required — the Provider is never inferred from the model id. See [Models & Providers](/models) for the built-in groups.
-- The API key can also come from environment variables: when a model entry has no inline api_key, AgentHub (the LLM gateway library) reads variables such as `DEEPSEEK_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and `GEMINI_API_KEY`. A `.env` file in the working directory is loaded automatically.
+You can also add models later on the **Models** page of the Web App.
+
+- A model is always named by a `(provider, model_id)` pair, so `--provider` and `--model-id` are both required. PenguinHarness never infers the provider from the model id. See [Models & Providers](/models) for the built-in groups.
+- The API key can also come from an environment variable. When a model entry has no inline `api_key`, AgentHub (the LLM gateway library) reads variables such as `DEEPSEEK_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `GEMINI_API_KEY`. A `.env` file in the working directory is loaded automatically.
## Start the Web App
@@ -46,49 +56,70 @@ penguin config model add --provider deepseek --model-id deepseek-flash --api-key
penguin web
```
-The service runs at http://127.0.0.1:7364 and opens your browser (`--no-open` to skip). The account is `admin`, and it has no password yet: the server prints a first-login link in a framed notice, which opens the browser signed in so you can set one. The link works until a password exists (30-day ceiling — a restart prints a fresh one), and you can reopen it as often as you need. `penguin server` starts the same process headless.
+The service starts at http://127.0.0.1:7364 and opens your browser. Add `--no-open` to skip opening the browser. `penguin server` starts the same process headless.
+
+The account is `admin`, and it has no password yet. The server prints a first-login link in a framed notice. Open the link: the browser signs in, and you set a password.
+
+> [!NOTE]
+> The first-login link works until a password is set, for at most 30 days. You can open it as often as you need, and a restart prints a fresh one.
+
+To find your way around the interface, see [Web App](/web-app).
-The [Web App Guide](/web-app) covers the interface in full.
+## Run your first Task
-## One-shot run
+Run a single Task from the terminal, or start a chat. Both work the same way underneath, described in [How terminal Sessions work](#how-terminal-sessions-work).
+
+### Run a single Task
```bash
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.
+The command streams the agent's work and exits when the Task ends. The Task runs in the current directory, which becomes its Workspace. Pass `--workspace /path` to use another directory; it must already exist.
-## Interactive chat
+### Chat in the terminal
```bash
penguin chat
```
-- Each input line starts a Task.
-- `/compact` compacts the context; `/clear` starts a fresh Session (the old one stays resumable); `/exit` or `/quit` quits; Ctrl-C interrupts the running Task.
-- On exit it prints a `penguin chat --resume <sessionId>` hint for resuming this Session; `--resume` without an id resumes the Agent's latest Session.
+Each line you enter starts a Task. While chatting:
-The full command and option list is in the [CLI Reference](/cli).
+- `/compact` compacts the context.
+- `/clear` starts a fresh Session. The old one can still be resumed.
+- `/exit` or `/quit` quits.
+- Ctrl-C interrupts the running Task.
-## Installation reference
+When you quit, the chat prints a `penguin chat --resume <sessionId>` command that resumes this Session. `--resume` without an id resumes the agent's latest Session.
-The three commands above cover nearly every case; the rest of the options and details follow.
+### How terminal Sessions work
-### Requirements
+`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. On the local machine they need no login; the [CLI Reference](/cli) describes the connection rules.
+
+Everything these commands create also shows up in the Web App, and `penguin ls`, `penguin logs` and `penguin input` work with those Sessions from the terminal. The [CLI Reference](/cli) lists every command and option.
+
+## Installation reference
-- Linux / macOS (x64 or arm64): the install script ships platform tarballs with an official Node.js runtime bundled — no local Node needed.
-- Windows 10 or later (x64) with PowerShell 5.1+: the Windows installer ships `penguin-win32-x64.zip` with the runtime bundled — no local Node needed.
-- Other platforms, or installing via npm / from source: system Node.js >= 24.
+The install commands above cover nearly every case. This section holds the remaining options and details.
### Install script details
-The script downloads the matching `penguin-{linux,darwin}-{x64,arm64}.tar.gz` — the canonical installer bundle, sealing the program payload (with an official Node.js runtime), the payload's SHA256 checksum and this same installer. The download is verified against its published `.sha256`, then the sealed payload checksum is verified again before anything is staged. Other POSIX platforms do **not** fall back automatically: the script exits and asks you to install Node.js >= 24 and re-run with `--universal`, which selects the runtime-less `penguin-universal.tar.gz` bundle (Windows is served by its own installer, not by `--universal`).
+On Linux and macOS, the script downloads the bundle for your platform, `penguin-{linux,darwin}-{x64,arm64}.tar.gz`. This is the canonical installer bundle. It seals the program payload (with an official Node.js runtime), the payload's SHA256 checksum, and a copy of this same installer. The script verifies the download against its published `.sha256`, then verifies the sealed payload checksum before it stages anything. On Windows, the installer downloads `penguin-win32-x64.zip`, which bundles the runtime in the same way.
-The stable entry point defaults to `PENGUIN_DOWNLOAD_SOURCE=auto`: it resolves the target through an immutable OSS release directory only after that release has been completely uploaded and verified, and falls back to the matching GitHub Release if the metadata is unavailable. Which source then serves the package is measured, not assumed. The installer times a probe file on GitHub and keeps GitHub whenever it reaches 256 KB/s; only below that does it measure the OSS mirror, and it switches only when the mirror is more than 1.5x faster — a mirror that is merely a little quicker is not worth its bandwidth bill, and a slow GitHub download still resumes. Set `PENGUIN_DOWNLOAD_SPEED_PROBE=0` to skip the measurement, or `PENGUIN_DOWNLOAD_SOURCE` to `oss` or `github` to force either source. Normal installer output names the source without printing the mirror's full URL.
+Other POSIX platforms do not fall back automatically. The script exits and asks you to install Node.js >= 24 and run it again with `--universal`, which selects the runtime-less `penguin-universal.tar.gz` bundle. Windows has its own installer and does not use `--universal`.
-The `penguin.ooo` stable entry resolves the current stable version each time it runs. A standalone script downloaded from a versioned GitHub or OSS Release is stamped with that Release tag and defaults to the same version, keeping the installer and package format matched; set `PENGUIN_VERSION` (or `--version` on POSIX) to override it explicitly. To pin a version on Windows, set the env var before running the installer:
+### Download source and version
+
+The stable entry point defaults to `PENGUIN_DOWNLOAD_SOURCE=auto`. It resolves the target through an immutable OSS release directory, and only after that release has been completely uploaded and verified. If the metadata is unavailable, it falls back to the matching GitHub Release.
+
+Which source then serves the package is measured, not assumed:
+
+- The installer times a probe file on GitHub and keeps GitHub whenever the download reaches 256 KB/s.
+- Only below that does it measure the OSS mirror, and it switches only when the mirror is more than 1.5x faster. A mirror that is only a little quicker is not worth its bandwidth bill, and a slow GitHub download still resumes.
+
+Set `PENGUIN_DOWNLOAD_SPEED_PROBE=0` to skip the measurement, or set `PENGUIN_DOWNLOAD_SOURCE` to `oss` or `github` to force a source. The normal installer output names the source without printing the mirror's full URL.
+
+The `penguin.ooo` stable entry resolves the current stable version each time it runs. A standalone script downloaded from a versioned GitHub or OSS Release is stamped with that Release's tag and installs the same version by default, which keeps the installer and the package format matched. To override the version, set `PENGUIN_VERSION`, or pass `--version` on POSIX systems. On Windows, set the variable before you run the installer:
```powershell
$env:PENGUIN_VERSION = "vX.Y.Z"; irm https://penguin.ooo/install.ps1 | iex
@@ -96,25 +127,27 @@ $env:PENGUIN_VERSION = "vX.Y.Z"; irm https://penguin.ooo/install.ps1 | iex
### Offline install
-The same Release artifacts serve offline installation — there is no separate offline package. Download the file matching the target computer on a connected machine (`penguin-<target>.tar.gz`, or `penguin-win32-x64.zip` for Windows), transfer that one file, then extract it once.
+Offline installs use the same Release files as online installs; there is no separate offline package.
-On Windows, double-click `install.cmd`, or run:
+1. On a connected machine, download the file that matches the target computer: `penguin-<target>.tar.gz`, or `penguin-win32-x64.zip` for Windows.
+2. Transfer that one file to the target computer and extract it.
+3. In the extracted directory, run the installer. On Windows, double-click `install.cmd` or run `.\install.ps1`. On Linux and macOS, run `./install.sh`.
-```powershell
+```powershell tab="Windows"
.\install.ps1
```
-On Linux / macOS, run:
-
-```bash
+```bash tab="Linux / macOS"
./install.sh
```
-The extracted bundle keeps the installer, the program payload (`payload.tar.gz` / `payload.zip`) and the payload's `.sha256` together; the installer finds the sibling payload by itself, always verifies the sealed checksum and performs no network requests — no separate checksum file needs to be transferred. You can also point the installer at a file explicitly: `install.sh --archive <file>`, `PENGUIN_ARCHIVE=<file>`, `install.ps1 -ArchivePath <file>`, or `$env:PENGUIN_ARCHIVE` — accepting a Release bundle, its inner payload, or a pre-0.1.6 legacy program archive alike.
+The extracted bundle holds the installer, the program payload (`payload.tar.gz` / `payload.zip`) and the payload's `.sha256`. The installer finds the payload next to it by itself, always verifies the sealed checksum, and makes no network requests, so you don't need to transfer a separate checksum file.
-### From source
+You can also point the installer at a file explicitly: `install.sh --archive <file>`, `PENGUIN_ARCHIVE=<file>`, `install.ps1 -ArchivePath <file>`, or `$env:PENGUIN_ARCHIVE`. Each accepts a Release bundle, its inner payload, or a legacy program archive from before 0.1.6.
-Requires Node.js >= 24 and pnpm:
+### Install from source
+
+Building from source requires Node.js >= 24 and pnpm:
```bash
git clone https://github.com/Prism-Shadow/penguin-harness.git
@@ -122,56 +155,61 @@ cd penguin-harness
pnpm install && pnpm build
```
-After the build, run `pnpm penguin <args>` inside the repo as the dev runner, or use the globally linked `penguin` command. Dev entry points (`pnpm penguin`, `pnpm dev`, `pnpm desktop`) default to a separate data root `~/.penguin/dev-data`, while the linked/installed `penguin` keeps `~/.penguin/data`; export `PENGUIN_HOME` to override. The desktop dev run also uses its own app identity (`PenguinHarness-Dev`), so it can run alongside an installed desktop build without conflicts.
+After the build, run `pnpm penguin <args>` inside the repository as the dev runner, or use the globally linked `penguin` command.
+
+The dev entry points (`pnpm penguin`, `pnpm dev`, `pnpm desktop`) default to a separate data root, `~/.penguin/dev-data`, while the linked or installed `penguin` keeps `~/.penguin/data`. Set `PENGUIN_HOME` to override. The desktop dev run also uses its own app identity (`PenguinHarness-Dev`), so it can run alongside an installed desktop app without conflicts.
### Install location and options
| Item | Details |
| --- | --- |
-| Install dir | `~/.penguin` by default; override with the `PENGUIN_INSTALL_DIR` env var |
-| Command entry | A symlink `~/.local/bin/penguin` is created (the script warns if `~/.local/bin` is not on PATH) |
-| Version selection | `PENGUIN_VERSION=vX.Y.Z` env var, or the `--version vX.Y.Z` script flag; the stable entry defaults to the latest Release, while a versioned Release installer defaults to its own tag |
-| Download source | `PENGUIN_DOWNLOAD_SOURCE=auto` (default), `oss`, or `github`; auto times a probe file and keeps the free GitHub download unless the OSS mirror is clearly faster, falling back to the same version on the other source (`PENGUIN_DOWNLOAD_SPEED_PROBE=0` skips the measurement) |
-| Local archive | `PENGUIN_ARCHIVE=<file>` or `--archive <file>`; accepts a Release bundle (self-verifying via its sealed payload checksum) or a payload/legacy program archive with an adjacent `<file>.sha256` (renamed legacy files may use the platform asset's canonical `.sha256`) |
-| Integrity check | Always on: online downloads are verified against the published `.sha256`, and bundle payloads against the checksum sealed inside the bundle |
-| Upgrade | Re-run the install script; files are swapped atomically |
+| Install directory | `~/.penguin` by default; override it with the `PENGUIN_INSTALL_DIR` environment variable |
+| Command entry | A symlink, `~/.local/bin/penguin`. The script warns if `~/.local/bin` is not on `PATH` |
+| Version | The `PENGUIN_VERSION=vX.Y.Z` environment variable, or the `--version vX.Y.Z` script flag. The stable entry installs the latest Release by default; a versioned Release installer installs its own tag |
+| Download source | `PENGUIN_DOWNLOAD_SOURCE=auto` (default), `oss` or `github`. `auto` times a probe file and keeps the free GitHub download unless the OSS mirror is clearly faster, and falls back to the same version on the other source. `PENGUIN_DOWNLOAD_SPEED_PROBE=0` skips the measurement |
+| Local archive | `PENGUIN_ARCHIVE=<file>` or `--archive <file>`. Accepts a Release bundle, which verifies itself with its sealed payload checksum, or a payload or legacy program archive with a `<file>.sha256` next to it. A renamed legacy file may use the platform asset's canonical `.sha256` |
+| Integrity check | Always on. Online downloads are verified against the published `.sha256`, and bundle payloads against the checksum sealed inside the bundle |
+| Upgrade | Run the install script again; files are swapped atomically |
-Script flags go after `sh -s --`, e.g. `curl -fsSL https://penguin.ooo/install.sh | sh -s -- --universal`.
+Script flags go after `sh -s --`, for example `curl -fsSL https://penguin.ooo/install.sh | sh -s -- --universal`.
### Windows specifics
| Item | Details |
| --- | --- |
-| Install dir | `%USERPROFILE%\.penguin` by default; override with the `PENGUIN_INSTALL_DIR` env var |
-| Command entry | the `bin\penguin.cmd` launcher (deliberately no `.ps1` launcher — batch files are exempt from the PowerShell execution policy, so `penguin` works even under the default Restricted policy); the installer adds `%USERPROFILE%\.penguin\bin` to your **user** Path and broadcasts the change — open a **new terminal window** once (a new tab of an already-running terminal keeps the old Path) |
-| Version pin | `$env:PENGUIN_VERSION = "vX.Y.Z"` before running the installer |
-| Local archive | `$env:PENGUIN_ARCHIVE = "<file>"` or `-ArchivePath <file>`; accepts the Release bundle (self-verifying via its sealed payload checksum) or a payload/legacy zip with an adjacent `<file>.sha256` (renamed legacy files may use `penguin-win32-x64.zip.sha256`) |
-| Integrity check | Always on: online downloads are verified against the published `.sha256`, and bundle payloads against the checksum sealed inside the bundle |
-| Upgrade | Re-run the installer; it swaps `bin`/`lib`/`web`/`node` and never touches `data` |
+| Install directory | `%USERPROFILE%\.penguin` by default; override it with the `PENGUIN_INSTALL_DIR` environment variable |
+| Command entry | The `bin\penguin.cmd` launcher. There is deliberately no `.ps1` launcher: batch files are exempt from the PowerShell execution policy, so `penguin` works even under the default Restricted policy. The installer adds `%USERPROFILE%\.penguin\bin` to your **user** Path and broadcasts the change. Open a **new terminal window** once; a new tab of an already-running terminal keeps the old Path |
+| Version pin | Set `$env:PENGUIN_VERSION = "vX.Y.Z"` before running the installer |
+| Local archive | `$env:PENGUIN_ARCHIVE = "<file>"` or `-ArchivePath <file>`. Accepts the Release bundle, which verifies itself with its sealed payload checksum, or a payload or legacy zip with a `<file>.sha256` next to it. A renamed legacy file may use `penguin-win32-x64.zip.sha256` |
+| Integrity check | Always on. Online downloads are verified against the published `.sha256`, and bundle payloads against the checksum sealed inside the bundle |
+| Upgrade | Run the installer again. It swaps `bin`/`lib`/`web`/`node` and never touches `data` |
+
+Other differences on Windows:
-- **Agent shell**: on Windows, the agent's `exec_command` runs in a POSIX shell, for compatibility with skills written for one. It picks, in order: `bash` on PATH (your own [Git for Windows](https://gitforwindows.org/), preferred because it carries the full MSYS userland); then the **bundled bash** — the Windows zip ships MinGit under `git\`, so a machine with no Git for Windows still gets a POSIX shell, about sixty core utilities and `git.exe`; then PowerShell (`pwsh`, then `powershell`). The PowerShell fallback is only reached by npm installs, which bundle nothing. The `PENGUIN_SHELL` env var overrides the pick; the session's system prompt tells the model which shell is active. The bundled shell's licensing is recorded in [THIRD-PARTY-NOTICES.md](https://github.com/Prism-Shadow/penguin-harness/blob/main/THIRD-PARTY-NOTICES.md).
-- **Ctrl-C semantics**: on Windows, sending Ctrl-C to a running command session (`input_command` with `"\u0003"`) terminates the whole command session tree instead of interrupting the foreground command — Windows cannot deliver a console Ctrl-C to a piped child process, so the interrupt degrades to a hard tree kill.
-- **In-place update**: `penguin update` is not yet supported on Windows — upgrade by re-running the installer above.
-- **Config file permissions**: on POSIX, config/credential files are written with `0600` (owner-only) permissions; Windows has no such mode bits, so files fall under your profile's default NTFS ACLs.
-- If PowerShell refuses to run `penguin` with "running scripts is disabled", the blocked file is a `penguin.ps1` launcher — from an install older than 0.1.6 (re-run the installer: upgrades replace `bin\` and remove it) or generated by an npm global install (call `penguin.cmd` explicitly, or allow local scripts with `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`). The packaged install itself ships only `penguin.cmd`, which runs under any execution policy.
+- **Agent shell**: the agent's `exec_command` runs in a POSIX shell, so Skills written for one keep working. The shell is picked in this order: `bash` on PATH, which is preferred because your own [Git for Windows](https://gitforwindows.org/) carries the full MSYS userland; then the **bundled bash**, since the Windows zip ships MinGit under `git\` and gives a machine without Git for Windows a POSIX shell, about sixty core utilities and `git.exe`; then PowerShell (`pwsh`, then `powershell`). Only npm installs, which bundle nothing, reach the PowerShell fallback. The `PENGUIN_SHELL` environment variable overrides the pick, and the Session's system prompt tells the model which shell is active. The bundled shell's licensing is recorded in [THIRD-PARTY-NOTICES.md](https://github.com/Prism-Shadow/penguin-harness/blob/main/THIRD-PARTY-NOTICES.md).
+- **Ctrl-C**: sending Ctrl-C to a running command session (`input_command` with `"\u0003"`) terminates the whole command session tree instead of interrupting the foreground command. Windows cannot deliver a console Ctrl-C to a piped child process, so the interrupt becomes a hard kill of the tree.
+- **In-place update**: `penguin update` is not yet supported on Windows. To upgrade, run the installer again.
+- **Config file permissions**: on POSIX systems, config and credential files are written with `0600` (owner-only) permissions. Windows has no such mode bits, so these files fall under your profile's default NTFS ACLs.
+- **"running scripts is disabled"**: if PowerShell refuses to run `penguin` with this error, the blocked file is a `penguin.ps1` launcher. It comes either from an install older than 0.1.6, which you fix by running the installer again (the upgrade replaces `bin\` and removes it), or from an npm global install, where you call `penguin.cmd` explicitly or allow local scripts with `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`. The packaged install ships only `penguin.cmd`, which runs under any execution policy.
-### Data directory
+### Data root
-The data directory defaults to `~/.penguin/data` (`%USERPROFILE%\.penguin\data` on Windows) — under the install home, but never modified by install or upgrade — and is overridable with the `PENGUIN_HOME` env var. Model configuration, Session records, and other data are preserved across upgrades.
+The data root is `~/.penguin/data` by default (`%USERPROFILE%\.penguin\data` on Windows). It sits under the install directory, but installing and upgrading never modify it. Set the `PENGUIN_HOME` environment variable to use another directory. Model configuration, Session records and other data are kept across upgrades.
### Published npm packages
| Package | Description |
| --- | --- |
-| `@prismshadow/penguin-cli` | Command-line tool providing the `penguin` command |
-| `@prismshadow/penguin-core` | SDK for creating Agents and Sessions programmatically |
-| `@prismshadow/penguin-server` | Web service, including the Web UI assets |
-| `@penguinharness/*` | The built-in plugins, one package each (skills and session hooks); core loads them |
+| `@prismshadow/penguin-cli` | Command-line tool that provides the `penguin` command |
+| `@prismshadow/penguin-core` | SDK for creating agents and Sessions from code |
+| `@prismshadow/penguin-server` | Web service, including the Web App assets |
+| `@penguinharness/*` | The built-in plugins, one package each (Skills and session hooks); core loads them |
All packages are published under the Apache-2.0 license.
## Next steps
-- [Web App Guide](/web-app): use PenguinHarness from the browser.
-- [CLI Reference](/cli): the full list of commands and options.
+- [Web App](/web-app): use PenguinHarness from the browser.
+- [CLI Reference](/cli): every command and option.
+- [Update PenguinHarness](/updates): check your version and upgrade.
- [SDK](/quickstart-sdk): embed the engine in your own program.
diff --git a/packages/docs/content/quickstart-cli.zh.md b/packages/docs/content/quickstart-cli.zh.md
index 0f50b7ca..f9c15cd9 100644
--- a/packages/docs/content/quickstart-cli.zh.md
+++ b/packages/docs/content/quickstart-cli.zh.md
@@ -1,13 +1,19 @@
---
-title: 命令行与 Web 应用
-description: 一行命令装出 penguin,配置模型,用 penguin web 打开浏览器界面——附完整安装参考。
+title: 命令行与 Web App
+description: 安装 penguin 命令,配置模型,打开 Web App,在终端或浏览器里跑通第一个 Task。
---
-一行命令装出 `penguin`,再用 `penguin web` 在浏览器里打开与[桌面端应用](/quickstart-desktop)相同的界面。在线安装器自带官方 Node.js 运行时,解压即用,本机无需安装 Node。
+一行命令装好 `penguin`,配置模型,然后在终端或浏览器里跑通第一个 Task。`penguin web` 会在浏览器里打开与[桌面应用](/quickstart-desktop)相同的界面。
-## 安装
+## 开始之前
-选择你的平台。前两种自带 Node.js 运行时;npm 方式需要本机已有 Node.js >= 24。
+- Linux 或 macOS(x64 或 arm64),或 Windows 10 及以上(x64)且 PowerShell 为 5.1 或更高版本。这些平台的安装器自带官方 Node.js 运行时,机器上不需要另装 Node.js。
+- Node.js >= 24:用 npm 安装、从源码构建或在其他平台上使用时才需要。
+- 一个模型供应商的 API Key。
+
+## 安装 CLI
+
+按平台运行对应的安装命令。Linux / macOS 与 Windows 的安装器自带 Node.js 运行时;npm 方式要求机器上已经装有 Node.js >= 24。
```bash tab="Linux / macOS"
curl -fsSL https://penguin.ooo/install.sh | sh
@@ -21,24 +27,28 @@ irm https://penguin.ooo/install.ps1 | iex
npm install -g @prismshadow/penguin-cli
```
-安装完成后验证:
+验证安装:
```bash
penguin -v
```
-离线安装、源码安装、安装目录、版本固定与 Windows 细节,见本页末尾的[安装参考](#安装参考)。
+命令会输出刚装好的版本号。
+
+离线安装、从源码安装、安装位置、版本固定与 Windows 细节,见本页末尾的[安装参考](#安装参考)。
## 配置模型
-可以在 Web UI 的模型页完成,也可以用 CLI:
+PenguinHarness 不内置任何模型凭据,跑第一个 Task 之前要先添加模型。下面这条命令添加 DeepSeek 的 `deepseek-flash`,并设为默认模型:
```bash
penguin config model add --provider deepseek --model-id deepseek-flash --api-key sk-... --set-default
```
-- 模型引用始终是 `(provider, model_id)` 二元组,因此 `--provider` 与 `--model-id` 均为必填——Provider 绝不由模型 id 推断。内置分组见[模型与 Provider](/models)。
-- API Key 也可以来自环境变量:当模型条目没有内联 api_key 时,LLM 网关库 AgentHub 会读取 `DEEPSEEK_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY`、`GEMINI_API_KEY` 等变量;工作目录下的 `.env` 会被自动加载。
+之后也可以在 Web App 的**模型库**页面添加模型。
+
+- 模型始终以 `(provider, model_id)` 二元组引用,因此 `--provider` 与 `--model-id` 都必填。PenguinHarness 不会根据模型 id 推断供应商。内置分组见[模型与 Provider](/models)。
+- API Key 也可以来自环境变量。模型条目没有内联 `api_key` 时,LLM 网关库 AgentHub 会读取 `DEEPSEEK_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY`、`GEMINI_API_KEY` 等变量。工作目录下的 `.env` 文件会自动加载。
## 启动 Web App
@@ -46,49 +56,70 @@ penguin config model add --provider deepseek --model-id deepseek-flash --api-key
penguin web
```
-服务运行在 http://127.0.0.1:7364 并自动打开浏览器(`--no-open` 跳过)。账号是 `admin`,此时它还没有密码:服务端会以边框提示打印一条首次登录链接,打开即以登录态进入,随后设置密码即可。在密码被设置之前该链接一直有效(上限 30 天,重启会打印新的),可以重复打开。`penguin server` 启动同一进程的 headless 版本。
+服务在 http://127.0.0.1:7364 启动,并自动打开浏览器;加 `--no-open` 则不打开浏览器。`penguin server` 以 headless 方式启动同一个进程。
+
+账号是 `admin`,此时还没有密码。服务端会以带边框的提示打印一条首次登录链接。打开链接,浏览器即以登录状态进入,随后设置密码。
+
+> [!NOTE]
+> 首次登录链接在设置密码之前一直有效,最长 30 天。链接可以反复打开,重启服务会打印一条新链接。
+
+界面的整体介绍见 [Web App](/web-app)。
-界面的完整说明见 [Web App 指南](/web-app)。
+## 跑通第一个 Task
-## 单次运行
+可以在终端里运行单个 Task,也可以开启一段对话。两种方式的底层机制相同,见[终端会话的工作方式](#终端会话的工作方式)。
+
+### 运行单个 Task
```bash
-penguin run -m "创建 hello.txt,内容为 Hello, Penguin"
+penguin run -m "Create hello.txt containing Hello, Penguin"
```
-Workspace 默认为当前目录,可用 `--workspace /path` 指定;目标目录必须已存在。
-
-`run`、`chat` 与其余会话命令都是服务端的瘦客户端:本机有服务器运行时直接附着,没有时静默拉起一个(连接本机无需登录——连接规则见 [CLI 参考](/cli))。它们创建的一切同样出现在 Web App 里,也可以在终端用 `penguin ls` / `penguin logs` / `penguin input` 继续操作这些会话。
+命令会流式输出 Agent 的执行过程,Task 结束后退出。Task 在当前目录下运行,当前目录就是它的 Workspace。要换一个目录,传入 `--workspace /path`,目录必须已经存在。
-## 交互式对话
+### 在终端里对话
```bash
penguin chat
```
-- 每输入一行即发起一个 Task。
-- `/compact` 压缩上下文;`/clear` 开启全新 Session(原会话仍可恢复);`/exit` 或 `/quit` 退出;Ctrl-C 中断正在运行的 Task。
-- 退出时会打印 `penguin chat --resume <sessionId>` 提示,用于恢复本次 Session;`--resume` 不带 id 时恢复该 Agent 最近的 Session。
+每输入一行就发起一个 Task。对话中可以使用:
-完整命令与选项见 [CLI 参考](/cli)。
+- `/compact`:压缩上下文。
+- `/clear`:开启一个全新的 Session,原来的 Session 之后仍可恢复。
+- `/exit` 或 `/quit`:退出。
+- Ctrl-C:中断正在运行的 Task。
-## 安装参考
+退出时会打印一条 `penguin chat --resume <sessionId>` 命令,用它可以恢复这个 Session。`--resume` 不带 id 时,恢复这个 Agent 最近的 Session。
-上面的三条安装命令覆盖绝大多数情况;以下是其余选项与细节。
+### 终端会话的工作方式
-### 系统要求
+`run`、`chat` 以及其他会话命令都是服务端的瘦客户端:本机已有服务端在运行时直接连上它,没有时静默启动一个。连接本机的服务端无需登录,连接规则见 [CLI 参考](/cli)。
-- Linux / macOS(x64 或 arm64):安装脚本提供内置官方 Node.js 运行时的平台压缩包,解压即用,无需本机安装 Node。
-- Windows 10 及以上(x64),PowerShell 5.1+:Windows 安装器提供内置运行时的 `penguin-win32-x64.zip`,同样无需本机安装 Node。
-- 其他平台,或通过 npm / 源码安装:需要系统 Node.js >= 24。
+这些命令创建的内容同样会出现在 Web App 里;在终端里也可以用 `penguin ls`、`penguin logs`、`penguin input` 继续操作这些会话。全部命令与选项见 [CLI 参考](/cli)。
+
+## 安装参考
+
+上面的安装命令覆盖了绝大多数情况,本节是其余的选项与细节。
### 安装脚本细节
-脚本按平台下载 `penguin-{linux,darwin}-{x64,arm64}.tar.gz`——即标准安装包:包内封入程序负载(捆绑官方 Node.js 运行时)、负载的 SHA256 校验文件与同一个安装器。下载后先对照 Release 发布的 `.sha256` 校验外层,再校验包内封入的负载 checksum,然后才进入暂存安装。其他 POSIX 平台**不会自动回退**:脚本会退出并提示先安装 Node.js >= 24、再携带 `--universal` 重新执行,改用不含运行时的 `penguin-universal.tar.gz` 安装包(Windows 使用专属安装器,而不是 `--universal`)。
+在 Linux 和 macOS 上,脚本会下载对应平台的安装包 `penguin-{linux,darwin}-{x64,arm64}.tar.gz`。这是标准安装包,里面封入了程序负载(含官方 Node.js 运行时)、负载的 SHA256 校验值,以及这份安装器本身。脚本先对照发布的 `.sha256` 校验下载的文件,再校验封入的负载校验值,之后才开始暂存安装。在 Windows 上,安装器下载的是 `penguin-win32-x64.zip`,同样自带运行时。
+
+其他 POSIX 平台不会自动回退:脚本会退出,提示先安装 Node.js >= 24,再加上 `--universal` 重新运行,改用不含运行时的 `penguin-universal.tar.gz` 安装包。Windows 有自己的安装器,不使用 `--universal`。
-稳定入口默认使用 `PENGUIN_DOWNLOAD_SOURCE=auto`:先经已完整上传并验证的 OSS 不可变版本目录确定目标版本,元数据不可用时回退到同一版本的 GitHub Release。至于由哪个源提供安装包,则由实测决定,而非预设:安装器先对 GitHub 上的测速文件计时,达到 256 KB/s 即保持 GitHub;只有低于该值时才测量 OSS 镜像,且仅当镜像快出 1.5 倍以上才切换——仅快一点的镜像不值得其带宽成本,而较慢的 GitHub 下载仍可续传。设置 `PENGUIN_DOWNLOAD_SPEED_PROBE=0` 可跳过测速,设置 `PENGUIN_DOWNLOAD_SOURCE` 为 `oss` 或 `github` 可强制指定来源。安装器只显示来源名称,不在常规输出中打印镜像的完整 URL。
+### 下载来源与版本
-`penguin.ooo` 稳定入口每次执行时都会解析当前稳定版本。从 GitHub 或 OSS 的版本化 Release 中直接下载的独立安装脚本会写入该 Release tag,并默认安装同一版本,确保安装器与安装包格式匹配;如需覆盖,可显式设置 `PENGUIN_VERSION`(POSIX 也可使用 `--version`)。Windows 上固定版本,在运行安装器前设置环境变量:
+稳定入口默认使用 `PENGUIN_DOWNLOAD_SOURCE=auto`。它通过 OSS 上不可变的版本目录确定目标版本,而且只认已经完整上传并通过验证的版本;元数据不可用时,回退到对应的 GitHub Release。
+
+安装包实际从哪个来源下载,由实测决定,而不是预设:
+
+- 安装器先对 GitHub 上的测速文件计时,速度达到 256 KB/s 就继续用 GitHub。
+- 只有低于这个速度,才会测量 OSS 镜像,并且镜像要快 1.5 倍以上才会切换。只快一点的镜像不值得为它支付带宽费用,GitHub 下载即使慢,也能断点续传。
+
+设置 `PENGUIN_DOWNLOAD_SPEED_PROBE=0` 可以跳过测速,把 `PENGUIN_DOWNLOAD_SOURCE` 设为 `oss` 或 `github` 可以强制指定来源。安装器的常规输出只写明来源,不打印镜像的完整 URL。
+
+`penguin.ooo` 稳定入口每次运行时都会解析当前的稳定版本。从 GitHub 或 OSS 某个版本的 Release 里单独下载的安装脚本,会写入所属 Release 的 tag,默认安装同一版本,从而保证安装器与安装包格式相互匹配。要改用其他版本,设置 `PENGUIN_VERSION`;在 POSIX 系统上也可以传入 `--version`。在 Windows 上,先设置环境变量,再运行安装器:
```powershell
$env:PENGUIN_VERSION = "vX.Y.Z"; irm https://penguin.ooo/install.ps1 | iex
@@ -96,25 +127,27 @@ $env:PENGUIN_VERSION = "vX.Y.Z"; irm https://penguin.ooo/install.ps1 | iex
### 离线安装
-离线安装使用与在线安装相同的 Release 制品——不再有单独的离线包。先在可联网电脑上下载与目标电脑匹配的那一个文件(`penguin-<target>.tar.gz`,Windows 为 `penguin-win32-x64.zip`),传输后解压一次。
+离线安装使用的就是在线安装的 Release 文件,没有单独的离线包。
-Windows 上双击 `install.cmd`,或执行:
+1. 在一台能联网的电脑上,下载与目标电脑匹配的文件:`penguin-<target>.tar.gz`,Windows 为 `penguin-win32-x64.zip`。
+2. 把这一个文件传到目标电脑上并解压。
+3. 在解压出的目录里运行安装器。Windows 上双击 `install.cmd`,或运行 `.\install.ps1`;Linux 和 macOS 上运行 `./install.sh`。
-```powershell
+```powershell tab="Windows"
.\install.ps1
```
-Linux / macOS 上执行:
-
-```bash
+```bash tab="Linux / macOS"
./install.sh
```
-解压后的目录同时包含安装器、程序负载(`payload.tar.gz` / `payload.zip`)与负载的 `.sha256`;安装器会自行找到同目录负载,始终校验包内封入的 checksum,且不发起任何网络请求——无需另外传输校验文件。也可以显式指定本地文件:`install.sh --archive <file>`、`PENGUIN_ARCHIVE=<file>`、`install.ps1 -ArchivePath <file>` 或 `$env:PENGUIN_ARCHIVE`——Release 安装包、其内部负载或 0.1.6 之前的旧版程序压缩包均可。
+解压后的目录里同时有安装器、程序负载(`payload.tar.gz` / `payload.zip`)和负载的 `.sha256`。安装器会自己找到同目录下的负载,始终校验封入的校验值,全程不发起网络请求,因此不需要另外传输校验文件。
+
+也可以显式指定本地文件:`install.sh --archive <file>`、`PENGUIN_ARCHIVE=<file>`、`install.ps1 -ArchivePath <file>` 或 `$env:PENGUIN_ARCHIVE`。这几种方式都接受 Release 安装包、其中的负载,以及 0.1.6 之前的旧版程序压缩包。
-### 源码安装
+### 从源码安装
-需要 Node.js >= 24 与 pnpm:
+从源码构建需要 Node.js >= 24 与 pnpm:
```bash
git clone https://github.com/Prism-Shadow/penguin-harness.git
@@ -122,19 +155,21 @@ cd penguin-harness
pnpm install && pnpm build
```
-构建完成后,在仓库内用 `pnpm penguin <args>` 作为开发入口运行,或使用全局链接的 `penguin` 命令。开发入口(`pnpm penguin`、`pnpm dev`、`pnpm desktop`)默认使用独立数据根目录 `~/.penguin/dev-data`,全局链接或安装的 `penguin` 仍使用 `~/.penguin/data`;可通过环境变量 `PENGUIN_HOME` 覆盖。桌面开发运行还会使用独立的应用标识(`PenguinHarness-Dev`),因此可以与已安装的桌面版同时运行、互不冲突。
+构建完成后,可以在仓库内用 `pnpm penguin <args>` 以开发方式运行,也可以使用全局链接的 `penguin` 命令。
+
+开发入口(`pnpm penguin`、`pnpm dev`、`pnpm desktop`)默认使用独立的数据目录 `~/.penguin/dev-data`,全局链接或正式安装的 `penguin` 仍使用 `~/.penguin/data`,设置 `PENGUIN_HOME` 可以覆盖。桌面应用的开发运行还使用独立的应用标识(`PenguinHarness-Dev`),因此可以和已安装的桌面应用同时运行,互不冲突。
### 安装位置与选项
| 项目 | 说明 |
| --- | --- |
-| 安装目录 | 默认 `~/.penguin`,可用环境变量 `PENGUIN_INSTALL_DIR` 覆盖 |
-| 命令入口 | 创建符号链接 `~/.local/bin/penguin`(若 `~/.local/bin` 不在 PATH 上,脚本会给出提示) |
-| 版本选择 | 环境变量 `PENGUIN_VERSION=vX.Y.Z`,或脚本参数 `--version vX.Y.Z`;稳定入口默认安装最新 Release,版本化 Release 安装器默认安装自身 tag |
-| 下载来源 | `PENGUIN_DOWNLOAD_SOURCE=auto`(默认)、`oss` 或 `github`;自动模式对测速文件计时,除非 OSS 镜像明显更快,否则保持免费的 GitHub 下载,并按同一版本回退到另一个源(`PENGUIN_DOWNLOAD_SPEED_PROBE=0` 可跳过测速) |
-| 本地压缩包 | `PENGUIN_ARCHIVE=<file>` 或 `--archive <file>`;接受 Release 安装包(凭包内封入的负载 checksum 自校验),或旁边带 `<file>.sha256` 的负载 / 旧版程序压缩包(重命名的旧版文件可用平台标准名称的 `.sha256`) |
-| 完整性校验 | 始终进行:在线下载对照发布的 `.sha256` 校验,安装包负载对照包内封入的 checksum 校验 |
-| 升级 | 重新执行安装脚本即可,文件原子替换 |
+| 安装目录 | 默认为 `~/.penguin`,可用环境变量 `PENGUIN_INSTALL_DIR` 覆盖 |
+| 命令入口 | 符号链接 `~/.local/bin/penguin`。如果 `~/.local/bin` 不在 `PATH` 中,脚本会给出提示 |
+| 版本 | 环境变量 `PENGUIN_VERSION=vX.Y.Z`,或脚本参数 `--version vX.Y.Z`。稳定入口默认安装最新的 Release,某个版本的 Release 安装器默认安装自身的 tag |
+| 下载来源 | `PENGUIN_DOWNLOAD_SOURCE=auto`(默认)、`oss` 或 `github`。`auto` 会对测速文件计时,除非 OSS 镜像明显更快,否则保持免费的 GitHub 下载,并可回退到另一个来源的同一版本。`PENGUIN_DOWNLOAD_SPEED_PROBE=0` 跳过测速 |
+| 本地压缩包 | `PENGUIN_ARCHIVE=<file>` 或 `--archive <file>`。接受 Release 安装包(凭封入的负载校验值自行校验),或旁边带有 `<file>.sha256` 的负载、旧版程序压缩包。重命名过的旧版文件可以使用平台标准文件名的 `.sha256` |
+| 完整性校验 | 始终开启。在线下载对照发布的 `.sha256` 校验,安装包里的负载对照包内封入的校验值校验 |
+| 升级 | 重新运行安装脚本,文件以原子方式替换 |
脚本参数写在 `sh -s --` 之后,例如 `curl -fsSL https://penguin.ooo/install.sh | sh -s -- --universal`。
@@ -142,36 +177,39 @@ pnpm install && pnpm build
| 项目 | 说明 |
| --- | --- |
-| 安装目录 | 默认 `%USERPROFILE%\.penguin`,可用环境变量 `PENGUIN_INSTALL_DIR` 覆盖 |
-| 命令入口 | `bin\penguin.cmd` 启动器(特意不带 `.ps1` 启动器——批处理不受 PowerShell 执行策略限制,默认 Restricted 策略下 `penguin` 也能直接运行);安装器会把 `%USERPROFILE%\.penguin\bin` 加入**用户** Path 并广播变更——请**新开一个终端窗口**(已开终端的新标签页仍沿用旧 Path) |
-| 版本固定 | 运行安装器前设置 `$env:PENGUIN_VERSION = "vX.Y.Z"` |
-| 本地压缩包 | `$env:PENGUIN_ARCHIVE = "<file>"` 或 `-ArchivePath <file>`;接受 Release 安装包(凭包内封入的负载 checksum 自校验),或旁边带 `<file>.sha256` 的负载 / 旧版 zip(重命名的旧版文件可用 `penguin-win32-x64.zip.sha256`) |
-| 完整性校验 | 始终进行:在线下载对照发布的 `.sha256` 校验,安装包负载对照包内封入的 checksum 校验 |
-| 升级 | 重新运行安装器;只替换 `bin`/`lib`/`web`/`node`,绝不触碰 `data` |
-
-- **Agent shell**:Windows 上 `exec_command` 在 POSIX shell 中执行,以兼容面向 POSIX 编写的技能生态。选择顺序为:PATH 上的 `bash`(你自己安装的 [Git for Windows](https://gitforwindows.org/),优先,因为它带完整的 MSYS 工具集);其次是**内置 bash**——Windows zip 在 `git\` 下自带 MinGit,因此未安装 Git for Windows 的机器同样有 POSIX shell、约六十个核心工具和 `git.exe`;最后才是 PowerShell(先 `pwsh` 后 `powershell`)。只有经 npm 安装(不含内置包)才会走到 PowerShell。环境变量 `PENGUIN_SHELL` 可强制指定;会话的系统提示词会告知模型当前 shell。内置 shell 的许可信息见 [THIRD-PARTY-NOTICES.md](https://github.com/Prism-Shadow/penguin-harness/blob/main/THIRD-PARTY-NOTICES.md)。
-- **Ctrl-C 语义**:Windows 上向运行中的命令会话发送 Ctrl-C(`input_command` 传 `"\u0003"`)会终止整棵命令会话进程树,而不是中断前台命令——Windows 无法向管道子进程投递控制台 Ctrl-C,中断因此退化为整树强杀。
-- **就地更新**:`penguin update` 暂不支持 Windows——升级请重新运行上面的安装器。
-- **配置文件权限**:POSIX 上配置/凭据文件以 `0600`(仅属主可读写)写入;Windows 没有对应的权限位,文件遵循你用户目录的默认 NTFS ACL。
-- 如果 PowerShell 提示 "running scripts is disabled" 而无法运行 `penguin`,被拦下的是某个 `penguin.ps1` 启动器——来自 0.1.6 之前的旧安装(重新运行安装器即可:升级会整体替换 `bin\` 并移除它),或来自 npm 全局安装生成的 shim(可显式调用 `penguin.cmd`,或用 `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` 允许本地脚本)。安装包本身只带 `penguin.cmd`,任何执行策略下都能运行。
+| 安装目录 | 默认为 `%USERPROFILE%\.penguin`,可用环境变量 `PENGUIN_INSTALL_DIR` 覆盖 |
+| 命令入口 | 启动器 `bin\penguin.cmd`。特意不提供 `.ps1` 启动器:批处理文件不受 PowerShell 执行策略限制,所以在默认的 Restricted 策略下 `penguin` 也能运行。安装器会把 `%USERPROFILE%\.penguin\bin` 加入**用户** Path 并广播这一变更。之后请**新开一个终端窗口**,已在运行的终端即使新开标签页,也仍沿用旧的 Path |
+| 版本固定 | 运行安装器之前设置 `$env:PENGUIN_VERSION = "vX.Y.Z"` |
+| 本地压缩包 | `$env:PENGUIN_ARCHIVE = "<file>"` 或 `-ArchivePath <file>`。接受 Release 安装包(凭封入的负载校验值自行校验),或旁边带有 `<file>.sha256` 的负载、旧版 zip。重命名过的旧版文件可以使用 `penguin-win32-x64.zip.sha256` |
+| 完整性校验 | 始终开启。在线下载对照发布的 `.sha256` 校验,安装包里的负载对照包内封入的校验值校验 |
+| 升级 | 重新运行安装器。它只替换 `bin`/`lib`/`web`/`node`,从不改动 `data` |
+
+Windows 上还有以下不同:
+
+- **Agent shell**:Agent 的 `exec_command` 在 POSIX shell 中运行,这样面向 POSIX 编写的 Skill 可以照常工作。shell 的选择顺序是:首先是 PATH 上的 `bash`,优先使用它,因为你自己安装的 [Git for Windows](https://gitforwindows.org/) 带有完整的 MSYS 工具集;其次是**内置 bash**,Windows zip 在 `git\` 下自带 MinGit,没有安装 Git for Windows 的机器也能得到 POSIX shell、约六十个核心工具和 `git.exe`;最后是 PowerShell(先 `pwsh`,后 `powershell`)。只有 npm 安装不带任何内置组件,才会用到 PowerShell 这一兜底。环境变量 `PENGUIN_SHELL` 可以强制指定 shell,Session 的系统提示词会告诉模型当前使用的是哪个 shell。内置 shell 的许可信息见 [THIRD-PARTY-NOTICES.md](https://github.com/Prism-Shadow/penguin-harness/blob/main/THIRD-PARTY-NOTICES.md)。
+- **Ctrl-C**:向运行中的命令会话发送 Ctrl-C(`input_command` 传入 `"\u0003"`),会终止整棵命令会话进程树,而不是中断前台命令。Windows 无法把控制台 Ctrl-C 投递给通过管道连接的子进程,中断因此退化为强制结束整棵进程树。
+- **就地更新**:Windows 暂不支持 `penguin update`,升级请重新运行安装器。
+- **配置文件权限**:在 POSIX 系统上,配置文件与凭据文件以 `0600`(仅属主可读写)权限写入。Windows 没有这类权限位,这些文件遵循你用户目录的默认 NTFS ACL。
+- **「running scripts is disabled」**:PowerShell 报这个错误、拒绝运行 `penguin` 时,PowerShell 拦下的其实是某个 `penguin.ps1` 启动器。它可能来自 0.1.6 之前的旧安装,重新运行安装器即可(升级会替换 `bin\` 并删除它);也可能是 npm 全局安装生成的,这时可以显式调用 `penguin.cmd`,或用 `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` 允许运行本地脚本。安装包本身只带 `penguin.cmd`,在任何执行策略下都能运行。
### 数据目录
-数据目录默认位于 `~/.penguin/data`(Windows 为 `%USERPROFILE%\.penguin\data`),在安装主目录之下,但安装与升级都不会改动它,可用环境变量 `PENGUIN_HOME` 覆盖。模型配置、Session 记录等在升级后均会保留。
+数据目录默认为 `~/.penguin/data`(Windows 为 `%USERPROFILE%\.penguin\data`)。它位于安装目录之下,但安装和升级都不会改动它。设置环境变量 `PENGUIN_HOME` 可以改用其他目录。模型配置、Session 记录等数据在升级后都会保留。
### 已发布的 npm 包
| 包 | 说明 |
| --- | --- |
| `@prismshadow/penguin-cli` | 命令行工具,提供 `penguin` 命令 |
-| `@prismshadow/penguin-core` | SDK,程序化创建 Agent 与 Session |
-| `@prismshadow/penguin-server` | Web 服务,含 Web UI 静态资源 |
-| `@penguinharness/*` | 内置插件,一插件一包(Skill 与会话钩子);由 core 加载 |
+| `@prismshadow/penguin-core` | SDK,用代码创建 Agent 与 Session |
+| `@prismshadow/penguin-server` | Web 服务,含 Web App 的静态资源 |
+| `@penguinharness/*` | 内置插件,每个插件一个包(Skill 与会话钩子),由 core 加载 |
-全部包以 Apache-2.0 协议发布。
+所有包均以 Apache-2.0 许可证发布。
## 下一步
-- [Web App 指南](/web-app):在浏览器中使用 PenguinHarness。
-- [CLI 参考](/cli):完整命令与选项。
-- [SDK](/quickstart-sdk):把引擎嵌进自己的程序。
+- [Web App](/web-app):在浏览器里使用 PenguinHarness。
+- [CLI 参考](/cli):全部命令与选项。
+- [更新 PenguinHarness](/updates):查看版本并升级。
+- [SDK](/quickstart-sdk):把引擎嵌入自己的程序。
diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.md
index 7ebf081f..146e929d 100644
--- a/packages/docs/content/quickstart-desktop.en.md
+++ b/packages/docs/content/quickstart-desktop.en.md
@@ -1,13 +1,18 @@
---
title: Desktop app
-description: A double-click install that opens already signed in — the route that asks the least of a terminal.
+description: Install the PenguinHarness desktop app, configure a model, and run your first Task, with no terminal required.
---
-The full Web experience as a standalone application: it embeds the server and opens already signed in — no login page, no initial password to copy, and nothing to install from a command line. The user menu leaves out **Change password** accordingly: the window signs itself in, so there is no password to type or to change. It also installs the `penguin` command for you, so the terminal is there when you want it. It shares its data root with a [CLI install](/quickstart-cli), so the two can be mixed freely — if you later serve that root over the network with `penguin server`, give its admin a usable password first with `penguin server reset-admin-password` (server stopped), since the desktop app deliberately seeds one nobody can read.
+The desktop app is the full Web App as a standalone application. It embeds the server and opens already signed in, so there is no login page, no initial password to copy, and nothing to install from a command line. It also installs the `penguin` command, so the terminal is there when you want it.
+
+## Before you begin
+
+- macOS 11 or later, Windows 10 or later (x64), or Linux (x64).
+- An API key for one model provider.
## Download and install
-Get the installer for your platform from the [download page](https://penguin.ooo/download) (it serves the OSS-accelerated mirror when reachable); the same files are attached to every [GitHub Release](https://github.com/Prism-Shadow/penguin-harness/releases).
+Download the installer for your platform from the [download page](https://penguin.ooo/download), which serves the OSS-accelerated mirror when it is reachable. The same files are attached to every [GitHub Release](https://github.com/Prism-Shadow/penguin-harness/releases).
| Platform | Installers |
| --- | --- |
@@ -15,47 +20,76 @@ Get the installer for your platform from the [download page](https://penguin.ooo
| Windows 10+ | installer (.exe, x64) |
| Linux (x64) | AppImage / deb |
+Install the app and open it. On macOS, drag the app into **Applications** and open it from there.
+
The macOS builds are Developer ID signed and notarized, and the Windows installers are Authenticode signed, so neither platform needs a first-launch unblock. Linux is the one exception:
> [!INFO]- Double-clicking the Linux AppImage does nothing
>
-> Browsers download AppImages without the execute permission. Grant it once and the app starts normally from then on (the deb package installs through the package manager and is not affected):
+> Browsers download AppImages without the execute permission. Grant it once, and the app starts normally from then on. The deb package installs through the package manager and is not affected.
>
> ```bash
> chmod +x penguin-desktop-linux-x86_64.AppImage
> ```
+The app opens signed in. The window signs itself in, so there is no password to type or to change: in the app's window, **System settings** has no **Account** page with **Change password**.
+
+## Configure a model
+
+PenguinHarness ships with no model credentials. Give it an API key for the model you want to use:
+
+1. In the sidebar, select **Models**. Models are listed in one group per provider, and the default model is marked **Default**.
+2. In your provider's group, click **Set key**, enter the API key, and click **Confirm**. The key is written to every model in that group.
+3. If you want a model other than the default, open that model and click **Set as default model**.
+
+To add a model that is not listed, click **Add model** in its provider's group and fill in the **Model ID** and **API key**.
+
+A model is always referenced as a `(provider, model_id)` pair: the provider is never inferred from the model id. See [Models & Providers](/models) for the built-in groups.
+
+### Use API keys from your shell profile
+
+API keys already exported in your shell profile (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, …) work without entering them again. On macOS and Linux, when you launch the app from the Dock or the desktop, it imports the login shell's environment, filling in only the variables the launch itself did not set. The agent shell's `PATH` benefits the same way. Set `PENGUIN_NO_LOGIN_SHELL_ENV` to turn this off.
+
+For an official provider's model with no stored key, the **Models** page shows the detected variable's value masked, just as it shows a stored key: on the model's card, and in the model's dialog, which marks the key as **Read from environment variable**. Gateway and custom groups are not matched against these variables.
+
+## Run your first Task
+
+1. In the sidebar, click **New chat**.
+2. Pick the agent, the Workspace and the approval mode. You choose the Workspace with the server-side directory browser.
+3. Send a first message, for example "Create hello.txt containing Hello, Penguin".
+
+Tool calls appear inline as cards; open one to inspect its arguments and output. With the **Ask every time** (`always-ask`) approval mode, every file write waits for you to click **Allow**. [Tools & Approval](/tools) describes the four approval modes.
+
## The `penguin` command
-The app installs the `penguin` command itself, at every launch, from the CLI bundled inside it. The two always come from the same build, so updating the app updates the command with it, and no system Node.js is involved — the launcher runs the bundled CLI on the app's own runtime.
+The app installs the `penguin` command itself, at every launch, from the CLI bundled inside it. The app and the command always come from the same build, so updating the app updates the command too. No system Node.js is involved: the launcher runs the bundled CLI on the app's own runtime.
| Platform | Where the command goes |
| --- | --- |
-| macOS | `/usr/local/bin/penguin`, linked to the app. Creating that directory can need an administrator password; macOS asks only when the plain write is refused, and declining leaves the command uninstalled. |
-| Windows | the app's `bin` directory is appended to your user `Path`. Open a **new** terminal window afterwards — an already-running one keeps the old `Path`. |
+| macOS | `/usr/local/bin/penguin`, linked to the app. Creating that directory can need an administrator password. macOS asks only when the plain write is refused, and if you decline, the command is not installed. |
+| Windows | The app's `bin` directory is appended to your user `Path`. Open a **new** terminal window afterwards; a terminal that is already running keeps the old `Path`. |
| Linux (deb) | `/usr/bin/penguin`, created by the package's own install script. |
| Linux (AppImage) | `~/.local/bin/penguin`, a wrapper that runs the AppImage. Most distributions put that directory on `PATH` at login. |
-**An existing `penguin` is never replaced.** If something else already provides the command — a [CLI install](/quickstart-cli), a global npm package, a script of your own — the app leaves it exactly as it is and installs nothing. Choose **Install 'penguin' Command…** from the application menu to replace it deliberately; that menu item is also the way back if you declined the macOS administrator prompt.
-
-On macOS the app will not install the command while it is running from the mounted dmg, because the link would break the moment you eject it. Drag the app into **Applications** and open it from there.
+The app never replaces an existing `penguin`. If something else already provides the command, such as a [CLI install](/quickstart-cli), a global npm package or a script of your own, the app leaves it exactly as it is and installs nothing. To replace it deliberately, choose **Install 'penguin' Command…** from the application menu. The same menu item installs the command if you declined the macOS administrator prompt.
-## Configure a model
+On macOS, the app does not install the command while it runs from the mounted dmg, because the link would break the moment you eject the disk image. Drag the app into **Applications** and open it from there.
-Open the app, go to the **Models** page in the sidebar, click "Add model" and fill in the Provider, model id and API key, then set it as the default.
+## Share the data root with the CLI
-API keys already exported in your shell profile (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, …) work without re-entering them: on macOS and Linux the app imports the login shell's environment when launched from the Dock or desktop, filling only variables the launch itself did not set (the agent shell's `PATH` benefits the same way; set `PENGUIN_NO_LOGIN_SHELL_ENV` to opt out). For an official-provider model without a stored key, the Models page shows the detected variable's value masked, exactly as a stored key is shown: on the card, and in the model's dialog, which marks it as read from an environment variable (gateway and custom groups are not matched against these variables).
+The desktop app uses the same data root as a [CLI install](/quickstart-cli), so you can use the two side by side.
-A model is always referenced as a `(provider, model_id)` pair — the Provider is never inferred from the model id. See [Models & Providers](/models) for the built-in groups.
-
-## Run your first Task
+If you later serve that data root over the network with `penguin server`, first give its `admin` a password you can use, because the desktop app deliberately seeds one that nobody can read. Stop the server, then run:
-Back on the **Chat** page, start a new session: pick the Agent, the Workspace (chosen with the server-side directory browser) and the approval mode, then send a first message such as "Create hello.txt containing Hello, Penguin".
+```bash
+penguin server reset-admin-password
+```
-Tool calls expand inline as cards you can open to inspect arguments and output; with the `always-ask` approval mode, every file write waits for you to click Allow. The four approval modes are described in [Tools & Approval](/tools).
+The `admin` account returns to the unclaimed state. When you start the server again, it prints a first-login link where you set the new password.
## Next steps
-- [Web App Guide](/web-app): every page of the interface, one by one.
-- [CLI and Web App](/quickstart-cli): a standalone install, for a server or a remote machine. On the same machine you do not need one — the app already provides `penguin` — and installing it puts a second copy on your `PATH`.
-- [Architecture Overview](/architecture): how the pieces fit together.
+- [Web App](/web-app): find your way around the interface.
+- [Update PenguinHarness](/updates): how the desktop app updates itself.
+- [CLI and Web App](/quickstart-cli): a standalone install, for a server or a remote machine. On the same machine you don't need it: the app already provides `penguin`, and installing the CLI puts a second copy on your `PATH`.
+- [Architecture](/architecture): how the pieces fit together.
diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.md
index 19f43664..e255d1cc 100644
--- a/packages/docs/content/quickstart-desktop.zh.md
+++ b/packages/docs/content/quickstart-desktop.zh.md
@@ -1,61 +1,95 @@
---
-title: 桌面端应用
-description: 双击安装,打开即已登录——对终端要求最少的那条路线。
+title: 桌面应用
+description: 安装 PenguinHarness 桌面应用,配置模型,跑通第一个 Task,全程不需要终端。
---
-完整的 Web 体验打包成一个独立应用:内嵌服务端,双击打开即已登录——没有登录页,不用抄初始密码,也不必从命令行安装任何东西。用户菜单里相应地没有**修改密码**这一项:这个窗口自己完成登录,因此既没有要输的密码,也没有要改的密码。它还会替你装好 `penguin` 命令,需要用终端时随时可用。它与[命令行安装](/quickstart-cli)共用同一个数据目录,两者可以混用——如果之后想用 `penguin server` 把这个数据目录放到网络上,请先用 `penguin server reset-admin-password`(服务端已停止时执行)给其中的 admin 设一个可用的密码,因为桌面端刻意生成的是一个谁也读不到的初始密码。
+桌面应用把完整的 Web App 做成了一个独立应用。它内置服务端,打开即已登录:没有登录页,不用抄初始密码,也不必从命令行安装任何东西。它还会替你装好 `penguin` 命令,需要终端时随时可用。
-## 下载与安装
+## 开始之前
-前往[下载页](https://penguin.ooo/download)获取对应平台的安装包(国内自动走 OSS 镜像加速);同样的文件也附于每个 [GitHub Release](https://github.com/Prism-Shadow/penguin-harness/releases)。
+- macOS 11 及以上、Windows 10 及以上(x64),或 Linux(x64)。
+- 一个模型供应商的 API Key。
+
+## 下载并安装
+
+从[下载页](https://penguin.ooo/download)下载对应平台的安装包;OSS 加速镜像可用时,下载页会走镜像。同样的文件也附在每个 [GitHub Release](https://github.com/Prism-Shadow/penguin-harness/releases) 里。
| 平台 | 安装包 |
| --- | --- |
-| macOS 11+ | dmg(Apple 芯片 / Intel) |
+| macOS 11+ | dmg(Apple Silicon / Intel) |
| Windows 10+ | 安装程序(.exe,x64) |
| Linux(x64) | AppImage / deb |
-macOS 安装包已由 Developer ID 签名并公证,Windows 安装程序已 Authenticode 签名,两个平台首次启动都无需额外放行;只有 Linux 是例外:
+安装并打开应用。在 macOS 上,先把应用拖入**应用程序**文件夹,再从那里打开。
+
+macOS 安装包已经过 Developer ID 签名和公证,Windows 安装程序已经过 Authenticode 签名,两个平台首次启动都不需要手动放行。只有 Linux 是例外:
-> [!INFO]- Linux 双击 AppImage 没有反应
+> [!INFO]- 双击 Linux AppImage 没有反应
>
-> 浏览器下载的 AppImage 默认没有执行权限,赋权一次后即可正常启动(deb 包经包管理器安装,无此问题):
+> 浏览器下载的 AppImage 没有执行权限。赋予一次执行权限后,应用就能正常启动。deb 包通过包管理器安装,不受影响。
>
> ```bash
> chmod +x penguin-desktop-linux-x86_64.AppImage
> ```
-## `penguin` 命令
+应用打开即已登录。窗口自己完成登录,既没有要输入的密码,也没有可修改的密码,所以应用窗口里的**系统设置**没有带**修改密码**的**账户**页面。
-应用会在每次启动时,用打包在自身内部的那份 CLI 装好 `penguin` 命令。两者始终来自同一次构建,所以应用更新时命令也随之更新;过程中不需要系统里的 Node.js——启动器用应用自带的运行时执行打包好的 CLI。
+## 配置模型
-| 平台 | 命令装到哪里 |
-| --- | --- |
-| macOS | `/usr/local/bin/penguin`,链接到应用。创建该目录可能需要管理员密码;只有在普通写入被拒时 macOS 才会询问,取消则不安装该命令。 |
-| Windows | 应用的 `bin` 目录会追加到用户 `Path`。之后请**新开一个终端窗口**——已经开着的终端仍沿用旧 `Path`。 |
-| Linux(deb) | `/usr/bin/penguin`,由软件包自身的安装脚本创建。 |
-| Linux(AppImage) | `~/.local/bin/penguin`,一个运行该 AppImage 的包装脚本。多数发行版会在登录时把该目录加入 `PATH`。 |
+PenguinHarness 不内置任何模型凭据。为要使用的模型配置 API Key:
-**已存在的 `penguin` 绝不会被替换。**如果该命令已由别处提供——[命令行安装](/quickstart-cli)、全局 npm 包、你自己写的脚本——应用会原样保留它,不安装自己的那份。想主动替换,请在应用菜单里选择 **Install 'penguin' Command…**;在 macOS 上取消过管理员授权后,也从这里重新安装。
+1. 在侧边栏选择**模型库**。模型按供应商分组列出,默认模型带有**默认**标记。
+2. 在你所用供应商的分组里点击**手动设置密钥**,输入 API Key,然后点击**确认**。这个 Key 会写入分组里的每个模型。
+3. 如果要使用默认模型以外的模型,打开那个模型,点击**设为默认模型**。
-在 macOS 上,只要应用还是从挂载的 dmg 里运行,就不会安装该命令——推出磁盘映像后链接就会失效。请先把应用拖入「应用程序」文件夹,再从那里打开。
+要添加列表里没有的模型,在对应供应商的分组里点击**添加模型**,填写**模型 ID** 和 **API key**。
-## 配置模型
+模型始终以 `(provider, model_id)` 二元组引用,供应商绝不会由模型 id 推断。内置分组见[模型与 Provider](/models)。
-打开应用,在左侧进入**模型**页,点「添加模型」填入 Provider、模型 id 与 API key,保存后设为默认模型。
+### 使用 shell 配置里的 API Key
-已在 shell 配置里 export 过的 API key(`ANTHROPIC_API_KEY`、`OPENAI_API_KEY` 等)无需重复填写:macOS 与 Linux 上从 Dock / 桌面启动时,应用会导入登录 shell 的环境变量,且只补启动环境中缺失的项(agent shell 的 `PATH` 同样受益;设置 `PENGUIN_NO_LOGIN_SHELL_ENV` 可关闭导入)。未配置存储 key 的官方供应商模型,**模型**页会像显示存储 key 一样,以掩码显示检测到的变量取值:卡片上如此,模型详情里也一样,并注明该 key 读取自环境变量(网关与自定义分组不匹配这些变量)。
+已经在 shell 配置文件里 export 的 API Key(`ANTHROPIC_API_KEY`、`OPENAI_API_KEY` 等)不用再填一遍。在 macOS 和 Linux 上从 Dock 或桌面启动应用时,应用会导入登录 shell 的环境变量,只补上启动时没有设置的变量。Agent shell 的 `PATH` 也因此受益。设置 `PENGUIN_NO_LOGIN_SHELL_ENV` 可以关闭这项导入。
-模型引用始终是 `(provider, model_id)` 二元组,Provider 绝不由模型 id 推断;内置分组见[模型与 Provider](/models)。
+官方供应商的模型没有保存 Key 时,**模型库**页面会以掩码显示检测到的环境变量值,和显示已保存的 Key 一样:模型卡片上显示,模型详情弹窗里也显示,并标注为**读取自环境变量**。网关分组和自定义分组不会匹配这些变量。
## 跑通第一个 Task
-回到**对话**页新建会话:先选好 Agent、Workspace(用服务器端目录浏览器选取)与审批模式,再发送第一条消息,例如「创建 hello.txt,内容为 Hello, Penguin」。
+1. 在侧边栏点击**新建对话**。
+2. 选择 Agent、Workspace 和审批模式。Workspace 通过服务端的目录浏览器选择。
+3. 发送第一条消息,例如「创建 hello.txt,内容为 Hello, Penguin」。
+
+工具调用会以卡片形式显示在消息流里,点开卡片可以查看参数和输出。审批模式为**总是询问**(`always-ask`)时,每次写文件都会等你点击**允许**。四种审批模式的区别见[工具与审批](/tools)。
+
+## `penguin` 命令
+
+应用每次启动时,都会用自身打包的 CLI 装好 `penguin` 命令。应用和命令始终来自同一次构建,所以更新应用时命令也会随之更新。整个过程不需要系统里的 Node.js:启动器用应用自带的运行时执行打包的 CLI。
+
+| 平台 | 命令装到哪里 |
+| --- | --- |
+| macOS | `/usr/local/bin/penguin`,链接到应用。创建这个目录可能需要管理员密码。只有普通写入遭拒时,macOS 才会询问;如果拒绝授权,就不会安装命令。 |
+| Windows | 应用的 `bin` 目录会追加到你的用户 `Path`。之后请打开一个**新的**终端窗口,已经在运行的终端仍沿用旧的 `Path`。 |
+| Linux(deb) | `/usr/bin/penguin`,由软件包自己的安装脚本创建。 |
+| Linux(AppImage) | `~/.local/bin/penguin`,一个用来运行 AppImage 的包装脚本。多数发行版会在登录时把这个目录加入 `PATH`。 |
+
+应用绝不会替换已有的 `penguin`。如果别处已经提供了这个命令,比如 [CLI 安装](/quickstart-cli)、全局 npm 包或你自己写的脚本,应用会原样保留它,自己的那份不安装。要主动替换,在应用菜单里选择 **Install 'penguin' Command…**。如果在 macOS 上拒绝过管理员授权,也可以通过这个菜单项重新安装。
+
+在 macOS 上,应用从挂载的 dmg 里运行时不会安装命令,因为推出磁盘映像后链接就会失效。请把应用拖入**应用程序**文件夹,再从那里打开。
+
+## 与 CLI 共用数据目录
+
+桌面应用与 [CLI 安装](/quickstart-cli)使用同一个数据目录,两者可以搭配使用。
+
+如果之后要用 `penguin server` 把这个数据目录开放到网络上,要先给 `admin` 设置一个你能用的密码,因为桌面应用刻意生成了一个谁也读不到的密码。先停止服务端,再运行:
+
+```bash
+penguin server reset-admin-password
+```
-工具调用会在消息流里以卡片形式内联展开,可点开查看参数与输出;审批模式选 `always-ask` 时,每次写文件都会等你点「允许」。四种审批模式的区别见[工具与审批](/tools)。
+`admin` 账号会回到未认领状态。再次启动服务端时,它会打印一条首次登录链接,打开链接即可设置新密码。
## 下一步
-- [Web App 指南](/web-app):按页面逐一介绍界面的全部功能。
-- [命令行与 Web 应用](/quickstart-cli):独立安装,适用于服务器或远程机器。同一台机器上不必再装——应用已经提供了 `penguin`,再装一次只会在 `PATH` 上多出一份。
-- [架构总览](/architecture):了解整体设计。
+- [Web App](/web-app):熟悉界面。
+- [更新 PenguinHarness](/updates):桌面应用如何更新自身。
+- [命令行与 Web App](/quickstart-cli):独立安装,适用于服务器或远程机器。同一台机器上不需要再装:应用已经提供了 `penguin`,再装 CLI 只会在 `PATH` 上多出一份。
+- [架构总览](/architecture):各个部分如何协作。
diff --git a/packages/docs/content/quickstart-docker.en.md b/packages/docs/content/quickstart-docker.en.md
index 83802636..7a0282f3 100644
--- a/packages/docs/content/quickstart-docker.en.md
+++ b/packages/docs/content/quickstart-docker.en.md
@@ -1,17 +1,18 @@
---
title: Docker
-description: Run the official PenguinHarness image — one container, one volume, the full Web App on port 7364.
+description: Run the official PenguinHarness image, with one container and one volume serving the full Web App on port 7364.
---
-The official image runs the same server `penguin server` starts, with the Web App inside it. One container and one volume are the whole deployment, which makes it the shortest route onto a machine that is not your laptop.
+The official image runs the same server that `penguin server` starts, with the Web App inside it. One container and one volume are the whole deployment, which makes Docker the shortest route onto a machine that is not your laptop.
-```
-hiyouga/penguinharness
-```
+## Before you begin
+
+- Docker on the machine that will run PenguinHarness. The examples below cover both Docker Compose and `docker run`.
+- An API key for one model provider.
-The image has two kinds of tag: `latest` follows `main` — every push rebuilds it — and `X.Y.Z` is a release, built from that tag's own source. There is no `main-<sha>`, `X.Y` or `stable`: nothing that moves under a second name. Every tag is a multi-platform manifest covering `linux/amd64` and `linux/arm64`, so the same reference serves an x86 VPS and an arm64 one alike. The examples below use `latest`; a deployment that should move only when a version ships pins a version.
+## Start the container
-## Run it
+Use either tab: save the compose file, or run the commands.
```yaml tab="compose.yaml"
services:
@@ -37,18 +38,26 @@ docker run -d --name penguin \
hiyouga/penguinharness:latest
```
-With the compose file saved next to you, `docker compose up -d` starts it. Either way the Web App is then at `http://localhost:7364`, on the machine running Docker.
+With the compose file saved in the current directory, start it with `docker compose up -d`. Either way, the Web App is then at `http://localhost:7364` on the machine running Docker.
+
+### Reach it from another machine
+
+Both examples publish the port on the loopback interface of the machine running Docker, so a fresh deployment is not reachable from anywhere else. To use it from another machine, forward the port over ssh: `ssh -L 7364:127.0.0.1:7364 <host>`.
+
+Exposing it to a network is a deliberate step. Publish the port on all interfaces instead: `-p 7364:7364` or `-p 0.0.0.0:7364:7364` with `docker run`, or `"7364:7364"` in compose. Preferably put it behind a reverse proxy that terminates TLS; see [Run behind a reverse proxy](#run-behind-a-reverse-proxy).
-Both examples publish the port on that machine's loopback, so a fresh deployment is reachable from nowhere else — from another machine, forward it over ssh (`ssh -L 7364:127.0.0.1:7364 <host>`). Exposing it to a network is a deliberate step: publish on all interfaces instead (`-p 7364:7364` or `-p 0.0.0.0:7364:7364`, `"7364:7364"` in compose), preferably behind a reverse proxy that terminates TLS — see [Behind a reverse proxy](#behind-a-reverse-proxy). The container itself always listens on `0.0.0.0` inside its own network namespace, which is what makes a publish work at all; the address in `-p` is the host's half of it.
+Inside its own network namespace, the container always listens on `0.0.0.0`, which is what makes a published port work at all. The address in `-p` sets the host's side.
-## First sign-in
+## Sign in for the first time
-A fresh data root has no password. The server prints a sign-in link in a framed notice on every start until one is set — read it out of the container's log:
+A fresh data root has no password. Until one is set, the server prints a sign-in link in a framed notice every time it starts. Read it from the container's log:
```bash
docker compose logs penguin # or: docker logs penguin
```
+The notice looks like this:
+
```
+----------------------------------------------------------------------------------------------+
| This server has no admin password yet. Open this link to claim it: |
@@ -59,42 +68,73 @@ docker compose logs penguin # or: docker logs penguin
+----------------------------------------------------------------------------------------------+
```
-The `localhost` in that URL is the server's own view of itself. With the loopback publish above it is also yours, so open the link as it stands on the machine running Docker; if you published the container to a network, replace `localhost` with the host you reach it on. Either way keep the whole `?token=...`. You land signed in as `admin` and set a password. The link is re-minted on every start, so a restart invalidates the one you were looking at and prints a fresh one.
+The `localhost` in that URL is the server's view of itself. With the loopback publish above it is also yours, so open the link as it is on the machine running Docker. If you published the container to a network, replace `localhost` with the host you reach it on. Either way, keep the whole `?token=...`.
+
+The link signs you in as `admin`, and you set a password. A new link is minted on every start, so a restart invalidates the one you have and prints a fresh one.
+
+### Set the password in advance
-If reading a link out of a log does not suit your setup, pin the password instead — but do it **before the first start**:
+If reading a link from a log does not suit your setup, pin the password instead. Do this before the first start:
```yaml
environment:
PENGUIN_SEED_ADMIN_PASSWORD: "choose-something-long"
```
-It seeds the built-in `admin` with that password (8 characters minimum) and suppresses the notice. It applies **only while no user exists**, which is the first boot of an empty data root: adding it to a data root that has already been claimed changes nothing, and neither does changing it later.
+The server then creates the built-in `admin` with that password (at least 8 characters) and prints no notice. The variable applies only while no user exists, which means the first boot of an empty data root. Adding it to a data root that has already been claimed changes nothing, and neither does changing it later.
## Configure a model
-PenguinHarness ships with no model credentials. Use the **Models** page in the Web App, or the CLI inside the container:
+PenguinHarness ships with no model credentials. Add a model on the **Models** page of the Web App, or with the CLI inside the container:
```bash
docker compose exec -u penguin penguin \
penguin config model add --provider deepseek --model-id deepseek-flash --api-key sk-... --set-default
```
-The `-u penguin` matters: `docker exec` runs as root by default, and files it writes into `/data` would then be owned by root while the server runs as uid 1000. See [Models & Providers](/models) for the built-in groups.
+Keep `-u penguin` in the command. `docker exec` runs as root by default, so files it writes into `/data` would belong to root, while the server runs as uid 1000.
+
+See [Models & Providers](/models) for the built-in groups.
+
+## Run your first Task
+
+In the Web App's sidebar, click **New chat**, then send a first message, such as "Create hello.txt containing Hello, Penguin". The agent's commands run inside the container; [What the agent can reach](#what-the-agent-can-reach) explains how to give it a directory from the host. [Conversations](/chat) covers the chat page in full.
+
+## Choose an image tag
+
+The image is published as:
+
+```
+hiyouga/penguinharness
+```
+
+It has two kinds of tag:
+
+- `latest` follows `main`: every push rebuilds it.
+- `X.Y.Z` is a release, built from that tag's own source.
+
+There is no `main-<sha>`, `X.Y` or `stable` tag, so nothing moves under a second name. Every tag is a multi-platform manifest covering `linux/amd64` and `linux/arm64`, so the same reference works on an x86 VPS and an arm64 one alike. The examples on this page use `latest`. Pin a version for a deployment that should move only when a release ships.
## What is in the image
-| | |
+| Item | Details |
| --- | --- |
-| Base | Ubuntu 24.04 with the official Node.js runtime, matching the version the release tarballs bundle |
+| Base | Ubuntu 24.04 with the official Node.js runtime, at the version the release tarballs bundle |
| Command | `penguin server`, on `0.0.0.0:7364` |
-| Data root | `/data`, declared as a volume — model configuration, Sessions, Traces and the SQLite database |
-| Process user | `penguin`, uid/gid 1000; the entrypoint starts as root only to take ownership of the data root, then drops |
+| Data root | `/data`, declared as a volume. It holds model configuration, Sessions, Traces and the SQLite database |
+| Process user | `penguin`, uid/gid 1000. The entrypoint starts as root only to take ownership of the data root, then drops to that user |
| Healthcheck | `GET /api/install` every 30s |
| Tools | `git`, `curl` and the standard Ubuntu userland, for the commands an agent runs |
-Everything the agent's `exec_command` runs happens **inside this container**, on its filesystem and its network. That is the isolation boundary and also the limit: an agent can reach whatever the container can reach, and nothing else. Give it a Workspace by mounting a directory (`-v /srv/project:/srv/project`), and remember the mount needs to be writable by uid 1000.
+### What the agent can reach
+
+Everything the agent's `exec_command` runs happens inside this container, on its filesystem and its network. That is the isolation boundary, and also the limit: an agent can reach whatever the container can reach, and nothing else.
+
+To give the agent a Workspace, mount a directory, for example `-v /srv/project:/srv/project`. The mount must be writable by uid 1000.
+
+### Add tools to the image
-The image carries no compiler and no language runtimes beyond Node. `apt-get install` inside the container works for a one-off, but it is lost on the next `docker pull`; for anything you depend on, build a derived image:
+The image carries no compiler and no language runtime besides Node. `apt-get install` inside the container works for a one-off, but the package is gone after the next `docker pull`. For anything you depend on, build a derived image:
```dockerfile
FROM hiyouga/penguinharness:latest
@@ -104,31 +144,31 @@ RUN apt-get update && apt-get install -y --no-install-recommends python3 ripgrep
USER penguin
```
-Note that the runtime image deliberately has no C/C++ toolchain: it is a stage the build throws away.
+The runtime image deliberately has no C/C++ toolchain: the toolchain lives in a build stage that is thrown away.
-## Environment
+## Environment variables
-The full list is in the [Configuration Reference](/configuration); these are the ones a container deployment touches.
+These are the variables a container deployment touches. The full list is in the [Configuration Reference](/configuration).
| Variable | In this image |
| --- | --- |
-| `PENGUIN_HOME` | `/data` — change it only if you also move the volume |
-| `HOST` | `0.0.0.0` — the container's own namespace; `-p` decides the host side, and the examples keep it on loopback |
-| `PORT` | `7364`; changing it moves the healthcheck with it |
-| `PENGUIN_SEED_ADMIN_PASSWORD` | Pins the initial admin password, first boot only (see above) |
-| `PENGUIN_TRUST_PROXY` | Set to `1` behind a TLS-terminating reverse proxy, so session cookies are marked `Secure` |
+| `PENGUIN_HOME` | `/data`. Change it only if you also move the volume |
+| `HOST` | `0.0.0.0`, inside the container's own network namespace. `-p` decides the host side, and the examples keep it on loopback |
+| `PORT` | `7364`. Changing it moves the healthcheck with it |
+| `PENGUIN_SEED_ADMIN_PASSWORD` | Pins the initial admin password, on the first boot only. See [Set the password in advance](#set-the-password-in-advance) |
+| `PENGUIN_TRUST_PROXY` | Set to `1` behind a reverse proxy that terminates TLS, so session cookies are marked `Secure` |
| `PENGUIN_PREVIEW_ORIGIN` | A second hostname routed to the same container, for Workspace HTML previews |
-| `PENGUIN_UPDATE_CHECK` | `off` disables the automatic release check; owner-initiated provider key authorization may still make outbound requests |
+| `PENGUIN_UPDATE_CHECK` | `off` turns off the automatic release check. Model requests, remote-control connections, key authorization and the proxy test still go out |
-### Behind a reverse proxy
+### Run behind a reverse proxy
-Publish the container on loopback, terminate TLS in front of it, and set `PENGUIN_TRUST_PROXY=1`. The proxy must set or strip `x-forwarded-proto` itself; the header is caller-supplied, which is exactly why the server ignores it until you say otherwise. Leaving it unset on an HTTPS deployment issues session cookies without the `Secure` flag.
+Publish the container on loopback, terminate TLS in front of it, and set `PENGUIN_TRUST_PROXY=1`. The proxy must set or strip `x-forwarded-proto` itself. That header comes from the caller, which is exactly why the server ignores it until you tell it otherwise. If you leave `PENGUIN_TRUST_PROXY` unset on an HTTPS deployment, session cookies are issued without the `Secure` flag.
-### Workspace previews
+### Serve Workspace previews
-Previews of HTML a Task produces are served from a separate origin when there is one. On a non-loopback bind there is no loopback counterpart to derive, so they fall back to a same-origin sandbox where cookies, `localStorage` and third-party embeds do not work. Point `PENGUIN_PREVIEW_ORIGIN` at a second hostname routed to the same container to get the isolated version back — it must differ by hostname, not just port.
+Previews of the HTML a Task produces are served from a separate origin when there is one. On a non-loopback bind there is no loopback counterpart to derive, so previews fall back to a same-origin sandbox, where cookies, `localStorage` and third-party embeds do not work. To get the isolated previews back, point `PENGUIN_PREVIEW_ORIGIN` at a second hostname routed to the same container. It must differ by hostname, not just by port.
-## Upgrading
+## Upgrade the container
Pull a newer tag and recreate the container. The data root is on the volume and carries over:
@@ -136,13 +176,14 @@ Pull a newer tag and recreate the container. The data root is on the volume and
docker compose pull && docker compose up -d
```
-In-container self-update is **not** the path. The Web App's update button reports the release as unsupported here — the server has no re-runnable CLI entry to hand an update to — and the restart control reports that nothing supervises it. `penguin update` run inside the container would install into a filesystem the next recreate throws away, and it fails anyway: the runtime image carries no compiler, and `node-pty` has no Linux prebuild to fall back on.
+> [!WARNING]
+> Do not update from inside the container. The update dialog reports that this install cannot update itself, and anything `penguin update` installs there is lost when the container is recreated.
-Stopping is graceful: `SIGTERM` interrupts running Tasks, waits for them to wrap up, then closes the database. An idle server stops in well under a second; a busy one can take several, which is why the compose example raises Docker's 10-second grace period.
+Stopping is graceful. On `SIGTERM` the server interrupts running Tasks, waits for them to wrap up, then closes the database. An idle server stops in well under a second, and a busy one can take several seconds, which is why the compose example raises Docker's 10-second grace period.
-## Rescue: a forgotten admin password
+## Reset a forgotten admin password
-The data root is the authorization — someone who can run this command already has the database. The server has to be stopped first, because a data root only ever has one writer:
+Stop the server first, because a data root only ever has one writer. Then reset the password and start the server again:
```bash
docker compose stop penguin
@@ -150,10 +191,11 @@ docker compose run --rm penguin penguin server reset-admin-password
docker compose start penguin
```
-The account returns to the unclaimed state with its sessions revoked, so sign in again through the first-login link in the log, exactly as on a fresh server.
+The reset needs no other authorization: the data root is the authorization, and anyone who can run this command already has the database. The `admin` account returns to the unclaimed state and its login sessions are revoked. Sign in again with the first-login link from the log, as in [Sign in for the first time](#sign-in-for-the-first-time).
## Next steps
-- [Web App Guide](/web-app): use PenguinHarness from the browser.
+- [Web App](/web-app): use PenguinHarness from the browser.
+- [Update PenguinHarness](/updates): check your version and upgrade.
- [Security Model](/security): who can do what, and on the strength of which proof.
- [Configuration Reference](/configuration): every environment variable and config field.
diff --git a/packages/docs/content/quickstart-docker.zh.md b/packages/docs/content/quickstart-docker.zh.md
index 15ab7cfb..a7ddd8d6 100644
--- a/packages/docs/content/quickstart-docker.zh.md
+++ b/packages/docs/content/quickstart-docker.zh.md
@@ -1,17 +1,18 @@
---
title: Docker
-description: 运行官方 PenguinHarness 镜像——一个容器、一个卷,7364 端口上是完整的 Web 应用。
+description: 运行官方 PenguinHarness 镜像,一个容器加一个数据卷,就在 7364 端口提供完整的 Web App。
---
-官方镜像跑的就是 `penguin server` 启动的那个服务端,Web 应用在里面。整套部署只有一个容器和一个卷,因此它是把 PenguinHarness 装到自己电脑以外的机器上最短的一条路。
+官方镜像运行的就是 `penguin server` 启动的那个服务端,Web App 也在其中。整套部署只有一个容器和一个数据卷,所以要把 PenguinHarness 装到自己电脑以外的机器上,Docker 是最短的一条路。
-```
-hiyouga/penguinharness
-```
+## 开始之前
+
+- 在要运行 PenguinHarness 的机器上装好 Docker。下面的示例同时给出 Docker Compose 和 `docker run` 两种写法。
+- 一个模型供应商的 API Key。
-镜像只有两种 tag:`latest` 跟随 `main`——每次 push 都重新构建它;`X.Y.Z` 是某个发布版,由该 tag 自身的源码构建。没有 `main-<sha>`、`X.Y` 或 `stable` 之类会移动或重复的名字。每个 tag 都是覆盖 `linux/amd64` 与 `linux/arm64` 的多平台 manifest,同一个引用在 x86 VPS 与 arm64 机器上通用。下面的示例用 `latest`;只希望随发布版移动的部署应钉住某个版本号。
+## 启动容器
-## 跑起来
+在下面两个标签页中任选一种:保存 compose 文件,或者直接执行命令。
```yaml tab="compose.yaml"
services:
@@ -37,18 +38,26 @@ docker run -d --name penguin \
hiyouga/penguinharness:latest
```
-把 compose 文件放在当前目录,`docker compose up -d` 即启动。两种方式启动后,Web 应用都在运行 Docker 的那台机器的 `http://localhost:7364`。
+把 compose 文件保存在当前目录后,执行 `docker compose up -d` 启动。无论用哪种方式,启动后都能在运行 Docker 的那台机器上通过 `http://localhost:7364` 打开 Web App。
+
+### 从其他机器访问
+
+两个示例都把端口发布在运行 Docker 那台机器的回环接口上,所以新部署的服务从别处访问不到。要在另一台机器上使用,可以用 ssh 转发端口:`ssh -L 7364:127.0.0.1:7364 <host>`。
+
+对外开放需要你主动去做:改为把端口发布到所有网络接口,`docker run` 用 `-p 7364:7364` 或 `-p 0.0.0.0:7364:7364`,compose 里写 `"7364:7364"`。最好再放到一个终结 TLS 的反向代理之后,见[在反向代理后运行](#在反向代理后运行)。
-两个示例都把端口发布在该机器的回环上,因此新部署在别处一概不可达——要从另一台机器访问,用 ssh 转发(`ssh -L 7364:127.0.0.1:7364 <host>`)。对外开放是一个明确的动作:改为发布到所有接口(`-p 7364:7364` 或 `-p 0.0.0.0:7364:7364`,compose 写 `"7364:7364"`),并尽量置于终结 TLS 的反向代理之后——见[反向代理之后](#反向代理之后)。容器自身始终在自己的网络命名空间里监听 `0.0.0.0`,这正是端口发布得以成立的前提;`-p` 里的地址是宿主机这一侧。
+在容器自己的网络命名空间里,服务始终监听 `0.0.0.0`,端口发布正是靠这一点才能生效。`-p` 里的地址决定的是宿主机这一侧。
## 首次登录
-新数据目录没有密码。在密码被设置之前,服务端每次启动都会以边框提示打印一条登录链接——从容器日志里读它:
+新的数据目录还没有密码。在设置密码之前,服务端每次启动都会以带边框的提示打印一条登录链接。从容器日志里找到它:
```bash
-docker compose logs penguin # 或:docker logs penguin
+docker compose logs penguin # or: docker logs penguin
```
+提示如下:
+
```
+----------------------------------------------------------------------------------------------+
| This server has no admin password yet. Open this link to claim it: |
@@ -59,42 +68,73 @@ docker compose logs penguin # 或:docker logs penguin
+----------------------------------------------------------------------------------------------+
```
-那条 URL 里的 `localhost` 是服务端对自己的称呼。按上面的回环发布,它同时也是你的,因此在运行 Docker 的那台机器上原样打开即可;若你已把容器发布到网络上,则把 `localhost` 换成你实际访问它所用的主机名或 IP。两种情况都要保留整段 `?token=...`。落地即已登录为 `admin`,随即设置密码。链接在每次启动时重新铸造,所以一次重启就会作废你正看着的那条,并打印一条新的。
+链接里的 `localhost` 是服务端对自己的称呼。按上面的方式发布在回环接口上时,它对你来说也是同一台机器,所以在运行 Docker 的机器上原样打开链接即可。如果已经把容器发布到网络上,就把 `localhost` 换成你访问它时用的主机名。两种情况下都要保留完整的 `?token=...`。
+
+打开链接即以 `admin` 身份登录,然后设置密码。每次启动都会重新生成链接,所以重启之后,你手上那条链接就失效了,日志里会打印一条新的。
+
+### 提前设置密码
-如果从日志里读链接不适合你的场景,也可以直接把密码钉死——但必须**在首次启动之前**:
+如果不方便从日志里读取链接,可以直接固定密码,但要在首次启动之前设置:
```yaml
environment:
PENGUIN_SEED_ADMIN_PASSWORD: "choose-something-long"
```
-它以该密码(至少 8 位)种下内置管理员 `admin`,并不再打印提示。它**仅在尚无任何用户时生效**,也就是空数据目录的第一次启动:加到已被认领的数据目录上不会有任何效果,事后改动同样无效。
+服务端会用这个密码(至少 8 个字符)创建内置的 `admin` 账号,并且不再打印登录提示。这个变量只在还没有任何用户时生效,也就是空数据目录第一次启动的时候。给已经认领过的数据目录加上它不会有任何效果,事后修改同样无效。
## 配置模型
-PenguinHarness 不内置任何模型凭据。可以用 Web 应用的**模型**页,也可以用容器里的 CLI:
+PenguinHarness 不内置任何模型凭据。可以在 Web App 的**模型库**页面添加模型,也可以在容器里用 CLI 添加:
```bash
docker compose exec -u penguin penguin \
penguin config model add --provider deepseek --model-id deepseek-flash --api-key sk-... --set-default
```
-`-u penguin` 是必要的:`docker exec` 默认以 root 执行,它写进 `/data` 的文件会归 root 所有,而服务端是以 uid 1000 运行的。内置分组见[模型与 Provider](/models)。
+命令中的 `-u penguin` 不能省略。`docker exec` 默认以 root 身份执行,写进 `/data` 的文件会归 root 所有,而服务端是以 uid 1000 运行的。
+
+内置分组见[模型与 Provider](/models)。
+
+## 跑通第一个 Task
+
+在 Web App 的侧边栏点击**新建对话**,然后发送第一条消息,例如「创建 hello.txt,内容为 Hello, Penguin」。Agent 执行的命令都在容器内运行;怎样把宿主机上的目录交给 Agent,见 [Agent 能访问什么](#agent-能访问什么)。对话页面的完整说明见[对话](/chat)。
+
+## 选择镜像 tag
+
+镜像名为:
+
+```
+hiyouga/penguinharness
+```
+
+tag 分为两类:
+
+- `latest` 跟随 `main` 分支,每次推送都会重新构建。
+- `X.Y.Z` 是正式发布版,用这个 tag 自身的源码构建。
+
+没有 `main-<sha>`、`X.Y` 或 `stable` 这类 tag,因此不存在换个名字跟着变动的别名。每个 tag 都是覆盖 `linux/amd64` 与 `linux/arm64` 的多平台 manifest,同一个引用在 x86 VPS 和 arm64 VPS 上都能用。本页示例使用 `latest`;如果希望部署只在发布新版本时才更新,就固定到具体版本号。
## 镜像里有什么
-| | |
+| 项目 | 说明 |
| --- | --- |
-| 基础镜像 | Ubuntu 24.04,加官方 Node.js 运行时,版本与发布包内嵌的一致 |
+| 基础镜像 | Ubuntu 24.04,加上官方 Node.js 运行时,版本与发布包内置的一致 |
| 启动命令 | `penguin server`,监听 `0.0.0.0:7364` |
-| 数据目录 | `/data`,声明为卷——模型配置、会话、Trace 与 SQLite 数据库都在其中 |
-| 运行用户 | `penguin`,uid/gid 1000;入口脚本仅为接管数据目录的属主而以 root 启动,随即降权 |
-| 健康检查 | 每 30 秒一次 `GET /api/install` |
-| 工具 | `git`、`curl` 与 Ubuntu 标准用户态,供 Agent 执行命令 |
+| 数据目录 | `/data`,声明为数据卷,存放模型配置、Session、Trace 和 SQLite 数据库 |
+| 运行用户 | `penguin`,uid/gid 1000。入口脚本以 root 启动,只为接管数据目录的所有权,随后降权为 `penguin` 用户 |
+| 健康检查 | 每 30 秒请求一次 `GET /api/install` |
+| 工具 | `git`、`curl` 与 Ubuntu 标准用户态工具,供 Agent 执行命令 |
+
+### Agent 能访问什么
+
+Agent 通过 `exec_command` 执行的一切都发生在这个容器里,用的是容器的文件系统和网络。这是隔离边界,也是能力的上限:容器能访问到的,Agent 都能访问到,除此之外一概访问不到。
+
+要给 Agent 一个 Workspace,就挂载一个目录,例如 `-v /srv/project:/srv/project`。挂载的目录必须允许 uid 1000 写入。
-Agent 的 `exec_command` 跑的一切都发生在**这个容器内部**,用的是它的文件系统与它的网络。这既是隔离边界,也是能力边界:容器能访问什么,Agent 就能访问什么,仅此而已。要给它一个 Workspace 就挂一个目录进来(`-v /srv/project:/srv/project`),注意该挂载需要对 uid 1000 可写。
+### 给镜像添加工具
-镜像不带编译器,Node 之外也不带其他语言运行时。临时用一下,在容器里 `apt-get install` 是可行的,但下一次 `docker pull` 就没了;凡是要长期依赖的,构建一个派生镜像:
+镜像里没有编译器,除 Node 之外也没有其他语言运行时。在容器里执行 `apt-get install` 可以应付一次性的需要,但下一次 `docker pull` 之后装过的包就没了。长期依赖的工具,请构建一个派生镜像:
```dockerfile
FROM hiyouga/penguinharness:latest
@@ -104,45 +144,46 @@ RUN apt-get update && apt-get install -y --no-install-recommends python3 ripgrep
USER penguin
```
-注意运行镜像刻意不含 C/C++ 工具链:那是构建阶段用完即丢的一层。
+运行时镜像刻意不带 C/C++ 工具链:工具链只存在于构建阶段,构建完就丢弃了。
## 环境变量
-完整清单见[配置参考](/configuration),这里只列容器部署会用到的。
+下表列出容器部署会用到的变量,完整列表见[配置参考](/configuration)。
| 变量 | 在本镜像中 |
| --- | --- |
-| `PENGUIN_HOME` | `/data`——除非同时改卷的挂载点,否则不要改 |
-| `HOST` | `0.0.0.0`——容器自己的命名空间;宿主机这一侧由 `-p` 决定,示例把它留在回环上 |
-| `PORT` | `7364`;改它会连带把健康检查一起移过去 |
-| `PENGUIN_SEED_ADMIN_PASSWORD` | 钉死初始管理员密码,仅首次启动生效(见上文) |
-| `PENGUIN_TRUST_PROXY` | 在终结 TLS 的反向代理之后设为 `1`,使会话 Cookie 带上 `Secure` |
-| `PENGUIN_PREVIEW_ORIGIN` | 指向同一容器的第二个主机名,用于 Workspace 的 HTML 预览 |
-| `PENGUIN_UPDATE_CHECK` | `off` 关闭自动版本检查;Owner 主动发起的供应商 Key 授权仍可能产生出网请求 |
+| `PENGUIN_HOME` | `/data`。除非同时移动数据卷,否则不要修改 |
+| `HOST` | `0.0.0.0`,作用于容器自己的网络命名空间。宿主机一侧由 `-p` 决定,示例都保持在回环接口上 |
+| `PORT` | `7364`。修改后,健康检查会随之改用新端口 |
+| `PENGUIN_SEED_ADMIN_PASSWORD` | 固定初始管理员密码,仅在首次启动时生效,见[提前设置密码](#提前设置密码) |
+| `PENGUIN_TRUST_PROXY` | 放在终结 TLS 的反向代理之后时设为 `1`,会话 Cookie 才会带上 `Secure` 标记 |
+| `PENGUIN_PREVIEW_ORIGIN` | 路由到同一容器的第二个主机名,用于 Workspace 中的 HTML 预览 |
+| `PENGUIN_UPDATE_CHECK` | 设为 `off` 关闭自动的版本检查。模型请求、远程控制连接、Key 授权和代理测试照常出站 |
-### 反向代理之后
+### 在反向代理后运行
-把容器发布在回环上,在它前面终结 TLS,并设 `PENGUIN_TRUST_PROXY=1`。代理必须自己设置或剥除 `x-forwarded-proto`;该头由调用方提供,这正是服务端在你明说之前不予采信的原因。HTTPS 部署下不设它,签发的会话 Cookie 就不带 `Secure` 标记。
+把容器发布在回环接口上,在它前面终结 TLS,并设置 `PENGUIN_TRUST_PROXY=1`。反向代理必须自己设置或清除 `x-forwarded-proto`:这个请求头由调用方提供,服务端正因如此,在你明确开启之前一直不采信它。HTTPS 部署如果不设置 `PENGUIN_TRUST_PROXY`,签发的会话 Cookie 就不带 `Secure` 标记。
-### Workspace 预览
+### 提供 Workspace 预览
-Task 产出的 HTML,在有独立来源时会从另一个来源提供。非回环绑定下没有可推导的回环对应地址,预览会退化为同源沙箱,此时 Cookie、`localStorage` 与第三方内嵌都不可用。把 `PENGUIN_PREVIEW_ORIGIN` 指向路由到同一容器的第二个主机名即可恢复隔离版本——它必须在**主机名**上不同,仅端口不同不算。
+Task 生成的 HTML 在有独立来源时,会从独立的来源提供预览。绑定在非回环地址上时,推导不出对应的回环地址,预览会退回同源沙箱,这时 Cookie、`localStorage` 和第三方嵌入内容都不能用。要恢复隔离的预览,把 `PENGUIN_PREVIEW_ORIGIN` 指向路由到同一容器的第二个主机名。它必须在主机名上有所不同,只换端口不行。
-## 升级
+## 升级容器
-拉一个新 tag 并重建容器。数据目录在卷上,原样保留:
+拉取更新的 tag,然后重建容器。数据目录在数据卷上,会原样保留:
```bash
docker compose pull && docker compose up -d
```
-容器内的自更新**不是**升级路径。Web 应用的升级按钮在这里会报「不支持」——服务端没有可再次运行的 CLI 入口,无从把升级交出去——重启入口也会报没有托管进程。在容器里执行 `penguin update` 则会把新包装进下次重建即丢弃的文件系统,而且无论如何都会失败:运行镜像不含编译器,`node-pty` 也没有可回退的 Linux 预编译产物。
+> [!WARNING]
+> 不要在容器内更新。更新弹窗会提示当前安装无法自行更新,而 `penguin update` 在容器里装下的任何东西,都会在下次重建容器时丢失。
-停止是优雅的:`SIGTERM` 会打断运行中的 Task,等它们收尾,再关闭数据库。空闲的服务端远不到一秒就停住,繁忙的可能要几秒——compose 示例把 Docker 默认的 10 秒宽限期调高,正是为此。
+服务端会平稳停止:收到 `SIGTERM` 后,它先中断正在运行的 Task,等它们收尾,再关闭数据库。空闲时不到一秒就能停下,繁忙时可能要几秒,所以 compose 示例调大了 Docker 默认 10 秒的宽限期。
-## 救援:忘记管理员密码
+## 重置忘记的管理员密码
-授权模型就是数据目录本身——能执行这条命令的人本就持有那个数据库。必须先停掉服务端,因为一个数据目录同一时刻只有一个写者:
+先停止服务端,因为一个数据目录同一时刻只能有一个写入者。然后重置密码,再重新启动:
```bash
docker compose stop penguin
@@ -150,10 +191,11 @@ docker compose run --rm penguin penguin server reset-admin-password
docker compose start penguin
```
-账号回到未认领状态并清空全部会话,之后照新服务器的流程,从日志里的首次登录链接重新登录。
+重置不需要其他授权:数据目录本身就是授权,能执行这条命令的人本来就拥有这个数据库。`admin` 账号会回到未认领状态,已有的登录会话全部失效。之后按照[首次登录](#首次登录)的做法,用日志里的首次登录链接重新登录。
## 下一步
-- [Web 应用指南](/web-app):在浏览器里使用 PenguinHarness。
-- [安全模型](/security):谁能做什么,凭什么。
+- [Web App](/web-app):在浏览器里使用 PenguinHarness。
+- [更新 PenguinHarness](/updates):查看版本并升级。
+- [安全模型](/security):谁能做什么,凭的是什么。
- [配置参考](/configuration):全部环境变量与配置字段。
diff --git a/packages/docs/content/quickstart-sdk.en.md b/packages/docs/content/quickstart-sdk.en.md
index 21e55274..5bd79ac5 100644
--- a/packages/docs/content/quickstart-sdk.en.md
+++ b/packages/docs/content/quickstart-sdk.en.md
@@ -1,13 +1,18 @@
---
title: SDK
-description: Create Agents and Sessions from your own TypeScript program with @prismshadow/penguin-core.
+description: Create agents and Sessions from your own TypeScript program with @prismshadow/penguin-core.
---
-`@prismshadow/penguin-core` is the same engine the CLI and the Server run inside, and it embeds directly into your own program.
+`@prismshadow/penguin-core` is the same engine the CLI and the server run inside, and it embeds directly into your own program. On this page you install the SDK, make a model available to it, and run a first program that creates an agent, starts a Session and prints the model's replies.
-## Install
+## Before you begin
-Requires Node.js >= 24:
+- Node.js >= 24.
+- An API key for one model provider, unless a model is already configured on this machine.
+
+## Install the SDK
+
+In your project directory, install the package:
```bash
npm install @prismshadow/penguin-core
@@ -15,18 +20,22 @@ npm install @prismshadow/penguin-core
## Configure a model
-The SDK reads the same data root as the desktop app and the CLI, `~/.penguin/data`, so a model configured in the [desktop app](/quickstart-desktop) or the [CLI](/quickstart-cli) is immediately usable — there is nothing to configure twice.
+The SDK reads the same data root as the desktop app and the CLI, `~/.penguin/data`. A model configured in the [desktop app](/quickstart-desktop) or the [CLI](/quickstart-cli) is immediately usable, so there is nothing to configure twice.
-If this machine has no model configured yet, the shortest path is to install the CLI and do it once:
+If this machine has no model configured yet, the shortest path is to install the CLI and configure one there:
```bash
npm install -g @prismshadow/penguin-cli
penguin config model add --provider deepseek --model-id deepseek-flash --api-key sk-... --set-default
```
-You can also keep credentials off disk entirely: when a model entry has no inline api_key, AgentHub (the LLM gateway library) reads environment variables such as `DEEPSEEK_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and `GEMINI_API_KEY`. A `.env` file in the working directory is loaded automatically.
+Replace `sk-...` with your API key. The CLI writes the model to the data root, and the SDK can use it right away.
+
+You can also keep credentials off disk entirely. When a model entry has no inline `api_key`, AgentHub (the LLM gateway library) reads environment variables such as `DEEPSEEK_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `GEMINI_API_KEY`. A `.env` file in the working directory is loaded automatically.
-## Your first program
+## Run your first program
+
+Save this program in your project and run it:
```ts
import { createAgent, isCompleteModelMessage, userText } from "@prismshadow/penguin-core";
@@ -43,9 +52,13 @@ for await (const output of session.run([userText("Create hello.txt containing hi
}
```
-- `createAgent` loads an Agent's configuration by id (prompts, tools, runtime parameters); `default_agent` is the one seeded when the data root is initialized.
-- `session.run()` returns an async iterator yielding OmniMessages one by one — the guard above picks out complete model text messages, while tool calls, thinking blocks and the rest arrive on the same stream.
-- `approve` is the approval callback; returning `"allow"` permits everything. How the four approval modes map onto tools is described in [Tools & Approval](/tools).
+The program asks the agent to create `hello.txt`, using the current directory as the Session's Workspace, and prints each complete text reply from the model.
+
+### How the program works
+
+- `createAgent` loads an agent's configuration by id: its prompts, tools and runtime parameters. `default_agent` is the agent seeded when the data root is initialized.
+- `session.run()` returns an async iterator that yields OmniMessages one by one. The guard in the loop picks out complete model text messages; tool calls, thinking blocks and everything else arrive on the same stream.
+- `approve` is the approval callback, and returning `"allow"` permits everything. [Tools & Approval](/tools) describes how the four approval modes map onto tools.
## Next steps
diff --git a/packages/docs/content/quickstart-sdk.zh.md b/packages/docs/content/quickstart-sdk.zh.md
index 86884e6a..b6c2af09 100644
--- a/packages/docs/content/quickstart-sdk.zh.md
+++ b/packages/docs/content/quickstart-sdk.zh.md
@@ -3,11 +3,16 @@ title: SDK
description: 用 @prismshadow/penguin-core 在自己的 TypeScript 程序里创建 Agent 与 Session。
---
-`@prismshadow/penguin-core` 就是 CLI 与 Server 内部使用的同一个引擎,可以直接嵌进自己的程序。
+`@prismshadow/penguin-core` 就是 CLI 与服务端内部运行的那个引擎,可以直接嵌入你自己的程序。在本页中,你会安装 SDK、为它准备可用的模型,并运行第一个程序:创建 Agent,启动 Session,打印模型的回复。
-## 安装
+## 开始之前
-需要 Node.js >= 24:
+- Node.js >= 24。
+- 一个模型供应商的 API Key。这台机器上已经配置过模型时,可以省略。
+
+## 安装 SDK
+
+在项目目录里安装这个包:
```bash
npm install @prismshadow/penguin-core
@@ -15,18 +20,22 @@ npm install @prismshadow/penguin-core
## 配置模型
-SDK 与桌面端应用、CLI 读同一个数据目录 `~/.penguin/data`,所以在[桌面端应用](/quickstart-desktop)或 [CLI](/quickstart-cli) 里配好的模型,SDK 直接可用,无需重复配置。
+SDK 与桌面应用、CLI 读取同一个数据目录 `~/.penguin/data`。在[桌面应用](/quickstart-desktop)或 [CLI](/quickstart-cli) 里配置好的模型,SDK 可以直接使用,不需要重复配置。
-如果这台机器还没配过模型,最省事的方式是装上 CLI 配一次:
+如果这台机器上还没有配置过模型,最省事的办法是装上 CLI,在 CLI 里配置一次:
```bash
npm install -g @prismshadow/penguin-cli
penguin config model add --provider deepseek --model-id deepseek-flash --api-key sk-... --set-default
```
-也可以完全不落盘:模型条目没有内联 api_key 时,LLM 网关库 AgentHub 会读取 `DEEPSEEK_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY`、`GEMINI_API_KEY` 等环境变量;工作目录下的 `.env` 会被自动加载。
+把 `sk-...` 换成你的 API Key。CLI 会把模型写入数据目录,SDK 马上就能使用。
+
+凭据也可以完全不落盘。模型条目没有内联 `api_key` 时,LLM 网关库 AgentHub 会读取 `DEEPSEEK_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY`、`GEMINI_API_KEY` 等环境变量。工作目录下的 `.env` 文件会自动加载。
-## 第一个程序
+## 运行第一个程序
+
+把下面的程序保存到项目里,然后运行:
```ts
import { createAgent, isCompleteModelMessage, userText } from "@prismshadow/penguin-core";
@@ -43,13 +52,17 @@ for await (const output of session.run([userText("Create hello.txt containing hi
}
```
-- `createAgent` 按 agentId 载入 Agent 配置(提示词、工具、运行参数);`default_agent` 是初始化数据目录时自带的那个。
-- `session.run()` 返回一个异步迭代器,逐条产出 OmniMessage——上面的判断只挑出模型的完整文本消息,工具调用、思考块等都在同一个流里。
-- `approve` 是审批回调,返回 `"allow"` 即全部放行;四种审批模式与工具的对应关系见[工具与审批](/tools)。
+这个程序把当前目录用作 Session 的 Workspace,让 Agent 创建 `hello.txt`,并打印模型的每一条完整文本回复。
+
+### 程序是怎样工作的
+
+- `createAgent` 按 id 载入 Agent 的配置:提示词、工具和运行参数。`default_agent` 是初始化数据目录时自带的 Agent。
+- `session.run()` 返回一个异步迭代器,逐条产出 OmniMessage。循环里的判断只挑出模型的完整文本消息;工具调用、思考块等其他内容也在同一个流里。
+- `approve` 是审批回调,返回 `"allow"` 即全部放行。四种审批模式与工具的对应关系见[工具与审批](/tools)。
## 下一步
-- [核心接口](/interfaces):`createAgent`、`Session`、LLM 与 Environment 的接口契约。
+- [接口契约](/interfaces):`createAgent`、`Session`、LLM 与 Environment 背后的接口契约。
- [OmniMessage 协议](/omni-message):`session.run()` 产出的消息结构。
- [Agent 运行循环](/agent-loop):一个 Task 内部经历了什么。
-- [Session 与 Trace](/sessions-and-traces):会话与执行记录如何落盘。
+- [Session 与 Trace](/sessions-and-traces):会话与执行记录如何存储。
diff --git a/packages/docs/content/quickstart.en.md b/packages/docs/content/quickstart.en.md
index fca6c304..17a6601d 100644
--- a/packages/docs/content/quickstart.en.md
+++ b/packages/docs/content/quickstart.en.md
@@ -1,34 +1,37 @@
---
title: Quickstart
-description: Three routes — desktop app, CLI, or SDK — pick one to install PenguinHarness and run your first Task.
+description: Pick one of four routes, the desktop app, the CLI and Web App, Docker, or the SDK, to install PenguinHarness and run your first Task.
---
-PenguinHarness has four ways in. They run the same engine; they differ only in how you meet it. Pick the one that fits you — each route's page carries you all the way to a first Task:
+PenguinHarness has four ways in: the desktop app, the CLI and Web App, Docker, and the SDK. They run the same engine and differ only in how you meet it. Pick the route that fits you; each route's page takes you all the way to a first Task.
+
+## Before you begin
+
+PenguinHarness ships with no built-in model credentials, so you configure a model before your first Task. An API key for one provider is enough, and each route's page covers this step.
+
+A model is always referenced as a `(provider, model_id)` pair; the provider is never inferred from the model id. See [Models & Providers](/models) for the built-in groups.
+
+## Choose a route
| Route | Best for | Terminal needed? |
| --- | --- | --- |
-| [Desktop app](/quickstart-desktop) | Using PenguinHarness as a product, straight away | No — and it installs the `penguin` command for you |
+| [Desktop app](/quickstart-desktop) | Using PenguinHarness as a product, straight away | No, and it installs the `penguin` command for you |
| [CLI and Web App](/quickstart-cli) | Servers and remote machines, or wanting the `penguin` command | Once, to install |
-| [Docker](/quickstart-docker) | A server you deploy rather than install — one container, one volume | Once, to start it |
+| [Docker](/quickstart-docker) | A server you deploy rather than install, with one container and one volume | Once, to start it |
| [SDK](/quickstart-sdk) | Embedding the engine in your own TypeScript program | Yes |
-If you are unsure, take the [desktop app](/quickstart-desktop): it has the fewest steps, and moving to another route later costs you nothing. The macOS and Windows installers are signed, so only a downloaded Linux AppImage needs anything before the first launch — that page carries it.
-
-## What they all share
-
-- **One data root**: `~/.penguin/data` (`%USERPROFILE%\.penguin\data` on Windows; `/data` inside the container). Agents, model configuration and past Sessions live there, so the routes that share a machine can be mixed freely — a model configured in the desktop app is immediately usable from the CLI and the SDK.
-- **One server at a time**: a data root only ever runs one server process. If a CLI-started instance is already up from `penguin web`, the desktop app attaches to it instead of starting a second one.
-- **One interface**: the desktop app and `penguin web` open the same Web App; the former just embeds the server and skips the login.
-
-## Before you start
+If you are unsure, take the [desktop app](/quickstart-desktop). It has the fewest steps, and moving to another route later costs you nothing. The macOS and Windows installers are signed, so only a downloaded Linux AppImage needs a step before its first launch, which the desktop app page covers.
-PenguinHarness ships with no built-in model credentials, so a model must be configured before your first Task — an API key for one Provider is enough. Each route's page covers that step.
+## What all routes share
-A model is always referenced as a `(provider, model_id)` pair — the Provider is never inferred from the model id. See [Models & Providers](/models) for the built-in groups.
+- **One data root**: `~/.penguin/data` (`%USERPROFILE%\.penguin\data` on Windows; `/data` inside the container). Agents, model configuration and past Sessions live there, so routes on the same machine can be mixed freely: a model configured in the desktop app is immediately usable from the CLI and the SDK.
+- **One server at a time**: a data root only ever runs one server process. If you already started one with `penguin web`, the desktop app attaches to it instead of starting a second one.
+- **One interface**: the desktop app and `penguin web` open the same Web App. The desktop app embeds the server and skips the login.
## Next steps
- [Desktop app](/quickstart-desktop): a double-click install that opens already signed in.
-- [CLI and Web App](/quickstart-cli): one line installs `penguin`; includes the full installation reference.
+- [CLI and Web App](/quickstart-cli): one line installs `penguin`, with the full installation reference.
- [Docker](/quickstart-docker): the official image, for a server you reach over the network.
-- [SDK](/quickstart-sdk): create Agents and Sessions from your own program.
+- [SDK](/quickstart-sdk): create agents and Sessions from your own program.
+- [Key concepts](/concepts): the terms used throughout these docs.
diff --git a/packages/docs/content/quickstart.zh.md b/packages/docs/content/quickstart.zh.md
index 4812d3b0..621663a6 100644
--- a/packages/docs/content/quickstart.zh.md
+++ b/packages/docs/content/quickstart.zh.md
@@ -1,34 +1,37 @@
---
title: 快速开始
-description: 桌面端、命令行、SDK 三条路线,挑一条装好 PenguinHarness 并跑通第一个 Task。
+description: 在桌面应用、命令行与 Web App、Docker、SDK 四条路线中任选一条,安装 PenguinHarness 并跑通第一个 Task。
---
-PenguinHarness 有四条入口,背后是同一个引擎,区别只在你以什么方式接触它。先挑一条适合自己的,各自的页面会把你一路带到第一个 Task:
+PenguinHarness 有四条入口:桌面应用、命令行与 Web App、Docker 和 SDK。它们背后是同一个引擎,区别只在于你以什么方式接触它。挑一条适合自己的路线,每条路线的页面都会一路带你跑通第一个 Task。
-| 路线 | 适合 | 需要用终端吗 |
-| --- | --- | --- |
-| [桌面端应用](/quickstart-desktop) | 想直接把 PenguinHarness 当成一个应用来用 | 不需要——而且它会替你装好 `penguin` 命令 |
-| [命令行与 Web 应用](/quickstart-cli) | 装到服务器或远程机器,或想要 `penguin` 命令 | 安装时用一次 |
-| [Docker](/quickstart-docker) | 部署而非安装——一个容器、一个卷 | 启动时用一次 |
-| [SDK](/quickstart-sdk) | 把引擎嵌进自己的 TypeScript 程序 | 需要 |
+## 开始之前
-拿不准就选[桌面端应用](/quickstart-desktop):它步骤最少,而且换到另一条路线不用重来。macOS 与 Windows 的安装包均已签名,只有下载来的 Linux AppImage 在首次启动前需要一步操作,那一页里写了。
+PenguinHarness 不内置任何模型凭据,跑第一个 Task 之前要先配置一个模型。准备好一个供应商的 API Key 即可,每条路线的页面都包含这一步。
-## 各条路线共用什么
+模型始终以 `(provider, model_id)` 二元组引用,供应商绝不由模型 id 推断。内置分组见[模型与 Provider](/models)。
-- **同一个数据目录**:`~/.penguin/data`(Windows 为 `%USERPROFILE%\.penguin\data`;容器内为 `/data`)。Agent、模型配置与历史会话都在其中,因此同机的几条路线可以随时混用——桌面端配好的模型,CLI 与 SDK 立刻就能用。
-- **同一时刻只有一个服务端**:一个数据目录只跑一个服务端进程。命令行已经用 `penguin web` 启动过实例时,桌面端应用会直接接入它,而不是再起一个。
-- **同一套界面**:桌面端应用与 `penguin web` 打开的是同一个 Web App,只是前者内嵌了服务端、免去登录。
+## 选择路线
-## 开始之前
+| 路线 | 适合 | 需要终端吗? |
+| --- | --- | --- |
+| [桌面应用](/quickstart-desktop) | 想直接把 PenguinHarness 当作产品来用 | 不需要,而且它会替你装好 `penguin` 命令 |
+| [命令行与 Web App](/quickstart-cli) | 装到服务器或远程机器上,或者想要 `penguin` 命令 | 安装时用一次 |
+| [Docker](/quickstart-docker) | 部署而非安装的服务端:一个容器、一个卷 | 启动时用一次 |
+| [SDK](/quickstart-sdk) | 把引擎嵌入自己的 TypeScript 程序 | 需要 |
+
+拿不准就选[桌面应用](/quickstart-desktop):它步骤最少,以后换到别的路线也不用付出任何代价。macOS 和 Windows 的安装包都已签名,只有下载来的 Linux AppImage 在首次启动前需要多做一步,桌面应用页面里写了。
-PenguinHarness 不内置任何模型凭据,跑第一个 Task 之前必须先配置一个模型,准备好一个 Provider 的 API Key 即可。三条路线各自的页面都包含这一步。
+## 各条路线的共同点
-模型引用始终是 `(provider, model_id)` 二元组,Provider 绝不由模型 id 推断;内置分组见[模型与 Provider](/models)。
+- **同一个数据目录**:`~/.penguin/data`(Windows 为 `%USERPROFILE%\.penguin\data`,容器内为 `/data`)。Agent、模型配置和历史会话都在其中,所以同一台机器上的几条路线可以随意混用:在桌面应用里配好的模型,CLI 和 SDK 立刻就能用。
+- **同一时刻只有一个服务端**:一个数据目录只运行一个服务端进程。如果你已经用 `penguin web` 启动了一个,桌面应用会直接接入它,而不会再启动第二个。
+- **同一套界面**:桌面应用与 `penguin web` 打开的是同一个 Web App,只是桌面应用内嵌了服务端,并免去了登录。
## 下一步
-- [桌面端应用](/quickstart-desktop):双击安装,打开即已登录。
-- [命令行与 Web 应用](/quickstart-cli):一行安装 `penguin`,含完整的安装参考。
+- [桌面应用](/quickstart-desktop):双击安装,打开即已登录。
+- [命令行与 Web App](/quickstart-cli):一行命令装好 `penguin`,附完整的安装参考。
- [Docker](/quickstart-docker):官方镜像,用于经网络访问的服务端。
- [SDK](/quickstart-sdk):在自己的程序里创建 Agent 与 Session。
+- [核心概念](/concepts):文档中通用的术语。
diff --git a/packages/docs/content/remote-control.en.md b/packages/docs/content/remote-control.en.md
new file mode 100644
index 00000000..b81434d6
--- /dev/null
+++ b/packages/docs/content/remote-control.en.md
@@ -0,0 +1,247 @@
+---
+title: Remote control
+description: Connect a conversation to a Feishu, Telegram, QQ or WeChat bot, and talk to its agent from that app.
+---
+
+Remote control connects one conversation to a bot on Feishu, Telegram, QQ or WeChat. Messages you send to the bot go into the conversation exactly as if you had typed them in the Web App, and the agent's replies are sent back to the chat. PenguinHarness opens the connection to the messaging platform itself, so you need no public address or callback URL.
+
+- To connect a bot, follow the section for your app: [Connect Feishu](#connect-feishu), [Connect Telegram](#connect-telegram), [Connect QQ](#connect-qq) or [Connect WeChat](#connect-wechat).
+- To learn what arrives where once a bot is connected, see [After you connect](#after-you-connect).
+- Before you connect a bot that other people can message, read [Security](#security).
+
+## Before you begin
+
+- **The conversation has started.** Remote control belongs to a conversation, and a conversation exists only after its first message. In a new, unsent chat, the panel shows "Available once the conversation starts".
+- **You are the Project owner.** Only the owner can save credentials, scan a QR code, and turn a connection on or off. Other members can open the settings, see the status, and run the tests.
+- **PenguinHarness is running.** The connection lives in the PenguinHarness server or desktop app. While it is stopped, the bot does not answer.
+
+## Open remote control
+
+Remote control is available from the conversation's menu in the sidebar and as a side panel next to the chat. The dialog and the panel hold the same settings.
+
+### Open the dialog
+
+1. In the sidebar, right-click the conversation. You can also hover over it and select **More** (the "…" button), press Shift+F10, or press and hold the row on a touch screen.
+2. Select **Remote control**. The **Remote control** dialog opens.
+
+In company mode, a desk conversation's menu offers **Remote control** too.
+
+### Open the side panel
+
+Use any of these:
+
+- In the top-right corner of the chat, select **Right sidebar**, then pick **Remote control**.
+- In the side panel, select **Add panel** (+), then pick **Remote control**.
+- Open the floating **Shortcuts** button and select the paper-plane entry, **Remote control**.
+
+## Remote control settings
+
+The settings run from top to bottom in this order:
+
+| Setting | What it does |
+| --- | --- |
+| Channel tabs | **Feishu**, **Telegram**, **QQ** and **WeChat**, along the top of the dialog. Each channel keeps its own saved settings for this conversation. |
+| **Enable connection** | Turns the connection on or off. Turning it on binds the bot to this conversation; turning it off releases the bot. Saved credentials stay either way. |
+| **Connection status** | **Not connected**, **Connecting**, **Connected** or **Connection error**, plus when the last message arrived and the last connection or delivery problem. The status refreshes on its own. |
+| **Test connection** | Checks that the saved or typed credentials sign in, and reports the response time. |
+| **Send test message** | Sends a short test message to the chat. It works once the bot is connected and has received at least one message. |
+| Channel fields | The credentials for the selected channel. See the section for your channel: [Feishu](#connect-feishu), [Telegram](#connect-telegram), [QQ](#connect-qq) or [WeChat](#connect-wechat). |
+| **Final reply only** | Off by default. See [Delivery options](#delivery-options). |
+| **One message per line** | Off by default. See [Delivery options](#delivery-options). |
+| **Render Markdown** | On by default. See [Delivery options](#delivery-options). |
+| **Save** | Saves the credentials and the delivery options. Saving does not turn the connection on or off. |
+
+Below the form, three collapsed sections explain the selected channel: **Set up the bot** (the setup steps and an **Open tutorial** link), **What binding does**, and **Troubleshooting**.
+
+When the **Enable connection** switch is unavailable, a line under the test buttons says why: the credentials are not saved yet, the form has unsaved changes, or another channel of this conversation is already enabled.
+
+A saved secret is never shown again. Leave its field empty to keep it. To delete it, turn off the connection, select the clear option under the field, such as **Clear stored App Secret** or **Clear stored Bot Token**, and select **Save**.
+
+## Connect Feishu
+
+**Before you begin**
+
+- A Feishu or Lark account that can create a self-built app in the developer console.
+
+1. In the [Feishu developer console](https://open.feishu.cn/app), create a self-built app.
+2. Enable the bot capability for the app.
+3. Subscribe to the message-receive event, and set the subscription mode to long connection.
+4. In PenguinHarness, open **Remote control** for the conversation and select the **Feishu** tab.
+5. From the app's credentials page, copy the App ID and App Secret into **App ID** and **App Secret**.
+6. If you use Lark, change **API domain** to `https://open.larksuite.com`. The default, `https://open.feishu.cn`, is for Feishu.
+7. Select **Save**.
+8. In the developer console, publish an app version and get it approved.
+9. Turn on **Enable connection**, and wait for **Connected**.
+10. In Feishu, send the bot a message.
+
+The bot works in direct chats and in groups. When a message starts by mentioning the bot, the mention is removed before the text reaches the agent.
+
+To receive images and files, the Feishu app needs the permission to read message resources in addition to receiving messages. If the permission is missing, the bot replies with the permissions to grant and a link to the developer console.
+
+## Connect Telegram
+
+**Before you begin**
+
+- A Telegram account.
+
+1. In Telegram, open [@BotFather](https://t.me/BotFather) and send `/newbot` to create a bot.
+2. Name the bot as prompted, and copy the Bot Token that @BotFather returns.
+3. In PenguinHarness, open **Remote control** for the conversation and select the **Telegram** tab.
+4. Paste the token into **Bot Token**. A Bot Token looks like `<digits>:<secret>`.
+5. Select **Save**.
+6. Turn on **Enable connection**, and wait for **Connected**.
+7. In Telegram, find the bot and send it a message.
+
+**Test connection** names the bot the token signs in as. If the bot's Group Privacy setting is on, the result also warns that the bot receives no ordinary messages in groups where it is not an administrator. See [Troubleshooting](#troubleshooting).
+
+In a forum group, replies stay in the topic the message came from. Telegram channel posts are not supported; the bot handles groups and direct chats.
+
+A Bot Token can serve only one program at a time. Do not use the same token in another PenguinHarness server or bot script while the connection is on.
+
+## Connect QQ
+
+**Before you begin**
+
+- A bot on the [QQ open platform](https://q.qq.com/qqbot/dashboard/). Register as a developer there to create one.
+- In the bot's development settings, the event subscription mode is set to WebSocket, with the callback URL left empty.
+- Your own QQ account, or a test group, is on the bot's sandbox allowlist.
+
+You can give PenguinHarness the bot's credentials by scanning a QR code or by entering them by hand.
+
+### Connect with a QR code
+
+1. In PenguinHarness, open **Remote control** for the conversation and select the **QQ** tab.
+2. Select **Connect by QR**.
+3. Scan the code with QQ on your phone.
+4. On the page that opens, pick the bot to authorize, and confirm. PenguinHarness saves the credentials and shows "Saved the credentials for bot {appId} — the connection can be enabled now".
+5. Turn on **Enable connection**, and wait for **Connected**.
+6. In QQ, find the bot and send it a message.
+
+### Enter the credentials by hand
+
+1. On the QQ open platform, copy the App ID and App Secret from the bot's development settings page.
+2. In PenguinHarness, open **Remote control**, select the **QQ** tab, and under **Or enter them by hand**, fill in **App ID** and **App Secret**.
+3. Select **Save**.
+4. Turn on **Enable connection**, and wait for **Connected**.
+5. In QQ, find the bot and send it a message.
+
+> [!WARNING]
+> QQ lets a bot reply only to a message you just sent it. The bot cannot start a message on its own.
+
+This rule shapes how QQ behaves:
+
+- A turn you start in the Web App is not sent to QQ.
+- A few minutes after your last QQ message, replies can no longer be delivered. Send the bot another message in QQ to continue.
+- One QQ message can receive at most 4 replies, or 5 in a group. When a run produces more messages than that, the last reply carries the rest combined.
+- With **Final reply only** on, a run that takes longer than about five minutes delivers nothing.
+- QQ carries text only. The bot does not read images or files you send, and the agent cannot send files to QQ.
+
+## Connect WeChat
+
+WeChat connects through its official bot channel. There is no console and nothing to register: you scan a QR code, and the credential is saved for you.
+
+1. In PenguinHarness, open **Remote control** for the conversation and select the **WeChat** tab.
+2. Select **Connect by scanning** to generate a QR code.
+3. Scan the code with WeChat on your phone.
+4. If your phone shows a number, type it into **Pairing code** and select **Confirm**.
+5. Confirm the authorization on your phone. PenguinHarness saves the credential and shows "Saved the credential for bot {botId} — the connection can be enabled now".
+6. Turn on **Enable connection**, and wait for **Connected**.
+7. Wait about 15 seconds.
+8. Find the bot in WeChat and send it a message. If you get no reply, send the message again.
+
+> [!NOTE]
+> Right after the status turns **Connected**, the connection clears messages that were waiting from before. A message that arrives in those first seconds is dropped rather than answered. This happens again each time the connection is turned on or the server restarts.
+
+If a code expires before you scan it, a new one appears automatically. To bind a different WeChat account later, turn off the connection, then select **Scan again**.
+
+WeChat differs from the other channels:
+
+- The bot receives direct chats only. Mentioning it in a group does nothing.
+- Text, images and files travel in both directions.
+- A voice message arrives as WeChat's own transcription. A recording WeChat could not transcribe cannot be read. A video arrives as a file.
+
+## After you connect
+
+A connected conversation shows a paper-plane icon on its row in the sidebar. Point at the icon to see which channel is enabled, for example "Telegram connection enabled".
+
+### Messages you send to the bot
+
+- A message to the bot starts a Task in the conversation, just like a message typed in the Web App. The agent is not told that the message came from a chat app.
+- If the agent is busy, the message waits in the queue and runs next.
+- On Feishu, Telegram and WeChat, images and files you send are attached to the message. Each image can be up to 20 MB, and one connection accepts up to 40 MB of images per 10 minutes. Files follow the upload limits in [System settings](/settings); Telegram also caps bot downloads at 20 MB.
+- Stickers are not supported, and neither are voice and video messages on Feishu and Telegram. The bot replies that only text, image and file messages are supported.
+- On Feishu, Telegram and WeChat, messages sent while the connection is off are not delivered later.
+
+### Replies the bot sends
+
+- Each assistant message is sent to the chat as soon as it is complete, unless **Final reply only** is on. Replies go to the chat that last messaged the bot, so nothing is sent before the bot has received its first message.
+- Turns you start in the Web App are sent to the chat too, except on QQ.
+- In a group, the first reply of a run replies to the message that started it.
+- A long reply is split into several messages of up to 4000 characters.
+- When a reply mentions a file that the run created or changed in the Workspace, the file follows the reply into the chat. A run sends at most 5 files, with images up to 10 MB and other files up to 30 MB. A file that could not be sent is not announced in the chat; it is recorded in the Cost Center's error records.
+
+### Approvals
+
+Tool approvals cannot be answered from the chat. When a tool call needs approval, the bot sends "A tool call is waiting for your approval in the PenguinHarness web UI." Approve or deny it in the Web App.
+
+Whether a tool call needs approval depends on the conversation's [approval mode](/tools#approval). New conversations start in **Approve everything**, which asks for nothing, so read [Security](#security) before you bind a bot to one.
+
+There are no chat commands. Text such as `/stop` goes to the agent as an ordinary message.
+
+### Delivery options
+
+| Option | Default | Effect |
+| --- | --- | --- |
+| **Final reply only** | Off | Sends only the last thing the assistant says in a run, when the run ends. The notes it writes between tool calls stay in the Web App, and the chat stays silent while a long run works. The approval reminder still arrives immediately. |
+| **One message per line** | Off | Sends each non-blank line of a reply as its own message, one second apart. A reply becomes at most 20 messages (on QQ, its reply limit); the remaining lines are combined into the last one. |
+| **Render Markdown** | On | Shows headings, bold text, lists, code and tables as formatting in the chat app, as far as the app supports them. If the app refuses the formatting, the reply is sent as plain text. |
+
+Change an option, then select **Save**. Options do not apply to the test message or to notices such as the approval reminder.
+
+How each app shows Markdown:
+
+| Channel | What renders |
+| --- | --- |
+| Feishu | A card with headings, bold, italic, strikethrough, code, code blocks, lists, quotes, rules, links and tables. A table longer than five rows arrives as a code block. |
+| Telegram | Bold, italic, strikethrough, links, inline code and code blocks. A heading becomes a bold line, list markers stay as text, and a table arrives as a code block. |
+| QQ | Headings, bold, italic, strikethrough, lists, quotes, rules and links. Code blocks arrive as plain lines and tables as their rows. A plain-text retry uses one more of the replies QQ allows. |
+| WeChat | Headings, bold, strikethrough, lists, quotes, rules, links, inline code, code blocks and tables. Headings past the fourth level, italics around Chinese text and inline images lose their formatting; images become links. |
+
+## Limits
+
+- **One channel per conversation.** A conversation can keep saved settings for all four channels, but only one of them can be enabled at a time.
+- **One conversation per bot.** The same bot can be saved in several conversations, but its connection can be enabled in only one. To move a bot, turn its connection off in the old conversation and turn it on in the new one; you do not need to delete the credentials.
+- **QQ replies only.** See [Connect QQ](#connect-qq).
+- **WeChat direct chats only.** See [Connect WeChat](#connect-wechat).
+- Deleting a conversation deletes its remote control settings.
+
+## Security
+
+> [!WARNING]
+> Remote control has no sender allow-list. Anyone who can message the bot controls the conversation: they can start Tasks, and the agent runs tools on their behalf under the conversation's approval mode.
+
+Keep the bot private. Do not add it to groups with people you do not trust, and use an approval mode that asks before risky tool calls.
+
+Credentials are stored on the server and never sent back to the browser in full. QR scanning keeps the secret on the server as well.
+
+## Troubleshooting
+
+**Send test message is unavailable.** The bot must receive a message first, so it knows which chat to send to. Send it a message in the chat app, then try again.
+
+**The status shows Connection error.** Check the credentials. For Feishu, also check **API domain** and that the event subscription uses long connection.
+
+**Only one channel can be enabled per conversation.** Turn off the other channel's connection in this conversation first.
+
+**This bot's connection is enabled on another conversation.** Turn off the connection in that conversation, then enable it here.
+
+**Telegram: the bot ignores messages in a group.** Telegram's Group Privacy is on by default. Under it, a bot that is not a group administrator receives only commands addressed to it and replies to its own messages. Either make the bot an administrator of the group, or turn Group Privacy off with `/setprivacy` in @BotFather and then remove the bot from the group and add it back. A group the bot is already in does not pick up the privacy change until you do.
+
+**Telegram: another program is polling.** A Bot Token serves one program at a time. Close the other PenguinHarness server or script that uses the token, or give this conversation its own bot. A `getUpdates` call you run by hand counts as another program too, so turn off the connection before running one.
+
+**Telegram: the panel says no message has arrived.** That line covers only the current connection. Turning the connection off and on, or saving the credentials, starts a new one. Send a fresh message. If nothing arrives, check that the bot is still in the group and that nothing else is polling the token.
+
+**QQ: replies stop arriving.** The reply window has closed. Send the bot another message in QQ.
+
+**WeChat: the bot does not answer in a group.** The WeChat channel receives direct chats only. Message the bot directly.
+
+**WeChat: the first message gets no reply.** A message sent in the first seconds after the status turns **Connected** is dropped. Wait about 15 seconds, then send the message again.
diff --git a/packages/docs/content/remote-control.zh.md b/packages/docs/content/remote-control.zh.md
new file mode 100644
index 00000000..884d364a
--- /dev/null
+++ b/packages/docs/content/remote-control.zh.md
@@ -0,0 +1,247 @@
+---
+title: 远程控制
+description: 把对话连接到飞书、Telegram、QQ 或微信机器人,在聊天应用里直接和 Agent 对话。
+---
+
+远程控制把一个对话连接到飞书、Telegram、QQ 或微信上的机器人。发给机器人的消息会进入这个对话,效果和在 Web App 里输入完全一样;Agent 的回复也会发回聊天里。连接由 PenguinHarness 主动向消息平台发起,所以不需要公网地址或回调 URL。
+
+- 连接机器人:按所用的应用查看[连接飞书](#连接飞书)、[连接 Telegram](#连接-telegram)、[连接 QQ](#连接-qq) 或[连接微信](#连接微信)。
+- 了解连接之后消息怎么流转:见[连接之后](#连接之后)。
+- 如果别人也能给这个机器人发消息,连接之前先读[安全](#安全)。
+
+## 开始之前
+
+- **对话已经开始。** 远程控制属于某个对话,而对话要在发出第一条消息后才存在。新建但还没发消息的对话里,面板会显示「发送第一条消息后可用」。
+- **你是 Project owner。** 只有 owner 能保存凭证、扫码,以及开启或关闭连接。其他成员可以打开设置、查看状态和运行测试。
+- **PenguinHarness 正在运行。** 连接运行在 PenguinHarness 服务端或桌面应用里,它们停止运行时,机器人不会应答。
+
+## 打开远程控制
+
+远程控制有两个入口:侧边栏里对话的菜单,以及对话页旁边的右侧栏面板。两处的设置完全相同。
+
+### 打开对话框
+
+1. 在侧边栏中右键点击对话。也可以把鼠标悬停在对话上,选择**更多**(「…」按钮),或者按 Shift+F10,在触屏上则长按这一行。
+2. 选择**远程控制**,打开**远程控制**对话框。
+
+公司模式下,工位对话的菜单里同样有**远程控制**。
+
+### 打开右侧栏面板
+
+以下方式任选其一:
+
+- 在对话页右上角选择**右侧栏**,再选择**远程控制**。
+- 在右侧栏里选择**添加面板**(+),再选择**远程控制**。
+- 点开悬浮的**快捷方式**按钮,选择纸飞机图标的**远程控制**。
+
+## 远程控制设置
+
+设置从上到下依次为:
+
+| 设置 | 作用 |
+| --- | --- |
+| 渠道标签页 | 对话框顶部的**飞书**、**Telegram**、**QQ** 和**微信**。每个渠道在这个对话里单独保存自己的设置。 |
+| **启用连接** | 开启或关闭连接。开启即把机器人绑定到这个对话,关闭即解除绑定。无论开关,已保存的凭证都会保留。 |
+| **连接状态** | **未连接**、**连接中**、**已连接**或**连接错误**,同时显示最近一条消息的到达时间,以及最近一次连接或投递问题。状态会自动刷新。 |
+| **测试连接** | 检查已保存或刚填写的凭证能否登录,并显示响应时间。 |
+| **发送测试消息** | 向聊天发送一条简短的测试消息。机器人已连接、并且至少收到过一条消息后才能使用。 |
+| 渠道字段 | 所选渠道的凭证,见各渠道的小节:[飞书](#连接飞书)、[Telegram](#连接-telegram)、[QQ](#连接-qq) 或[微信](#连接微信)。 |
+| **只发送最终回复** | 默认关闭,见[投递选项](#投递选项)。 |
+| **每行一条消息** | 默认关闭,见[投递选项](#投递选项)。 |
+| **渲染 Markdown** | 默认开启,见[投递选项](#投递选项)。 |
+| **保存** | 保存凭证和投递选项。保存不会开启或关闭连接。 |
+
+表单下方有三个折叠区块,讲解所选渠道:**如何创建机器人**(包括设置步骤和**前往教程**链接)、**绑定后会发生什么**和**常见问题**。
+
+**启用连接**开关不可用时,测试按钮下方会写明原因:凭证还没保存、表单有未保存的修改,或者这个对话已经启用了另一个渠道。
+
+已保存的密钥不会再显示出来。字段留空即保留原密钥。要删除密钥,先关闭连接,再勾选字段下方的清除选项,例如 **清除已存 App Secret** 或 **清除已存 Bot Token**,然后选择**保存**。
+
+## 连接飞书
+
+**开始之前**
+
+- 一个能在开发者后台创建企业自建应用的飞书或 Lark 账号。
+
+1. 在[飞书开发者后台](https://open.feishu.cn/app)创建一个企业自建应用。
+2. 为应用开通机器人能力。
+3. 订阅「接收消息」事件,事件订阅方式选择「长连接」。
+4. 在 PenguinHarness 中打开这个对话的**远程控制**,选择**飞书**标签页。
+5. 在应用的「凭证与基础信息」页取得 App ID 和 App Secret,分别填入 **App ID** 和 **App Secret**。
+6. 如果用的是 Lark,把 **API 域名**改为 `https://open.larksuite.com`。默认值 `https://open.feishu.cn` 对应飞书。
+7. 选择**保存**。
+8. 在开发者后台发布应用版本,并通过审核。
+9. 打开**启用连接**,等状态变为**已连接**。
+10. 在飞书里给机器人发一条消息。
+
+机器人在单聊和群聊中都能用。消息开头 @ 了机器人时,这段 @ 会在消息送达 Agent 之前去掉。
+
+要接收图片和文件,飞书应用除了接收消息的权限,还需要读取消息资源的权限。缺少这项权限时,机器人会回复需要开通的权限,并附上开发者后台的链接。
+
+## 连接 Telegram
+
+**开始之前**
+
+- 一个 Telegram 账号。
+
+1. 在 Telegram 中打开 [@BotFather](https://t.me/BotFather),发送 `/newbot` 创建机器人。
+2. 按提示给机器人取名,复制 @BotFather 返回的 Bot Token。
+3. 在 PenguinHarness 中打开这个对话的**远程控制**,选择 **Telegram** 标签页。
+4. 把 Token 粘贴到 **Bot Token**。Bot Token 形如 `<digits>:<secret>`。
+5. 选择**保存**。
+6. 打开**启用连接**,等状态变为**已连接**。
+7. 在 Telegram 中找到这个机器人,给它发一条消息。
+
+**测试连接**会显示这个 Token 登录的是哪个机器人。如果机器人开启了 Group Privacy,测试结果还会提醒:在它不担任管理员的群里,它收不到普通消息。解决办法见[常见问题](#常见问题)。
+
+在开启了话题的群组里,回复会留在消息所在的话题中。Telegram 频道的贴文不受支持,机器人只处理群聊和单聊。
+
+一个 Bot Token 同一时刻只能供一个程序使用。连接开启期间,不要在另一个 PenguinHarness 服务端或机器人脚本里使用同一个 Token。
+
+## 连接 QQ
+
+**开始之前**
+
+- 一个 [QQ 开放平台](https://q.qq.com/qqbot/dashboard/)上的机器人。需要先在平台注册成为开发者,才能创建机器人。
+- 机器人的「开发配置」里,事件订阅方式已设为 WebSocket,回调地址留空。
+- 你自己的 QQ 号或某个测试群已经加入机器人的沙箱白名单。
+
+机器人的凭证可以扫码交给 PenguinHarness,也可以手动填写。
+
+### 扫码连接
+
+1. 在 PenguinHarness 中打开这个对话的**远程控制**,选择 **QQ** 标签页。
+2. 选择**扫码连接**。
+3. 用手机 QQ 扫描二维码。
+4. 在打开的页面里选择要授权的机器人并确认。PenguinHarness 会保存凭证,并显示「已保存机器人 {appId} 的凭据,可以启用连接了」。
+5. 打开**启用连接**,等状态变为**已连接**。
+6. 在 QQ 中找到这个机器人,给它发一条消息。
+
+### 手动填写凭证
+
+1. 在 QQ 开放平台机器人的「开发设置」页,复制 App ID 和 App Secret。
+2. 在 PenguinHarness 中打开**远程控制**,选择 **QQ** 标签页,在**或手动填写**下方填入 **App ID** 和 **App Secret**。
+3. 选择**保存**。
+4. 打开**启用连接**,等状态变为**已连接**。
+5. 在 QQ 中找到这个机器人,给它发一条消息。
+
+> [!WARNING]
+> QQ 只允许机器人回复你刚发给它的消息,不允许机器人主动发消息。
+
+这条规则决定了 QQ 渠道的表现:
+
+- 在 Web App 里发起的对话不会同步到 QQ。
+- 距离你上一条 QQ 消息过去几分钟后,回复就发不出去了。想继续,在 QQ 里再给机器人发一条消息即可。
+- 一条 QQ 消息最多能收到 4 条回复,群聊里是 5 条。一次运行产生的消息超出这个数量时,余下的内容会合并到最后一条回复里。
+- 开启**只发送最终回复**时,运行超过约五分钟就一条也发不出去。
+- QQ 只支持文本。机器人不读取你发送的图片和文件,Agent 也不能向 QQ 发送文件。
+
+## 连接微信
+
+微信通过官方的机器人通道连接。不需要后台,也不用注册:扫码之后,凭证会自动保存。
+
+1. 在 PenguinHarness 中打开这个对话的**远程控制**,选择**微信**标签页。
+2. 选择**扫码连接**,生成二维码。
+3. 用手机微信扫描二维码。
+4. 如果手机上显示了一组数字,把它填入**配对码**,然后选择**确认**。
+5. 在手机上确认授权。PenguinHarness 会保存凭证,并显示「已保存机器人 {botId} 的凭据,可以启用连接了」。
+6. 打开**启用连接**,等状态变为**已连接**。
+7. 等待约 15 秒。
+8. 在微信里找到这个机器人,给它发一条消息。如果没有收到回复,再发一次。
+
+> [!NOTE]
+> 状态刚变为**已连接**时,连接会先清掉此前积压的消息,这最初几秒里到达的消息也会一并清掉,得不到回复。每次开启连接或服务端重启后,都会再经历一次。
+
+二维码在扫描前过期时,会自动换成新的。以后要绑定别的微信账号,先关闭连接,再选择**重新扫码**。
+
+微信和其他渠道有这些不同:
+
+- 机器人只接收单聊。在群里 @ 它不会有任何反应。
+- 文本、图片和文件都能双向传输。
+- 语音消息按微信自带的语音转文字结果送达;微信没能转写的语音无法读取。视频以文件形式送达。
+
+## 连接之后
+
+已连接的对话会在侧边栏的条目上显示一个纸飞机图标。鼠标指向图标,可以看到启用的是哪个渠道,例如「Telegram 连接已启用」。
+
+### 发给机器人的消息
+
+- 发给机器人的消息会在对话里启动一个 Task,和在 Web App 里输入的消息一样。Agent 不会知道这条消息来自聊天应用。
+- Agent 正忙时,消息会先排队,等轮到它再运行。
+- 在飞书、Telegram 和微信上,你发送的图片和文件会以附件形式随消息进入对话。每张图片最大 20 MB,同一个连接每 10 分钟最多接收 40 MB 图片。文件遵循[系统设置](/settings)里的上传限制;Telegram 另外把机器人能下载的文件限制在 20 MB。
+- 不支持贴纸,飞书和 Telegram 上的语音、视频消息也不支持。遇到这些消息,机器人会回复「目前仅支持文本、图片和文件消息。」
+- 在飞书、Telegram 和微信上,连接关闭期间发给机器人的消息,之后也不会补发。
+
+### 机器人发出的回复
+
+- 除非开启了**只发送最终回复**,否则每条助手消息一完成就发到聊天里。回复会发往最近一次给机器人发消息的聊天,所以机器人收到第一条消息之前,什么都不会发送。
+- 在 Web App 里发起的对话也会同步到聊天,QQ 除外。
+- 在群聊里,一次运行的第一条回复会引用触发这次运行的那条消息。
+- 过长的回复会拆成多条消息,每条不超过 4000 个字符。
+- 如果回复提到了本次运行在 Workspace 里创建或修改的文件,这些文件会跟着回复发到聊天里。一次运行最多发送 5 个文件,图片不超过 10 MB,其他文件不超过 30 MB。有文件没发出去时不会在聊天里说明,而是记入成本中心的异常记录。
+
+### 审批
+
+工具审批不能在聊天里完成。有工具调用等待审批时,机器人会发送「有工具调用正在等待你在网页端审批。」请到 Web App 里批准或拒绝。
+
+工具调用要不要审批,取决于对话的[审批模式](/tools#审批)。新对话默认是**全部放行**,什么都不询问,所以把机器人绑定到这样的对话之前,先读[安全](#安全)。
+
+聊天里不支持命令。`/stop` 这样的文本也会当成普通消息发给 Agent。
+
+### 投递选项
+
+| 选项 | 默认 | 效果 |
+| --- | --- | --- |
+| **只发送最终回复** | 关 | 运行结束时,只发送助手在这次运行中说的最后一段话。工具调用之间写下的过程记录留在 Web App 里,长时间运行期间聊天里一片安静。审批提醒仍会立即送达。 |
+| **每行一条消息** | 关 | 回复的每个非空行各发一条消息,每条间隔一秒。一条回复最多拆成 20 条消息(QQ 以它的回复上限为准),余下的行合并成最后一条。 |
+| **渲染 Markdown** | 开 | 在聊天应用里把标题、粗体、列表、代码和表格显示为排版格式,具体取决于应用支持到什么程度。应用拒绝这种排版时,回复改以纯文本发送。 |
+
+修改选项后,选择**保存**。这些选项对测试消息和审批提醒之类的通知不起作用。
+
+各应用对 Markdown 的支持:
+
+| 渠道 | 能显示的格式 |
+| --- | --- |
+| 飞书 | 以卡片显示标题、粗体、斜体、删除线、代码、代码块、列表、引用、分割线、链接和表格。超过五行的表格以代码块发送。 |
+| Telegram | 粗体、斜体、删除线、链接、行内代码和代码块。标题变成一行粗体,列表符号保留为文本,表格以代码块发送。 |
+| QQ | 标题、粗体、斜体、删除线、列表、引用、分割线和链接。代码块按普通文本行发送,表格按行发送。改以纯文本重发时,会多占用一条 QQ 允许的回复。 |
+| 微信 | 标题、粗体、删除线、列表、引用、分割线、链接、行内代码、代码块和表格。五级以下的标题、中文两侧的斜体和行内图片会失去格式,图片改为链接。 |
+
+## 限制
+
+- **一个对话只能启用一个渠道。** 一个对话可以保存全部四个渠道的设置,但同一时刻只能启用其中一个。
+- **一个机器人只能在一个对话里启用。** 同一个机器人可以保存在多个对话里,但它的连接只能在其中一个对话里启用。要换到别的对话,先在原对话关闭连接,再到新对话开启,不必删除凭证。
+- **QQ 只能被动回复。** 见[连接 QQ](#连接-qq)。
+- **微信只支持单聊。** 见[连接微信](#连接微信)。
+- 删除对话时,它的远程控制设置会一并删除。
+
+## 安全
+
+> [!WARNING]
+> 远程控制没有发送者白名单。任何能给机器人发消息的人都能操控这个对话:他们可以发起 Task,Agent 会按这个对话的审批模式替他们运行工具。
+
+不要公开机器人:别把它拉进有你不信任的人的群,并选用在有风险的工具调用前先询问的审批模式。
+
+凭证保存在服务端,不会完整地发回浏览器。扫码连接时,密钥同样只留在服务端。
+
+## 常见问题
+
+**发送测试消息不可用。** 机器人要先收到一条消息,才知道该发到哪个聊天。先在聊天应用里给它发一条消息,再试一次。
+
+**状态显示连接错误。** 检查凭证。如果是飞书,还要检查 **API 域名**,并确认事件订阅方式是长连接。
+
+**同一会话只能启用一个渠道。** 先在这个对话里关闭另一个渠道的连接。
+
+**该机器人的连接已在另一个会话中启用。** 先到那个对话里关闭连接,再在这里启用。
+
+**Telegram:机器人不理会群里的消息。** Telegram 的 Group Privacy 默认开启。开启时,不担任群管理员的机器人只能收到明确发给它的命令,以及对它自己消息的回复。解决办法有两个:把机器人设为这个群的管理员;或者在 @BotFather 里用 `/setprivacy` 关闭 Group Privacy,再把机器人移出群、重新拉进来。机器人已经在的群,不做这一步就不会应用隐私设置的变更。
+
+**Telegram:提示有其他程序在轮询。** 一个 Bot Token 同一时刻只能供一个程序使用。关掉正在用这个 Token 的另一个 PenguinHarness 服务端或脚本,或者给这个对话单独建一个机器人。手动调用 `getUpdates` 也算另一个程序,调用之前先关闭连接。
+
+**Telegram:面板显示还没有收到过消息。** 这一行只统计当前这条连接。关闭再开启连接,或者再保存一次凭证,都会开启一条新连接。先重新发一条消息。如果仍然显示没有收到,检查机器人是否还在群里,以及有没有别的程序在轮询这个 Token。
+
+**QQ:收不到回复了。** 回复窗口已经关闭。在 QQ 里再给机器人发一条消息。
+
+**微信:机器人在群里没有反应。** 微信渠道只接收单聊,请直接私聊机器人。
+
+**微信:第一条消息没有回复。** 状态变为**已连接**后的最初几秒里,连接会清掉收到的消息。等约 15 秒,再重新发送。
diff --git a/packages/docs/content/schedules.en.md b/packages/docs/content/schedules.en.md
new file mode 100644
index 00000000..fb55a1ea
--- /dev/null
+++ b/packages/docs/content/schedules.en.md
@@ -0,0 +1,102 @@
+---
+title: Scheduled tasks
+description: Have an agent run a prompt on a schedule in a conversation, and manage those tasks from the conversation's Scheduled tasks panel.
+---
+
+A scheduled task sends a prompt to an agent at a set time, once or on a repeating period. A task bound to a conversation sends its prompt into that conversation, so the agent works with everything the conversation already holds. You create and manage these tasks in the conversation's **Scheduled tasks** panel.
+
+> [!NOTE] Tasks that start a new Session
+> A scheduled task can instead open a new Session each time it runs. You create those on the agent's settings page, which lists all of that agent's scheduled tasks, including the ones bound to conversations. See [Agents](/agents).
+
+- To see a conversation's tasks, see [Open the Scheduled tasks panel](#open-the-scheduled-tasks-panel).
+- To add a task, see [Create a task with AI](#create-a-task-with-ai) or [Create a task manually](#create-a-task-manually).
+- To pause, change or remove a task, see [Turn a task on or off](#turn-a-task-on-or-off) and [Edit or delete a task](#edit-or-delete-a-task).
+
+## Open the Scheduled tasks panel
+
+The panel is one of the side panels of the chat page. It is available once the conversation has started: in a draft, it asks you to send the first message first.
+
+1. Open the conversation.
+2. In the top-right corner of the chat toolbar, select **Right sidebar** or **Bottom panel**. You can also use the **Shortcuts** launcher on the conversation's right edge.
+3. Choose **Scheduled tasks**. If the side panel already shows other panels, select **Add panel** first.
+
+The panel lists the tasks bound to this conversation. The search box matches a task's name and its prompt. The filters are **All**, **Active**, **Paused** and **Completed**; **Completed** covers tasks that are done, expired or missed. Each row shows a state icon, the task name and its schedule in plain words, for example:
+
+- "Every day at 08:00 · Next: tomorrow 08:00"
+- "Every 30 minutes"
+- "Every Monday at 09:00"
+- "One-off · Sep 3, 10:00"
+
+When a task fires while the conversation is still working, its prompt waits and is sent once the conversation is idle. Until then, the row carries a **Queued** badge. A task queues at most one run: further fire times during the wait do not stack up.
+
+A task whose file cannot be used, for example because its conversation was deleted, shows under **All** only. Its row reads **Invalid**, and pointing at the red icon shows the reason.
+
+## Create a task with AI
+
+Any member of the Project can create a task this way. The agent of this conversation creates the task and confirms the time it set.
+
+1. In the panel, under the title, select **Create with AI**.
+2. Describe what to schedule and when.
+3. Select **Edit in this conversation**. The prompt appears in this conversation's composer.
+4. Review the prompt, and send it when you are ready.
+
+Nothing is sent until you press Send, and sending works like any message you type. The prompt goes into this conversation rather than a new one because a task created from inside a conversation is bound to that conversation.
+
+### Start from a suggestion
+
+Below the list, **Suggestions** offers four ready-made requests: **Daily brief**, **Weekly review**, **Follow-up reminder** and **Monitor for updates**. Select one to open the AI dialog with that request filled in, then continue from step 2. The suggestions are hidden while the search box has text.
+
+## Create a task manually
+
+**Before you begin:** only a Project owner can create a task manually.
+
+1. In the panel, under the title, select **Create manually**.
+2. Fill in the form. It is the same form as on the agent's settings page, with **Target** set to **This conversation**:
+ - **Name** (required): the task's file name. It cannot be changed later.
+ - **Period**: `30m`, `12h`, `7d` and so on. Leave it empty for a one-off task.
+ - **Start at** (required) and, optionally, **End at**.
+ - **Prompt** (required): what to send to the agent.
+ - **Enabled**: whether the task is on.
+3. Select **Create**.
+
+## Turn a task on or off
+
+**Before you begin:** only a Project owner can turn a task on or off.
+
+In the panel, use the switch on the task's row. The change takes effect at once: a scheduled task fires on the scheduler's clock, independent of any conversation's context.
+
+## Edit or delete a task
+
+**Before you begin:** only a Project owner can edit or delete a task.
+
+1. In the panel, open the **More actions** menu on the task's row.
+2. Select **Edit**, or select **Delete** and confirm.
+
+## The alarm clock mark
+
+In the sidebar's conversation list, a conversation shows an alarm clock icon while it has a bound task that still has a next fire time. The mark appears whichever agent the conversation belongs to and however the list is grouped. It shows no count.
+
+A task has no next fire time when it is switched off, when it is past its end time, or when it is a one-off that has already run.
+
+## When the list refreshes
+
+The panel's list refreshes:
+
+- When the panel comes to the front.
+- When the window regains focus.
+- When a task fires or is queued.
+- When a conversation turn finishes.
+- Every 30 seconds while the panel is visible.
+- After every change.
+
+The alarm clock mark reads the same list and refreshes with it, so the mark and the panel always agree.
+
+## Limits
+
+- A repeating task runs at most once every 5 minutes: the shortest period is 5 minutes. A shorter period makes the task invalid.
+- Tasks run only while the PenguinHarness service is running.
+- Missed runs are not made up. When a fire time passes while the service is stopped, a repeating task skips it and a one-off task is marked missed.
+
+## How it works
+
+Each task is a TOML file under the agent's `agent_state/schedule/` directory. The file format is described in the [Configuration Reference](/configuration#schedules). The scheduler checks the files every 30 seconds, so a file you edit by hand takes effect at the next check.
diff --git a/packages/docs/content/schedules.zh.md b/packages/docs/content/schedules.zh.md
new file mode 100644
index 00000000..a55091af
--- /dev/null
+++ b/packages/docs/content/schedules.zh.md
@@ -0,0 +1,102 @@
+---
+title: 定时任务
+description: 让 Agent 按设定的时间在对话中执行 Prompt,并在对话的定时任务面板里管理这些任务。
+---
+
+定时任务在设定的时间向 Agent 发送一条 Prompt,可以只执行一次,也可以按周期重复。绑定到对话的任务把 Prompt 发进这段对话,Agent 因此能接着对话里已有的内容工作。这类任务在对话的**定时任务**面板中创建和管理。
+
+> [!NOTE] 每次新建会话的任务
+> 定时任务也可以设成每次运行都新开一个 Session。这类任务在 Agent 的设置页创建;设置页会列出该 Agent 的全部定时任务,也包括绑定到对话的任务。见[智能体](/agents)。
+
+- 查看一段对话的任务,见[打开定时任务面板](#打开定时任务面板)。
+- 添加任务,见[用 AI 创建任务](#用-ai-创建任务)或[手动创建任务](#手动创建任务)。
+- 暂停、修改或移除任务,见[开启或关闭任务](#开启或关闭任务)和[编辑或删除任务](#编辑或删除任务)。
+
+## 打开定时任务面板
+
+定时任务面板是对话页的侧边面板之一,对话开始后才能使用:还在草稿状态时,面板会提示先发送第一条消息。
+
+1. 打开对话。
+2. 在对话工具栏右上角选择**右侧栏**或**下侧栏**。也可以点对话区右缘的**快捷方式**悬浮球。
+3. 选择**定时任务**。如果侧栏里已经有别的面板,先选择**添加面板**。
+
+面板列出绑定到这段对话的任务。搜索框同时匹配任务名称和 Prompt。筛选项有**全部**、**生效中**、**已暂停**和**已完成**,其中**已完成**包括已执行完、已过期和已错过的任务。每行显示状态图标、任务名称和一句话描述的执行时间,例如:
+
+- 「每天 08:00 · 下次 明天 08:00」
+- 「每 30 分钟」
+- 「每周一 09:00」
+- 「一次性 · 9月3日 10:00」
+
+任务到点时如果对话还在运行,Prompt 会先等着,对话空闲后再发送,等待期间该行带有**排队中**标记。一个任务最多排队一次,等待期间再到的触发时间不会累加。
+
+任务文件无法使用时(例如绑定的对话已被删除),任务只出现在**全部**下,该行显示**无效**,鼠标指向红色图标可以看到原因。
+
+## 用 AI 创建任务
+
+Project 的所有成员都可以用这种方式创建任务。创建由这段对话的 Agent 完成,它会回复确认设定的时间。
+
+1. 在面板标题下方选择**用 AI 创建**。
+2. 描述要安排的事情和时间。
+3. 选择**在本对话中编辑**,提示词会填入这段对话的输入框。
+4. 检查提示词,确认无误后发送。
+
+按下发送之前什么都不会发出,发送时和手动输入的消息走同一条路径。提示词之所以填进当前对话而不是新对话,是因为在对话里创建的任务默认绑定到这段对话。
+
+### 从建议开始
+
+列表下方的**建议**提供四个现成的请求:**每日简报**、**每周回顾**、**跟进提醒**和**监控更新**。选择其中一个,会打开已经填好请求的 AI 对话框,接着从第 2 步继续。搜索框里有文字时,建议会隐藏。
+
+## 手动创建任务
+
+**开始之前**:只有 Project owner 可以手动创建任务。
+
+1. 在面板标题下方选择**手动创建**。
+2. 填写表单。表单与 Agent 设置页上的相同,**目标**固定为**本对话**:
+ - **名称**(必填):任务的文件名,创建后不能修改。
+ - **周期**:如 `30m`、`12h`、`7d`。一次性任务留空。
+ - **开始时间**(必填),以及可选的**结束时间**。
+ - **Prompt**(必填):发给 Agent 的内容。
+ - **启用**:任务是否开启。
+3. 选择**创建**。
+
+## 开启或关闭任务
+
+**开始之前**:只有 Project owner 可以开启或关闭任务。
+
+在面板中拨动任务所在行的开关即可,改动立即生效:定时任务按调度器的时钟触发,与任何对话的上下文无关。
+
+## 编辑或删除任务
+
+**开始之前**:只有 Project owner 可以编辑或删除任务。
+
+1. 在面板中打开任务所在行的**更多操作**菜单。
+2. 选择**编辑**;或者选择**删除**,再确认。
+
+## 闹钟标记
+
+侧边栏的对话列表里,只要某段对话绑定的任务还有下一次触发时间,这段对话就会显示一个闹钟图标。不论对话属于哪个 Agent、列表怎样分组,都会显示这个标记,但标记不带数量。
+
+任务已关闭、已过结束时间,或是已经执行过的一次性任务,都没有下一次触发时间。
+
+## 列表的刷新时机
+
+面板里的列表在以下时机刷新:
+
+- 面板切换到前台时。
+- 窗口重新获得焦点时。
+- 有任务触发或进入排队时。
+- 对话的一轮结束时。
+- 面板可见期间,每 30 秒一次。
+- 每次改动之后。
+
+闹钟标记读的是同一份列表,跟着同一次刷新更新,因此标记和面板不会互相矛盾。
+
+## 限制
+
+- 周期性任务最快每 5 分钟运行一次,即最短周期为 5 分钟。周期短于 5 分钟的任务会被判为无效。
+- 定时任务只在 PenguinHarness 服务运行期间执行。
+- 错过的运行不会补跑。服务停止期间错过的触发时间,周期性任务直接跳过,一次性任务标记为已错过。
+
+## 工作原理
+
+每个任务是 Agent 的 `agent_state/schedule/` 目录下的一个 TOML 文件,文件格式见[配置参考](/configuration#定时任务)。调度器每 30 秒检查一次这些文件,因此手动编辑的文件会在下一次检查时生效。
diff --git a/packages/docs/content/security.en.md b/packages/docs/content/security.en.md
index d9891e64..291e30c3 100644
--- a/packages/docs/content/security.en.md
+++ b/packages/docs/content/security.en.md
@@ -1,109 +1,189 @@
---
title: Security Model
-description: How access works, scenario by scenario — first login, passwords, automation, remote machines, revocation — and the mechanics underneath.
+description: How access to PenguinHarness works, from claiming a fresh server to revoking sessions, plus the mechanics underneath.
---
-PenguinHarness runs agents with real credentials on real machines, so it is worth knowing exactly who can do what, on the strength of which proof. This page walks the model in the order you meet it: claiming a fresh server, managing passwords, automating on the local machine, managing remote machines, and taking access away. The mechanics — token format, what is on disk, the network surface — are collected at the end.
+PenguinHarness runs agents with real credentials on real machines, so it is worth knowing exactly who can do what, and on what proof. This page follows the scenarios in the order you meet them, and collects the mechanics (session tokens, what is on disk, the network surface) at the end.
-One principle carries every scenario:
+- **First start of a new server?** See [Claim a fresh server](#claim-a-fresh-server).
+- **Need to set, change, or recover a password?** See [Manage passwords](#manage-passwords).
+- **Scripting or using the CLI on the same machine?** See [Automate on the local machine](#automate-on-the-local-machine).
+- **Driving other machines over ssh?** See [Manage remote machines over ssh](#manage-remote-machines-over-ssh).
+- **Need to take access away?** See [Revoke access](#revoke-access).
-> **Reading the data root is ownership.** The data root (`~/.penguin/data` by default) holds every model credential and every conversation. A secret stored beside them could not guard them from someone who can already read them — so the model never pretends otherwise, and instead makes that ownership safe to exercise: short-lived, revocable, and never requiring a password to be stored or transmitted.
+One principle runs through every scenario:
-## 0. What you get
+> **Reading the data root is ownership.** The data root (`~/.penguin/data` by default) holds every model credential and every conversation. A secret stored beside them could not protect them from someone who can already read them, so the model never pretends otherwise. Instead, it makes that ownership safe to use: short-lived, revocable, and never requiring a password to be stored or sent.
+
+## What you get
| Capability | Where |
| --- | --- |
-| Claim a fresh server through a printed sign-in link — no password exists yet, none is shown | The startup notice |
-| Sign in with a password; storage is scrypt hashes, attempts are throttled | Web login page, `penguin auth login` |
-| The desktop app signs its own window in, silently | One-shot token at window open |
-| Mint a session from local ownership — no password involved | `penguin auth token` |
-| Manage machines over ssh with no password on the wire | The Machines page |
-| Sessions are server-side rows: individually revocable, surviving a restart, 30-day sliding renewal | Everywhere |
-| Every session records how it was established | `via`: `password` (a typed password, or a session minted by `penguin auth token`) / `desktop` / `setup` / `token` (a request carrying the local API token as a Bearer header — no stored session) |
-| Revoke one session, or every session a user holds | Logout / admin password reset |
+| Claim a fresh server through a printed sign-in link; no password exists yet, and none is shown | The startup notice |
+| Sign in with a password, stored as an scrypt hash, with attempts throttled | Web login page, `penguin auth login` |
+| The desktop app signs its own window in, silently | A one-shot token when the window opens |
+| Mint a session from local ownership, with no password involved | `penguin auth token` |
+| Manage machines over ssh with no password on the wire | The **Machines** page |
+| Sessions are server-side rows: revocable one by one, surviving a restart, renewed while in use (30 days) | Everywhere |
+| Every session records how it was established | Its `via` value (see below) |
+| Revoke one session, or every session a user holds | **Sign out**, admin password reset |
| Recover a lost admin password from the machine itself | `penguin server reset-admin-password` |
-## 1. Claiming a fresh server
+Each session's `via` value records how it was established:
+
+- `password`: a typed password, or a session minted by `penguin auth token`
+- `desktop`: the desktop app's own window
+- `setup`: the sign-in link on a fresh server
+- `token`: a request that carries the local API token as a Bearer header; no session is stored
+
+## Claim a fresh server
-**Web.** A fresh server has no usable password: the seeded value is generated, hashed, and discarded unseen. To let you in anyway, every start prints a sign-in link until a password is set:
+A fresh server has no usable password: the seeded value is generated, hashed, and discarded unseen. To let you in anyway, the server prints a sign-in link at every start until a password is set:
```
-+--------------------------------------------------------------------+
-| This server has no admin password yet. Open this link to claim: |
-| |
-| http://localhost:7364/api/auth/claim?token=... |
-| |
-| The link works until a password is set, and changes on restart. |
-+--------------------------------------------------------------------+
++---------------------------------------------------------------------------------------+
+| This server has no admin password yet. Open this link to claim it: |
+| |
+| http://localhost:7364/api/auth/claim?token=... |
+| |
+| The link lasts 30 days or until a password is set; restarting prints a fresh one. |
++---------------------------------------------------------------------------------------+
```
-Open it, land signed in, set a password. The link is not one-shot — a mail client may fetch it before you do, and a second open must still work — so three other bounds make it printable into a console:
+1. Start the server.
+2. Copy the sign-in link from the startup output.
+3. Open the link in a browser. You land signed in as the built-in `admin` account.
+4. Set a password.
+
+### Why the link is safe to print
+
+The link is not one-shot, because a mail client may fetch it before you do and a second open must still work. Three other limits make it safe to print to a console:
+
+- It works **only while the server is unclaimed**, and for at most 30 days. Once a password exists it is refused, so a console scrollback is not a way in.
+- The value it is checked against lives **in memory and is replaced at every restart**. A link from an earlier run is refused; if you missed the notice, restart the server and read the new one.
+- A wrong token and an already-claimed server get **the same answer**, so a stale link cannot even reveal which of the two it is.
+
+> [!NOTE]
+> In a container, the notice goes to the container's log (`docker logs`). The `localhost` in the link is the server's own view of itself. With the documented loopback port mapping, that is your view too, so open the link as printed on the machine running Docker. If the container is published to a network, replace `localhost` with the host you reach it on. Keep the token as it is either way.
+
+`PENGUIN_SEED_ADMIN_PASSWORD` pins the password instead, but only on the first start with an empty data root.
+
+The session the link grants carries `via: setup`. It has exactly one special allowance, setting a password without entering an old one (none exists), and nothing else; in particular, it gets none of the desktop-only routes.
+
+### Sign in from the desktop app
+
+The desktop app's shell owns the server process it embeds, so its window is let in on that fact alone. The window's first navigation redeems a one-shot token the shell minted, and lands signed in with `via: desktop`. The token dies when it is redeemed, so a leaked URL replays nothing.
+
+## Manage passwords
+
+A password must be at least 8 characters. It is stored one way only: as an scrypt hash (`N=16384`, a salt per password, and the parameters stored alongside so the cost can rise later). There are four ways to set one, depending on who is asking.
+
+### Change your own password
+
+If you know the current password, use **Change password** in your user settings (see [Change your password](/settings#change-your-password)). The current password is verified first.
+
+### Set a password without an old one
+
+A `setup` session (see [Claim a fresh server](#claim-a-fresh-server)) or the desktop app's own window can set a password without supplying an old one. Both belong to accounts whose password is a random value nobody has seen, so there is nothing to enter as the old password. How the session was established is the authorization.
+
+### Reset another user's password
-- It works **only while the server is unclaimed**. Once a password exists it is refused, so a console scrollback is not a way in.
-- The value it is compared against lives **in memory and is re-minted on every restart**. A link from an earlier run is refused; if you miss the notice, restart and read the new one.
-- A wrong token and an already-claimed server answer **identically** — a stale link cannot even reveal which of the two it is.
+An admin sets a new initial password for another account with **Reset password** in user management (see [Reset a user's password](/settings#reset-a-users-password)). The user is asked to change it at the next sign-in, and every session that user holds is revoked. See [Revoke access](#revoke-access).
-In a container the notice goes to the container's log (`docker logs`), and the `localhost` in the link is the server's own view of itself — with the documented loopback publish that is your view too, so open it as it stands on the machine running Docker; a container published to a network needs `localhost` replaced with the host you reach it on. Keep the token either way. `PENGUIN_SEED_ADMIN_PASSWORD` pins the password instead, but only on the first boot of an empty data root.
+### Recover a lost admin password
-The session it grants carries `via: setup`. It has exactly one special allowance — setting a password without an old one, since no old one exists — and no more: in particular, none of the desktop-only routes.
+**Before you begin**
-**Desktop.** The shell owns the server process it embeds, so its window is let in on that fact alone: the window's first navigation redeems a one-shot token minted by the shell, and lands signed in as `via: desktop`. The token dies on redemption — a leaked URL replays nothing.
+- Access to the server's machine, with the server stopped. Local filesystem access is the authorization.
-Password logins, wherever they come from, are throttled per username with exponential backoff — and unknown usernames are throttled identically, so timing does not reveal whether an account exists.
+1. Run `penguin server reset-admin-password`.
+2. Start the server. It prints a fresh sign-in link.
+3. Open the link and set a password, as in [Claim a fresh server](#claim-a-fresh-server).
-## 2. Passwords
+The admin account returns to the unclaimed state, and all of its sessions are revoked. The rescue produces nothing to write down.
-A chosen password is stored one way only: as an scrypt hash (`N=16384`, per-password salt, parameters stored alongside so cost can rise later). Four ways to set one, each shaped by who is asking:
+### Sign-in attempt limits
-- **You, knowing the current password** — user settings. The current password is verified first.
-- **You, in a session that never had one** — a `setup` session (§1), or the desktop shell's own window. Both belong to accounts whose password is a random value nobody has seen, so there is nothing to put in an "old password" field; the session's provenance is the authorization.
-- **An admin, for another user** — the account gets a fresh initial password, and every session that user holds is revoked (§5).
-- **Nobody remembers the admin password** — on the server's machine, with the server stopped: `penguin server reset-admin-password`. Local filesystem access is the authorization. The account returns to the unclaimed state with its sessions revoked, and the rescue produces nothing to write down — start the server and claim it through the link, as in §1.
+Password logins, wherever they come from, are throttled per username with exponential backoff. After five failed attempts, each further attempt waits 1 second, doubling up to 60 seconds. Unknown usernames are throttled identically, so the throttling does not reveal whether an account exists. Neither does the response time: an unknown username is checked against a dummy hash, so every attempt costs exactly one scrypt derivation.
-## 3. Automation on this machine
+## Automate on the local machine
-Scripts and the CLI never need a password, because local ownership already outranks one. A session is a row in the data root's `web.db`, so the CLI writes one:
+Scripts and the CLI never need a password, because local ownership already outranks one.
+
+When a CLI command runs against a server on this machine, it authenticates with the local API token, which the server writes to `<root>/api-token` at every start. See [CLI Reference](/cli#server-connection).
+
+A script that needs a session of its own mints one. A session is a row in the data root's `web.db`, so the CLI writes one:
```bash
penguin auth token # no password, no prompt: inserts a session row
```
-Being able to read and write that data root is the whole authorization, and it grants nothing new — the root already holds every credential the token could reach. It works whether or not a server is running, and safely alongside one — on a root a server has started at least once, since the account it mints for lives in that root's `web.db`. The token lives an hour by default (`--ttl-seconds` sets another lifetime) and acts as an ordinary password session, never the desktop kind.
+Being able to read and write the data root is the whole authorization, and it grants nothing new: the root already holds every credential the token could reach. Minting works whether or not a server is running, and safely alongside one, on any root a server has started at least once: the account it mints for lives in that root's `web.db`.
+
+The minted token lives one hour by default and acts as an ordinary password session, never the desktop kind. Pass `--ttl-seconds` to set another lifetime (at most 30 days), or `--user-id` to mint for an account other than `admin`.
+
+On a multi-user machine, that scoping is the point. The data root belongs to the OS account running the server, so only that account can mint. Everyone else signs in with a password: `penguin auth login --server <url>`.
+
+## Manage remote machines over ssh
-On a multi-user machine that scoping is the point: the data root belongs to the OS account running the server, so only that account can mint. Everyone else signs in with a password — `penguin auth login --server <url>`.
+The **Machines** page manages other machines over ssh, and everything runs under the ssh account's identity.
-## 4. Remote machines: ssh access is CLI access
+To act on a machine's API, the controller runs `penguin auth token` on that machine, over ssh. The machine's own CLI writes a session row into the machine's own database. The only thing that crosses the wire is a one-hour session token.
-The Machines page manages other machines over ssh, and the identity everything runs under is the ssh account's:
+No password crosses the wire, ever. A machine's admin password stays on that machine, because ssh has already proven everything a password would.
-- To act on a machine's API, the controller runs `penguin auth token` **on that machine, over ssh**. The machine's own CLI writes a session row into the machine's own database. The only thing that crosses the wire is a one-hour session token.
-- **No password crosses the wire, ever.** A machine's admin password stays on that machine; ssh has already proven everything a password would.
-- The equation cuts both ways. ssh access to a machine can read its data root by hand, so the token grants nothing ssh had not already granted — and precisely for that reason, **your ssh key is the master credential for every machine it reaches**. Guard it at that level.
-- A Project that syncs model credentials to its machines puts those API keys in each machine's own Project config (mode 0600): a machine that runs your agents necessarily holds the keys they run with.
+> [!WARNING]
+> The trust cuts both ways. Anyone with ssh access to a machine can read its data root by hand, so a minted token grants nothing ssh had not already granted. For exactly that reason, your ssh key is the master credential for every machine it reaches. Guard it at that level.
-## 5. Taking access away
+A Project that syncs model credentials to its machines puts those API keys in each machine's own Project config (mode 0600). A machine that runs your agents necessarily holds the keys they run with.
-| To revoke | Do | Effect |
+## Revoke access
+
+A session is a row on the server, so deleting the row revokes the session at once.
+
+| To revoke | Do this | Takes effect |
| --- | --- | --- |
-| One session | `penguin auth logout`, or sign out in the UI | Immediate — the row is deleted, and a session is its row |
-| One user's sessions | Admin password reset for that user | Immediate — every row for that account is deleted |
-| The admin's own sessions | `penguin server reset-admin-password` (server stopped) | On the next start, which prints a fresh first-login link |
-| A model API key | Rotate it with the provider, update the Project config | Provider-side |
+| One session | `penguin auth logout`, or **Sign out** in the Web App | Immediately: the row is deleted |
+| One user's sessions | An admin resets that user's password | Immediately: every row for that account is deleted |
+| The admin's own sessions | `penguin server reset-admin-password` (server stopped) | At the next start, which prints a fresh first-login link |
+| The local API token | Restart the server | At the next start, which writes a fresh token |
+| A model API key | Rotate it with the provider, then update the Project config | At the provider |
+
+### If a backup leaks
+
+The design is built around the worst case: **a full backup of the data root leaks**. The response is to rotate the model API keys it contains and to restart the server, and nothing more. Passwords in a backup are scrypt hashes, and the session table holds only the sha256 of each token, never a token.
-The scenario the design is built around is the worst one — **a full data-root backup leaks**. The response is a credential rotation for the model API keys it contains, and nothing more: passwords in a backup are scrypt hashes, and the session table holds only the sha256 of each token, never a token. Nothing copied out of a backup can be presented to the live server as a session.
+The one usable credential a backup can hold is the local API token of the server start it was taken from, and a restart replaces it. After that, nothing copied out of the backup can be presented to the live server.
-## The mechanics underneath
+## How it works
-**Sessions.** The cookie carries a 32-byte random token; the `auth_sessions` row keyed by its sha256 is the session, and holds the account, the provenance (`via`) and the expiry. Because the row is the session, deleting it revokes immediately and a restart signs nobody out. Browser sessions run 30 days and renew **in place** as expiry nears — the row's expiry moves, the cookie value does not — so one in regular use never expires and there is never a second copy to chase. Only a session whose own term reaches the renewal window slides, so an hour-long minted token expires at its hour. Cookies are HttpOnly and SameSite=Lax, plus Secure when the request is really https or a **trusted** proxy says so (`PENGUIN_TRUST_PROXY=1`); the header is ignored by default.
+### Sessions
-**On disk, and deliberately not.**
+Each cookie carries a 32-byte random token. The session is the `auth_sessions` row keyed by the token's sha256, which holds the account, how the session was established (`via`) and the expiry. Because the row is the session, deleting it revokes the session immediately, and a restart signs nobody out.
-| File | Contains | Lives |
+A browser session lasts 30 days. Using it a day or more after it was issued or last renewed renews it **in place** for another 30 days: the row's expiry moves, and the cookie value stays the same. The 30 days therefore act as an idle timeout: a session in regular use never expires, and there is never a second copy to chase. Only a session whose own lifetime reaches the renewal window slides, so a one-hour minted token expires after its hour.
+
+Cookies are HttpOnly and SameSite=Lax. They are also Secure when the request really is https, or when a **trusted** proxy says so (`PENGUIN_TRUST_PROXY=1`); by default the `x-forwarded-proto` header is ignored.
+
+### What is on disk
+
+| File | Contains | Kept |
| --- | --- | --- |
| `web.db` | Password **hashes**, session **hashes**, application data | Permanently |
| `<project>/.project_config.toml` | Model API keys, inline, mode 0600 | Until edited |
-| `cli-session.json` | One live session token, mode 0600 | Until logout or expiry |
+| `cli-session.json` | One live session token, mode 0600 | Until sign-out or expiry |
+| `api-token` | The local API token, mode 0600: admin authority for any request that sends it as a Bearer header | Until the next server start |
+
+Never on disk in usable form: session tokens (only their sha256) and passwords. A chosen password exists only as an scrypt hash, and a seeded one is discarded as soon as it is created.
+
+The local API token is on disk on purpose. Reading it proves access to the data root, which is admin authority already, and each server start replaces it.
+
+Model API keys are the one secret that cannot be reduced further: they must reach the providers verbatim, so they cannot be hashed. They are confined to the Project config, masked in every API response and in the UI, and read in plaintext only at the moment a request is made.
+
+### Network surface
+
+The server binds `127.0.0.1` by default. Exposing it (`HOST=0.0.0.0`) is a deployment decision that belongs behind TLS termination, with the proxy setting `x-forwarded-proto`.
-Never on disk in usable form: session tokens (only their sha256) and every password — chosen ones exist as scrypt hashes, seeded ones are discarded at birth. Model API keys are the irreducible remainder: they must reach upstream providers verbatim, so they cannot be hashed. They are confined to the Project config, masked in every API response and UI surface, and read in plaintext only at the moment a request is made.
+The API answers only under its canonical application host, which keeps user-generated preview content in a different browser origin from the application's cookies.
-**Network surface.** The server binds 127.0.0.1 by default; exposing it (`HOST=0.0.0.0`) is a deployment decision that belongs behind TLS termination, with the proxy setting `x-forwarded-proto`. The API answers only under its canonical application host, which keeps user-generated preview content in a separate browser origin from the application's cookies. Cross-site request forgery is blocked by two independent layers: the SameSite=Lax cookie, and a Content-Type gate that rejects any write request whose content type an HTML form could produce.
+Two independent layers block cross-site request forgery: the SameSite=Lax cookie, and a Content-Type check that rejects any write request whose content type an HTML form could produce.
diff --git a/packages/docs/content/security.zh.md b/packages/docs/content/security.zh.md
index 506aed0f..06a84500 100644
--- a/packages/docs/content/security.zh.md
+++ b/packages/docs/content/security.zh.md
@@ -1,109 +1,189 @@
---
title: 安全模型
-description: 按场景讲清访问是怎么运作的——首次登录、密码、自动化、远程机器、吊销——底层机制附于文末。
+description: PenguinHarness 的访问机制如何运作:从认领新服务器到收回会话,以及底层的实现细节。
---
-PenguinHarness 用真实凭据在真实机器上跑智能体,所以"谁凭什么证明、能做什么"值得确切地知道。本页按你遇到它们的顺序展开:认领新服务器、管理密码、本机自动化、管理远程机器、收回访问权。底层机制——令牌格式、磁盘内容、网络暴露面——集中在文末。
+PenguinHarness 用真实凭据在真实机器上运行 Agent,所以值得弄清楚:谁能做什么,凭什么。本页按你遇到这些场景的顺序依次讲解,最后集中说明底层机制(会话令牌、磁盘内容、网络暴露面)。
-一条原则贯穿所有场景:
+- **第一次启动新服务器?** 参见[认领新服务器](#认领新服务器)。
+- **需要设置、修改或找回密码?** 参见[管理密码](#管理密码)。
+- **要在同一台机器上跑脚本或用 CLI?** 参见[在本机自动化](#在本机自动化)。
+- **要通过 ssh 操作其他机器?** 参见[通过 ssh 管理远程机器](#通过-ssh-管理远程机器)。
+- **需要收回访问权限?** 参见[收回访问权限](#收回访问权限)。
-> **能读数据根即拥有服务器。** 数据根(默认 `~/.penguin/data`)装着全部模型凭据和全部对话。放在它们旁边的秘密防不住已经能读到它们的人——所以这套模型不假装能防,而是把这份所有权变得可以安全行使:短命、可吊销、永远不要求存储或传输密码。
+所有场景都贯穿着同一条原则:
-## 0. 你得到什么
+> **能读到数据根目录,就等于拥有它。** 数据根目录(默认为 `~/.penguin/data`)存放着全部模型凭据和全部对话。在它们旁边再藏一个秘密,也拦不住本来就能读到这些内容的人,所以这套安全模型从不假装做得到。它做的反而是让这种所有权可以放心使用:有效期短、随时可收回,而且从不要求存储或发送密码。
-| 能力 | 在哪里 |
+## 功能一览
+
+| 能力 | 位置 |
| --- | --- |
-| 通过启动时打印的登录链接认领新服务器——密码尚不存在,也不会展示 | 启动提示 |
-| 密码登录;存储为 scrypt 哈希,尝试被节流 | Web 登录页、`penguin auth login` |
-| 桌面应用静默登入自己的窗口 | 窗口打开时的一次性令牌 |
-| 凭本机所有权铸造会话——全程不涉及密码 | `penguin auth token` |
-| 通过 ssh 管理机器,密码不过线 | Machines 页 |
-| 会话是服务端的行:可逐个吊销、跨重启存活、30 天滑动续期 | 所有场景 |
-| 每个会话记录自己的建立方式 | `via`:`password`(输入的密码,或 `penguin auth token` 铸造的会话)/ `desktop` / `setup` / `token`(以 Bearer 头携带本地 API token 的请求——不存储会话) |
-| 吊销一个会话,或一个用户的全部会话 | 登出 / 管理员重置密码 |
-| 在服务器所在机器上找回丢失的管理员密码 | `penguin server reset-admin-password` |
+| 通过启动时打印的登录链接认领新服务器;此时还不存在密码,也不会显示任何密码 | 启动提示 |
+| 用密码登录;密码以 scrypt 哈希存储,登录尝试有频率限制 | Web 登录页、`penguin auth login` |
+| 桌面应用静默登录自己的窗口 | 窗口打开时的一次性令牌 |
+| 凭本地所有权铸造会话,全程不需要密码 | `penguin auth token` |
+| 通过 ssh 管理机器,网络上不传密码 | **机器**页面 |
+| 会话是服务端的一行记录:可逐个收回、重启后依然存在、使用期间自动续期(30 天) | 所有场景 |
+| 每个会话都记录自己的建立方式 | 会话的 `via` 值(见下文) |
+| 收回单个会话,或收回某个用户的全部会话 | **登出**、管理员重置用户密码 |
+| 就在这台机器上找回丢失的管理员密码 | `penguin server reset-admin-password` |
+
+每个会话的 `via` 值记录它的建立方式:
+
+- `password`:手动输入的密码,或由 `penguin auth token` 铸造的会话
+- `desktop`:桌面应用自己的窗口
+- `setup`:新服务器上的登录链接
+- `token`:请求在 Bearer 头里携带本地 API token;不存储会话
-## 1. 认领新服务器
+## 认领新服务器
-**Web。** 新服务器没有可用的密码:种子值生成后即哈希、丢弃,无人见过。为了仍然让你进来,在密码被设置之前,每次启动都会打印一条登录链接:
+全新的服务器没有可用的密码:预置值生成后完成哈希便立即丢弃,没人见过明文。为了让你照样能进去,在设置密码之前,服务器每次启动都会打印一个登录链接:
```
-+--------------------------------------------------------------------+
-| This server has no admin password yet. Open this link to claim: |
-| |
-| http://localhost:7364/api/auth/claim?token=... |
-| |
-| The link works until a password is set, and changes on restart. |
-+--------------------------------------------------------------------+
++---------------------------------------------------------------------------------------+
+| This server has no admin password yet. Open this link to claim it: |
+| |
+| http://localhost:7364/api/auth/claim?token=... |
+| |
+| The link lasts 30 days or until a password is set; restarting prints a fresh one. |
++---------------------------------------------------------------------------------------+
```
-打开、落地即已登录、设置密码。这条链接不是一次性的——邮件客户端可能先于你抓取它,第二次打开必须仍然有效——因此靠另外三重边界让它可以放心打印进控制台:
+1. 启动服务器。
+2. 从启动输出中复制登录链接。
+3. 在浏览器中打开链接,即以内置的 `admin` 账户身份登录。
+4. 设置密码。
+
+### 为什么可以放心打印链接
+
+这个链接不是一次性的,因为邮件客户端可能抢在你之前抓取它,第二次打开也必须仍然有效。真正让它能放心打印到控制台的,是另外三条限制:
+
+- 它**只在服务器尚未认领时**有效,且最长 30 天。一旦设置了密码,服务器就拒绝这个链接,所以翻控制台的历史输出也进不去。
+- 链接比对用的值**存在内存里,每次重启都会更换**。上一次运行打印的链接不再有效;错过了提示,重启服务器就能看到新的。
+- 错误的 token 和已认领的服务器得到**同一个答复**,所以过期的链接连是哪种情况都区分不出来。
+
+> [!NOTE]
+> 在容器里,这条提示输出到容器日志(`docker logs`)。链接中的 `localhost` 是服务器眼中的自己。按文档给出的回环端口映射来部署时,这也是你眼中的它,所以在运行 Docker 的那台机器上按打印的原样打开链接即可。如果容器发布到了网络上,就把 `localhost` 换成你实际访问所用的主机;无论哪种情况,token 都保持原样。
+
+也可以改用 `PENGUIN_SEED_ADMIN_PASSWORD` 直接固定密码,但只在数据根目录为空的首次启动时生效。
+
+链接授予的会话带有 `via: setup`。它只有一项特殊许可:设置密码时不必输入旧密码(反正也不存在);除此之外没有任何特权,尤其拿不到任何仅限桌面应用的路由。
+
+### 从桌面应用登录
+
+桌面应用的外壳拥有它内嵌的服务器进程,仅凭这一点,窗口即可进入。窗口的首次导航会兑换外壳铸造的一次性令牌,随后以 `via: desktop` 登录。令牌一经兑换即作废,URL 泄露也无法重放。
+
+## 管理密码
+
+密码至少 8 个字符,存储方式只有一种:scrypt 哈希(`N=16384`,每个密码各带一个盐值,参数与哈希存放在一起,以便日后提高计算成本)。按操作者不同,设置密码有四种方式。
+
+### 修改自己的密码
+
+如果你知道当前密码,在用户设置里使用**修改密码**(见[修改密码](/settings#修改密码))。操作会先验证当前密码。
+
+### 不提供旧密码设置密码
+
+`setup` 会话(见[认领新服务器](#认领新服务器))和桌面应用自己的窗口都可以在不出示旧密码的情况下设置新密码。这两种会话所在的账户,密码本来就是无人见过的随机值,没有旧密码可填。会话的建立方式本身就是授权。
+
+### 重置其他用户的密码
-- **只在服务器未被认领时有效。** 密码一旦存在即被拒绝,控制台回滚记录不构成入口。
-- 用来比对的那个值**只在内存里,每次重启重新铸造**。更早一次运行的链接会被拒绝;错过提示,重启再读新的即可。
-- 错误令牌与已认领的服务器返回**完全一致**——一条过期链接连"属于哪种情况"都无法透露。
+管理员在用户管理里用**重置密码**为其他账户设置一个新的初始密码(见[重置用户密码](/settings#重置用户密码))。用户下次登录时要先修改这个密码,名下所有会话同时收回。见[收回访问权限](#收回访问权限)。
-在容器里,这条提示打在容器日志(`docker logs`)中,链接里的 `localhost` 是服务端对自己的称呼——按文档给出的回环发布,它也正是你的视角,在运行 Docker 的那台机器上原样打开即可;若容器已发布到网络上,则把 `localhost` 换成你实际访问它所用的地址。两种情况下令牌都保持不变。`PENGUIN_SEED_ADMIN_PASSWORD` 可以改为直接钉死密码,但仅在空数据目录的首次启动时生效。
+### 找回管理员密码
-它授予的会话带 `via: setup`,恰好持有一项特殊豁免——免旧密码设置密码,因为旧密码并不存在——再无其他:尤其是,不含任何桌面专属路由。
+**开始之前**
-**桌面。** 客户端拥有它内嵌的服务进程,它的窗口凭这一事实被放行:窗口的首次导航兑换一枚由客户端铸造的一次性令牌,落地即以 `via: desktop` 登录。令牌在兑换的瞬间死亡——泄露的 URL 无法重放。
+- 能访问服务器所在的机器,且服务器已停止。本地文件系统的访问权就是授权。
-无论来自哪里,密码登录都按用户名指数退避节流——不存在的用户名以完全相同的方式节流,时间上看不出账号是否存在。
+1. 运行 `penguin server reset-admin-password`。
+2. 启动服务器,它会打印一个新的登录链接。
+3. 打开链接并设置密码,方法同[认领新服务器](#认领新服务器)。
-## 2. 密码
+管理员账户回到未认领状态,名下所有会话全部收回。整个恢复过程不产生任何需要记下来的东西。
-选定的密码只以一种方式存储:scrypt 哈希(`N=16384`,每密码随机盐,参数随哈希保存,成本可日后提高)。设置密码有四条路,各由"谁在请求"决定形状:
+### 登录尝试限制
-- **你,知道当前密码**——用户设置页。先验当前密码。
-- **你,处在一个从未有过密码的会话里**——`setup` 会话(§1),或桌面客户端自己的窗口。两者的账号密码都是无人见过的随机值,"旧密码"框里没有东西可填;会话的来历就是授权。
-- **管理员,为另一个用户**——该账号获得新的初始密码,其持有的所有会话被吊销(§5)。
-- **没人记得管理员密码**——在服务器所在机器上、停止服务后执行 `penguin server reset-admin-password`。本机文件系统访问就是授权。账号回到未认领状态、会话全部吊销,救援不产生任何需要抄写的东西——启动服务,按 §1 用链接认领。
+无论来自哪里,密码登录都按用户名限速,采用指数退避。失败五次后,每次新的尝试要先等 1 秒,逐次翻倍,最长 60 秒。不存在的用户名也按同样方式限速,因此限流本身不会暴露账户是否存在。响应耗时同样不会:不存在的用户名会拿一个占位哈希来校验,因此每次尝试都恰好做一次 scrypt 推导。
-## 3. 本机自动化
+## 在本机自动化
-脚本和 CLI 永远不需要密码,因为本机所有权本就高于密码。会话就是数据根 `web.db` 里的一行,所以 CLI 直接写入一行:
+脚本和 CLI 从来不需要密码,因为本地所有权本来就高于密码。
+
+CLI 命令访问本机上的服务器时,用本地 API token 认证;服务器每次启动都会把它写入 `<root>/api-token`。参见 [CLI 参考](/cli#服务器连接)。
+
+脚本需要自己的会话时,就自己铸造一个。会话是数据根目录下 `web.db` 里的一行记录,所以 CLI 直接写入一行:
```bash
-penguin auth token # 无密码、无提问:插入一行会话
+penguin auth token # no password, no prompt: inserts a session row
```
-能读写那个数据根就是全部授权,而且它不带来任何新权限——数据根本就装着这枚令牌所能触及的一切凭据。服务在跑或不在跑都能用,在跑时也安全——前提是该数据根上服务至少启动过一次,因为它铸造的账号就在那个根的 `web.db` 里。令牌默认活一小时(`--ttl-seconds` 可另设),作为普通密码会话行事,永远不是桌面那种。
+能读写数据根目录就是全部授权,而且它不会授予任何新东西:数据根目录本来就存着这个 token 能触达的每一份凭据。服务器在不在运行都可以铸造,与运行中的服务器并存也安全。前提是服务器至少在这个根目录上启动过一次:铸造所用的账户就存放在这个根目录的 `web.db` 里。
+
+铸造出的 token 默认有效期一小时,等同普通的密码会话,绝不是桌面会话。用 `--ttl-seconds` 指定其他有效期(最长 30 天),或用 `--user-id` 为 `admin` 以外的账户铸造。
+
+在多用户机器上,这道限定正是关键。数据根目录属于运行服务器的操作系统账户,所以只有这个账户能铸造。其他人一律用密码登录:`penguin auth login --server <url>`。
+
+## 通过 ssh 管理远程机器
-在多用户机器上,这个界定正是要点:数据根属于运行服务的那个操作系统账号,因此只有该账号能铸造。其他人一律用密码登录——`penguin auth login --server <url>`。
+**机器**页面通过 ssh 管理其他机器,一切操作都以 ssh 账户的身份运行。
-## 4. 远程机器:ssh 权限即 CLI 权限
+要对一台机器的 API 执行操作,控制器通过 ssh 在那台机器上运行 `penguin auth token`。机器自己的 CLI 往机器自己的数据库里写入一行会话记录。经过网络的只有会话令牌,有效期一小时。
-Machines 页通过 ssh 管理其他机器,一切都运行在 ssh 账户的身份之下:
+密码永远不经过网络。一台机器的管理员密码就留在那台机器上,因为 ssh 已经证明了密码所能证明的一切。
-- 要操作某台机器的 API,控制端**通过 ssh 在那台机器上**执行 `penguin auth token`:那台机器自己的 CLI 往那台机器自己的数据库里写一行会话。过线的只有一枚一小时的会话令牌。
-- **密码永不过线。** 机器的管理员密码留在那台机器上;ssh 已经证明了密码所能证明的一切。
-- 这个等式两面成立。ssh 到一台机器就能徒手读它的数据根,令牌没有授予 ssh 未曾授予的任何东西——也正因如此,**你的 ssh 私钥是它所能到达的所有机器的主凭据**,请按这个等级保护。
-- 项目向机器同步模型凭据时,API key 进入各机器自己的项目配置(0600):替你跑智能体的机器,必然持有智能体运行所用的 key。
+> [!WARNING]
+> 这种信任是双向的。任何能 ssh 到一台机器的人都能亲手读取它的数据根目录,所以铸造 token 并不会带来 ssh 之外的任何权限。正因如此,你的 ssh 密钥就是它能到达的每台机器的主凭据。请按这个级别保管。
-## 5. 收回访问权
+把模型凭据同步到自己各台机器的 Project,会把这批 API key 放进每台机器自己的 Project 配置(权限 0600)。运行你的 Agent 的机器,必然持有这些 Agent 运行所用的 key。
-| 要吊销 | 操作 | 效果 |
+## 收回访问权限
+
+会话是服务器上的一行记录,删掉这一行,会话立刻失效。
+
+| 收回对象 | 操作 | 生效时机 |
| --- | --- | --- |
-| 一个会话 | `penguin auth logout`,或界面登出 | 立即——行被删除,而行即会话 |
-| 一个用户的会话 | 管理员重置该用户密码 | 立即——该账号的全部行被删除 |
-| 管理员自己的会话 | 停止服务后执行 `penguin server reset-admin-password` | 下次启动时生效,并打印新的首次登录链接 |
-| 模型 API key | 在服务商处轮换,更新项目配置 | 取决于服务商 |
+| 单个会话 | `penguin auth logout`,或在 Web App 里**登出** | 立即:删除对应记录 |
+| 某个用户的全部会话 | 管理员重置这个用户的密码 | 立即:删除这个账户的所有记录 |
+| 管理员自己的会话 | `penguin server reset-admin-password`(服务器停止时) | 下次启动时,同时打印新的首次登录链接 |
+| 本地 API token | 重启服务器 | 下次启动时,同时写入新 token |
+| 模型 API key | 先在供应商处轮换,再更新 Project 配置 | 在供应商处生效 |
+
+### 备份泄露时
+
+整套设计围绕最坏情况构建:**数据根目录的完整备份泄露**。应对办法就是轮换其中的模型 API key,再重启服务器,仅此而已。备份里的密码只是 scrypt 哈希;会话表里也只有每个 token 的 sha256,绝没有 token 本身。
-这套设计围绕的正是最坏的那个场景——**整个数据根备份泄露**。应对只是一次针对其中模型 API key 的凭据轮换,仅此而已:备份里的密码是 scrypt 哈希,会话表里只有每枚令牌的 sha256、从来没有令牌本身。从备份里抄出来的任何东西都无法作为会话呈递给线上服务器。
+备份里唯一可用的凭据,是做备份那次服务器启动写入的本地 API token,而一次重启就会更换它。此后,从备份里复制出来的任何东西都无法向运行中的服务器出示。
-## 底层机制
+## 工作原理
-**会话。** Cookie 里装的是 32 字节随机令牌;以其 sha256 为键的 `auth_sessions` 行才是会话,行里存账号、来历(`via`)和过期时间。因为行即会话,删除它即刻吊销,而重启不会登出任何人。浏览器会话 30 天,临近过期**原地**续期——移动的是行的过期时间,Cookie 的值不变——因此常规使用中的会话永不过期,也从不产生需要追杀的第二个副本。只有自身期限达到续期窗口的会话才滑动,所以一小时的铸造令牌就在一小时到期。Cookie 为 HttpOnly、SameSite=Lax;只有请求确实是 https、或**受信任的**代理这样声明时(`PENGUIN_TRUST_PROXY=1`)才加 Secure,该头默认被忽略。
+### 会话
-**磁盘上有的,和刻意没有的。**
+每个 cookie 携带一个 32 字节的随机 token。会话就是 `auth_sessions` 表里以 token 的 sha256 为键的那一行,其中记录着账户、建立方式(`via`)和过期时间。正因为这一行就是会话本身,删掉它就等于立即收回会话,而重启不会让任何人退出登录。
-| 文件 | 内容 | 存续 |
+浏览器会话有效期 30 天。签发或上次续期之后满一天再使用,会话就**原地**续期 30 天:只更新记录里的过期时间,cookie 值保持不变。因此这 30 天相当于空闲超时:经常使用的会话永不过期,也不会冒出需要追查的第二份副本。只有自身寿命能撑到续期窗口的会话才会顺延,所以铸造的一小时 token 到一小时就到期。
+
+Cookie 设置为 HttpOnly 和 SameSite=Lax。请求确实是 https,或者**受信任**的代理声明如此(`PENGUIN_TRUST_PROXY=1`)时,还会加上 Secure。默认忽略 `x-forwarded-proto` 头。
+
+### 磁盘上存了什么
+
+| 文件 | 内容 | 保留多久 |
| --- | --- | --- |
| `web.db` | 密码**哈希**、会话**哈希**、应用数据 | 永久 |
-| `<project>/.project_config.toml` | 模型 API key,内联,0600 | 直到被编辑 |
-| `cli-session.json` | 一枚活跃会话令牌,0600 | 到登出或过期 |
+| `<project>/.project_config.toml` | 模型 API key,直接内联存放,权限 0600 | 直到下次编辑 |
+| `cli-session.json` | 一个有效的会话令牌,权限 0600 | 直到登出或过期 |
+| `api-token` | 本地 API token,权限 0600:任何请求只要在 Bearer 头里带上它,就拥有管理员权限 | 直到下次服务器启动 |
+
+磁盘上从不以可用形式保存会话令牌(只存 sha256)和密码。你选定的密码只以 scrypt 哈希存在;预置的密码生成后立即丢弃。
+
+本地 API token 是有意放在磁盘上的。能读到它就证明能访问数据根目录,而这本身就是管理员权限;每次启动服务器也都会更换它。
+
+模型 API key 是唯一无法进一步降低暴露的秘密:必须原文送达供应商,因此无法哈希。它们只存在 Project 配置里,在所有 API 响应和界面中都显示为掩码,只有在真正发起请求的那一刻才以明文读取。
+
+### 网络暴露面
+
+服务器默认绑定 `127.0.0.1`。要对外暴露(`HOST=0.0.0.0`),那是部署层面的决定,必须放在 TLS 终结之后,并由代理设置 `x-forwarded-proto`。
-从不以可用形式落盘的:会话令牌(只有其 sha256)、以及一切密码——选定的以 scrypt 哈希存在,种子在诞生时即被丢弃。模型 API key 是无法消除的剩余项:它们必须原样抵达上游服务商,无法哈希。它们被限制在项目配置里,在所有 API 响应和界面上被掩码,只在发出请求的那一刻以明文被读出。
+API 只在规范的应用主机名下应答,这样用户生成的预览内容与应用的 cookie 就处于不同的浏览器源(origin)。
-**网络暴露面。** 服务默认绑定 127.0.0.1;对外暴露(`HOST=0.0.0.0`)是部署决定,应置于 TLS 终结之后,由代理设置 `x-forwarded-proto`。API 只在规范应用主机名下应答,这让用户生成的预览内容与应用 cookie 处于不同的浏览器源。跨站请求伪造由两层独立防线阻断:SameSite=Lax cookie,加一道 Content-Type 闸——凡 HTML 表单能够产生的内容类型的写请求,一律拒绝。
+跨站请求伪造要面对两层相互独立的防线:SameSite=Lax 的 cookie,以及 Content-Type 检查:凡是 HTML 表单能产生的 Content-Type,对应的写请求一律拒绝。
diff --git a/packages/docs/content/self-improvement.en.md b/packages/docs/content/self-improvement.en.md
index 92e3d91b..aac3e696 100644
--- a/packages/docs/content/self-improvement.en.md
+++ b/packages/docs/content/self-improvement.en.md
@@ -1,50 +1,118 @@
---
title: Self-Improvement
-description: The Skill-orchestrated Benchmark and optimization loop: score, improve, snapshot, roll back.
+description: How Skills build a Benchmark, score an agent on it, and keep only the changes that raise its score, with every version snapshotted and every score traceable.
---
-Self-improvement in PenguinHarness uses Skills to orchestrate the ordinary Agent machinery: evaluations are ordinary Sessions and optimization is ordinary file editing. Evaluation construction and optimization run in two independent top-level Sessions, while individual evaluations are delegated through the built-in `run_subagent` tool. Top-level prompts provide the Agent, Benchmark, capability, score, and round settings for the task; Skills own call relationships, calibration, Freeze, protocol, repair, rollback, and reporting.
+Self-improvement in PenguinHarness is a loop: build a Benchmark for an agent, score the agent on it, change the agent, and keep a change only when the score strictly improves. The loop adds no runtime of its own. Skills orchestrate the ordinary agent machinery: evaluations are ordinary Sessions, optimization is ordinary file editing, and every result is a file in the Project.
-## Roles and call relationships
+Building a Benchmark and optimizing an agent run in two independent top-level Sessions, and each single evaluation is delegated through the built-in `run_subagent` tool. The top-level prompt supplies the settings for the task: the agent, the Benchmark, the capability, the scores and the rounds. The Skills own everything else: call relationships, calibration, Freeze, the result protocol, repair, rollback and reporting.
-| Role | Responsibility |
-| --- | --- |
-| Builder | Top-level Agent that directly follows `agent-initialization` and then `benchmark-design` |
-| Target Agent | The Agent being improved; runs evaluation tasks only inside its own Workspace |
-| Evaluator | Leaf worker created through `run_subagent`; runs and scores one Benchmark Case run |
-| Optimizer | New top-level Agent that directly follows `agent-optimization` |
+## Roles
+
+| Role | Skill | Runs as | Responsibility |
+| --- | --- | --- | --- |
+| Builder | `agent-initialization`, then `benchmark-design` | A top-level Session | Sets up the agent, then writes and calibrates a multi-Case Benchmark and records its baseline |
+| Target Agent | — | A fresh top-level Session for every run | The agent being evaluated or improved; it works only inside its own isolated Workspace |
+| Evaluator | `agent-evaluation` | A leaf subagent created through `run_subagent` | Runs the Target Agent on one Case once and scores that run |
+| Optimizer | `agent-optimization` | A separate top-level Session | Changes the Target Agent under a falsifiable hypothesis and keeps a new version only when its score strictly improves |
+
+No built-in agent is reserved for a role: each role is a Skill, and all four Skills ship in the `agent-tuning` plugin. The Web App calls the Target Agent the **Test Agent** or the **Tested agent**.
+
+### How the roles call each other
+
+1. The Builder or the Optimizer dispatches the full Case × runs matrix in parallel through `run_subagent`: one Evaluator per cell, each told to use `agent-evaluation`.
+2. Each Evaluator uses the Penguin CLI to launch the Target Agent once, in a fresh top-level Session and a unique Workspace under the Target Agent's `workspaces/` directory, given by its absolute path. The launch passes `--source benchmark`, so every Test Session lands in the **Evaluations** folder of the Web App's session list instead of among the agent's active conversations. The Evaluator's own Session is an ordinary subagent Session.
+3. When the Target Agent finishes, the Evaluator scores the run against the rubric and returns one protocol result: the score, cost, duration and Test Session id. It changes no agent or Benchmark, and never writes `scoreboard.yaml`.
+4. The caller checks the complete matrix and writes `scoreboard.yaml`.
+
+Both callers first check that each Evaluator's complete response is plain protocol YAML, and only then read its status or score. When the formatting is invalid, the same Evaluator resends its existing result; the Target Agent is not run again.
+
+## The information barrier
+
+A score is only meaningful while the agent under test cannot see how it is scored. Each role therefore reads a different part of a Benchmark:
+
+| Role | Reads | Does not read |
+| --- | --- | --- |
+| Target Agent | A copy of the Case's `statement/` in a fresh Workspace, and its own Agent State | The rubric: it never enters that Workspace, and its path is never given |
+| Evaluator | The statement, the rubric, the Target Agent's State, and the run's Workspace and Traces | Other agents, Project secrets, unrelated Workspaces or Traces |
+| Optimizer | Public statements, the Scoreboard, score-linked Test Traces, and the Target Agent's State | Rubrics, Gold answers, private scoring conditions, the Evaluator's State, Workspace or Trace, other agents, and Project secrets |
+| Builder | The whole Benchmark, including the rubrics it writes, the Target Agent's State, and the Test Traces | The Evaluator's State, Workspace or Trace, other agents, and Project secrets |
+
+The Evaluator keeps rubric contents, Gold answers, per-item scores and scoring rationale out of the result it returns. Before a new or changed Case is dispatched, the Builder runs a leak check: no public file may reveal Gold answers, private scoring conditions, or hints that identify the intended solution. If private evaluation information ever reaches the Optimizer's context, the Optimizer rolls back the active Candidate and stops as contaminated.
+
+> [!WARNING]
+> The barrier is enforced by Skill instructions and auditable Traces, not by a sandbox. No file-system sandbox, file permission or tool restriction stops an agent from reading a rubric: the Target Agent runs with `--approve allow-all`, its Workspace simply contains no rubric, and the Skills tell the other roles what they may read. Every tool call an agent makes is recorded in its Trace, so a breach can be found afterwards. Project members can also read every rubric in the Web App.
+
+## Building a Benchmark
+
+The first top-level Session creates the agent and its capability evaluation. The Builder follows `agent-initialization`, then `benchmark-design`, and is given the Target Agent, the capability to measure, a desired baseline score and a Pilot iteration limit.
+
+The evaluation runtime is fixed before the first Pilot. A `(provider, model_id)` pair the user specifies takes priority; otherwise the pair is inherited from the Builder Session. The thinking level comes from the Target Agent's `model.thinking_level`, `medium` when the field is absent. Calibration always runs each Case once, so the Builder's `runs` is fixed at 1.
+
+### Designing the Cases
+
+The evaluation contract and the private standard must be clear and fixed. The public statement does not have to determine the Gold answer uniquely. A Benchmark may use incomplete public information, conflicting signals, and a fixed private decision standard, as long as that standard expresses a reusable policy, priority or inference boundary, and is not rewritten after seeing the run's answer.
+
+Most points should rest on decisions or concise artifacts where the intended behavior and a plausible shortcut produce different results. Format, evidence enumeration and analysis completeness should not give a high score floor.
+
+Before the first dispatch of every new or changed Case, the Builder reviews it:
+
+- the statement is internally coherent;
+- the rubric agrees with the current statement and the fixed private standard;
+- every scoring item relies only on premises that are defined, provided, or explicitly private.
-The Builder and Optimizer directly follow their Skills in their own top-level Sessions. Evaluators are created through `run_subagent`; each follows `agent-evaluation` and uses the Penguin CLI to launch the specified Target Agent in an isolated Workspace identified by an absolute path. The Penguin CLI launches the Target Agent for the requested Case run. The launch passes `--source benchmark`, so every Test Session lands in the Evaluations folder of the Web App's session list instead of the Test Agent's active conversations.
+The review does not require the public materials to reproduce the private standard. Before Freeze, the Builder repeats the full review across all Cases.
-## Two independent steps
+### Calibrating difficulty
-The first top-level Session creates the Agent and its capability evaluation. The Builder first uses `agent-initialization`, then uses `benchmark-design` to build a multi-Case Benchmark. It may build the complete initial Case set before Pilot 1 and may refine multiple Cases or difficulty dimensions in a later iteration. The evaluation contract and private standard must be clear and fixed, while the public Statement need not uniquely determine the Gold. A Benchmark may use incomplete public information, conflicting signals, and a fixed private decision standard when that standard expresses a reusable policy, priority, or inference boundary and is not rewritten after seeing the run's answer.
+A **Pilot** iteration runs every Case exactly once. The Builder may write the complete initial Case set before Pilot 1, and may refine several Cases or difficulty dimensions in one later iteration.
-Before the first dispatch of every new or changed Case, the Builder checks that the Statement is internally coherent, the Rubric agrees with the current Statement and fixed private standard, and every scoring item relies only on defined, provided, or explicitly private premises; this does not require the public materials to reproduce the private standard. It repeats the full review across all Cases before Freeze. Most points should rest on decisions or concise artifacts for which the intended behavior and a plausible shortcut produce different results, rather than giving a high floor for format, evidence enumeration, or analysis completeness.
+Before each calibration dispatch, the Builder predicts three things: the result the strategy observed in the Trace will produce, the different result the desired behavior will produce, and the range of the score that is affected. Adding another public rule, exception, source or check that the model can follow directly does not by itself make a Case harder. When both strategies would still reach the same scored result, the Builder picks a different refinement.
-Before each calibration dispatch, the Builder predicts the result produced by the observed Trace strategy, the different result produced by the desired behavior, and the score range affected. Adding another public rule, exception, source, or check that the model can directly execute does not automatically increase difficulty. If both strategies still reach the same scored result, the Builder chooses another refinement.
+### Freezing the baseline
-Every Pilot iteration runs each Case exactly once. The Pilot score is a desired target: meeting it permits an early Freeze; otherwise the Builder completes the configured number of valid Pilot iterations and freezes the lowest-scoring valid revision. The Builder temporarily retains only the current lowest valid revision and its complete result. After the final consistency review, it records that selected Pilot's one-Run result directly as the Formal Baseline without rerunning or backfilling more Runs, then removes the temporary copy and other calibration scaffolding. A Formal score that misses the desired target does not invalidate the Benchmark.
+The desired baseline score is a target, not a gate:
-After the user confirms that step is complete, they start the second top-level Session in a new conversation and specify `runs` per Case for every Candidate. The Optimizer checks the Benchmark and its first complete Formal Baseline before following `agent-optimization`:
+- A valid Pilot that meets it allows an early **Freeze**.
+- Otherwise the Builder completes the configured number of valid Pilot iterations and freezes the lowest-scoring valid revision. Meanwhile it keeps only the current lowest valid revision and its complete result as a temporary copy.
-1. orchestrate Evaluators in parallel through `run_subagent`, covering the Case × user-specified `runs` matrix;
-2. use scores and linked Traces to propose one bounded Candidate;
-3. edit the Target Agent's editable state — `AGENTS.md`, Skills, config — to produce version N+1;
-4. keep the Candidate only when its Evaluation score strictly improves; otherwise roll it back;
-5. stop early when the desired score is reached, or complete the configured number of valid Candidate rounds and retain the highest-scoring Reference.
+After a final consistency review, the Builder records the selected Pilot's one-run result directly as the **Formal Baseline**, without rerunning or backfilling runs. It then removes the temporary copy and other calibration scaffolding.
-Invalid evaluations and correction reruns do not count toward the round limit. On an execution failure, the Optimizer keeps the same Candidate and repairs only the missing cell; it keeps trying while each attempt follows a new diagnosis and applies a distinct safe repair. Both Builder and Optimizer validate that the complete Evaluator response is plain protocol YAML before reading status or score; if formatting is invalid, that same Evaluator resends from its existing result without rerunning the Target Agent.
+Missing the desired score does not invalidate a Benchmark. The publish gate is a fixed 85: a Formal Baseline below 85 is published. `benchmark-design` reports `calibration_failed` only when no valid Pilot result can be frozen, or when every valid revision still scores 85 or above at the iteration limit.
-Every accepted Candidate is appended to and verified in the Scoreboard immediately. A strictly higher Evaluation score decides acceptance; the first comparison directly compares the Candidate's multi-Run average with the Formal Baseline's one-Run score without backfilling the Baseline. Whether the predicted Case behavior changed is reported separately so unrelated single-run variation is not presented as causal evidence. Agent optimization requires a complete Formal Baseline in the Scoreboard — without one there is no improvement to compare against.
+## Optimizing an agent
-## From the Evaluation Center
+After the user confirms that the first step is complete, they start a second top-level Session in a new conversation, and set the `runs` per Case for every Candidate, a target score and a round limit. The Optimizer checks that the Benchmark is `published` and has a complete Formal Baseline for the agent, and then follows `agent-optimization`. If a prerequisite is missing, it stops and explains.
-The Web App's Evaluation Center starts the same two Sessions without a hand-written prompt. **Create with AI** takes the Test Agent and a description and prefills the `benchmark-design` request — agent id, a desired baseline score, a pilot-iteration limit — into a new conversation with the Project's default agent; **Create manually** writes a Benchmark from a form in the layout below, ready for evaluation, and asks for no owning Agent. **Use** opens one dialog with two tabs: **Evaluate** prefills the `agent-evaluation` request — Test Agent picked in the form, Benchmark id, runs per case — into a new conversation with the evaluator agent of your choice, and **Optimize** prefills the `agent-optimization` request — the same Test Agent and Benchmark id plus round limit and target score — into one with the optimizer agent. Every entry only prefills: sending is the user's decision in that conversation. The evaluation runtime is never chosen there: an evaluation takes the Test Agent's own configured model and thinking level, and the Optimizer reuses the pair and thinking level the baseline recorded.
+The **Reference** is the Agent State currently kept as best, together with its complete evaluation. Each round tests one **Candidate** built from it:
+
+1. Diagnose capability gaps from the per-Case scores and the score-linked Traces.
+2. State one falsifiable hypothesis and make one bounded change: behavioral guidance in `AGENTS.md`, a focused Skill of the agent's own, or safe `system_config.yaml` fields. The Candidate's version is the Reference version + 1, and a rejected version number is never reused.
+3. Evaluate the Candidate on the full Case × runs matrix through Evaluators in parallel, with the Reference's provider, model and thinking level.
+4. Keep the Candidate only when its evaluation score is strictly higher than the Reference's; otherwise roll it back.
+5. Stop early once the target score is reached. Otherwise complete the configured number of valid rounds and keep the highest-scoring Reference.
+
+The Optimizer does not edit `system_prompt` unless asked, and never changes `model.thinking_level`, because the Reference's scores fix the evaluation thinking level. It changes neither the Benchmark, the Test Traces nor the Project configuration. Its only Benchmark write is appending an accepted evaluation to `scoreboard.yaml`.
+
+### Scoring and acceptance
+
+Every accepted Candidate is appended to the Scoreboard and verified immediately. A strictly higher evaluation score decides acceptance. The first comparison sets the Candidate's multi-run average directly against the Formal Baseline's one-run score, without backfilling the baseline. Whether the predicted Case behavior actually changed is reported separately, so that unrelated single-run variation is not presented as evidence of cause.
+
+Optimization needs a complete Formal Baseline in the Scoreboard: without one, there is no improvement to compare against. Rejected Candidates never enter the Scoreboard; the per-round report stays in the conversation.
+
+### Failures and stopping
+
+Invalid evaluations and correction reruns do not count toward the round limit; a complete, valid evaluation of a rejected Candidate does. When an execution fails, the Optimizer keeps the same Candidate and repairs only the missing cell. It keeps trying as long as each attempt follows a new diagnosis and applies a different safe repair.
+
+The Optimizer also stops on contamination, on `version_changed` or `benchmark_invalid`, or when no safe repair remains.
+
+## Starting from the Web App
+
+The Web App's [Evaluation Center](/evaluation-center) starts the same two top-level Sessions without a hand-written prompt. Its dialogs prefill the request, with the matching Skills selected, into a new conversation, and nothing runs until you send it. The dialogs never choose the Target Agent's evaluation runtime. For the steps, see [Evaluation Center](/evaluation-center).
## Benchmark storage
-Benchmarks belong to the Project, stored in `<root>/<project>/benchmarks/<id>/`, a sibling of `agents/`. A Benchmark and an Agent are peers rather than one owning the other: a Benchmark can evaluate several Agents and an Agent can be evaluated by several Benchmarks, so `benchmark_config.toml` names no Agent — the Agent under test is recorded on each evaluation instead.
+Benchmarks belong to the Project. Each one is stored in `<root>/<project>/benchmarks/<id>/`, a sibling of `agents/`. Benchmarks and agents are peers rather than owner and owned: one Benchmark can evaluate several agents, and one agent can be evaluated by several Benchmarks. So `benchmark_config.toml` names no agent; each evaluation records the agent it tested.
```text
<project>/benchmarks/<id>/
@@ -55,43 +123,63 @@ Benchmarks belong to the Project, stored in `<root>/<project>/benchmarks/<id>/`,
└── scoreboard.yaml # evaluation records (current format)
```
-The separation of `rubric/` from `statement/` is deliberate: the Target Agent sees only the task statement and never touches the scoring rubric.
+`rubric/` is kept apart from `statement/` on purpose: the Target Agent receives only the task statement and never the scoring rubric.
+
+`benchmark_config.toml` is what makes a directory a Benchmark: a directory under `benchmarks/` without one is not listed. A Benchmark that has never been evaluated still has its config and is listed as usual. Deleting a Benchmark while an evaluation is still running leaves such a config-less directory behind, because the running evaluation keeps writing to its paths; it is safe to delete by hand.
+
+### Benchmark status
+
+`status` says whether the Benchmark is finished:
+
+| Status | Set when | In the Web App |
+| --- | --- | --- |
+| `draft` | `benchmark-design` is still writing the cases and calibrating their difficulty | Masked: no **Use**, no detail page |
+| `published` | The Formal Baseline is recorded | Usable |
+| `failed` | `benchmark-design` reports `calibration_failed` | Masked as a failed creation, with a request to delete it and create it again |
-`benchmark_config.toml` is what makes a directory a Benchmark: a directory under `benchmarks/` without one is not listed. Deleting a Benchmark while an evaluation is still running leaves such a directory behind, because the running evaluation keeps writing to the paths it was deleted from. A Benchmark that has simply never been evaluated still has its config and is listed as usual; a leftover directory is safe to delete by hand.
+A failed Benchmark cannot be used. A Benchmark created by hand, and the built-in example, are published from the start. A config without the field, or with any value other than `draft` or `failed`, reads as published.
-`status` says whether the Benchmark is finished: `draft` while `benchmark-design` is still writing its cases and calibrating their difficulty, which the Web App masks — no Use, no detail — `published` once the Formal Baseline is recorded, and `failed` once `benchmark-design` reports `calibration_failed`, meaning no valid Pilot result could be frozen or every valid one still scored 85 or above at the iteration limit. The publish gate is that fixed 85, not the desired baseline score the request asked for: a Formal Baseline below 85 is published even when it missed the desired score. A failed Benchmark is unusable: the Web App masks it as a failed creation and asks the user to delete it and create it again. A Benchmark created by hand and the built-in example are published from the start. A config without the field, or with any value other than `draft` or `failed`, reads as published.
+### Evaluation records
Each evaluation record in `scoreboard.yaml` is timestamped and carries:
-- `agent_id`, the Agent that round evaluated. Together with `model_id` and `thinking_level` it forms the record's **label**: the trend chart plots time against score and draws one series per label, and only scores under the same label are comparable. The Agent State `version` is not part of it — successive versions of one Agent on one runtime are the trend the chart exists to show, so they share a line and each point names its version on hover. A record written before evaluations carried an Agent reads as unlabelled and falls into the chart's grey series;
-- the evaluation runtime: a user-specified `(provider, model_id)` pair takes priority, otherwise the pair is inherited from the Builder Session; `thinking_level` is read from the Target Agent config and does not depend on Trace metadata;
-- `summary_title` and `summary` (the round's conclusion and the hypothesis for the next one);
-- Score, cost, and duration averages written by the model — Case-level values average Runs and Evaluation-level values average Cases; Run cost preserves its recorded precision, cost averages ignore `null` inputs and remain `null` only when every contributing cost is unknown; Score uses two decimals, cost averages use six decimals, and `duration_ms` is an integer;
-- per-Case run details, each run recording `score`, `cost`, `duration_ms`, and `session_id`.
+- `agent_id`, the agent the evaluation tested. Together with `model_id` and `thinking_level`, it forms the record's **label**. The trend chart plots score against time with one series per label, and only scores under the same label are comparable. The Agent State `version` is not part of the label: successive versions of one agent on one runtime are the trend the chart exists to show, so they share a line, and each point names its version on hover. A record written before evaluations carried an agent reads as unlabelled and falls into the chart's grey series.
+- The evaluation runtime: `provider`, `model_id` and `thinking_level`. For the baseline, a `(provider, model_id)` pair the user specifies takes priority; otherwise the pair is inherited from the Builder Session. An optimization reuses the Reference's runtime. `thinking_level` is read from the Target Agent's config, not from Trace metadata.
+- `summary_title` and `summary`: the round's conclusion and the hypothesis for the next one.
+- Score, cost and duration averages, written by the model. Case-level values average the runs, and evaluation-level values average the Cases. Run cost keeps its recorded precision. Cost averages ignore `null` inputs and are `null` only when every contributing cost is unknown. Scores use two decimals, cost averages six, and `duration_ms` is an integer.
+- Per-Case run details: each run records `score`, `cost`, `duration_ms` and `session_id`.
-Every Run and every Case has a fixed maximum Score of 100, so Scoreboard entries do not carry `max_score`. The server and Web UI trust the stored aggregate values and do not recompute or cross-check them. Old Scoreboard formats are not migrated or backfilled.
+Every run and every Case is scored out of 100, so Scoreboard entries carry no `max_score`. The server and the Web App trust the stored averages and neither recompute nor cross-check them. Older Scoreboard formats are not migrated or backfilled.
-Initializing a Project's `default_agent` seeds an example Benchmark at the Project level (`packages/core/src/state/example-benchmark.ts`), its three sample evaluations labelled `agent_id: default_agent`, so the evaluation pages have data out of the box; the whole directory can be deleted or replaced at any time. The check is the example's own directory, `benchmarks/example-benchmark/`: when it is missing, loading `default_agent` writes it, whatever else `benchmarks/` already holds and whatever an older data root still keeps at the retired per-agent location `agents/<agent>/benchmarks/` (which nothing reads). An example that is present is never touched, and a deleted one comes back on the next load.
+### The example Benchmark
+
+Initializing a Project's `default_agent` seeds an example Benchmark at the Project level (`packages/core/src/state/example-benchmark.ts`). Its three sample evaluations are labelled `agent_id: default_agent`, so the evaluation pages have data out of the box. The whole directory can be deleted or replaced at any time.
+
+The check looks only at the example's own directory, `benchmarks/example-benchmark/`. Whenever it is missing and `default_agent` is initialized or loaded, the example is written, whatever else `benchmarks/` holds, and whatever an older data root still keeps at the retired per-agent location `agents/<agent>/benchmarks/`, which nothing reads. An example that is present is never touched, and a deleted one comes back on the next load.
## Snapshots and versions
-Before each optimization round, the Agent State is packed into `snapshots/v<version>.tar.gz` (excluding the Vault — secrets never enter a snapshot). The `version` in `system_config.yaml` increments on successful optimization. The Web UI supports exporting and importing snapshots; importing a version not higher than the current one requires explicit confirmation. A new Agent can also be created straight from an exported package in the Agents page's create dialog: it starts with the package's state and version, no confirmation needed.
+The `version` field in `system_config.yaml` is the Agent State version. It increases with each accepted optimization.
+
+Before the Optimizer changes a Reference State, it makes sure `<agent>/snapshots/v<version>.tar.gz` exists for the Reference version. It reuses an existing snapshot, and otherwise creates one by archiving `agent_state/` without the Vault (`.vault.toml`): secrets never enter a snapshot. It never overwrites a snapshot of the same version, and if it cannot create one, it stops before changing anything. A rejected Candidate is rolled back in the same round: the Optimizer restores the original files and version and removes files the Candidate created.
+
+In the Web App, an agent's settings page offers **Export snapshot** to any member and **Import snapshot** to the Project owner. An import replaces the whole Agent State, takes the `version` inside the package, and keeps the current Vault; the current version is snapshotted first. Importing a version that is not newer than the current one asks for confirmation. The create dialog on the Agents page can also start a new agent from an exported package (**Initialize from a snapshot**): the agent starts with the package's state and version, with no confirmation.
-## Auditable end to end
+## Auditability
-- Every Evaluator run is an ordinary Session with a full Trace;
-- Scoreboard records link back to those Sessions via `session_id`; see [Sessions & Traces](/sessions-and-traces);
-- The Web evaluation pages are read-only views of these files; the trend chart shows Score only, while the detail table shows the Agent under test, model ID and thinking level as separate columns. See the [Web App Guide](/web-app).
+- Every Evaluator run and every Test Session is an ordinary Session with a full Trace.
+- Scoreboard records link back to the Test Sessions through `session_id`. See [Sessions & Traces](/sessions-and-traces).
+- The Web App's evaluation pages are read-only views of these files. The trend chart shows Score only; the evaluation table shows the tested agent, the model ID and the thinking level in separate columns. See [Evaluation Center](/evaluation-center).
-Scores are not black-box output: every number can be traced back to the run that produced it.
+Every score can be traced back to the run that produced it.
## Related Skills
| Skill | Purpose |
| --- | --- |
-| `agent-initialization` | Turn a requirement into a working Agent: write its `AGENTS.md`, install the Skills it needs |
+| `agent-initialization` | Turn a requirement into a working agent: write its `AGENTS.md` and install the Skills it needs |
| `benchmark-design` | Design and calibrate a multi-Case capability Benchmark |
| `agent-evaluation` | Run and score one isolated Benchmark Case run |
-| `agent-optimization` | Improve an Agent from Benchmark results |
+| `agent-optimization` | Improve an agent from Benchmark results |
-How Skills are organized and installed is covered in the [Skill System](/skills).
+How Skills are organized and installed is covered in [Skills](/skills).
diff --git a/packages/docs/content/self-improvement.zh.md b/packages/docs/content/self-improvement.zh.md
index 4e6048a6..b0546a77 100644
--- a/packages/docs/content/self-improvement.zh.md
+++ b/packages/docs/content/self-improvement.zh.md
@@ -1,97 +1,185 @@
---
title: 自我进化
-description: 由 Skill 编排的 Benchmark 评测与优化闭环:评分、改进、Snapshot 与回滚。
+description: Skill 如何构建 Benchmark、给 Agent 打分,并只保留让分数提高的改动;每个版本都有快照,每个分数都能追溯。
---
-PenguinHarness 中的自我进化由 Skill 编排普通的 Agent 机制完成:评测是普通的 Session,优化是普通的文件编辑。创建评测与优化分别运行在两个独立的顶层 Session 中,单次评测通过内置的 `run_subagent` 工具委托。顶层 Prompt 提供 Agent、Benchmark、能力目标、分数和轮数等本次设定;调用关系、校准、Freeze、协议、重试、回滚和报告格式由 Skill 负责。
+PenguinHarness 的自我进化是一个循环:为 Agent 构建 Benchmark,在上面给 Agent 打分,修改 Agent,只有分数严格提升才保留改动。这个循环不额外引入任何运行机制,而是由 Skill 编排普通的 Agent 机制:评估是普通的 Session,优化是普通的文件编辑,每个结果都是 Project 里的文件。
-## 角色与调用关系
+构建 Benchmark 和优化 Agent 分别在两个独立的顶层 Session 中运行,每一次单独的评估则通过内置的 `run_subagent` 工具委派出去。顶层 Prompt 提供这次任务的设定:Agent、Benchmark、要考察的能力、分数和轮数。其余一切都由 Skill 负责:调用关系、校准、Freeze、结果协议、修复、回滚和汇报。
-| 角色 | 职责 |
-| --- | --- |
-| Builder | 顶层 Agent,依次直接执行 `agent-initialization` 和 `benchmark-design` |
-| Target Agent | 被改进的 Agent,只在自己的 Workspace 里执行评测任务 |
-| Evaluator | `run_subagent` 创建的叶子 Worker,执行并评分一次 Benchmark Case 运行 |
-| Optimizer | 新顶层 Agent,直接执行 `agent-optimization` |
+## 角色
+
+| 角色 | Skill | 运行方式 | 职责 |
+| --- | --- | --- | --- |
+| Builder | 先 `agent-initialization`,后 `benchmark-design` | 一个顶层 Session | 搭建 Agent,然后编写并校准一个包含多道题目的 Benchmark,记录基线 |
+| Target Agent | — | 每次运行一个全新的顶层 Session | 被评估或被优化的 Agent,只在自己隔离的 Workspace 里工作 |
+| Evaluator | `agent-evaluation` | 通过 `run_subagent` 创建的叶子子 Agent | 让 Target Agent 在一道题目上运行一次,并为这次运行打分 |
+| Optimizer | `agent-optimization` | 另一个独立的顶层 Session | 按可证伪的假设修改 Target Agent,分数严格提升才保留新版本 |
+
+没有为这些角色专门预留的内置 Agent:每个角色就是一个 Skill,四个 Skill 都随 `agent-tuning` 插件提供。在 Web App 界面里,Target Agent 叫作**被测智能体**。
+
+### 角色之间的调用
+
+1. Builder 或 Optimizer 通过 `run_subagent` 并行下发完整的 Case × runs 矩阵:矩阵中的每一格对应一个 Evaluator,并要求它使用 `agent-evaluation`。
+2. 每个 Evaluator 用 Penguin CLI 启动一次 Target Agent:开一个全新的顶层 Session,在 Target Agent 的 `workspaces/` 目录下建一个专属 Workspace,并以绝对路径传入。启动时带上 `--source benchmark`,所以每个被测会话都会归入 Web App 会话列表的**评估任务**折叠夹,不会混进这个 Agent 的活跃对话。Evaluator 自己的 Session 是普通的子 Agent Session。
+3. Target Agent 运行结束后,Evaluator 按评分细则为这次运行打分,返回一条协议结果:分数、成本、耗时和被测会话 id。Evaluator 不改动任何 Agent 或 Benchmark,也从不写 `scoreboard.yaml`。
+4. 调用方核对完整的矩阵后写入 `scoreboard.yaml`。
+
+两种调用方都会先确认 Evaluator 的完整响应是纯协议 YAML,然后才读取其中的状态或分数。格式不合规时,由同一个 Evaluator 基于已有结果重发,不重新运行 Target Agent。
+
+## 信息隔离
+
+被测的 Agent 看不到评分方式,分数才有意义。因此每个角色读取的是 Benchmark 的不同部分:
+
+| 角色 | 读取 | 不读取 |
+| --- | --- | --- |
+| Target Agent | 全新 Workspace 里题目 `statement/` 的副本,以及自己的 Agent State | 评分细则:它从不进入这个 Workspace,路径也不会告诉 Target Agent |
+| Evaluator | 题干、评分细则、Target Agent 的 State,以及本次运行的 Workspace 和 Trace | 其他 Agent、Project 的密钥、无关的 Workspace 或 Trace |
+| Optimizer | 公开的题干、记分板、与分数关联的被测 Trace,以及 Target Agent 的 State | 评分细则、Gold(标准答案)、私有评分条件、Evaluator 的 State、Workspace 或 Trace、其他 Agent,以及 Project 的密钥 |
+| Builder | 整个 Benchmark(包括它自己写的评分细则)、Target Agent 的 State,以及被测 Trace | Evaluator 的 State、Workspace 或 Trace、其他 Agent,以及 Project 的密钥 |
+
+Evaluator 返回的结果里不含评分细则的内容、Gold、逐项得分和评分理由。新增或修改的题目下发之前,Builder 先做泄题检查:任何公开文件都不得泄露 Gold、私有评分条件,或能指向预期解法的提示。一旦私有的评估信息进入 Optimizer 的上下文,Optimizer 就回滚正在测试的 Candidate,并以「污染」为由停止。
+
+> [!WARNING]
+> 信息隔离靠的是 Skill 指令和可审计的 Trace,不是沙箱。这里没有文件系统沙箱、文件权限或工具限制来阻止 Agent 读取评分细则:Target Agent 以 `--approve allow-all` 运行,只是它的 Workspace 里没有评分细则;其他角色能读什么,则由 Skill 规定。Agent 的每一次工具调用都记在它的 Trace 里,违规事后可以查出来。Project 成员也能在 Web App 里查看所有评分细则。
+
+## 构建 Benchmark
+
+第一个顶层 Session 负责创建 Agent 和它的能力评估。Builder 先执行 `agent-initialization`,再执行 `benchmark-design`,拿到的输入是 Target Agent、要考察的能力、期望的基线分数和 Pilot 迭代上限。
+
+评估 Runtime 在第一次 Pilot 之前就固定下来。用户指定的 `(provider, model_id)` 模型对优先;没有指定时,沿用 Builder Session 的模型对。思考等级取自 Target Agent 的 `model.thinking_level`,字段缺失时为 `medium`。校准时每道题目总是只运行一次,所以 Builder 的 `runs` 固定为 1。
+
+### 设计题目
+
+评估契约和私有标准必须清楚且固定,公开的题干却不必唯一确定 Gold。Benchmark 可以使用不完整的公开信息、相互冲突的信号和固定的私有决策标准,前提是这个标准表达的是可复用的策略、优先级或推断边界,而且不会在看到本次运行的答案之后再改。
+
+大部分分数应落在这样的决策或简洁产物上:预期行为与看似合理的捷径在这里会得出不同的结果。格式、证据罗列和分析完整度不应构成偏高的保底分。
+
+每道新增或修改过的题目在首次下发之前,Builder 都要检查一遍:
+
+- 题干内部自洽;
+- 评分细则与当前题干、固定的私有标准一致;
+- 每个评分项所依赖的前提,要么已经定义,要么已经提供,要么明确属于私有标准。
-Builder 和 Optimizer 在各自的顶层 Session 中直接遵循对应 Skill。Evaluator 通过 `run_subagent` 创建,遵循 `agent-evaluation`,并通过 Penguin CLI 在绝对路径的隔离 Workspace 中启动指定的 Target Agent。Penguin CLI 在每次请求中启动 Target Agent 完成对应的 Case Run。启动时传入 `--source benchmark`,因此每个 Test Session 都会落到 Web App 会话列表的「评估任务」子夹,而不是留在 Test Agent 的活跃对话中。
+这项检查不要求公开材料足以还原私有标准。Freeze 之前,Builder 还要对所有题目完整检查一遍。
-## 两个独立步骤
+### 校准难度
-第一个顶层 Session 创建 Agent 和能力评测。Builder 先使用 `agent-initialization`,再使用 `benchmark-design` 构建多 Case Benchmark。初版 Cases 可以一次建好并形成完整 Pilot 1;后续每轮可以同时调整多个 Case 或难度维度。评测契约和私有标准必须明确、固定,公开 Statement 则不必唯一决定 Gold。Benchmark 可以通过公开信息不足、冲突信号和固定的私有决策标准形成信息差,只要该标准表达可复用的策略、优先级或推断边界,而且不会根据本次答案改写。
+每一轮 **Pilot**(试测迭代)中,每道题目恰好运行一次。Builder 可以在 Pilot 1 之前就写好完整的初始题目集,之后的某一轮迭代也可以同时打磨多道题目或多个难度维度。
-每个新增或修改后的 Case 在首次派发前都要检查 Statement 自洽、Rubric 与当前 Statement 和固定私有标准一致,并确认评分项只依赖已定义、已提供或明确属于私有标准的前提;这不要求公开材料足以复现私有标准。Freeze 前再对所有 Case 完整检查一次。大部分分数应落在目标行为与合理捷径会产生不同结果的决定或简洁产物上,避免格式、证据罗列和分析完整度形成过高的保底分。
+每次下发校准之前,Builder 先预测三件事:Trace 中观察到的策略会得出什么结果,预期行为会得出什么不同的结果,以及会影响多大范围的分数。再加一条模型可以直接照做的公开规则、例外、来源或检查项,并不会自动让题目变难。如果两种策略仍会得到相同的计分结果,Builder 就换一种打磨方式。
-每轮校准都要在派发前预测:当前 Trace 中的策略会产生什么结果、期望行为会产生什么不同结果,以及会影响多少分。增加一条模型可以直接执行的公开规则、例外、来源或检查项并不会自动增加难度;如果两种策略仍会得到相同的计分结果,就应选择其他改法。
+### 冻结基线
-每个 Pilot iteration 对每个 Case 固定只运行一次。Pilot 分数是期望目标:达到后可以提前 Freeze;未达到时完成设定数量的有效 Pilot iteration,并选择其中分数最低的有效版本 Freeze。Builder 在临时目录只保留当前最低有效版本及其完整结果。最终一致性检查通过后,直接把被选中 Pilot 的单次运行结果记录为 Formal Baseline,不再重新运行或补齐更多 Runs;记录后清理临时副本和校准脚手架。Formal 分数没有达到期望也不会使 Benchmark 作废。
+期望的基线分数是目标,不是门槛:
-用户确认第一步完成后,在新对话中启动第二个顶层 Session,并指定每个 Candidate、每个 Case 的 `runs`。Optimizer 先检查 Benchmark 和第一条完整 Formal Baseline,再使用 `agent-optimization`:
+- 有效的 Pilot 达到期望分数,就可以提前 **Freeze**(冻结)。
+- 否则 Builder 跑完设定数量的有效 Pilot 迭代,冻结得分最低的有效版本。期间它只把当前得分最低的有效版本及其完整结果留作临时副本。
-1. 通过 `run_subagent` 并行编排 Evaluator,覆盖 Case × 用户指定 `runs` 的矩阵;
-2. 根据得分和关联 Trace 提出一个有界 Candidate;
-3. 编辑 Target Agent 的可编辑状态——`AGENTS.md`、Skills、配置——产出版本 N+1;
-4. Evaluation 分数严格提升才保留 Candidate,否则回滚;
-5. 达到期望分数时提前结束,否则完成本次设定数量的有效 Candidate round,并保留最高分 Reference。
+最终的一致性检查通过后,Builder 把选中那次 Pilot 的单次运行结果直接记为 **Formal Baseline**(正式基线),不重跑,也不补跑其他运行。随后删掉临时副本和其他校准用的脚手架。
-无效评测和修复重跑不计入轮数。出现执行失败时,Optimizer 保持同一个 Candidate,只补齐失败单元;只要还能根据新诊断提出不同的安全修复,就继续尝试。Builder 和 Optimizer 都先验证 Evaluator 的完整响应是否为纯协议 YAML,再读取状态或分数;格式不合规时,由同一个 Evaluator 基于已有结果重发,不重新运行 Target Agent。
+没达到期望分数不会让 Benchmark 作废。发布门槛固定为 85 分:Formal Baseline 低于 85 就发布。只有两种情况 `benchmark-design` 才报告 `calibration_failed`:没有任何可冻结的有效 Pilot 结果,或者到了迭代上限,所有有效版本的得分仍不低于 85。
-每个 Accepted Candidate 立即写入并校验 Scoreboard。Evaluation 分数严格提高决定是否接受;第一次比较允许直接用 Candidate 的多 Run 平均分比较 Formal Baseline 的单 Run 分数,不为 Baseline 补跑。假设是否在预期 Case 上得到支持单独报告,避免把单次运行中的无关波动解释为改动因果。Agent 优化要求 Scoreboard 中已有完整 Formal Baseline——没有基线,就没有可比较的提升。
+## 优化 Agent
-## 从评估中心发起
+用户确认第一步完成后,在新对话中启动第二个顶层 Session,并设定每个 Candidate(候选版本)每道题目的 `runs`、目标分数和轮数上限。Optimizer 先确认 Benchmark 是 `published`、并且已有这个 Agent 的完整 Formal Baseline,然后按 `agent-optimization` 执行。缺少任何前提,它就停下来说明原因。
-Web App 的评估中心不需要手写提示词就能启动同样的两个 Session。**用 AI 创建**选定被测 Agent 并描述需求后,把 `benchmark-design` 请求——Agent id、期望基线分、Pilot 迭代上限——预填进与 Project 默认 Agent 的新对话;**手动创建**则按下文的目录结构从表单写出一个 Benchmark,可直接评测,且不要求指定所属 Agent。**使用**打开一个含两个 tab 的弹窗:**评估**把 `agent-evaluation` 请求——在表单中选择的被测 Agent、Benchmark id、每题运行次数——预填进与所选执行评估 Agent 的新对话,**优化**把 `agent-optimization` 请求——同样的被测 Agent 与 Benchmark id,另加最多轮数与目标分数——预填进与所选优化 Agent 的新对话。这些入口都只做预填:发送由用户在对话里决定。评测 Runtime 从不在那里选择:评估取被测 Agent 当前配置的模型与思考等级,Optimizer 沿用基线记录的模型对与推理强度。
+**Reference**(参照版本)是当前保留的最佳 Agent State,连同它的完整评估。每一轮都基于它构建一个 **Candidate** 来测试:
+
+1. 根据每道题目的分数和关联的 Trace,诊断能力缺口。
+2. 提出一个可证伪的假设,只做一处有边界的改动:`AGENTS.md` 中的行为指引、Agent 自有的一个专项 Skill,或 `system_config.yaml` 中可以安全修改的字段。Candidate 的版本号是 Reference 的版本号 + 1,落选过的版本号永不复用。
+3. 由多个 Evaluator 并行评估完整的 Case × runs 矩阵,沿用 Reference 的供应商、模型和思考等级。
+4. Candidate 的评估分数严格高于 Reference 才保留,否则回滚。
+5. 达到目标分数就提前停止;否则跑完设定数量的有效轮次,保留得分最高的 Reference。
+
+除非用户要求,Optimizer 不修改 `system_prompt`,也从不修改 `model.thinking_level`,因为 Reference 的分数已经确定了评估用的思考等级。Benchmark、被测 Trace 和 Project 配置都不在它的改动范围内。它对 Benchmark 唯一的写入,是把采纳的评估追加到 `scoreboard.yaml`。
+
+### 评分与采纳
+
+每个采纳的 Candidate 都会立即追加进记分板并核验。是否采纳,只看评估分数是否严格更高。第一次比较直接拿 Candidate 的多次运行平均分对比 Formal Baseline 的单次运行分数,不为基线补跑。预测的题目行为是否真的发生了变化,会单独报告,以免把单次运行中无关的波动说成因果证据。
+
+优化要求记分板里已有完整的 Formal Baseline:没有基线,就没有可比较的提升。落选的 Candidate 永远不进记分板,每一轮的报告只留在对话里。
+
+### 失败与停止
+
+无效的评估和纠正性的重跑不计入轮数上限;落选 Candidate 的完整有效评估则计入。执行失败时,Optimizer 保留同一个 Candidate,只补齐缺失的那一格。只要每次尝试都基于新的诊断、采用不同的安全修复,它就会继续尝试。
+
+遇到污染、`version_changed` 或 `benchmark_invalid`,或者再也没有安全的修复办法时,Optimizer 也会停止。
+
+## 从 Web App 发起
+
+Web App 的[评估中心](/evaluation-center)不需要手写 Prompt,就能启动同样的两个顶层 Session。它的对话框把请求预填进一个新对话,并选好对应的 Skill;你发送之前,什么都不会运行。对话框从不选择 Target Agent 的评估 Runtime。具体步骤见[评估中心](/evaluation-center)。
## Benchmark 存储
-Benchmark 属于 Project,存放在与 `agents/` 平级的 `<root>/<project>/benchmarks/<id>/` 下。Benchmark 与 Agent 是平级关系而非从属:一个 Benchmark 可以评测多个 Agent,一个 Agent 也可以被多个 Benchmark 评测,因此 `benchmark_config.toml` 不记录任何 Agent——被测 Agent 记录在每条 evaluation 上。
+Benchmark 属于 Project,每个 Benchmark 存放在 `<root>/<project>/benchmarks/<id>/`,与 `agents/` 平级。Benchmark 与 Agent 是平级关系,谁也不隶属于谁:一个 Benchmark 可以评估多个 Agent,一个 Agent 也可以接受多个 Benchmark 的评估。因此 `benchmark_config.toml` 不记录任何 Agent,被测的 Agent 记在每一条评估上。
```text
<project>/benchmarks/<id>/
-├── benchmark_config.toml # Benchmark 配置:title、description、runs(Builder 的 runs 固定为 1)、status
+├── benchmark_config.toml # Benchmark configuration: title, description, runs (Builder runs is fixed at 1), status
├── <case-id>/
-│ ├── statement/ # 交给 Target Agent 的任务描述
-│ └── rubric/ # 私有评分标准,对 Target Agent 隔离
-└── scoreboard.yaml # 当前格式的评测记录
+│ ├── statement/ # the task given to the Target Agent
+│ └── rubric/ # private scoring rubric, isolated from the Target Agent
+└── scoreboard.yaml # evaluation records (current format)
```
-`rubric/` 与 `statement/` 的隔离是刻意设计:Target Agent 只能看到题面,永远接触不到评分标准。
+`rubric/` 与 `statement/` 刻意分开存放:Target Agent 只拿到题干,永远拿不到评分细则。
+
+有 `benchmark_config.toml` 的目录才算 Benchmark:`benchmarks/` 下缺少这个文件的目录不会列出。从未评估过的 Benchmark 照样有配置文件,照常列出。评估还在运行时删除 Benchmark,会留下这样一个没有配置文件的目录,因为运行中的评估还在往原来的路径里写;这种残留目录可以放心手动删除。
+
+### Benchmark 状态
+
+`status` 表示 Benchmark 是否已经完成:
+
+| 状态 | 何时设置 | 在 Web App 中 |
+| --- | --- | --- |
+| `draft` | `benchmark-design` 还在编写题目、校准难度 | 遮罩显示:不能**使用**,也没有详情页 |
+| `published` | Formal Baseline 已经记录 | 可以使用 |
+| `failed` | `benchmark-design` 报告了 `calibration_failed` | 遮罩显示为创建失败,并提示删除后重新创建 |
+
+`failed` 的 Benchmark 不能使用。手动创建的 Benchmark 和内置示例一开始就是 `published`。配置里没有这个字段,或者取值既不是 `draft` 也不是 `failed`,都按 `published` 读取。
+
+### 评估记录
+
+`scoreboard.yaml` 里的每条评估记录都带时间戳,并包含:
+
+- `agent_id`:这次评估测试的 Agent。它与 `model_id`、`thinking_level` 一起组成这条记录的**标签**。趋势图以时间为横轴、分数为纵轴,每个标签画一条线,只有同一标签下的分数才可比。Agent State 的 `version` 不属于标签:同一个 Agent 在同一 Runtime 下的历次版本,正是这张图要展示的趋势,所以它们共用一条线,每个点的悬停提示里写着对应的版本。评估记录还不带 Agent 的时期写下的记录,读作未标注,归入图表的灰色系列。
+- 评估 Runtime:`provider`、`model_id` 和 `thinking_level`。对于基线,用户指定的 `(provider, model_id)` 模型对优先,否则沿用 Builder Session 的模型对;优化则沿用 Reference 的 Runtime。`thinking_level` 从 Target Agent 的配置读取,不依赖 Trace 元数据。
+- `summary_title` 和 `summary`:这一轮的结论和下一轮的假设。
+- 由模型写入的分数、成本和耗时平均值。题目级的值是各次运行的平均,评估级的值是各道题目的平均。单次运行的成本保留记录时的精度。成本平均值忽略 `null`,只有所有参与计算的成本都未知时才为 `null`。分数保留两位小数,成本平均值保留六位小数,`duration_ms` 为整数。
+- 每道题目的逐次运行明细:每次运行记录 `score`、`cost`、`duration_ms` 和 `session_id`。
-`benchmark_config.toml` 是目录成为 Benchmark 的标志:`benchmarks/` 下缺少该文件的目录不会被列出。在评测运行期间删除 Benchmark 会留下这样的目录——正在运行的评测仍在向被删除的路径写入。从未评测过的 Benchmark 仍带有配置文件,照常列出;残留目录可以手工删除。
+每次运行和每道题目都以 100 分为满分,所以记分板条目不带 `max_score`。服务端和 Web App 直接信任已存储的平均值,既不重算,也不交叉核对。旧格式的记分板不迁移,也不回填。
-`status` 表示这个 Benchmark 是否已经完成:`benchmark-design` 仍在出题与校准难度时为草稿 `draft`,Web App 对其遮罩——不能使用、也看不到详情;记录 Formal Baseline 后为发布 `published`;`benchmark-design` 报告 `calibration_failed`(没有任何可冻结的有效 Pilot 结果,或迭代上限内最低分的有效版本仍不低于 85)时为失败 `failed`。发布的门槛是固定的 85 分,而不是请求里要求的 desired_baseline_score:Formal Baseline 低于 85 就发布,未达期望分数不算失败。失败的 Benchmark 不可用:Web App 同样遮罩,提示创建失败、请删除后重新创建。手动创建的 Benchmark 与内置示例一开始就是 `published`。没有该字段、或取值既不是 `draft` 也不是 `failed` 的配置,都按 `published` 读。
+### 示例 Benchmark
-`scoreboard.yaml` 中的每条评测记录带时间戳,并记录:
+初始化 Project 的 `default_agent` 时,会在 Project 层级预置一个示例 Benchmark(`packages/core/src/state/example-benchmark.ts`)。它的三条示例评估都标注为 `agent_id: default_agent`,所以评估页面开箱就有数据。整个目录随时可以删除或替换。
-- `agent_id`,本轮评测的被测 Agent。它与 `model_id`、`thinking_level` 合成该条记录的**标签**:走势图以时间为横轴、分数为纵轴,按标签分系列,只有同一标签下的分数才可比。Agent State `version` 不进标签——同一被测 Agent 在同一 Runtime 下的历次版本正是走势图要显示的东西,因此它们连成一条线,版本号标在每个点的悬停提示里。评估记录写于 evaluation 尚未携带 Agent 之前时归为未标注,落在图表的灰色系列;
-- 本轮 Runtime:用户显式指定的 `(provider, model_id)` 成对值优先,否则继承 Builder Session;`thinking_level` 从 Target Agent 配置读取,不依赖 Trace 元数据;
-- `summary_title` 与 `summary`(本轮结论与下一轮假设);
-- 由模型写入的 Score、成本与耗时平均值——Case 级对 Runs 求平均,Evaluation 级对 Cases 求平均;单次 Run 成本保留记录中的原始精度,成本平均值忽略 `null`,全部未知时才为 `null`;Score 保留两位小数,成本平均值保留六位小数,`duration_ms` 取整;
-- 每个 Case 的逐次运行明细,每次运行含 `score`、`cost`、`duration_ms` 与 `session_id`。
+判断只看示例自己的目录 `benchmarks/example-benchmark/`:只要它不存在,初始化或加载 `default_agent` 时就会写入示例,不管 `benchmarks/` 里已经有什么,也不管旧的数据根在已退役的按 Agent 存放位置 `agents/<agent>/benchmarks/` 下还留着什么(没有任何代码读取那里)。已经存在的示例一概不动,删掉的示例会在下次加载时回来。
-每个 Run 和每个 Case 都固定满分 100,因此 Scoreboard 不再记录 `max_score`。服务端与 Web UI 直接信任已写入的聚合值,不重算、不交叉校验;旧 Scoreboard 不迁移、不回填。
+## 快照与版本
-初始化 Project 的 `default_agent` 时会在 Project 层级预置一个示例 Benchmark(`packages/core/src/state/example-benchmark.ts`),三条示例评估都标注 `agent_id: default_agent`,评测页面开箱即有数据;整个目录可随时删除或替换。判定只看示例自己的目录 `benchmarks/example-benchmark/`:它不存在时,装载 `default_agent` 就写入——不管 `benchmarks/` 里已经有什么,也不管旧数据根是否还留着已退役的按 Agent 存放的 `agents/<agent>/benchmarks/`(没有任何代码读它)。已存在的示例一概不动,删掉的示例会在下次装载时回来。
+`system_config.yaml` 里的 `version` 字段是 Agent State 的版本号,每采纳一次优化,版本号就会增加。
-## Snapshot 与版本
+Optimizer 改动 Reference State 之前,会先确保 Reference 版本对应的 `<agent>/snapshots/v<version>.tar.gz` 存在。已有快照就直接复用;没有就把 `agent_state/` 打包成一个,打包时排除 Vault(`.vault.toml`),密钥永远不会进入快照。它从不覆盖同一版本已有的快照;如果创建不了快照,就在改动任何东西之前停下。落选的 Candidate 在同一轮内回滚:Optimizer 恢复原来的文件和版本号,并删除 Candidate 新建的文件。
-每轮优化前,Agent State 被打包为 `snapshots/v<version>.tar.gz`(Vault 除外——密钥永不进入快照)。`system_config.yaml` 的 `version` 在优化成功后自增。Web UI 支持导出与导入快照,导入版本不高于当前版本时需要显式确认。也可以在智能体页的创建弹窗里直接从导出的快照包新建 Agent:新 Agent 以包内状态与版本创建,无需确认。
+在 Web App 中,Agent 的设置页向所有成员提供**导出快照**,向 Project owner 提供**导入快照**。导入会整体替换 Agent State,版本号取包内的 `version`,并保留当前的 Vault;导入之前会先为当前版本打一个快照。导入的版本不比当前版本新时,需要先确认。智能体页面的创建对话框也可以直接用导出的快照包新建 Agent(**从快照初始化**):新 Agent 以包内的状态和版本起步,无需确认。
-## 全程可审计
+## 可审计性
-- 每次 Evaluator 运行都是一个普通的 Session,留有完整 Trace;
-- scoreboard 记录通过 `session_id` 链接回这些 Session,见 [Session 与 Trace](/sessions-and-traces);
-- Web 的评测页面是这些文件的只读视图;折线图只展示 Score,明细表将被测 Agent、模型 ID 与推理强度分列显示。见 [Web App 指南](/web-app)。
+- 每次 Evaluator 运行和每个被测会话,都是带完整 Trace 的普通 Session。
+- 记分板记录通过 `session_id` 关联到对应的被测会话,见 [Session 与 Trace](/sessions-and-traces)。
+- Web App 的评估页面是这些文件的只读视图。趋势图只显示分数;评估明细表把被测 Agent、模型 ID 和推理强度分列显示。见[评估中心](/evaluation-center)。
-分数不是黑盒输出:任何一个数字都可以回溯到产生它的那次运行。
+每一个分数都能追溯到产生它的那次运行。
## 相关 Skill
| Skill | 用途 |
| --- | --- |
-| `agent-initialization` | 把需求变成可用的 Agent:撰写其 `AGENTS.md`、安装所需 Skill |
-| `benchmark-design` | 设计并校准多 Case 的能力 Benchmark |
-| `agent-evaluation` | 隔离执行并评分一次 Benchmark Case 运行 |
-| `agent-optimization` | 根据 Benchmark 结果改进 Agent |
+| `agent-initialization` | 把需求变成可用的 Agent:编写它的 `AGENTS.md`,安装它需要的 Skill |
+| `benchmark-design` | 设计并校准包含多道题目的能力 Benchmark |
+| `agent-evaluation` | 隔离地运行一道 Benchmark 题目一次,并为这次运行打分 |
+| `agent-optimization` | 根据 Benchmark 的结果改进 Agent |
-Skill 的组织与安装方式见[技能系统](/skills)。
+Skill 如何组织和安装,见[技能与插件](/skills)。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index df3308bd..c2c045a3 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -1,17 +1,17 @@
---
title: Server API
-description: HTTP API reference — authentication, routes, the SSE streaming protocol, and DTO type imports.
+description: Reference for the PenguinHarness server's HTTP API, covering authentication, every route group, the SSE streaming protocol and DTO type imports.
---
-The PenguinHarness server exposes a same-origin HTTP API used by the bundled Web App and by any other HTTP client. This page is the reference: authentication, route tables, and the SSE streaming protocol. For starting the server, see the [Quickstart](/quickstart).
+The PenguinHarness server exposes a same-origin HTTP API that the bundled Web App and any other HTTP client use. This page covers authentication first, then the routes grouped by area, each with a route table followed by details, and ends with the SSE streaming protocol. To start the server, see the [Quickstart](/quickstart).
## Overview
-- Stack: Hono + @hono/node-server, requires Node >= 24;
-- Storage: SQLite (built-in `node:sqlite`, WAL mode) holds only indexes and aggregates — users, auth sessions, Project authorization, Agent / Session indexes, usage, UI preferences, error records, and Schedule state; all Agent, Trace, and Workspace data stays as files under `~/.penguin/data`, shared with the CLI / SDK — see the [Configuration Reference](/configuration);
-- Binding: defaults to `127.0.0.1:7364`, adjustable via the `PORT` / `HOST` environment variables;
-- Request bodies: writes accept JSON only (Content-Type check, one of the CSRF defenses), capped at a size **derived from the attachment budget** rather than fixed — attachments ride the request as base64 `data:` URLs (4/3 inflation), so the cap is `base64(attachmentTotalMb) + headroom for one inline image and the JSON framing`, about 190MB at the default 120MB total and falling again if an admin lowers it. It is counted as the body is read, so a request that declares no length (chunked) is capped just the same;
-- Errors share a single shape:
+- Stack: Hono and `@hono/node-server`; requires Node >= 24.
+- Storage: SQLite (the built-in `node:sqlite`, in WAL mode) holds only indexes and aggregates: users, auth sessions, Project authorization, agent and Session indexes, usage, UI preferences, error records and schedule state. All agent, Trace and Workspace data stays as files under `~/.penguin/data`, shared with the CLI and SDK; see the [Configuration Reference](/configuration).
+- Binding: `127.0.0.1:7364` by default, adjustable with the `PORT` / `HOST` environment variables.
+- Request bodies: writes accept JSON only; the Content-Type check is one of the CSRF defenses. The body size cap is derived from the attachment budget rather than fixed. Attachments travel in the request as base64 `data:` URLs, which inflate them by 4/3, so the cap is `base64(attachmentTotalMb)` plus headroom for one inline image and the JSON framing. That is about 190MB at the default 120MB total, and the cap drops again if an admin lowers the total. The server counts bytes as it reads the body, so a request that declares no length (chunked) is capped the same way.
+- Errors share one shape:
```text
{ "error": { "code": "<machine-readable code>", "message": "<user-facing text>" } }
@@ -21,22 +21,29 @@ The PenguinHarness server exposes a same-origin HTTP API used by the bundled Web
```text
packages/server/src
-├── index.ts / config.ts / app.ts # startup entry · env config · Hono assembly (the runtime app; the business routes are assembled by the http module under src/modules — no port bound — testable)
+├── index.ts / config.ts / app.ts # startup entry · env config · the HMR layer's app (network guards, /api/hmr, the platform seam, static hosting; binds no port, testable)
├── api/types.ts # the outward DTO contract (type-only import via the "./api" subpath)
├── auth/ # scrypt passwords, admin seeding, cookie sessions, auth middleware
├── db/ # node:sqlite connection, schema SQL, one repo per table
-├── http/ # error bodies, request validation, SSE adapter, routes/ all route groups
+├── hmr/ # hot update: the platform seam and the /api/hmr routes
+├── http/ # the business routes' assembly (app.ts), error bodies, request validation, SSE adapter, routes/
+├── machines/ # remote machines: ssh config, install and connect jobs, the /server/<machineId> proxy
+├── organization/ # company mode's files: chart, tickets, channels, handbook
├── runtime/ # session-manager (runtime driving) · channel (SSE ring buffer)
-│ # approvals · usage-recorder · scheduler · title-generator
-└── services/ # authorization rules, TOML/YAML config IO, Session/Trace/usage/snapshot services
+│ # approvals · usage-recorder · scheduler · title-generator · messaging/ · organization/
+├── services/ # authorization rules, TOML/YAML config IO, Session/Trace/usage/snapshot services
+└── terminal/ # terminals: /api/terminals and the byte-stream WebSocket
```
## Authentication
-- Cookie session: `penguin_session` (HttpOnly, SameSite=Lax), valid for 30 days with sliding renewal;
-- Passwords are stored as scrypt hashes. A session is a row in `auth_sessions` keyed by the sha256 of a random cookie token (the raw token is never stored); it survives a restart, renews in place, and logout deletes the row;
-- No open registration: the built-in admin `admin` is seeded at startup with a random password that is hashed and discarded unseen. Until a password is actually set, every start prints a first-login link that claims the account (`PENGUIN_SEED_ADMIN_PASSWORD` pins a known password instead, for automation). All other accounts are created by an admin;
-- Same-origin only — no CORS middleware is enabled.
+The API accepts two credentials: a cookie session and the local API token.
+
+- Cookie session: `penguin_session` (HttpOnly, SameSite=Lax), valid for 30 days with sliding renewal.
+- Passwords are stored as scrypt hashes. A session is a row in `auth_sessions`, keyed by the sha256 of a random cookie token; the raw token is never stored. A session survives a restart and renews in place, and logout deletes the row.
+- There is no open registration. At startup the server seeds the built-in admin `admin` with a random password, which it hashes and discards without anyone seeing it. Until a password is set, every start prints a first-login link that claims the account. For automation, `PENGUIN_SEED_ADMIN_PASSWORD` pins a known password instead. An admin creates all other accounts.
+- Same-origin only: no CORS middleware is enabled.
+- Routes marked admin only answer other users with `403` `admin_required`.
```bash
# Use the password you set when claiming the account from the first-login link.
@@ -47,348 +54,627 @@ curl -c cookies.txt -H "Content-Type: application/json" \
### 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:
+Every protected route also accepts `Authorization: Bearer <token>` with the **local API token**. The CLI, and agents that drive the harness through it, use this machine-local credential 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.
+- The server mints a fresh token at every boot and writes it to `<root>/api-token` with owner-only permissions (`0600`). The previous boot's token stops working as soon as the new one is minted.
+- A valid Bearer token authenticates as the built-in `admin`. This is the authorization model by design: local filesystem access to the data root already is admin authority, since whoever can read `api-token` can also read `web.db` next to it. `penguin server reset-admin-password` relies on the same rule.
+- 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` and `PENGUIN_SESSION_ID`. That is what authorizes an agent's own `penguin` and API calls to reach the server that runs them.
+- SSE endpoints accept the header like any other route. Consume them with `fetch`, not `EventSource`, which cannot send headers.
+- The JSON-only Content-Type check on writes applies to Bearer requests too.
```bash
curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
http://127.0.0.1:7364/api/me
```
-## Route Reference
+## Auth and Account
-### Auth and Account
+Sign-in, sign-out, account claiming, and the current user's password, profile and preferences.
| Method | Path | Description |
| --- | --- | --- |
-| POST | /api/auth/login | Log in: `{userId, password}` → `{user}` |
-| POST | /api/auth/logout | Log out, returns 204 |
-| GET | /api/auth/claim?token=… | Redeem a sign-in link (first-login, or the desktop shell's one-shot token): sets the cookie, redirects to `/`. An invalid or already-used link redirects to `/login?claimFailed=…` instead, where the Web App says how to get a working one |
-| GET | /api/install | Public: `{installId}` — an opaque id identifying the data root being served (`<root>/install-id`), minted the first time the root is used. The Web App compares it against the one it stored and clears the browser-side UI state that references server entities when it differs, so replacing the data root no longer leaves the old Workspace, drafts and pins in place. `null` means the server could not establish one; clients must then change nothing. |
-| GET | /api/me | Current user info |
-| PUT | /api/me/password | Change password: `{oldPassword, newPassword}`; a desktop or first-login session may omit `oldPassword` — its current password is random and was never shown |
-| PUT | /api/me/profile | Set the avatar and nickname: `{displayName?, avatar?}` → `{user}`. A patch — an absent field keeps its stored value, `null` clears it, and a body naming neither is a `400`. `displayName` must be 1–32 characters once trimmed (counted as characters, so a CJK name may be 32 of them) and carry no control characters; `avatar` must be a `data:image/(png|jpeg|webp);base64,…` URL of at most 131072 characters whose payload decodes. Open to every authenticated session, the desktop shell's token session included — unlike the password route above, a profile has no old credential to check |
-| GET | /api/me/prefs | Read UI preferences |
-| PUT | /api/me/prefs | Write UI preferences (shallow merge) |
-
-### User Administration (admin only)
+| POST | `/api/auth/login` | Logs in: `{userId, password}` → `{user}` |
+| POST | `/api/auth/logout` | Logs out; returns `204` |
+| GET | `/api/auth/claim?token=…` | Redeems a sign-in link: sets the cookie and redirects to `/` |
+| GET | `/api/install` | Public: `{installId}`, the id of the data root being served |
+| GET | `/api/me` | The current user's info |
+| PUT | `/api/me/password` | Changes the password: `{oldPassword, newPassword}` |
+| PUT | `/api/me/profile` | Sets the avatar and nickname: `{displayName?, avatar?}` → `{user}` |
+| GET | `/api/me/prefs` | Reads UI preferences |
+| PUT | `/api/me/prefs` | Writes UI preferences (shallow merge) |
+
+- `GET /api/auth/claim` redeems a first-login link or the desktop shell's one-shot token. An invalid or already-used link redirects to `/login?claimFailed=…` instead, where the Web App explains how to get a working one.
+- `GET /api/install` needs no authentication. `installId` is an opaque id stored in `<root>/install-id`, minted the first time the root is used. The Web App compares it with the id it stored and, when they differ, clears the browser-side UI state that refers to server entities, so replacing the data root no longer leaves the old Workspace, drafts and pins behind. `null` means the server could not establish an id, and clients must then change nothing.
+- `PUT /api/me/password`: a desktop or first-login session may omit `oldPassword`, because its current password is random and was never shown.
+- `PUT /api/me/profile` is a patch. An absent field keeps its stored value, `null` clears it, and a body that names neither field is a `400`.
+ - `displayName` must be 1–32 characters after trimming, counted as characters (so a CJK name may have 32), with no control characters.
+ - `avatar` must be a `data:image/(png|jpeg|webp);base64,…` URL of at most 131072 characters whose payload decodes.
+ - Every authenticated session may call it, including the desktop shell's token session. Unlike the password route, a profile has no old credential to check.
+
+## User Administration (admin only)
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/admin/users | List users. Each row carries the account's nickname when it has one; avatars are deliberately left out, since the list is unpaged and one data URL per account would dwarf the rest of the response |
-| POST | /api/admin/users | Create a user: `{userId, password}` |
-| POST | /api/admin/users/:userId/password | Reset a password (invalidates all of that user's login sessions) |
-| DELETE | /api/admin/users/:userId | Delete a user |
+| GET | `/api/admin/users` | Lists users |
+| POST | `/api/admin/users` | Creates a user: `{userId, password}` |
+| POST | `/api/admin/users/:userId/password` | Resets a password and invalidates all of that user's login sessions |
+| DELETE | `/api/admin/users/:userId` | Deletes a user |
+
+Each row of the user list carries the account's nickname when it has one. Avatars are deliberately left out: the list is not paged, and one data URL per account would dwarf the rest of the response.
+
+In desktop mode (a server spawned by the desktop app), every route in this group answers `403` with code `desktop_single_user`. The desktop app is single-user, so user management is disabled; users already in the data root are untouched.
-In desktop mode (the server spawned by the desktop app) the whole surface answers `403` with code `desktop_single_user`: the desktop app is single-user, so user management is disabled — existing users in the data root are untouched.
+## Server Settings (admin only)
-### Server Settings (admin only)
+Server-wide proxy, attachment and company-mode settings.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/admin/settings | Server-global settings: `{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb}}` |
-| PUT | /api/admin/settings | Update settings (fields optional; omitted fields keep their current value), returns the full updated settings |
-| GET | /api/admin/settings/proxy-probe | The reachability probe's targets: `{targets: [{provider, url}]}` (no request is made) |
-| POST | /api/admin/settings/proxy-probe/:provider | Probe one of those targets over the server's outbound path, no credential sent: `{probe: {provider, url, outcome, ms, status?}}`; `outcome` is `reachable` for any HTTP answer, else `timeout` / `dns` / `refused` / `tls` / `network`; 404 `probe_target_not_found` for an id outside the list |
+| GET | `/api/admin/settings` | Server-wide settings: `{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb, companyMode}}` |
+| PUT | `/api/admin/settings` | Updates settings; omitted fields keep their current value, and an invalid field rejects the whole PUT. Returns the full updated settings |
+| GET | `/api/admin/settings/proxy-probe` | The reachability probe's targets: `{targets: [{provider, url}]}`. Makes no request |
+| POST | `/api/admin/settings/proxy-probe/:provider` | Probes one target over the server's outbound path, sending no credential: `{probe: {provider, url, outcome, ms, status?}}` |
-The proxy settings are two independent switches sharing one optional explicit address; changes take effect for newly initiated connections/spawns immediately — no restart:
+A probe's `outcome` is `reachable` for any HTTP answer, and otherwise `timeout`, `dns`, `refused`, `tls` or `network`. A `:provider` that is not in the target list returns `404` `probe_target_not_found`.
-- `proxyForApp` ("application uses the proxy", default on) governs the server's own outbound traffic (LLM requests, the update check, image fetches): on with `proxyUrl` set → that address for both http and https, **taking precedence over the proxy environment variables** — no environment variable needs to be configured; on without an address → the environment variables HTTP_PROXY / HTTPS_PROXY / NO_PROXY (both spellings); off → always direct.
-- `proxyForAgent` ("agent environment uses the proxy", default on) governs agent command subprocess environments: on with `proxyUrl` set → `HTTP_PROXY` / `HTTPS_PROXY` (plus lowercase twins) are injected as that address together with the merged NO_PROXY, overriding inherited values (a `socks5://` address is injected verbatim — tools vary in accepting SOCKS URLs in these variables); on without an address → the host environment passes through unchanged; off → the proxy variables are stripped (NO_PROXY is kept).
-- `proxyUrl` (default null = follow the environment variables) is the shared explicit address. Validation on PUT: the value is trimmed; empty or null clears the address; accepted are the proxy URLs undici's dispatcher takes — `http://`, `https://` and (experimental in undici) `socks5://` / `socks://` addresses, credentials allowed — plus bare `host[:port]` (normalized to `http://host[:port]`); only normalized values are stored, and the response echoes the stored form. Anything else — unparseable, or a scheme undici refuses, such as `socks4://` — is `400` with code `invalid_proxy_url`, and the rejected PUT writes nothing.
+### Proxy settings
-The upload limits are two whole-MB integers governing composer file attachments; both apply to the next request with no restart (the validators and the body cap read them per request):
+The proxy settings are two independent switches that share one optional explicit address. Changes apply to newly opened connections and newly spawned processes right away, with no restart.
-- `attachmentMaxMb` (default 100) is the per-file cap — a larger file is `413` `file_too_large`.
-- `attachmentTotalMb` (default 120) is the per-message total of decoded bytes — `413` `payload_too_large` beyond it.
-- Validation on PUT: each must be an integer between 1 and 200, and the **effective** total (the value in this PUT, or the stored one when this PUT does not change it) must not be below the effective per-file cap. Anything else is `400` with code `invalid_attachment_limit`, and the rejected PUT writes nothing.
-- Not settable: the per-message file count (20) and the inline-image cap (20MB, `413` `image_too_large`). An inline image is written into the Trace and re-read on every history page and resume, so it deliberately does not follow the attachment cap up; `GET /api/me` reports all of these under `uploadLimits` so a client can pre-check a pick against the numbers actually in force.
+`proxyForApp` (the **Application uses the proxy** switch, on by default) governs the server's own outbound traffic: LLM requests, the update check and image fetches.
-In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::1` (loopback is never proxied).
+- On, with `proxyUrl` set: both http and https use that address, which takes precedence over the proxy environment variables. No environment variable needs to be configured.
+- On, without an address: the server follows the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables, in either spelling.
+- Off: always direct.
-### Machines (admin only)
+`proxyForAgent` (the **Agent environment uses the proxy** switch, on by default) governs the environment of agent command subprocesses.
-| Method | Path | Description |
-| --- | --- | --- |
-| GET | /api/projects/:projectId/machines | This machine and the host aliases of the SERVER's own `~/.ssh/config` with what THIS PROJECT has installed on each, the last status probed for each, the version this server would install, and the running or last job: `{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, status}], imageVersion, job}`. `elsewhere` is a host another Project installed — a machine to adopt rather than install |
-| POST | /api/projects/:projectId/machines/probe | Ask this Project's installed machines what they are doing (one ssh round trip each, five at a time) and answer the list with the fresh statuses |
-| POST | /api/projects/:projectId/machines/:machineId/install | Start installing this build on that host and give it to this Project; `202` with the same body, the job now running. Body `{replaceProgram: true}` answers a job that came back asking for it: install the program even though its version already matches, and restart it |
-| POST | /api/projects/:projectId/machines/:machineId/connect | Bring that machine's server up and HOLD the one connection to it — an `ssh -T -D` session that never idles out, is re-established on its own if it drops, and is restored after a restart or a hot push; `202` with the same body, the connect job now running. A Windows machine is `409` `connect_unsupported`: there is no shell to hold a session on |
-| POST | /api/projects/:projectId/machines/:machineId/disconnect | Drop the connection. The remote server is left running — it is that machine's own, and other people may be on it |
-| POST | /api/projects/:projectId/machines/:machineId/restart | Stop that machine's server and start it again on the same port; `202`, or `409` while a job runs. Its own control because a machine's FILES can be brought forward while it runs, and only a restart makes the process match them |
-| GET | /api/projects/:projectId/machines/:machineId/dirs?path= | The subdirectories of `path` on that machine, over the held connection — what the workspace picker browses. Addressed by the machine's OWN id, like the proxy. `404` when the machine is not connected: a read never opens ssh on its own |
-| POST | /api/projects/:projectId/machines/:machineId/release | Drop that machine from this Project; the install on it stays |
+- On, with `proxyUrl` set: `HTTP_PROXY` and `HTTPS_PROXY` (plus their lowercase twins) are injected with that address, together with the merged `NO_PROXY`, overriding inherited values. A `socks5://` address is injected as-is; tools differ in whether they accept SOCKS URLs in these variables.
+- On, without an address: the host environment passes through unchanged.
+- Off: the proxy variables are removed, and `NO_PROXY` is kept.
-Admin only on a personal server as much as a multi-user one: the install spawns ssh with the **server account's** keys and writes a program directory on another machine, which is an owner's capability rather than a visitor's. Nothing writes to the ssh config, and nothing resolves it: the list is the config's text (one file read, however many hosts it declares), and an alias is handed to ssh as written — what it means is ssh's to apply, from its own config, every time.
+`proxyUrl` is the shared explicit address. It defaults to `null`, which means following the environment variables. PUT validates it as follows:
-`imageVersion` is what would be pushed, or `null` when this server has no image at all (a development checkout that has never been hot-pushed to is the one such shape) — every install then refuses with `409` `no_install_image`. The version is the running install's own: a hot-pushed server sends the bundle it runs (`0.0.0-hmr.<cli>.<web>`), a tarball or packaged one sends its own tree, so the two ends match by construction.
+- The value is trimmed, and an empty value or `null` clears the address.
+- Accepted values are the proxy URLs undici's dispatcher takes (`http://`, `https://`, and the experimental `socks5://` / `socks://`, with credentials allowed), plus a bare `host[:port]`, which is normalized to `http://host[:port]`. Only the normalized value is stored, and the response echoes it.
+- Anything else, whether unparseable or a scheme undici refuses such as `socks4://`, returns `400` with code `invalid_proxy_url`, and the rejected PUT writes nothing.
-`installed` is the last install THIS server carried out on that machine — `{version, at}`, or `null` when it never has. It is persisted under the data root, so it survives a restart, a hot push, and installing on some other machine; a record of what was done rather than a survey of the far side, so a machine wiped by hand still reads as installed until the next install corrects it. A failed install records nothing.
+In every on-state, the effective `NO_PROXY` includes `localhost,127.0.0.1,::1`, so loopback traffic is never proxied.
-`machineId` is that machine's OWN id — 16 base64url characters minted by the server running there (its `machine` table), stable across renames, re-aliasing and reinstalls, and the thing stored references should point at. It is `null` until a server has started on that machine, since nothing has minted one yet; it is learned on the same round trip as `status` and remembered beside the install record. Two aliases for one host report the same `machineId`.
+### Attachment limits
-`local` marks the machine this server runs on. It is always listed, always installed, always running — it is the thing answering — and is never an install target: `POST …/install` on it is `409` `self_install`.
+Two whole-MB integers govern file attachments in the composer. Both apply from the next request with no restart, because the validators and the body cap read them on every request.
-`status` is `{state, checkedAt, port?, detail?}` with `state` one of `running` / `stopped` / `unreachable`, or `null` when that machine has not been probed. There is no separate ssh status: ssh is the transport, so a machine it cannot reach is `unreachable` and carries OpenSSH's own message in `detail`. `GET` never probes — it reports the last answer — because a probe is an ssh round trip per machine while the list itself is only the config's text. `POST /api/machines/probe` is what spends them, and only on machines something was installed on.
+- `attachmentMaxMb` (default 100) is the per-file cap. A larger file returns `413` `file_too_large`.
+- `attachmentTotalMb` (default 120) is the per-message total of decoded bytes. A larger total returns `413` `payload_too_large`.
-A connected machine's API is reachable at `/server/<machineId>/api/…` on THIS origin, dialled through the one ssh session this server holds to it — a channel inside that session, via its SOCKS port, never a second connection. Addressed by the machine's own id rather than the ssh alias it was reached through: an alias lives in one config file, so keying on it would change a machine's URLs the moment someone renamed a host — and being base64url, an id needs no percent-encoding in a path. **Admin only**, and one identity: the request is made over there as that machine's admin, with a session this server mints through its own ssh access (`penguin auth token` on the machine) — the browser's cookies never cross, and the machine's never come back. Only `/api` is forwarded — the frontend stays local.
+PUT validates them as follows:
-An install is a job, not a request: it probes the far side, may fetch and verify a Node runtime, and copies an image over scp — minutes in the bad case. `POST` starts it and returns at once; the client polls `GET` for `job.log`, which carries the far side's own words (ssh's diagnostics, the remote installer's output). A connect (`POST …/connect`) and a restart (`POST …/restart`) are jobs of the same shape, `job.kind` (`install` / `connect` / `restart`) telling them apart. `job.result` is `null` while running, then `{ok: true, installed: "installed" | "already-installed", version}` for an install, `{ok: true, connected: true}` for a connect or a restart, or `{ok: false, step, message, canReplaceProgram?}` — `canReplaceProgram` marks a failure whose next step is installing the program anyway (`POST …/install` with `{replaceProgram: true}`), offered rather than done because it restarts a server other people may be using. One job at a time; the job lives in memory and does not survive a hot push or a restart, and re-running is the recovery — every step is idempotent.
+- Each must be an integer from 1 to 200.
+- The effective total (the value in this PUT, or the stored one if this PUT does not change it) must not be below the effective per-file cap.
+- Anything else returns `400` with code `invalid_attachment_limit`, and the rejected PUT writes nothing.
-Refusals decided before any ssh runs have their own codes: `409` `install_running`, `404` `unknown_machine`, `409` `no_install_image`, and `409` `self_install` — this server will not push this build over the program directory it is running from. Besides the `local` row, that covers an alias pointing back home (`Host localhost`, a second name for this host) once a probe has heard this server's own id from it.
+Two limits cannot be changed: the number of files per message (20) and the inline-image cap (20MB, `413` `image_too_large`). An inline image is written into the Trace and read again on every history page and every resume, so it deliberately does not follow the attachment cap upward. `GET /api/me` reports all of these limits under `uploadLimits`, so a client can check a file against the limits actually in force before sending it.
-### Version and Self-Update
+### Company mode switch
-| Method | Path | Description |
-| --- | --- | --- |
-| GET | /api/version | Identity of the running build plus this root's pushed harness: `{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}` — the same record `penguin version --json` prints. `harness` describes the data root's HMR store (`{source, pushedAt, bundles}`, where `source` is the pushing checkout's `{repo, revision}`) and is null when nothing was ever pushed there. `describe` is the one-line identity (`v0.2.3` for a release, `v0.2.3-14-g9e8f7d6-dirty` for a build from a checkout); `channel` is `release` or `source`; `buildDate` (UTC yyyy-mm-dd) and `commit` are stamped at build time, so no network is needed, and are null in a source build or a release predating the stamping; `branch` and `dirty` carry a source build's git position and are null for a release |
-| GET | /api/version/update-check | Compares the newest GitHub release with the running version: `{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`; `?force=1` (the manual "check for updates" action) bypasses the TTL cache, and the outcome is cached as usual |
-| GET | /api/version/update | **Admin only.** The self-update job's status: `{state: idle \| running \| done, targetVersion, phase?, percent?, output, result?, startedAt?, finishedAt?}` — `phase` (`resolving` / `downloading` / `installing`) and `percent` (read off the installer's progress bar) while running; `result` (`{status, reason?, output, needsRestart}`) once done. Polled by the update dialog while a run is in flight |
-| POST | /api/version/update | **Admin only.** Starts the self-update job — `penguin update --yes` on the server host, in the background — unless one is running (then it is joined); answers with the status exactly as GET does. A finished run may be started again (a retry) |
-| POST | /api/version/restart | **Admin only.** Asks the process to exit with the supervisor's restart code after a graceful shutdown, so `penguin server \| penguin web` relaunches it on the installed release: `{restarting: true}`; `{restarting: false, reason: "no_supervisor"}` when nothing supervises the process |
+`companyMode` is the server's **Enable company mode** switch, off by default. A change applies without a restart: while the switch is off, every organization route returns `404` `company_mode_off` and the organization scheduler fires nothing.
-`update-check` is the server's only automatic outbound internet call and is strictly fail-soft: a failed lookup still returns 200 with `error` set (`network` / `rate_limited` / `bad_response`) and `latestVersion: null`, results are cached in memory (success 1 h, failure 10 min), and setting `PENGUIN_UPDATE_CHECK=off` disables the lookup entirely (`disabled: true`, no network call). Owner-initiated provider key authorization makes its own outbound requests. The update `status` is `updated` (restart the service to run the new version), `failed`, or `unsupported` — the latter both when the server was not started via `penguin server|web` (`reason: "not_launched_via_cli"`) and when the CLI refuses (source checkout, unrecognized install layout, Windows); `output` carries the tail of the CLI's own output.
+## Machines (admin only)
-### Projects and Members
+Installs this server's build on other hosts over ssh and manages the connections to them.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/projects | Projects visible to the current user |
-| POST | /api/projects | Create a Project |
-| DELETE | /api/projects/:projectId | Delete a Project |
-| POST | /api/projects/:projectId/suggest-id | A semantic id proposed for the display name of an object being created: `{name, kind, taken?}`, `kind` being `project`, `agent`, `benchmark`, `org` or `channel` and `taken` the ids the proposal must avoid → `{id, source, reason?}`. The default model of the Project in the path translates the name into one English id in the kind's spelling (`source: model`) — the New Project dialog borrows the Project it was opened from — and is asked a second time with the format spelled out when the first answer yields no id; an ASCII slug of the name answers when no model is configured or neither answer is usable (`source: fallback`); a name neither path can name gets a dated placeholder (`source: placeholder`) with a `reason` of `no_default_model`, `model_failed`, `unusable_answer` or `no_ascii`. The route never fails for a name it cannot translate — a dialog that asked for an id always gets one. Kinds differ only in the id's shape, the ids the server avoids on its own, and who may ask: `project` is snake_case for the admin and `<username>-<suffix>` for anyone else, avoiding every Project id on the server; `agent` is snake_case, avoiding the Project's Agents; `benchmark` is kebab-case, avoiding the Project's Benchmarks, owner only; `org` and `channel` carry a `co_` / `ch_` prefix, never doubled when the model's answer already has it, and answer 404 `company_mode_off` while company mode is off. Every other caller must be a member of the Project. The ids the server avoids on its own are every name the kind's create route refuses as taken — a leftover folder no list shows, such as a Benchmark directory with no config, included — and never reach the prompt, only a `_2` / `-2` suffix on a collision; an id the kind's rule rejects for starting with a digit or being one character long gets the kind's name in front (`agent_3d_viewer`); the placeholders are `project_<yyyymmdd>`, `agent_<yyyymmdd>`, `benchmark-<yyyymmdd>`, `co_org_<yyyymmdd>` and `ch_channel_<yyyymmdd>` (a non-admin's Project with the username in front). Every model dead end is recorded as an `id_suggest_failed` error, under the source `organization` for `org` / `channel` and `id_suggest` for the rest; the completion runs with thinking off and the shared meta budget, belongs to no Session and is not metered |
-| GET | /api/projects/:projectId/members | List members |
-| POST | /api/projects/:projectId/members | Add a member: `{userId}` |
-| DELETE | /api/projects/:projectId/members/:userId | Remove a member |
+| GET | `/api/projects/:projectId/machines` | This machine and the host aliases in the server's own `~/.ssh/config`, with this Project's installs, the last statuses and the current job: `{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, status}], imageVersion, job}` |
+| POST | `/api/projects/:projectId/machines/probe` | Asks this Project's installed machines what they are doing (one ssh round trip each, five at a time) and returns the list with fresh statuses |
+| POST | `/api/projects/:projectId/machines/:machineId/install` | Starts installing this build on that host and assigns the host to this Project; `202` with the same body while the job runs |
+| POST | `/api/projects/:projectId/machines/:machineId/connect` | Starts that machine's server and holds the one connection to it; `202` with the same body while the connect job runs |
+| POST | `/api/projects/:projectId/machines/:machineId/disconnect` | Drops the connection and leaves the remote server running |
+| POST | `/api/projects/:projectId/machines/:machineId/restart` | Stops that machine's server and starts it again on the same port; `202`, or `409` while a job runs |
+| GET | `/api/projects/:projectId/machines/:machineId/dirs?path=` | The subdirectories of `path` on that machine, read over the held connection; the Workspace picker browses these |
+| POST | `/api/projects/:projectId/machines/:machineId/release` | Removes that machine from this Project; the install on it stays |
+
+These routes are admin only on a personal server as much as on a multi-user one: an install runs ssh with the server account's keys and writes a program directory on another machine, which is an owner's capability rather than a visitor's. The server never writes to its ssh config and never resolves it. The list is the config's text, read once however many hosts it declares, and each alias goes to ssh exactly as written, so ssh applies its own config every time.
+
+- `POST …/install` accepts the body `{replaceProgram: true}` to answer a job that came back asking for it: the server installs the program even though its version already matches, and restarts it.
+- `POST …/connect` holds an `ssh -T -D` session that never times out when idle, reconnects on its own if it drops, and is restored after a restart or a hot push. A Windows machine returns `409` `connect_unsupported`, because there is no shell to hold a session on.
+- `POST …/disconnect` leaves the remote server running because it belongs to that machine, and other people may be using it.
+- `POST …/restart` exists as its own action because a machine's files can be updated while it runs, and only a restart makes the process match them.
+- `GET …/dirs` addresses the machine by its own id, like the API proxy below. It returns `404` when the machine is not connected, because a read never opens ssh by itself.
+
+### Machine fields
+
+- `elsewhere`: the host was installed by another Project, so it can be adopted instead of installed.
+- `imageVersion`: the version that would be pushed, or `null` when this server has no install image at all. A development checkout that was never hot-pushed to is the only such case, and every install then fails with `409` `no_install_image`. The version is the running install's own: a hot-pushed server sends the bundle it runs (`0.0.0-hmr.<cli>.<web>`), and a tarball or packaged install sends its own tree, so both ends match by construction.
+- `installed`: the last install this server carried out on that machine, as `{version, at}`, or `null` if there was none. It is stored under the data root, so it survives a restart, a hot push and installs on other machines. It records what was done rather than checking the far side, so a machine wiped by hand still shows as installed until the next install corrects it. A failed install records nothing.
+- `machineId`: the machine's own id, 16 base64url characters minted by the server running there (in its `machine` table). It stays the same across renames, alias changes and reinstalls, and stored references should point at it. It is `null` until a server has started on that machine, since nothing has minted it yet. The server learns it on the same round trip as `status` and stores it beside the install record. Two aliases for one host report the same `machineId`.
+- `local`: marks the machine this server runs on. It is always listed, always installed and always running, since it is the one answering, and it is never an install target: `POST …/install` on it returns `409` `self_install`.
+- `status`: `{state, checkedAt, port?, detail?}`, where `state` is `running`, `stopped` or `unreachable`; `null` when the machine has never been probed. There is no separate ssh status. Because ssh is the transport, a machine ssh cannot reach is `unreachable`, and `detail` carries OpenSSH's own message. `GET` never probes and reports the last answer, because a probe costs one ssh round trip per machine while the list itself is only the config's text. Only `POST …/machines/probe` spends those round trips, and only on machines that have an install.
+
+### Connected machine API
+
+A connected machine's API is reachable at `/server/<machineId>/api/…` on this server's origin. Requests travel through the single ssh session this server holds to that machine, as a channel inside the session through its SOCKS port, never as a second connection.
+
+The URL uses the machine's own id rather than the ssh alias it was reached through. An alias lives in one config file, so keying on it would change a machine's URLs as soon as someone renamed a host. The id is base64url, so it needs no percent-encoding in a path.
+
+This proxy is admin only and uses one identity: the request runs on the far side as that machine's admin, with a session this server mints through its own ssh access (`penguin auth token` on the machine). The browser's cookies never go across, and the machine's cookies never come back. Only `/api` is forwarded; the frontend stays local.
+
+### Jobs
+
+An install is a job, not a single request. It probes the far side, may download and verify a Node runtime, and copies an image over scp, which can take minutes. `POST` starts the job and returns at once. The client polls `GET` for `job.log`, which carries the far side's own output (ssh's diagnostics and the remote installer's output).
+
+A connect (`POST …/connect`) and a restart (`POST …/restart`) are jobs of the same shape, told apart by `job.kind` (`install`, `connect` or `restart`). `job.result` is `null` while the job runs, and then one of:
+
+- `{ok: true, installed: "installed" | "already-installed", version}` for an install
+- `{ok: true, connected: true}` for a connect or a restart
+- `{ok: false, step, message, canReplaceProgram?}` for a failure
-Member writes are owner-only. The member routes also answer `403 desktop_single_user` in desktop mode (see User Administration above).
+`canReplaceProgram` marks a failure whose next step is to install the program anyway, with `POST …/install` and `{replaceProgram: true}`. The server offers this step instead of taking it, because it restarts a server other people may be using.
-### Models
+Only one job runs at a time. Jobs live in memory and do not survive a hot push or a restart. To recover, run the job again: every step is idempotent.
+
+### Refusals
+
+These refusals are decided before any ssh command runs, and each has its own code:
+
+- `409` `install_running`
+- `404` `unknown_machine`
+- `409` `no_install_image`
+- `409` `self_install`: this server will not push its build over the program directory it runs from. Besides the `local` row, this also covers an alias that points back to this host (such as `Host localhost` or a second name for this host) once a probe has heard this server's own id from it.
+
+## Version and Self-Update
+
+Report the running build, check GitHub for a newer release, and run the self-update.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/projects/:projectId/models | List models (api_key masked); a row with a running promotion carries it as `discount` |
-| PUT | /api/projects/:projectId/models | Full-table replace, keyed by `(provider, modelId)`; an entry's `discount` stores or clears its promotion (see below) |
-| POST | /api/projects/:projectId/models/test | Connectivity test: `{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
-| POST | /api/projects/:projectId/models/detect | Protocol auto-detection for a custom base URL: probes `openai-responses` → `ant-messages` → `openai-chat` in order, first on the URL as typed (normalized, a pasted endpoint path stripped) and then on its neighbouring `/v1` form, reporting the first served protocol and the base URL that served it: `{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}` |
-| POST | /api/projects/:projectId/models/list | Endpoint model listing for the add-group import: the ids the endpoint serves on a detected protocol: `{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |
-| POST | /api/projects/:projectId/models/detect-vision | Vision capability probe: sends one 1x1 image on this model's credential (a real, billed completion): `{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported\|unsupported\|failed, message?}` |
+| GET | `/api/version` | The running build's identity and this root's pushed harness |
+| GET | `/api/version/update-check` | Compares the newest GitHub release with the running version |
+| GET | `/api/version/update` | Admin only. The self-update job's status |
+| POST | `/api/version/update` | Admin only. Starts the self-update job |
+| POST | `/api/version/restart` | Admin only. Restarts the process through its supervisor |
+
+### GET /api/version
+
+Returns the identity of the running build plus this root's pushed harness: `{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}`. It is the same record `penguin version --json` prints.
+
+- `describe` is the one-line identity: `v0.2.3` for a release, `v0.2.3-14-g9e8f7d6-dirty` for a build from a checkout.
+- `channel` is `release` or `source`.
+- `buildDate` (UTC yyyy-mm-dd) and `commit` are stamped at build time, so reading them needs no network. They are null in a source build and in a release that predates the stamping.
+- `branch` and `dirty` carry a source build's git position and are null for a release.
+- `harness` describes the data root's HMR store as `{source, pushedAt, bundles}`, where `source` is the pushing checkout's `{repo, revision}`. It is null when nothing was ever pushed to that root.
+
+### GET /api/version/update-check
+
+Compares the newest GitHub release with the running version: `{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`. `?force=1`, which the manual **Check for updates** action sends, bypasses the TTL cache, and the result is cached as usual.
+
+The lookup fails softly:
+
+- A failed lookup still returns 200, with `error` set (`network`, `rate_limited` or `bad_response`) and `latestVersion: null`.
+- Results are cached in memory: for 1 h after a success and 10 min after a failure.
+- `PENGUIN_UPDATE_CHECK=off` disables the lookup entirely: the response carries `disabled: true`, and no network call is made.
+
+That switch turns off this check and nothing else. Model requests, an enabled remote-control connection, owner-initiated provider key authorization and the proxy test go out whatever it is set to.
+
+### GET /api/version/update
+
+Admin only. Returns the self-update job's status: `{state: idle | running | done, targetVersion, phase?, percent?, output, result?, startedAt?, finishedAt?}`. The update dialog polls it while a run is in progress.
+
+- While the job runs, `phase` is `resolving`, `downloading` or `installing`, and `percent` is read from the installer's progress bar.
+- When the job is done, `result` is `{status, reason?, output, needsRestart}`.
+
+The `status` in `result` is one of:
+
+- `updated`: restart the service to run the new version.
+- `failed`.
+- `unsupported`: either the server was not started with `penguin server` or `penguin web` (`reason: "not_launched_via_cli"`), or the CLI refused to update (a source checkout, an unrecognized install layout, or Windows).
+
+`output` carries the last part of the CLI's own output.
-Every endpoint that names a model takes the complete `(provider, modelId)` pair. Nothing is inferred: a request carrying only one half is a 400, never a lookup. Where the reference itself is optional (Session creation, Schedules), omitting both halves selects the Project's default model.
+### POST /api/version/update
-A row's `pricing` is always the list price. A promotion — a fraction in (0, 1) off that price — is not written to `.project_config.toml`: the server keeps it per row in `web.db` and takes it off when it prices usage. On `PUT /models`, an entry that carries `discount` gets exactly that: a number stores it, `null` clears it, and any other value is a 400 before anything is written. An entry that omits it keeps the stored promotion, unless the entry renames the row (`renamedFrom` naming a different pair) or its `pricing` differs from the stored one — then the promotion is cleared. Rows absent from the new table lose theirs.
+Admin only. Starts the self-update job, which runs `penguin update --yes` on the server host in the background. If a job is already running, the request joins it. The response is the status, exactly as `GET /api/version/update` returns it. A finished job can be started again as a retry.
-`PUT /models` also invalidates the Project's cached Session runtimes (same effective-value semantics as a vault update): no hot swap into a run already in flight, but the next Task on any Session of the Project re-resumes and reads the new `api_key` / `base_url`. It additionally publishes a `credentials_updated` event to the Project's open Session channels (see Streaming below), and the models response carries `updatedAt` (the config file's mtime) — the Web App compares it against the last auth failure to decide whether an auth-dead composer should stay disabled.
+### POST /api/version/restart
-#### Penguin Go key authorization
+Admin only. Asks the process to exit with the supervisor's restart code after a graceful shutdown, so `penguin server` or `penguin web` relaunches it on the installed release. Returns `{restarting: true}`, or `{restarting: false, reason: "no_supervisor"}` when no supervisor runs the process.
-All routes are owner-only. The browser receives a local flow id and authorization URL, never the device secret, delivered API key, or other platform response fields. PenguinHarness validates the platform catalog server-side, writes the delivered key across existing `penguin-go` entries, and creates locally missing models from the platform metadata. Existing models refresh their platform list price and client protocol; endpoints and other Project-owned configuration are not overwritten, and models are never deleted. Once the Project model table is written, the platform's discounts replace the group's stored promotions in `web.db`; they are never persisted in `.project_config.toml`.
+## Projects and Members
+
+Projects, their members, and the Project-wide settings stored in `.project_config.toml`.
| Method | Path | Description |
| --- | --- | --- |
-| POST | /api/projects/:projectId/platform-auth/start | Start a one-time authorization flow; its platform deadline is capped locally at ten minutes |
-| POST | /api/projects/:projectId/platform-auth/sync | Fetch the platform catalog with the stored key, add locally missing models, and refresh existing platform-owned metadata; returns `added` / `updated` counts, or `platform_reauthorization_required` when that key is invalid |
-| GET | /api/projects/:projectId/platform-auth/:flowId/status | Poll Penguin Go server-side, write the delivered key to the group, and add platform models |
-| POST | /api/projects/:projectId/platform-auth/:flowId/retry | Retry only the local atomic write after an apply failure; does not request the single-use delivery again |
-| POST | /api/projects/:projectId/platform-auth/:flowId/cancel | Cancel the local flow; the platform-side pending record expires by its TTL |
+| GET | `/api/projects` | The Projects visible to the current user |
+| POST | `/api/projects` | Creates a Project: `{projectId, name?}` → 201 `{project}` |
+| PATCH | `/api/projects/:projectId` | Renames a Project: `{name}` → `{project}` |
+| DELETE | `/api/projects/:projectId` | Deletes a Project |
+| GET | `/api/projects/:projectId/members` | Lists members |
+| POST | `/api/projects/:projectId/members` | Adds a member: `{userId}` |
+| DELETE | `/api/projects/:projectId/members/:userId` | Removes a member |
+| GET / PUT | `/api/projects/:projectId/chat-defaults` | Reads / replaces the defaults a new chat starts with |
+| GET / PUT | `/api/projects/:projectId/command-policy` | Reads / replaces the sandbox command policy |
+| POST | `/api/projects/:projectId/suggest-id` | Proposes a semantic id for the display name of an object being created |
+
+- `PATCH /api/projects/:projectId` is owner only and changes only the display name (1–100 characters). The Project id names its directory and never changes.
+- `DELETE /api/projects/:projectId` is owner only. `default_project` is shared with the CLI and cannot be deleted: `409` `cannot_delete_default_project`.
+- Member writes are owner only. In desktop mode the member routes also answer `403 desktop_single_user`; see [User Administration (admin only)](#user-administration-admin-only).
+- `chat-defaults` is the `[default_chat]` block: `{agentId?, workspace?, approvalMode?, thinkingLevel?}`. Any member can read it, and only the owner can replace it. A PUT replaces the whole block: an omitted key clears that default, and an empty body removes the block. `agentId` must name an existing agent of the Project (otherwise `400` `unknown_agent`). `workspace` is a prefill and is not checked until a Session is created; an empty value means a temporary Workspace. `thinkingLevel` is the fallback for agents whose config sets none, and `none` is not accepted. The default model is not part of this block; it stays with the model routes.
+- `command-policy` is the `[command_policy]` block: `{enabled?, rules: [{name, pattern, description?, enabled?}]}`. Any member can read it, and only the owner can replace it. A PUT always carries the full rule list (an empty array means no rules), with at most 64 rules. Each rule needs a name of up to 64 characters and a pattern of up to 512 characters that compiles as a regular expression, and a description may have up to 300 characters. A pattern that does not compile returns `400` `invalid_rule_pattern`, any other malformed rule returns `400` `invalid_rules`, and a non-boolean `enabled` returns `400` `invalid_enabled`. See [Command policy](/configuration#command-policy).
+
+### Semantic id proposals
+
+`POST /api/projects/:projectId/suggest-id` takes `{name, kind, taken?}` and returns `{id, source, reason?}`. `kind` is `project`, `agent`, `benchmark`, `org` or `channel`, and `taken` names the ids the proposal must avoid. It is the one route behind every **Generate with AI** button beside an id field.
+
+- The default model of the Project in the path translates the name into one English id in the kind's spelling (`source: model`); the **New Project** dialog borrows the Project it was opened from. An answer that yields no id has the model asked once more, with the format spelled out.
+- An ASCII slug of the name answers when no model is configured or neither answer is usable (`source: fallback`).
+- A name neither path can name gets a dated placeholder (`source: placeholder`) with a `reason` of `no_default_model`, `model_failed`, `unusable_answer` or `no_ascii`: `project_<yyyymmdd>`, `agent_<yyyymmdd>`, `benchmark-<yyyymmdd>`, `co_org_<yyyymmdd>` or `ch_channel_<yyyymmdd>`, with the username in front for a non-admin's Project.
+- The kinds differ only in the id's shape, the ids the server avoids on its own, and who may ask. `project` is snake_case for an admin and `<username>-<suffix>` for everyone else, and avoids every Project id on the server; `agent` is snake_case and avoids the Project's agents; `benchmark` is kebab-case, avoids the Project's Benchmarks and is owner only; `org` and `channel` carry the `co_` and `ch_` prefix, never doubled when the answer already has it, and return `404` `company_mode_off` while company mode is off. Every other caller must be a member of the Project.
+- The ids the server avoids on its own are the names the kind's create route would refuse as taken, a leftover folder no list shows included. They never reach the prompt; a collision only adds a `_2` / `-2` suffix. A core the kind's rule rejects for starting with a digit or being one character long is retried behind the kind's noun (`3D Viewer` → `agent_3d_viewer`).
+- The route never fails for a name it cannot translate, so a dialog that asked for an id always gets one. Every model dead end is recorded as an `id_suggest_failed` error, under the source `organization` for `org` and `channel` and `id_suggest` for the rest. The completion runs with thinking off and within the shared meta budget, belongs to no Session and is not metered.
+
+## Models
+
+Manage a Project's model table and probe model endpoints. Reading the table is open to any member; every other route here is owner only.
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | `/api/projects/:projectId/models` | Lists models (`api_key` masked); a row with a running promotion carries it as `discount` |
+| PUT | `/api/projects/:projectId/models` | Replaces the whole table, keyed by `(provider, modelId)`; an entry's `discount` stores or clears its promotion |
+| PUT | `/api/projects/:projectId/models/default` | Sets the default model: `{provider, modelId}` → `{defaultModel}` |
+| POST | `/api/projects/:projectId/models/test` | Tests connectivity: `{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
+| POST | `/api/projects/:projectId/models/detect` | Detects the protocol a custom base URL speaks |
+| POST | `/api/projects/:projectId/models/list` | Lists the model ids an endpoint serves, for the add-group import |
+| POST | `/api/projects/:projectId/models/detect-vision` | Probes whether a model accepts images |
+
+Every route that names a model takes the complete `(provider, modelId)` pair. Nothing is inferred: a request that carries only half the pair is a 400, never a lookup. Where the model reference itself is optional (Session creation, schedules), omitting both halves selects the Project's default model.
-A completed write invalidates cached Project runtimes and publishes `credentials_updated`. A non-empty platform catalog can create the group when it is absent; `apply_failed` means the validated delivery could not be applied to local configuration, and its retry route repeats only that local write.
+A row's `pricing` is always the list price. A promotion, a fraction above 0 and below 1 taken off that price, is never written to `.project_config.toml`: the server keeps it per row in `web.db` and applies it when it prices usage. On `PUT /models`, an entry's `discount` decides it outright — a number stores the promotion, `null` clears it, and any other value is a `400` before anything is written. An entry that omits `discount` keeps the stored promotion, unless it renames the row (`renamedFrom` naming another pair) or its `pricing` differs from the stored one, in which case the promotion is cleared. A row left out of the new table takes its promotion with it.
-#### Provider key minting
+- `PUT /models` also invalidates the Project's cached Session runtimes, with the same effective-value semantics as a vault update. A run already in progress is not switched over, but the next Task on any Session of the Project reloads its runtime and reads the new `api_key` / `base_url`. The route also publishes a `credentials_updated` event to the Project's open Session channels (see [Streaming (SSE)](#streaming-sse)). The models response carries `updatedAt`, the config file's modification time, which the Web App compares with the last auth failure to decide whether a composer disabled by that failure stays disabled.
+- `PUT /models/default` changes only the default model, without resending the table or its credentials. The pair must name a configured entry, otherwise the route returns 400. Existing Sessions keep the model they were created with, so the route neither invalidates runtimes nor publishes `credentials_updated`.
+- `POST /models/detect` probes `openai-responses`, then `ant-messages`, then `openai-chat`. It tries the URL as typed first (normalized, with any pasted endpoint path stripped), then the same URL with `/v1` added or removed, and reports the first protocol served and the base URL that served it: `{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}`.
+- `POST /models/list` returns the ids the endpoint serves on a detected protocol: `{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}`.
+- `POST /models/detect-vision` sends one 1x1 image with this model's credential, which is a real, billed completion: `{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported|unsupported|failed, message?}`.
-Owner-only, except the redirect receiver `GET /callback`, which answers without a session and can do nothing but hand the code it was redirected with to the flow — see below. A provider group that publishes an authorization flow in the built-in catalog can mint a **new** API key for the user in the browser, instead of the user copying one out of a console.
+### Provider key minting
+
+A provider group that publishes an authorization flow in the built-in catalog can mint a new API key for the user in the browser, so the user does not have to copy one out of a console. These routes are owner only, except the redirect receiver `GET /callback`, which answers without a session and can only hand the code it was redirected with to the flow (see below).
| Method | Path | Description |
| --- | --- | --- |
-| POST | /api/projects/:projectId/model-oauth/start | Open a flow: `{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |
-| GET | /api/projects/:projectId/model-oauth/callback | Where the provider redirects (`?flow=&code=`); deposits the code on the flow and answers an HTML page. `HEAD` answers 405 |
-| GET | /api/projects/:projectId/model-oauth/:flowId | Poll a flow, redeeming a deposited code and applying the key: `{status: pending\|done\|error, provider, error?}` |
-| POST | /api/projects/:projectId/model-oauth/:flowId/code | Redeem a code the user pasted: `{code}` → `{ok, applied?, error?}` |
+| POST | `/api/projects/:projectId/model-oauth/start` | Opens a flow: `{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |
+| GET | `/api/projects/:projectId/model-oauth/callback` | Where the provider redirects (`?flow=&code=`): stores the code on the flow and answers with an HTML page. `HEAD` answers 405 |
+| GET | `/api/projects/:projectId/model-oauth/:flowId` | Polls a flow, redeeming a stored code and applying the key: `{status: pending\|done\|error, provider, error?}` |
+| POST | `/api/projects/:projectId/model-oauth/:flowId/code` | Redeems a code the user pasted: `{code}` → `{ok, applied?, error?}` |
+
+The server generates the PKCE verifier, keeps it in memory for ten minutes and never sends it to a client. The minted key goes straight into the provider group's models and is never returned, logged or put in a URL. A flow belongs to one user in one Project and can be used once: a second redemption is refused, and `/start`, `/:flowId` and `/:flowId/code` refuse anyone except that user.
+
+`GET /callback` has to be the exception. A loopback OAuth redirect arrives in whichever browser the provider redirected, which is not necessarily the one that started the flow. The desktop shell, for example, opens the authorization page in the *system* browser, which holds no cookie for the app's origin. So this one path is mounted outside the session gate and authorizes with the flow id instead: 32 random bytes, valid for ten minutes and usable for one deposit. A deposit is accepted only for the Project the flow was opened in, and only for a flow that asked for a callback: a `manual` flow is refused, because it was never given a callback URL.
-The PKCE verifier is generated server-side, held in memory for ten minutes, and never sent to a client; the minted key goes straight into the provider group's models and is never returned, logged, or put in a URL. A flow belongs to one user in one Project and is single-use: a second redemption is refused, and `/start`, `/:flowId` and `/:flowId/code` refuse anyone but that owner.
+What the callback may do is limited a second time: it stores the code on the flow and nothing else. The exchange with the provider and the write into the Project's models both happen on `GET /:flowId`, the owner's own poll, behind the session gate. No key reaches a Project unless its owner asks for the flow's status, and a failed exchange is reported there as `{status: error, error}` rather than on the redirect page. Nothing next to the callback is exempt either: a longer path, any other method (`HEAD` on the exact path answers 405), and the three sibling routes all still require a session.
-`GET /callback` is the exception, and has to be. A loopback OAuth redirect is delivered by whichever browser the provider redirected, which is not necessarily the one that started the flow — the desktop shell opens the authorization page in the *system* browser, which holds no cookie for the app's origin. So that one path is mounted outside the session gate and authorizes on the flow id instead: 32 random bytes, valid for ten minutes, depositable once, and only against the Project the flow was opened in, and only for a flow that asked for a callback at all (a `manual` flow is refused, since it was handed no callback URL).
+`mode: manual` sends no callback URL, so the authorization page shows a one-time code for the user to paste back, for deployments the redirect cannot reach. Whichever route redeems the code, a completed flow invalidates cached runtimes and publishes `credentials_updated`, exactly as `PUT /models` does.
-What that route may do is bounded a second time: it stores the code on the flow and nothing else. The exchange with the provider and the write into the Project's models both run on `GET /:flowId`, the owner's own poll, behind the session gate — so no key reaches a Project without its owner asking for its flow's status, and a failed exchange is reported there as `{status: error, error}` rather than on the redirect page. Nothing adjacent is exempt either: a longer path, any other method (`HEAD` on the literal path answers 405), and the three sibling routes all still require the session.
+### Penguin Go key authorization
-`mode: manual` omits the callback so the authorization page shows a one-time code to carry back by hand, for deployments the redirect cannot reach. Whichever route redeems the code, a completed flow invalidates cached runtimes and publishes `credentials_updated`, exactly as `PUT /models` does.
-### Plugin Registry
+Penguin Go delivers its key through a device authorization the server polls, not through a redirect, so it has routes of its own. All of them are owner only. The browser is handed a local flow id and an authorization URL, and never the device secret, the delivered key or anything else the platform returns.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/plugins/registry | Plugin index for the Plugins page: `{plugins: PluginIndexEntry[]}` — the merged index of every configured registry (currently the builtin one) |
-| GET | /api/plugins/registry/readme?name=… | One listed entry's readme: `{name, readme}` (`readme` null when the registry has none); 404 for a name the index does not list |
-| GET | /api/projects/:projectId/plugins/installed | What this Project asks for, joined with what the process runs: `{plugins: [{specifier, active, builtin, modules, replaces, error?}], shipped, file, restartPending}` (any member) |
-| POST | /api/projects/:projectId/plugins/installed | `{specifier}` — ask this Project for a plugin the build ships (400 `plugin_not_shipped` otherwise), applied without a restart — the App re-assembles itself, which stops the agent runs in progress in every Project; a change whose boot fails is undone (admin) |
-| PUT | /api/projects/:projectId/plugins/installed | `{plugins}` — rewrite this Project's list and apply; a name new to the list must be a shipped package's (admin) |
-| DELETE | /api/projects/:projectId/plugins/installed?specifier=… | Drop it from this Project's list and apply; nothing on disk changes (admin) |
+| POST | `/api/projects/:projectId/platform-auth/start` | Opens a one-time flow, with the platform's deadline capped locally at ten minutes: → 201 `{flowId, authorizeUrl, expiresAt}` |
+| POST | `/api/projects/:projectId/platform-auth/sync` | Fetches the platform catalog with the stored key, adds the models the Project lacks and refreshes platform-owned fields: → the model table plus `added` and `updated` counts |
+| GET | `/api/projects/:projectId/platform-auth/:flowId/status` | Polls Penguin Go from the server, then writes the delivered key across the group and adds the platform's models: `{status: pending\|applying\|completed\|cancelled\|apply_failed\|error, error?, applied?}` |
+| POST | `/api/projects/:projectId/platform-auth/:flowId/retry` | Retries the local write after it failed; the single-use delivery is not requested again, and a flow in any other state answers `409 platform_auth_not_retryable` |
+| POST | `/api/projects/:projectId/platform-auth/:flowId/cancel` | Cancels the local flow; the platform's pending record expires on its own TTL |
-The index format follows typst/packages' `index.json` schema: a flat array of per-version entries (`name`, `version`, `description`, `authors`, `license`, plus optional `repository` / `homepage` / `keywords` / `categories` / `updatedAt`). The registry is discovery only and never imports plugin code; a Project asks for an entry through the routes above, and its list lives in its own `.project_config.toml` as the `[plugins]` table — package name → requirement, in the shape of Cargo's `[dependencies]` (`"@scope/name" = "*"`, a version string, or `{ version = "…" }`). The process runs the union over every Project's table.
+The server validates the delivered key, the endpoints and the catalog before it writes anything. It then writes the key to every existing `penguin-go` entry, creates the models the platform advertises and the Project does not have, refreshes the list price and client protocol of the ones it does, and replaces the group's stored promotions with the platform's. Endpoints and other Project-owned fields are preserved, nothing is deleted, and a non-empty catalog creates the group when it is missing. A completed write invalidates cached runtimes and publishes `credentials_updated`, exactly as `PUT /models` does.
-### Agents
+A flow id that names no live flow is `404 platform_auth_flow_not_found`. `sync` answers `409 platform_reauthorization_required` when there is no stored key or the platform rejects it, and `502 platform_sync_failed` when the platform refuses the catalog or returns one that does not parse; the platform being unreachable is `502 platform_unreachable`. A delivery the server could not write locally leaves the flow in `apply_failed`, which is what the retry route is for.
-The paths below omit the `/api/projects/:projectId` prefix.
+## Agents
+
+The paths below omit the `/api/projects/:projectId` prefix, except the two global `/api/plugins` routes.
| Method | Path | Description |
| --- | --- | --- |
-| GET / POST | /agents | List / create Agents |
-| DELETE | /agents/:agentId | Delete an Agent |
-| GET / PUT | /agents/:agentId/config | Read / write config (AGENTS.md + system_config.yaml; PUT preserves YAML comments) |
-| GET / PUT | /agents/:agentId/vault | Vault environment variables (values masked; PUT is a full replace) |
-| GET | /agents/:agentId/memory | Memory overview: the switch, whether the template carries `{{MEMORY}}`, and one entry per scope — the user scope (`user`, `kind: "user"`) first, then the Workspaces |
-| POST | /agents/:agentId/memory/template-placeholder | Insert the `{{MEMORY}}` placeholder into the prompt template (idempotent; the explicit adoption path for an Agent created before Memory) |
-| GET | /agents/:agentId/memory/scopes/:key/files | List one scope's topic files (frontmatter + stats); `:key` is a workspace key or `user` |
-| GET / DELETE | /agents/:agentId/memory/scopes/:key/files/:name | Read one topic file / delete it (also pruning its `MEMORY.md` index lines) |
-| GET | /agents/:agentId/memory/scopes/:key/export | One scope as a single JSON document: every topic file plus its `MEMORY.md`, downloaded as an attachment |
-| POST | /agents/:agentId/memory/scopes/:key/import | Write such a document back (owner only): `{payload, mode?, confirm?}`. `mode` is `skip` (the default — adds only names the scope lacks), `overwrite` (replaces same-named files) or `replace` (also deletes what the document omits); anything that would overwrite or delete needs `confirm`, else 409 `memory_import_confirm_required` |
-| GET | /agents/:agentId/export | Export the Agent State snapshot (tar.gz download) |
-| POST | /agents/:agentId/import | Import a snapshot: `{dataBase64, confirm?}`; 409 on version conflict without confirm |
-| GET | /agents/:agentId/skills | Installed Skills (library installs go through `/plugins`) |
-| DELETE | /agents/:agentId/skills/:name | Uninstall a Skill |
-| POST | /agents/:agentId/plugins | Install library plugins by name — each one's skills and hook package; reinstalling updates. `{ names }` → 201 `{ skills, hooks }`; 404 `unknown_plugin` writes nothing |
-| GET | /agents/:agentId/hooks | Installed hook packages: name, description, version, hook points, the plugin's icon |
-| POST | /agents/:agentId/hooks/archive | Install a hook package from a zip: `{dataBase64, overwrite?}` — hooks.json and its scripts at the root or in one top-level directory, every listed command naming a file inside; 409 `hook_exists` without overwrite |
-| GET | /agents/:agentId/hooks/:name/archive | Export an installed hook package as a zip (round-trips through the POST) |
-| GET | `/api/plugins` (global) | The plugin library by category — every plugin with its skills' metadata and hook points (any logged-in user) |
-| GET | `/api/plugins/:plugin/files` (global) | Everything one library plugin ships as text keyed by path — each skill's installable SKILL.md and reference files under `skills/<name>/`, the hook scripts under `hooks/` — for the plugin detail view's file browser (any logged-in user) |
-| DELETE | /agents/:agentId/hooks/:name | Uninstall a hook package |
-
-### Schedules
+| GET / POST | `/agents` | Lists agents / creates one |
+| DELETE | `/agents/:agentId` | Deletes an agent (owner only) |
+| GET / PUT | `/agents/:agentId/config` | Reads / writes the config (`AGENTS.md` and `system_config.yaml`; PUT preserves YAML comments) |
+| POST | `/agents/:agentId/config/mcp-test` | Tests one MCP server entry: `{name, config}` → `{ok, tools?, error?, latencyMs?}` |
+| POST | `/agents/:agentId/config/kernel-update` | Merges the config up to the current defaults: → `{advanced, kept, kernelVersion}` |
+| POST | `/agents/:agentId/config/reset` | Overwrites `system_config.yaml` with the current defaults and returns the fresh config |
+| GET / PUT | `/agents/:agentId/vault` | Vault environment variables (values masked; PUT replaces all of them and is owner only) |
+| POST | `/agents/:agentId/vault/template-placeholder` | Inserts the `{{VAULT}}` placeholder into the prompt template (owner only) |
+| GET | `/agents/:agentId/memory` | Memory overview |
+| POST | `/agents/:agentId/memory/template-placeholder` | Inserts the `{{MEMORY}}` placeholder into the prompt template |
+| GET | `/agents/:agentId/memory/scopes/:key/files` | Lists one scope's topic files |
+| GET / DELETE | `/agents/:agentId/memory/scopes/:key/files/:name` | Reads one topic file / deletes it |
+| GET | `/agents/:agentId/memory/scopes/:key/export` | Exports one scope as a single JSON document |
+| POST | `/agents/:agentId/memory/scopes/:key/import` | Writes an exported scope back (owner only) |
+| GET | `/agents/:agentId/export` | Exports the Agent State snapshot (tar.gz download) |
+| POST | `/agents/:agentId/import` | Imports a snapshot: `{dataBase64, confirm?}`; 409 on a version conflict without `confirm` |
+| GET | `/agents/:agentId/skills` | Installed Skills (library installs go through `/plugins`) |
+| POST | `/agents/:agentId/skills/template-placeholder` | Inserts the `{{SKILLS}}` placeholder into the prompt template |
+| POST | `/agents/:agentId/skills/archive` | Installs a Skill from a zip: `{dataBase64, overwrite?}` → 201 with the Skill list |
+| GET | `/agents/:agentId/skills/:name/archive` | Exports an installed Skill as a zip |
+| DELETE | `/agents/:agentId/skills/:name` | Uninstalls a Skill |
+| POST | `/agents/:agentId/plugins` | Installs library plugins by name: `{names}` → 201 `{skills, hooks}` |
+| GET | `/agents/:agentId/hooks` | Installed hook packages |
+| POST | `/agents/:agentId/hooks/archive` | Installs a hook package from a zip: `{dataBase64, overwrite?}` |
+| GET | `/agents/:agentId/hooks/:name/archive` | Exports an installed hook package as a zip |
+| DELETE | `/agents/:agentId/hooks/:name` | Uninstalls a hook package |
+| GET | `/api/plugins` (global) | The plugin library by category (any signed-in user) |
+| GET | `/api/plugins/:plugin/files` (global) | The files one library plugin ships, as text keyed by path (any signed-in user) |
+
+### Agent routes
+
+- `POST /agents` takes `{agentId, name?, description?, plugins?, skillsDirectory?, directorySkills?, dataBase64?}` and answers 201 `{agent}`. `plugins` names library plugins to preinstall, and unknown names are rejected before the agent's directory exists. `skillsDirectory` and `directorySkills` import Skills from a directory the user picked (see `GET /dir-skills` under [Session Creation and Directory Browsing](#session-creation-and-directory-browsing)) and must be sent together. `dataBase64` starts the agent from an exported snapshot instead of the default template.
+- `POST …/config/mcp-test` connects to one MCP server entry from this host, lists its tools and disconnects, and writes nothing to the Agent State. A malformed entry returns 400. An unreachable server is a normal `{ok: false, error}` result.
+- `POST …/config/kernel-update` is the non-destructive sibling of `reset`. It moves settings tabs that are absent or still hold an old default up to the current defaults (`advanced`), keeps customized tabs whole (`kept`), and writes the new defaults generation (`kernelVersion`).
+- The `template-placeholder` routes are idempotent. The vault and Skills routes insert `{{VAULT}}` or `{{SKILLS}}` into the prompt template, or turn a legacy hard-coded `# Vault` or `# Skills` section into the placeholder. The Memory route inserts `{{MEMORY}}` and is how an agent created before Memory adopts it.
+- `POST …/skills/archive` accepts a zip of up to 14MB. Without `overwrite`, a Skill that is already installed returns 409 `skill_exists`. `GET …/skills/:name/archive` names the file `<name>.zip`, or `<name>-v<version>.zip` when the Skill's `SKILL.md` declares a version. The export and uninstall routes return 404 `not_found` for a Skill that is not installed.
+
+### Memory
+
+- `GET …/memory` returns the Memory switch, whether the prompt template carries `{{MEMORY}}`, and one entry per scope: the user scope (`user`, `kind: "user"`) first, then the Workspaces.
+- In the scope routes, `:key` is a workspace key or `user`.
+- `GET …/scopes/:key/files` lists one scope's topic files with their frontmatter and file stats.
+- `DELETE …/scopes/:key/files/:name` deletes a topic file and removes its lines from the `MEMORY.md` index.
+- `GET …/scopes/:key/export` returns every topic file of the scope plus its `MEMORY.md` as one JSON document, downloaded as an attachment.
+- `POST …/scopes/:key/import` takes `{payload, mode?, confirm?}`. `mode` is `skip` (the default, which adds only names the scope lacks), `overwrite` (which replaces same-named files) or `replace` (which also deletes what the document omits). Anything that would overwrite or delete needs `confirm`, otherwise the route returns 409 `memory_import_confirm_required`.
+
+### Plugins and hooks
+
+- `POST …/plugins` installs each named plugin's Skills and hook package, and reinstalling updates them. An unknown name returns 404 `unknown_plugin`, and nothing is written.
+- `GET …/hooks` returns each installed hook package's name, description, version, hook points and plugin icon.
+- `POST …/hooks/archive` expects `hooks.json` and its scripts at the root of the zip or inside one top-level directory, and every listed command must name a file inside the package. Without `overwrite`, an installed package of the same name returns 409 `hook_exists`. The zip that `GET …/hooks/:name/archive` exports can be installed again through this route.
+- `GET /api/plugins` returns every library plugin by category, with its Skills' metadata and hook points.
+- `GET /api/plugins/:plugin/files` returns everything one library plugin ships, as text keyed by path: each Skill's installable `SKILL.md` and reference files under `skills/<name>/`, and the hook scripts under `hooks/`. The plugin detail view's file browser uses it.
+
+## Plugin Registry and Project Plugins
+
+The plugins in this section are server-side packages: modules the server loads into its own module tree, such as the sandbox backends. They are not the library plugins installed on an agent, which are covered under [Plugins and hooks](#plugins-and-hooks). The registry routes are global and open to any signed-in user; the installed-plugin routes belong to one Project.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /schedules | Every agent's scheduled tasks in the Project in one list, each stamped with its `agentId` (any member) |
-| GET / POST | /agents/:agentId/schedules | List scheduled tasks / create one (409 if the name exists) |
-| GET / PUT / DELETE | /agents/:agentId/schedules/:name | Read / update / delete a single task |
+| GET | `/api/plugins/registry` | The plugin index: `{plugins: PluginIndexEntry[]}` |
+| GET | `/api/plugins/registry/readme?name=…` | One listed entry's readme: `{name, readme}` |
+| GET | `/api/projects/:projectId/plugins/installed` | The plugins this Project asks for, joined with what the process runs: `{plugins, shipped, file, restartPending}` |
+| POST | `/api/projects/:projectId/plugins/installed` | Admin only. Adds a plugin the build ships: `{specifier}` |
+| PUT | `/api/projects/:projectId/plugins/installed` | Admin only. Replaces the list: `{plugins}` |
+| DELETE | `/api/projects/:projectId/plugins/installed?specifier=…` | Admin only. Removes a plugin from the list |
+
+- The index follows the schema of typst/packages' `index.json`: a flat array of per-version entries with `name`, `version`, `description`, `authors` and `license`, plus optional `repository`, `homepage`, `keywords`, `categories` and `updatedAt`. An entry's `name` is the package name a Project's list uses. The index currently comes from a single registry built into the server, which lists the four sandbox backends. A registry is for discovery only and never imports plugin code.
+- `GET …/readme` returns the package's own `README.md`, read from the copy on this machine; `readme` is `null` when there is none. A name the index does not list returns `404` `not_found`, and a request without `name` returns `400` `bad_request`.
+- `GET …/installed` is open to any member of the Project. Each entry in `plugins` is `{specifier, active, builtin, modules, replaces, error?}`: `active` means the process has loaded the package, `builtin` that it ships with this build, `modules` and `replaces` are the nodes its generated `ifaces.json` declares, and `error` says why it is not running, such as a package that is not on this machine or a load that failed. `shipped` lists every plugin package the build ships, asked for or not. `file` names the file that holds the list. `restartPending` is true when a listed plugin is neither running nor failed, which a server restart resolves. A Project whose `.project_config.toml` cannot be read returns `400` `invalid_plugins_file`.
+- The writes answer with the same body as the GET. A specifier must be a package name, never a path, a URL or a version range (`400` `bad_request`). A name that enters the list must be a package the build ships, otherwise the route returns `400` `plugin_not_shipped`: nothing is downloaded. `PUT` sends names only, and a name that stays in the list keeps the requirement the file records for it. `DELETE` edits the list only and removes nothing from disk.
+- A write takes effect without a restart: the App [re-assembles itself](/server-boot#re-assembly) around the new list, with the effects of a hot swap. Agent runs in progress are stopped in every Project, because all Projects share one module tree. If the new App fails to boot, the edit is undone and the previous App is restored.
+- The list is the `[plugins]` table of the Project's `.project_config.toml` (see [Project config](/configuration#project-config)). The process loads the union of every Project's table, so a plugin one Project asks for is loaded for all of them.
+
+## Schedules
-Schedule writes are owner-only. A task in new-Session mode carries `modelId` and `provider` together or not at all; the pair is checked against the Project's model table when the task is saved and again when the scheduler reconciles it.
+The paths below omit the `/api/projects/:projectId` prefix.
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | `/schedules` | Every agent's scheduled tasks in the Project in one list, each stamped with its `agentId` (any member) |
+| GET / POST | `/agents/:agentId/schedules` | Lists scheduled tasks / creates one (409 if the name exists) |
+| POST | `/agents/:agentId/schedules/template-placeholder` | Inserts the `{{SCHEDULES}}` placeholder into the prompt template (idempotent) |
+| GET / PUT / DELETE | `/agents/:agentId/schedules/:name` | Reads / updates / deletes a single task |
+
+Schedule writes are owner only. A task in new-Session mode carries `modelId` and `provider` together or not at all. The pair is checked against the Project's model table when the task is saved, and again when the scheduler reconciles it.
-### Benchmarks
+## Benchmarks
-Benchmarks hang off the Project, not off an Agent: one Benchmark evaluates as many Agents as it is pointed at, and each evaluation names the Agent it tested (`agentId`, `null` on a record that carries none). A summary's `agentIds` lists those Agents in first-seen order. The paths below again omit the `/api/projects/:projectId` prefix.
+Benchmarks belong to the Project, not to an agent: one Benchmark can evaluate any number of agents, and each evaluation names the agent it tested (`agentId`, or `null` for a record that names none). A summary's `agentIds` lists those agents in the order they first appear. The paths below again omit the `/api/projects/:projectId` prefix.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /benchmarks | Benchmark scoring data — only directories holding a `benchmark_config.toml`; one without it (what a Benchmark deleted mid-evaluation leaves behind) is skipped; each entry carries `status` (`draft` while the Skill is still building it, `failed` when its calibration never finished, else `published`) |
-| POST | /benchmarks | Create a Benchmark by hand (owner only): `{ id, title, description?, runs?, cases: [{ id, title, statement, rubric }] }` → 201 `{ benchmark }`. The server writes `benchmark_config.toml` (with `status = "published"`), a `scoreboard.yaml` with `evaluations: []`, and each case's `statement/README.md` (the title as its heading) and `rubric/README.md`; ids follow the agent-id alphabet, case ids start with `CASE-`; 409 `benchmark_exists` when the directory is already there |
-| DELETE | /benchmarks/:benchmarkId | Remove a Benchmark directory whole — cases, config and scoreboard (owner only; 204, 404 when absent) |
-| GET | /benchmarks/:benchmarkId/cases | Case list of one Benchmark: id and the statement README's heading. Rubrics are never returned |
-| GET | /benchmarks/:benchmarkId/cases/:caseId/files | Browse one case's `statement/`; add `/rubric` before `/files` for the rubric side |
-| GET | /benchmarks/:benchmarkId/cases/:caseId/files/content | Read one file from that material (`?path=`, `?preview=1`, `?download=1`), with the same inline hardening as Workspace files |
+| GET | `/benchmarks` | Benchmark scoring data |
+| POST | `/benchmarks` | Creates a Benchmark by hand (owner only) |
+| DELETE | `/benchmarks/:benchmarkId` | Deletes a Benchmark directory with its cases, config and scoreboard (owner only; 204, or 404 when absent) |
+| GET | `/benchmarks/:benchmarkId/cases` | A Benchmark's cases: each case's id and the heading of its statement README. Rubrics are never returned |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/files` | Browses one case's `statement/` |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/files/content` | Reads one file of the statement (`?path=`, `?preview=1`, `?download=1`) |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/rubric/files` | Browses one case's `rubric/` |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/rubric/files/content` | Reads one file of the rubric, with the same parameters |
-### Organizations (company mode)
+- `GET /benchmarks` lists only directories that hold a `benchmark_config.toml`. A directory without one, which is what a Benchmark deleted during an evaluation leaves behind, is skipped. Each entry carries `status`: `draft` while the Skill is still building the Benchmark, `failed` when its calibration never finished, and `published` otherwise.
+- `POST /benchmarks` takes `{id, title, description?, runs?, cases: [{id, title, statement, rubric}]}` and answers 201 `{benchmark}`. The server writes `benchmark_config.toml` (with `status = "published"`), a `scoreboard.yaml` with `evaluations: []`, and each case's `statement/README.md` (with the title as its heading) and `rubric/README.md`. Ids use the same characters as agent ids, and case ids start with `CASE-`. If the directory already exists, the route returns 409 `benchmark_exists`.
+- The file-content routes apply the same inline hardening as Workspace files; see [Workspace file responses](#workspace-file-responses).
-All paths below are under `/api/projects/:projectId/organizations`. Every route answers 404 while the admin's company-mode switch is off. Any Project member reads and writes. There is no route that deletes an organization: `status` (`active` / `paused`) is the off switch, and a paused organization keeps its conversations, employees, desks and tickets. Write bodies may carry `agentId` and `sessionId` — the calling employee and the calling session, which the CLI fills from `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID` — so the file records the employee rather than the token's user; `agentId` wins when it names an employee, the session answers otherwise. The channel reads and the member DELETE, which have no body, take the same pair as `?agentId=` / `?sessionId=`. Both are honoured only for a request carrying the local API token, which is how an employee is answered as itself instead of as the signed-in person. See [Company Mode](/company-mode) for the files behind these routes.
+## Organizations (company mode)
+
+All paths below are under `/api/projects/:projectId/organizations`. While the server's company-mode switch is off, every route answers `404` `company_mode_off` (see [Company mode switch](#company-mode-switch)). Any Project member can read and write. No route deletes an organization: `status` (`active` / `paused`) is the off switch, and a paused organization keeps its conversations, employees, desks and tickets. For the files behind these routes, see [Company Mode](/company-mode).
| Method | Path | Description |
| --- | --- | --- |
-| GET / POST | / | List organizations / create one: `{orgId, mission, name?, timezone?, workspace?, model?, ceoBudget?, language?}` → 201 with the organization detail (creation makes the CEO Agent and opens its desk with an initialization run; 409 when the id or the CEO's Agent id is taken). The CEO's chart entry is written with `workspace: ceo`, a partition of the shared workspace like every other employee's. `ceoBudget` is the CEO's monthly USD budget, written as the `budget` of its `org_chart.yaml` entry — non-negative, omitted = 100; compared on the cumulative line, it is the whole company's cap. `language` is `zh` or `en`, the working language everything the organization writes is written in; omitted, it is detected from the mission |
-| GET / PATCH | /:orgId | Overview (settings, board counts, today's calendar, pending items, the all-hands channel's recent messages, `inbox`, alerts; the settings always carry the effective `language`, read from the mission when the file has none) / change name, mission, `status` (`active` / `paused` — pausing stops every automatic trigger), `approvalMode`, `timezone`, `language`, thresholds |
-| GET | /:orgId/chart | The employee tree with live state, desk and period spend per employee |
-| POST | /:orgId/employees | Hire: `{agentId}` for an existing Agent or `{newAgent: {agentId, name?, description?, plugins?}}`, plus `title`, `reportsTo`, `workspace?`, `budget?`, `duties?`, `model?`. `workspace` defaults to a sub-directory named after the employee's Agent id — the shared workspace's root holds the shared inputs and is nobody's desk. A relative `workspace` is normalized (`./hr` → `hr`) and created under the shared workspace, an absolute one must already exist, and one climbing out with `..` is 400 `invalid_workspace` |
-| PATCH / DELETE | /:orgId/employees/:agentId | Change title, manager, workspace (created and validated as on hire), budget (`null` clears), duties, model / leave (subordinates move up to the manager; the CEO cannot leave) |
-| GET / POST | /:orgId/employees/:agentId/desk | The desk session (opened when missing) / a renewed desk session |
-| GET / PUT | /:orgId/handbook | The handbook index (`handbook/README.md`) |
-| GET | /:orgId/handbook/files | The knowledge-base files, the index first |
-| GET / PUT / DELETE | /:orgId/handbook/files/\<path\> | One document by relative path; the index cannot be deleted |
-| GET / POST | /:orgId/calendar | Every employee's events with their run state / create: `{agentId, name, prompt, enabled, startAt, period?, endAt?, title?}` → the stored event plus advisory `warnings`, one line each: another employee's recurring event on the same start minute, a second recurring event for the same employee on the same period, a recurring event started at `now`. The write is never refused for them |
-| GET / PUT / DELETE | /:orgId/calendar/:agentId/:name | One event; `PUT` answers as the create above does, `warnings` included |
-| GET / POST | /:orgId/tickets | The board by column (plus unparsable files) / create: `{title, goal?, acceptanceCriteria?, body?, owner?, parent?, notify?, priority?, due?, slug?}`. `owner` is the ONE responsible principal — an employee (a bare Agent id or `agent:<id>`) or a Project member (`user:<id>`) — and defaults to the caller; when `notify` is absent it becomes the whole `notify`, but only when it is an employee, so a person is not @-mentioned for a ticket they own. Who filed it is the `created` entry of the ticket's `history`. The id's slug comes from `slug` when given (lowercase English words joined by hyphens, 400 otherwise), else from the title; a title that yields fewer than two words is put to the Project's model, and 400 `slug_required` asks the caller to name it when that fails too |
-| GET / PUT | /:orgId/tickets/:ticketId | Ticket detail (frontmatter fields, prose sections, `progress` as plain sentences, `history`, contributing sessions, children, rolled-up cost) / update `{title?, owner?, parent?, notify?, priority?, due?, goal?, acceptanceCriteria?, result?}`. `owner` takes no `null`: a ticket always has one, so it is reassigned, never cleared; `parent` and `due` still take `null` to clear |
-| POST | /:orgId/tickets/:ticketId/move | `{status, reason?}` — moving into `rejected` needs a reason |
-| POST | /:orgId/tickets/:ticketId/block | `{reason, by?}` — `by` is a ticket id or a principal; the ticket stays in its column |
-| POST | /:orgId/tickets/:ticketId/unblock | Clears the block |
-| POST | /:orgId/tickets/:ticketId/progress | `{text}` — appends one plain sentence to `## Progress`; who wrote it and when is the `progress` entry appended to `history` |
-| POST | /:orgId/tickets/:ticketId/start | `{agentId?, message?, workspace?}` → 202 `{sessionId}`: a ticket session of that employee, recorded in the ticket's `sessions` and `history`. This is the one route whose `agentId` is not an identity claim — it names the employee the session runs as. Who may start one depends on the caller: a person may start any ticket's session (`agentId` names the employee, defaulting to the owner), while a caller writing as an employee — a desk or ticket session quoting its own `sessionId` — may start one only for a ticket it OWNS, and gets 403 `not_ticket_owner` for anyone else's or for a ticket with no employee owner. An owner may still pass `agentId` to enlist a colleague on its own ticket |
-| POST | /:orgId/tickets/:ticketId/attach | `{sessionId}` — records an existing session as contributing |
-| GET / POST | /:orgId/channels | Every channel the caller may see (people: all of them; an employee: the ones it is in), `default_channel` first / open one: `{channelId, name?, purpose?}` → 201, holding only its creator (409 when the id is taken) |
-| GET / PATCH | /:orgId/channels/:channelId | The channel and its members / rename, change `purpose`, set `archived` (people only, never on `default_channel`) |
-| POST | /:orgId/channels/:channelId/members | `{principal}` — any member invites an `agent:<id>` employee or a `user:<id>` Project member; a person may add itself, an employee may not. Adding an existing member is a no-op 201 |
-| DELETE | /:orgId/channels/:channelId/members/:principal | Remove a member: anyone removes itself, a person removes anyone, an employee only itself; removing a non-member is a no-op 204 |
-| GET / POST | /:orgId/channels/:channelId/messages | A day's messages (`?date=yyyy-mm-dd`, default today in the organization's timezone) with the caller's unread and mention counts / send `{text, refs?}`; mentions are resolved from the text and must all be members. A `system` line also carries `notice` — a `kind` (`employee_joined`, `employee_left`, `channel_created`, `channel_archived`, `channel_unarchived`, `channel_joined`, `channel_invited`, `channel_left`, `channel_removed`, `budget_warned`, `budget_paused`, and the legacy `ticket_blocked`, `ticket_done`, `ticket_rejected` — nothing writes those three any more, they are kept so lines already on disk still render) and string `params` — beside its English `text`, so a client renders the sentence in the reader's language; lines written before the field have none |
-| POST | /:orgId/channels/:channelId/read | `{upTo}` — the caller's read cursor in this channel |
-| GET | /:orgId/finance | Spend per employee (own and cumulative along the reporting line), per ticket (rolled up along `Parent`), daily trend, alerts; `?period=yyyy-mm` |
-| GET | /:orgId/sessions | The organization's desk sessions and ticket sessions grouped by ticket; a desk whose Session has an enabled messaging binding carries its `messagingChannel`, as the Session's own row does |
-
-Channel errors: `channel_not_found` (404 — also for an id no channel could carry), `channel_exists` (409), `channel_archived` (409 — an archived channel takes no writes until it is unarchived), `not_a_member` (403 — reading, posting or inviting without membership, and any people-only action attempted by an employee), `all_hands_immutable` (400 — archiving `default_channel` or editing its membership), `mention_not_member` (400 — the message names principals the channel does not hold; nothing is written), `invalid_principal` (400).
-
-User-level events on `GET /api/events`: `org_run` (a work run or ticket session started), `org_channel` (a new message, with its `channelId` and mentions), `org_ticket` (a ticket's status, owner, block or sessions changed), `org_budget` (warned / paused / resumed).
-
-A desk session is driven by three things only: a calendar event, a channel `@`-mention, and a person talking to it (the CEO's creation-time initialization run is the one exception). **A ticket write starts no run.** `move`, `block`, `unblock` and an owner set through `PUT /:orgId/tickets/:ticketId` are recorded — in the ticket file, in the all-hands `system` line where the change has one, and as an `org_ticket` event — and queued for the employees they concern; the next calendar event of each carries them in its body under `## Since your last sweep`, one line per change. A queue survives a paused organization or employee and is delivered by the sweep that eventually fires; an employee that leaves takes its undelivered lines with it.
-
-### Session Creation and Directory Browsing
+| GET / POST | `/` | Lists organizations / creates one |
+| GET / PATCH | `/:orgId` | The organization's overview / changes its settings |
+| GET | `/:orgId/chart` | The employee tree, with each employee's live state, desk and spend for the period |
+| POST | `/:orgId/employees` | Hires an employee: an existing agent or a new one |
+| PATCH / DELETE | `/:orgId/employees/:agentId` | Changes an employee / removes the employee from the organization |
+| GET / POST | `/:orgId/employees/:agentId/desk` | The desk session, opened when missing / a renewed desk session |
+| GET / PUT | `/:orgId/handbook` | The handbook index (`handbook/README.md`) |
+| GET | `/:orgId/handbook/files` | The knowledge-base files, the index first |
+| GET / PUT / DELETE | `/:orgId/handbook/files/<path>` | One document by relative path; the index cannot be deleted |
+| GET / POST | `/:orgId/calendar` | Every employee's events with their run state / creates an event |
+| GET / PUT / DELETE | `/:orgId/calendar/:agentId/:name` | One event |
+| GET / POST | `/:orgId/tickets` | The board by column, plus files that could not be parsed / creates a ticket |
+| GET / PUT | `/:orgId/tickets/:ticketId` | Ticket detail / updates the ticket |
+| POST | `/:orgId/tickets/:ticketId/move` | `{status, reason?}`; moving into `rejected` needs a reason |
+| POST | `/:orgId/tickets/:ticketId/block` | `{reason, by?}`, where `by` is a ticket id or a principal; the ticket stays in its column |
+| POST | `/:orgId/tickets/:ticketId/unblock` | Clears the block |
+| POST | `/:orgId/tickets/:ticketId/progress` | `{text}`: appends one plain sentence to `## Progress` |
+| POST | `/:orgId/tickets/:ticketId/start` | `{agentId?, message?, workspace?}` → 202 `{sessionId}`: starts a ticket session |
+| POST | `/:orgId/tickets/:ticketId/attach` | `{sessionId}`: records an existing session as contributing |
+| GET / POST | `/:orgId/channels` | The channels the caller may see, `default_channel` first / opens a channel |
+| GET / PATCH | `/:orgId/channels/:channelId` | The channel and its members / renames it, changes `purpose`, sets `archived` |
+| POST | `/:orgId/channels/:channelId/members` | `{principal}`: adds a member |
+| DELETE | `/:orgId/channels/:channelId/members/:principal` | Removes a member |
+| GET / POST | `/:orgId/channels/:channelId/messages` | A day's messages with the caller's unread and mention counts / sends a message |
+| POST | `/:orgId/channels/:channelId/read` | `{upTo}`: the caller's read cursor in this channel |
+| GET | `/:orgId/finance` | Spend per employee (own and cumulative along the reporting line) and per ticket (rolled up along `Parent`), the daily trend and alerts; `?period=yyyy-mm` |
+| GET | `/:orgId/sessions` | The organization's desk sessions, and its ticket sessions grouped by ticket. A desk whose Session has an enabled messaging binding carries its `messagingChannel`, as the Session's own row does |
+
+### Caller identity
+
+Write bodies may carry `agentId` and `sessionId`, the calling employee and the calling session, which the CLI fills in from `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID`. The file then records the employee rather than the token's user: `agentId` wins when it names an employee, and the session decides otherwise. The channel reads and the member DELETE have no body, so they take the same pair as `?agentId=` / `?sessionId=`. The server honours both only on requests that carry the local API token; that is how an employee is answered as itself instead of as the signed-in person.
+
+### Organizations
+
+- `POST /` takes `{orgId, mission, name?, timezone?, workspace?, model?, ceoBudget?, language?}` and answers 201 with the organization detail. Creating an organization also creates the CEO agent and opens its desk with an initialization run. The route returns 409 when the id or the CEO's agent id is taken. The CEO's chart entry is written with `workspace: ceo`, a partition of the shared workspace like every other employee's.
+- `ceoBudget` is the CEO's monthly budget in USD, written as the `budget` of the CEO's `org_chart.yaml` entry. It must not be negative and defaults to 100. Budgets are compared along the cumulative line, so this is the whole company's cap.
+- `language` is `zh` or `en`, the working language of everything the organization writes. If omitted, it is detected from the mission.
+- `GET /:orgId` returns the overview: settings, board counts, today's calendar, pending items, the all-hands channel's recent messages, `inbox` and alerts. The settings always carry the effective `language`, read from the mission when the file has none.
+- `PATCH /:orgId` changes the name, mission, `status` (`active` / `paused`; pausing stops every automatic trigger), `approvalMode`, `timezone`, `language` and thresholds.
+
+An organization's and a channel's id proposals come from the Project-level route, `POST /api/projects/:projectId/suggest-id` with `kind: org` or `kind: channel`; see [Semantic id proposals](#semantic-id-proposals).
+
+### Employees
+
+- `POST /:orgId/employees` takes `{agentId}` for an existing agent or `{newAgent: {agentId, name?, description?, plugins?}}` for a new one, plus `title`, `reportsTo`, `workspace?`, `budget?`, `duties?` and `model?`.
+- `workspace` defaults to a subdirectory named after the employee's agent id, because the root of the shared workspace holds the shared inputs and is nobody's desk. A relative `workspace` is normalized (`./hr` → `hr`) and created under the shared workspace. An absolute one must already exist. One that climbs out with `..` returns 400 `invalid_workspace`.
+- `PATCH /:orgId/employees/:agentId` changes the title, manager, workspace (created and validated as on hire), budget (`null` clears it), duties and model.
+- `DELETE /:orgId/employees/:agentId` removes the employee from the organization: its subordinates move up to its manager. The CEO cannot leave.
+
+### Calendar
+
+`POST /:orgId/calendar` takes `{agentId, name, prompt, enabled, startAt, period?, endAt?, title?}` and answers with the stored event plus advisory `warnings`, one line each:
+
+- another employee's recurring event on the same start minute
+- a second recurring event for the same employee with the same period
+- a recurring event that starts at `now`
+
+Warnings never block the write. `PUT /:orgId/calendar/:agentId/:name` answers the same way as the create, `warnings` included.
+
+### Tickets
+
+- `POST /:orgId/tickets` takes `{title, goal?, acceptanceCriteria?, body?, owner?, parent?, notify?, priority?, due?, slug?}`.
+- `owner` is the one principal responsible: an employee (a bare agent id or `agent:<id>`) or a Project member (`user:<id>`). It defaults to the caller. When `notify` is absent, the owner becomes the whole `notify` list, but only if the owner is an employee, so a person is not @-mentioned about a ticket they own. Who filed the ticket is the `created` entry of its `history`.
+- The id's slug comes from `slug` when given, which must be lowercase English words joined by hyphens (400 otherwise). Without `slug`, it comes from the title. A title that yields fewer than two words is passed to the Project's model, and if that also fails, 400 `slug_required` asks the caller to name the slug.
+- `GET /:orgId/tickets/:ticketId` returns the frontmatter fields, the prose sections, `progress` as plain sentences, `history`, the contributing sessions, child tickets and the rolled-up cost.
+- `PUT /:orgId/tickets/:ticketId` takes `{title?, owner?, parent?, notify?, priority?, due?, goal?, acceptanceCriteria?, result?}`. `owner` does not accept `null`: a ticket always has an owner, who can be replaced but not removed. `parent` and `due` accept `null` to clear them.
+- `POST …/progress` records who wrote the sentence, and when, as a `progress` entry appended to `history`.
+
+`POST /:orgId/tickets/:ticketId/start` starts a ticket session for an employee and records it in the ticket's `sessions` and `history`. It is the one route whose `agentId` is not an identity claim: it names the employee the session runs as. Who may start a session depends on the caller:
+
+- A person may start a session on any ticket. `agentId` names the employee and defaults to the owner.
+- A caller writing as an employee (a desk or ticket session sending its own `sessionId`) may start one only for a ticket it owns. For anyone else's ticket, or a ticket with no employee owner, it gets 403 `not_ticket_owner`.
+- An owner may still pass `agentId` to bring a colleague onto its own ticket.
+
+### Channels
+
+- `GET /:orgId/channels` lists every channel the caller may see: all of them for a person, and the ones it belongs to for an employee.
+- `POST /:orgId/channels` takes `{channelId, name?, purpose?}` and answers 201 with a channel whose only member is its creator; 409 when the id is taken.
+- `PATCH /:orgId/channels/:channelId` can set `archived` only for people, and never on `default_channel`.
+- `POST …/members` lets any member invite an `agent:<id>` employee or a `user:<id>` Project member. A person may add itself; an employee may not. Adding an existing member is a no-op that returns 201.
+- `DELETE …/members/:principal` lets anyone remove itself, and a person remove anyone; an employee can only remove itself. Removing a non-member is a no-op that returns 204.
+- `GET …/messages` takes `?date=yyyy-mm-dd`, which defaults to today in the organization's timezone. `POST …/messages` sends `{text, refs?}`; mentions are resolved from the text and must all be channel members.
+
+A `system` line carries a `notice` beside its English `text`: a `kind` and string `params`, so a client can render the sentence in the reader's language. Lines written before this field existed have none. `kind` is one of `employee_joined`, `employee_left`, `channel_created`, `channel_archived`, `channel_unarchived`, `channel_joined`, `channel_invited`, `channel_left`, `channel_removed`, `budget_warned` and `budget_paused`, or one of the legacy `ticket_blocked`, `ticket_done` and `ticket_rejected`. Nothing writes the legacy kinds any more; they remain so that lines already on disk still render.
+
+Channel errors:
+
+| Code | Status | Meaning |
+| --- | --- | --- |
+| `channel_not_found` | 404 | The channel does not exist; also returned for an id no channel could have |
+| `channel_exists` | 409 | The channel id is taken |
+| `channel_archived` | 409 | The channel is archived and takes no writes until it is unarchived |
+| `not_a_member` | 403 | Reading, posting or inviting without membership, or an employee attempting a people-only action |
+| `all_hands_immutable` | 400 | Archiving `default_channel` or editing its membership |
+| `mention_not_member` | 400 | The message mentions principals that are not channel members; nothing is written |
+| `invalid_principal` | 400 | The principal is malformed |
+
+### Events and triggers
+
+Company mode publishes `org_run`, `org_channel`, `org_ticket` and `org_budget` on the user event stream `GET /api/events`; see [Streaming (SSE)](#streaming-sse).
+
+Only three things drive a desk session: a calendar event, an `@`-mention in a channel, and a person talking to it. The CEO's initialization run at creation is the one exception.
+
+A ticket write starts no run. `move`, `block`, `unblock` and an owner change through `PUT /:orgId/tickets/:ticketId` are recorded in the ticket file and published as an `org_ticket` event, and they are queued for the employees they concern. Each employee's next calendar event lists them in its body under `## Since your last sweep`, one line per change. The queue survives a paused organization or employee and is delivered by the sweep that eventually fires. An employee that leaves takes its undelivered lines with it.
+
+## Session Creation and Directory Browsing
+
+The paths below omit the `/api/projects/:projectId` prefix.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /agents/:agentId/sessions | List Sessions (including run state); every row is listed whichever client created it, unless `excludeOrg=1` asks for the user's own rows only — an organization's desk, ticket and sub-sessions then leave the page and the `counts=1` totals together (what development mode's list requests) |
-| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201. `client` is the creating-client hint stored on the row (`"cli"` from the CLI; default `"web"`) — informational provenance, never a list filter; `source` accepts only `"benchmark"` (a Benchmark evaluation or optimization), since `subagent` and `schedule` are set by the server itself `org` is the value the server itself writes for an organization's desk and ticket sessions (company mode); a client cannot pass it. |
-| GET | /dirs?path= | Server-side directory browser (backs the Workspace picker) |
+| GET | `/agents/:agentId/sessions` | Lists the agent's Sessions with their run state, whichever client created them, unless `excludeOrg=1` asks for the user's own rows only |
+| POST | `/agents/:agentId/sessions` | Creates a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201 `{session}` |
+| GET | `/dirs?path=` | Server-side directory browser behind the Workspace picker |
+| GET | `/dir-skills?path=` | The Skills a directory carries, for importing them into a new agent |
+
+- The Session list accepts optional query parameters. `limit` and `offset` page the list (`offset` requires `limit`). `category` (`active`, `subagent`, `schedule`, `benchmark` or `archived`) filters it before paging, and `workspaceGroup` filters it to one Workspace. `counts=1` adds `counts` (totals per category over the whole list), `workspaceCounts` (the same totals per Workspace path) and `workspaceLatest` (each Workspace's newest Session). Without paging parameters, the full list is returned.
+- `excludeOrg=1` leaves an organization's desk, ticket and subagent Sessions out of the page and out of the `counts=1` totals together, which is what development mode's list asks for. Any other value is a 400.
+- On creation, `modelId` and `provider` go together: send the complete pair to pick a model, or omit both to use the Project's default model. Sending only one is a 400.
+- An explicit `workspace` must be an existing directory; it is never created. When omitted, the Workspace is a temporary one created automatically. The approval mode defaults to `allow-all`.
+- `client` is a provenance hint stored on the row: `"cli"` from the CLI, `"web"` by default. The server itself writes `"org"` on an organization's desk and ticket sessions, and a client cannot send that value. Only `excludeOrg` reads it as a filter, and only to drop those rows.
+- `source` accepts only `"benchmark"`, for a Session created by a Benchmark evaluation or optimization. The server sets `subagent` and `schedule` itself.
+- `GET /dirs` starts at the home directory when `path` is omitted; an explicit `path` must be absolute. It answers `{path, parent, entries}` with the subdirectories only, and an unreadable directory lists as empty so the user can still go back up.
+- `GET /dir-skills` reads only `<path>/.agents/skills` and `<path>/.claude/skills` of an absolute `path`, and answers `{path, skills}`. A directory without Skills answers with an empty list. See `POST /agents` under [Agents](#agents).
+
+## Usage and Traces (Agent Level)
-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`.
-
-### Usage and Traces (Agent Level)
+The paths below omit the `/api/projects/:projectId` prefix.
| Method | Path | Description |
| --- | --- | --- |
-| GET | /usage | Usage statistics; query parameters `from`, `to`, `fromTs`/`toTs` (ISO timestamps bounding a trailing window, given together; required for `minute`), `groupBy`, `granularity` (`minute` / `hour` / `day` / `week` / `month` time-series precision, default `day`; oversized range × precision combinations are rejected), `agentId`, `provider`, `modelId` |
-| GET | /usage/errors | One page of the error detail table (newest first): `offset`, `limit`, plus the same `from` / `to` / `fromTs` / `toTs` / `agentId` filter and an optional `kind` (`unexpected` / `expected`) → `{items, total}` |
-| DELETE | /usage/errors | Empties the error table for the filter on screen: `from` / `to` / `fromTs` / `toTs` / `agentId`, the same set the reads take (no `kind` — the panel offers no such control) → `{deleted}`. `from` and `to` are both required here (400 otherwise) — an open bound would be the whole history rather than a filter. Project owner only; the clear reaches exactly what the caller's reads reach, so an admin's clear also takes the unattributed rows an admin's read shows, and a member's never does |
-| GET | /agents/:agentId/traces | Date → Session drill-down structure of Trace files |
-| GET | /agents/:agentId/traces/:sessionId/:index | Read Trace events (`offset` / `limit` pagination) |
-| GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace performance analysis |
-| GET | /agents/:agentId/traces/:sessionId/:index/download | Download the raw Trace file (JSONL attachment) |
-| POST | /agents/:agentId/traces/import | Import a Trace file: `{dataBase64}` → `{sessionId, index, date}` |
+| GET | `/usage` | Usage statistics |
+| GET | `/usage/model-totals` | Lifetime Token total per model; takes no filters |
+| GET | `/usage/errors` | One page of the error detail table, newest first: → `{items, total}` |
+| DELETE | `/usage/errors` | Empties the error table for the current filter: → `{deleted}` (Project owner only) |
+| GET | `/agents/:agentId/traces` | Trace files as a date → Session drill-down |
+| GET | `/agents/:agentId/traces/:sessionId/:index` | Reads Trace events (`offset` / `limit` pagination) |
+| GET | `/agents/:agentId/traces/:sessionId/:index/analysis` | Trace performance analysis |
+| GET | `/agents/:agentId/traces/:sessionId/:index/download` | Downloads the raw Trace file (JSONL attachment) |
+| POST | `/agents/:agentId/traces/import` | Imports a Trace file: `{dataBase64}` → `{sessionId, index, date}` |
+
+`GET /usage` takes these query parameters:
+
+| Parameter | Description |
+| --- | --- |
+| `from`, `to` | Date range, as `yyyy-mm-dd` |
+| `fromTs`, `toTs` | ISO timestamps bounding a trailing window. Given together; required for `minute` |
+| `groupBy` | `date`, `agent`, `model` or `session`; default `date` |
+| `granularity` | Time-series precision: `minute`, `hour`, `day`, `week` or `month`; default `day`. Combinations of range and precision that would be too large are rejected |
+| `agentId`, `provider`, `modelId` | Filters |
-Trace download is available to any member; import is owner-only (like the Agent snapshot import, capped at 14MB). An imported file must be valid Trace JSONL whose first record is a `session_meta` with a filename-safe `session_id`; a session id the Agent already has is rejected (409 `trace_session_exists`), so an imported file always becomes index 001 of a new Session, landing in the local date directory of its first record's timestamp.
+- `GET /usage/errors` takes `offset`, `limit`, the same `from` / `to` / `fromTs` / `toTs` / `agentId` filter, and an optional `kind` (`unexpected` or `expected`).
+- `DELETE /usage/errors` takes the same filter as the reads, `from` / `to` / `fromTs` / `toTs` / `agentId`, but no `kind`, because the panel offers no such control. `from` and `to` are both required here (400 otherwise), because an open bound would clear the whole history rather than a filtered part. The clear reaches exactly what the caller's reads reach: an admin's clear also removes the unattributed rows that only an admin's read shows, and a member's clear never does.
+- `GET /agents/:agentId/traces` also accepts `limit` and `offset` for paging, and `category` (which requires `limit`) to list one category of Sessions.
+- Any member can download a Trace. Import is owner only, like the Agent State snapshot import, and capped at 14MB. The imported file must be valid Trace JSONL whose first record is a `session_meta` with a filename-safe `session_id`. A session id the agent already has is rejected (409 `trace_session_exists`), so an imported file always becomes index 001 of a new Session, stored in the local date directory of its first record's timestamp.
-### Session-Level Endpoints
+## Session-Level Endpoints
The paths below omit the `/api/sessions/:sessionId` prefix. For the storage model behind Sessions and Traces, see [Sessions and Traces](/sessions-and-traces).
+Two conventions apply to every route here. A Session the caller cannot access always returns `404` `session_not_found`, so its existence is never revealed. And only one Task or compaction runs in a Session at a time: a conflicting request returns 409 (`task_in_progress` / `compacting`).
+
+### Session and history
+
| Method | Path | Description |
| --- | --- | --- |
-| GET | / | Session info (the single-session GET additionally carries `tracePath`, the absolute path of the latest Trace file; list rows omit it). `orgId` marks a Session the company-mode caches own — a desk session, or a session contributing to one of that organization's tickets — and is absent on every ordinary Session; the list route stamps it too |
-| PATCH | / | Update: `{approvalMode?, thinkingLevel?, archived?, title?}`. `thinkingLevel` pins the level on this Session (durable) and applies from its very next LLM request — the thinking level is soft-limited: changeable mid-context, at the cost of the provider's cached context, which is why the picker advises compacting first — and it comes back as `SessionInfo.thinkingLevel` (absent = never pinned: the Agent config applies) |
-| DELETE | / | Delete the Session (along with its Traces and scratch files) |
-| GET | /messages | Without parameters, the full OmniMessage history; `tailLimit=n` or `before=<cursor>&limit=n` reads a Task-aligned window instead (the bundled Web App opens a conversation on its latest 50 turns and backfills on scroll), and the response then carries `page` (the next-page cursor `before`, the turns before the window `earlierTurns`, and the cumulative `prior` stats). While a Task runs the response also carries `live` (the in-progress stream tail, see below) |
-| POST | /fork | Fork an idle Session through a completed assistant reply: `{position:{fileIndex,ordinal}}` → `{session}` |
-| GET | /stream | SSE event stream (next section) |
-| POST | /tasks | Start a Task: `{input: TaskInputPart[], queueIfBusy?}` → 202. With `queueIfBusy`, a busy session holds the input as a follow-up (`queued: true`) and auto-starts it as an ordinary next task once idle; `task_state` events report the queued count. `file` input parts are written to the Session scratchpad and handed to the model as `[attached file: <path>]` lines (see the request body below). With `goal: {budget?}` the input starts a goal loop instead (409 `goal_plugin_not_installed` unless the `goal` plugin is installed on the Agent): it must carry non-empty text (an image alone states no objective), any images it carries fold into the objective as scratchpad path lines whatever the model's vision, and `file` parts are refused — nothing folds them into a re-injected objective — see [Goal mode](/goal-mode) |
-| POST | /steer | Mid-run steering: `{text, images?}` queues a message for the running Task (delivered between turns as a standalone `[user_steering]` user message, with its images right behind it) → 202; either field can carry the message on its own, but a request with neither is a 400; 409 `not_running` when no Task is in progress |
-| DELETE | /steer/:steerId | Recall an undelivered steering message (ids ride `task_state`'s `pendingSteering`): withdraws it from the queue → 200 with its original content `{text, images, files}` (files read back from the scratchpad as data URLs, their disk copies deleted) so the composer can restore it for editing; 409 `not_pending` once it was delivered to the model |
-| DELETE | /follow-ups/:followUpId | Recall a queued follow-up task (ids ride `task_state`'s `pendingFollowUps`): removes it before it auto-starts → 200 with its original content `{text, images, files}` — every queued follow-up carries that content, however it was queued; 409 `follow_up_started` once it already started |
-| POST | /approvals/:toolCallId | Approval decision: `{decision}` is `allow` or `deny` → 204 |
-| POST | /tool-calls/:toolCallId/background | Hand one **executing** tool call back as a background task, so the turn can close and the conversation carries on: 204. The call ends `completed` with its `process_id` / `subagent_id`, nothing is killed, and the completion arrives later as the usual background-task notice. 404 `tool_call_not_found` when nothing with that id is executing (unknown, already finished, or the runtime is gone), 409 `tool_not_detachable` when the call is running but its tool has no background form (only `exec_command` and `run_subagent` have one) |
-| POST | /abort | Interrupt the current Task: 202 when triggered, 204 when idle |
-| POST | /retry-now | "Retry now" on the reconnect countdown: skips the in-progress backoff wait, firing the next retry immediately (attempt counter unchanged) → 200 `{skipped}` — `skipped:false` is the benign "no wait in progress" case, never an error |
-| POST | /compact | Trigger context compaction: 202; 409 when there is nothing to compact, the reason carried by the code — `compaction_not_configured` (this Agent has no compaction configured), `nothing_to_compact` (the context has no completed conversation turn yet), `already_compacted` (nothing new was said since the last compaction). A Session resumed after a server restart reports availability from its Trace, so an existing conversation stays compactable without running a Task first |
-| GET | /processes | Background processes the conversation started (`exec_command`s promoted past their yield window). Served from the active runtime only — an evicted or never-loaded session truthfully reports an empty list. Rows carry `serviceUrl` when a served address was detected (the last local URL the output printed, else a listen-port probe of the process group, refreshed on each fetch) |
-| POST | /processes/:processId/kill | Stop one background process (SIGTERM to the whole process group, SIGKILL after a grace period); the entry drops from the list. 404 `process_not_found` when it is gone |
-| DELETE | /processes/:processId | Remove one **exited** process entry from the list: 409 `process_running` while it still runs (stop it instead), 404 `process_not_found` when it is already gone. The entry leaves the runtime registry with the output captured from it, so `input_command` on that `process_id` fails afterwards |
-| GET | /files?path= | Browse the Workspace directory |
-| GET | /files/content?path=&download=&preview= | Read a Workspace file (`download=1` serves it as an attachment, `preview=1` renders it in a sandbox — see below) |
-| GET | /files/preview-redirect?path= | "Open in a new tab" for html: mints a signed token and 302s to the separate preview origin |
-| POST | /files/stat | Batch existence check: `{paths}` |
-| PUT | /files/content?path= | Upload a file: `{dataBase64}`, capped at 14MB |
-| POST | /files/move | Move or rename one Workspace file: `{from, to, ifVersion?}` → 204. **Files only** — a directory carries no single version marker, so the precondition that protects the operation cannot be expressed for one, and it is a 400. `to`'s parent directory is created when missing. 404 `path_not_found` when `from` is gone, 409 `file_changed` when `ifVersion` no longer matches it (a source that vanished under a marker counts as changed), 409 `target_exists` when something already sits at `to` — the destination was never read, so it is refused rather than overwritten — and 400 for a move onto the file's own path |
-| DELETE | /files/content?path=&ifVersion= | Delete one Workspace file: 204. Files only (a directory is a 400); 404 `path_not_found`, and 409 `file_changed` when `ifVersion` no longer matches. The marker is optional on the wire — without it the delete is unconditional — and the Files panel always sends the one its read returned |
-| POST | /files/reveal?path= | Show the file in the machine's own file manager (macOS and Windows select it, a Linux desktop opens its directory) → 204. Only the desktop shell's own window may ask: 404 `not_found` when the server was not spawned by a shell, 403 `desktop_shell_only` for a browser session against a desktop-mode server — it cannot be told apart from a remote one, and a folder opening on the server's machine helps nobody there. The path is confined the way a read is (400 out of bounds, 404 `path_not_found`); a file manager that will not start is 502 `reveal_failed` |
-| GET | /files/search?q= | Search the whole Workspace by entry **name** (case-insensitive substring; the path is not matched) → `{hits: [{path, kind, sizeBytes, mtime}], truncated}`, each hit carrying what a directory listing's entry carries. Breadth-first from the root, so hits come shallowest-first and a capped result is the most relevant ones rather than whatever the first directory held; `truncated` says a cap stopped the walk — 200 hits, or 20000 directory entries visited. An empty `q`, or one over 100 characters, is a 400 |
-| GET | /traces | List this Session's Trace files |
-| GET | /traces/:index | Read Trace events (paginated) |
-| GET | /traces/:index/analysis | Trace performance analysis |
-| GET | /scratchpad/:fileName | Read a session scratch file (e.g. input images, file attachments) |
-
-General conventions: Sessions the user cannot access always return 404 — their existence is never leaked; only one Task or compaction runs per Session at a time, and conflicts return 409 (`task_in_progress` / `compacting`).
-
-#### The `live` field on GET /messages
-
-The Trace stores only complete messages (streaming `partial_*` never reaches disk), so history alone cannot show a message that is still streaming. While the Session is running or compacting, the messages response therefore also carries the in-progress stream tail:
+| GET | `/` | Session info |
+| PATCH | `/` | Updates the Session: `{approvalMode?, thinkingLevel?, archived?, title?}` |
+| DELETE | `/` | Deletes the Session, with its Traces and scratch files |
+| GET | `/messages` | The OmniMessage history, in full or as a window of Tasks |
+| POST | `/fork` | Forks an idle Session after a completed assistant reply: `{position: {fileIndex, ordinal}}` → `{session}` |
+| GET | `/stream` | The SSE event stream; see [Streaming (SSE)](#streaming-sse) |
+| GET | `/context` | What the current model context is made of, and where compaction will start |
+| GET | `/goal` | The Session's most recent goal run |
+
+- `GET /` returns the Session's info. Unlike the list rows, the single-Session response also carries `tracePath`, the absolute path of the latest Trace file. `orgId` marks a Session that company mode's caches own (a desk session, or a session contributing to one of that organization's tickets); it is absent on every ordinary Session, and the list route sets it too.
+- `PATCH /` with `thinkingLevel` pins the level on this Session durably, from its very next LLM request. The thinking level is soft-limited: it can change mid-context, at the cost of the provider's cached context, which is why the level picker advises compacting first. The pinned level comes back as `SessionInfo.thinkingLevel`; when that is absent, no level was ever pinned and the agent config applies.
+- `GET /messages` without parameters returns the full OmniMessage history. `tailLimit=n` reads the newest n Task-aligned units instead, and `before=<cursor>&limit=n` reads the n units before a cursor. The two forms are exclusive, `n` is between 1 and 1000, and `limit` defaults to 200. The bundled Web App opens a conversation on its latest 50 turns and loads earlier ones as you scroll. A windowed response carries `page`, with the cursor for the next page (`before`), the number of turns before the window (`earlierTurns`) and the cumulative stats before it (`prior`). While a Task runs, the response also carries `live`; see [The live field on GET /messages](#the-live-field-on-get-messages).
+- `GET /context` returns the parts the current model context is made of, plus `compactionThreshold`: the context size, in tokens, at which the Session's next request starts compaction. That threshold is the agent's `compaction.max_context_length`, capped by the room the model's context window leaves. It is `null` when compaction is disabled, when the agent's config cannot be read, or when the threshold is not below the window. The route reads the newest Trace file on every call, so the figures are a snapshot rather than a live counter.
+- `GET /goal` returns `{goal}`, which is `null` if the Session never ran a goal, or otherwise `{objective, status, budget, used, rounds}`. `status` is `active`, `complete`, `blocked`, `budget_limited` or `aborted`, and a `budget` of -1 means unlimited. A goal lives only inside its run, so a goal that still reads as active while the Session is not running is reported as `aborted`. See [Goal mode](/goal-mode).
+
+### The `live` field on GET /messages
+
+The Trace stores only complete messages, and streaming `partial_*` messages never reach disk, so history alone cannot show a message that is still streaming. While the Session is running or compacting, the messages response therefore also carries the in-progress stream tail:
```ts
interface MessagesResponse {
@@ -406,86 +692,42 @@ interface MessagesResponse {
}
```
-`cursor` and `fragments` are captured atomically before the trace read starts. A client using the connect-first pattern (below) applies them after history: when the cursor's epoch matches the epoch of the SSE events it has buffered, it drops every buffered **partial** event with seq ≤ cursor (their content is already accumulated inside `fragments`), feeds `fragments` through its normal reducer, then replays the rest of the buffer. Buffered **complete** messages are never dropped by the cursor — the regular overlap dedup decides for them. `live` is omitted while idle.
-
-`tracePosition` is history-response metadata, not part of the persisted OmniMessage envelope. The Web App submits the final assistant record's immutable coordinate to `/fork`; the server validates that it closes a completed Task. A fork clones the retained Trace shards and snapshots the source scratchpad under the new Session id, rewriting system-generated local attachment markers so the fork remains usable if either Session is later deleted. Forks made from any reply in the same source Session share a persistent, language-neutral title sequence (`Source title (1)`, `Source title (2)`); deleting an older fork does not reuse its number. Running or compacting sources return 409.
-
-Workspace files may be Agent-generated, so `GET /files/content` treats them as untrusted: every response carries `X-Content-Type-Options: nosniff`, and the rest of the headers depend on the two flags (`download=1` wins over `preview=1`):
-
-| Query | Content-Type | Content-Disposition | Content-Security-Policy |
-| --- | --- | --- | --- |
-| neither | `text/plain; charset=utf-8` for `.html` / `.htm` / `.svg`, the real type otherwise | `inline` | — |
-| `preview=1` | the real type (`text/html`, `image/svg+xml`, …) | `inline` | `sandbox allow-scripts allow-popups allow-modals allow-forms`, sent only for `.html` / `.htm` / `.svg` |
-| `download=1` | the real type | `attachment` | — |
+`cursor` and `fragments` are captured together, atomically, before the Trace read starts. A client that connects to the stream first (see [Recommended Client Pattern](#recommended-client-pattern)) applies them after the history: when the cursor's epoch matches the epoch of the SSE events it has buffered, it drops every buffered partial event with a seq at or below the cursor, since `fragments` already contains that content. It then feeds `fragments` through its normal reducer and replays the rest of the buffer. The cursor never drops buffered complete messages; the usual overlap deduplication decides those. `live` is omitted while the Session is idle.
-`GET /scratchpad/:fileName` serves the same kind of untrusted bytes (uploads and Agent-written temp files) and is locked down the same way, without the flags: `nosniff` always, a fixed allowlist of five inert image types (`.png` / `.jpg` / `.jpeg` / `.gif` / `.webp`) served inline for the conversation's `<img>` tags, and everything else `application/octet-stream` with `Content-Disposition: attachment` — so nothing that isn't one of those images can render as a document on the App's origin.
+### Forks
-The filename always rides along as `filename*=UTF-8''` with percent-encoding. `preview=1` is where the preview redirect falls back when no separate preview origin is available: the document keeps its real type and does render and run, but the sandbox deliberately omits `allow-same-origin`, so it lands in an opaque origin and can reach neither this origin's cookies nor the API. That isolation is also why `localStorage`, `document.cookie` and third-party embeds do not work there.
+`tracePosition` is metadata of the history response, not part of the persisted OmniMessage envelope. The Web App sends the immutable position of the reply's final assistant record to `/fork`, and the server checks that this record closes a completed Task.
-### Messaging Bindings (Feishu, Telegram, QQ, WeChat)
+A fork clones the retained Trace files and snapshots the source scratchpad under the new Session id, rewriting the local attachment markers the system generated, so the fork keeps working if either Session is deleted later. Forks made from any reply of the same source Session share one persistent title sequence that does not depend on the interface language (`Source title (1)`, `Source title (2)`), and deleting an older fork does not free its number. A source Session that is running or compacting returns 409.
-A Session can be connected to a messaging bot — Feishu, Telegram, QQ and WeChat are the channels today, each under `/messaging/<channel>`. A Session keeps **at most one saved config per channel** (all of them may sit saved side by side), and **at most one of them is enabled** — the enabled channel holds the live connection. Enabling is what binds the bot account to the Session and disabling releases it, so the same app or bot may sit saved on any number of Sessions and only the enable is exclusive. Inbound messages to the bot start Tasks on the Session as ordinary user input, exactly as if typed into the web composer (no marker, queued as follow-ups while the Session is busy), and completed replies are relayed back to the chat, chunked under the channel's text-size limit (Telegram's hard cap is 4096 characters). Feishu listens over the SDK's WebSocket long connection, Telegram long-polls `getUpdates`, QQ holds the platform's WebSocket gateway with the `GROUP_AND_C2C_EVENT` intent, and WeChat long-polls `ilink/bot/getupdates` — none of them needs a public callback URL. Saving and connecting are separate: PUT persists credentials only, and the explicit state endpoint owns the connection. Paths omit the `/api/sessions/:sessionId` prefix like the table above.
+### Tasks and steering
| Method | Path | Description |
| --- | --- | --- |
-| GET | /messaging | Channel-agnostic read: EVERY saved channel config (`channel` discriminant, secrets masked, per-row `enabled` intent + `linePerMessage` + `finalReplyOnly` + `renderMarkdown` + runtime status + `lastChatKnown`). The channel-aware binding editor loads this one |
-| GET | /messaging/feishu | The Feishu config in a `{binding, status}` envelope (null when not saved) |
-| PUT | /messaging/feishu | Save credentials: `{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`. An omitted/blank `appSecret` keeps the stored one; `clearAppSecret: true` drops it (a typed secret wins; 409 `messaging_disable_before_clear` while enabled — the cleared config keeps its row and non-secret fields); `baseDomain` defaults to `https://open.feishu.cn`. No connection side effect — except that an **enabled** binding's connector restarts with the new credentials, so stored config and live connection never diverge. A save never conflicts across Sessions, with one exception that follows from that restart: re-pointing an **enabled** binding at an account ANOTHER Session has enabled answers 409 `account_enabled_elsewhere`, because the restart would otherwise carry a second live connection onto it without passing the enable gate |
-| POST | /messaging/feishu/state | The connection toggle: `{enabled}` — enabling connects with the STORED credentials, disabling terminates. 409 `another_channel_enabled` while the Session's other channel is enabled, 409 `account_enabled_elsewhere` while ANOTHER Session has the same account enabled (both mean: turn that one off first — the second names nothing about the holder, which may sit in a Project the caller cannot see); 400 `feishu_secret_required` when the stored config has no secret. New configs start disabled; server startup connects only enabled ones |
-| DELETE | /messaging/feishu | Remove this channel's config entirely (App Secret included; the other channel is untouched). API completeness only — the web UI's removal affordance is the clear flag |
-| POST | /messaging/feishu/test | Credential probe with the request's draft values, each falling back to the stored config → `{ok, latencyMs?, error?}` (a rejected credential is `ok: false`, not an HTTP error) |
-| POST | /messaging/feishu/test-message | Send a short fixed text to the last known chat; 409 `feishu_no_chat` until the bot has been messaged once in Feishu |
-| GET | /messaging/telegram | The Telegram config in the same envelope (`botId`, `botTokenMasked`) |
-| PUT | /messaging/telegram | Save the credential: `{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` — the whole credential is the one `<bot id>:<secret>` token from @BotFather (omitted/blank keeps the stored one; 400 `telegram_token_invalid` when the numeric id cannot be read; the clear flag works like Feishu's and the cleared config keeps its bot identity). Same save/enable split, the same 409 `account_enabled_elsewhere` when an enabled binding's token is swapped for one another Session has enabled, and otherwise the same absence of a cross-Session conflict on save |
-| POST | /messaging/telegram/state | Same contract as the Feishu toggle (400 `telegram_token_required` without a stored token) |
-| DELETE | /messaging/telegram | Remove this channel's config entirely (Bot Token included). API completeness only |
-| POST | /messaging/telegram/test | Credential probe (`getMe`) with the draft token falling back to the stored one → `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}` — success names the bot the token signs in as, and reports `groupPrivacy: true` when @BotFather's Group Privacy is on (the default), under which the bot receives no ordinary message in any group it does not administer |
-| POST | /messaging/telegram/test-message | Send a short fixed text to the last known chat; 409 `telegram_no_chat` until the bot has been messaged once in Telegram |
-| GET | /messaging/qq | The QQ config in the same envelope (`appId`, `appSecretMasked`) |
-| PUT | /messaging/qq | Save the credential pair: `{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` — the App ID and App Secret from the QQ open platform's development settings. Same keep-on-blank, clear flag and save/enable split as the Feishu PUT, the same 409 `account_enabled_elsewhere` when an enabled binding's App ID is swapped for one another Session has enabled, and no cross-Session conflict on save otherwise; there is no domain field, because API v2 has one host |
-| POST | /messaging/qq/state | Same contract as the other toggles (400 `qq_secret_required` without a stored secret) |
-| DELETE | /messaging/qq | Remove this channel's config entirely (App Secret included). API completeness only |
-| POST | /messaging/qq/test | Credential probe (the app-access-token exchange) → `{ok, latencyMs?, error?}`. No account label: the platform has no call that identifies the bot |
-| POST | /messaging/qq/scan | Start scan-to-connect: the server registers a bind task under a fresh AES key it keeps → `{taskId, qrUrl, pollMs}`. Render `qrUrl` as a QR code; it is opened by the QQ app, never fetched. 409 `messaging_disable_before_scan` while this Session's QQ connection is enabled — a scan rewrites both halves of the credential under a live connector; 502 `qq_scan_failed` when the platform refuses |
-| POST | /messaging/qq/scan/poll | `{taskId}` → `{status, appId?, binding?}`. `completed` means the server already decrypted the App Secret and **saved** the binding (enabling stays separate); `expired` means start a new task. 404 `qq_scan_task_unknown` for an unknown, foreign or already-resolved task |
-| POST | /messaging/qq/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its key is forgotten now rather than at the sweep |
-| POST | /messaging/qq/test-message | Send a short fixed text to the last known chat; 409 `qq_no_chat` until the bot has been messaged once in QQ, and 502 `qq_send_failed` when no recent QQ message can be replied to (see below) |
-| GET | /messaging/wechat | The WeChat config in the same envelope (`botId`, `botTokenMasked`) |
-| PUT | /messaging/wechat | Save the delivery preferences ONLY: `{clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`. The one PUT here that carries no credential — a WeChat bot token exists only where a scan put it, and there is no console to copy one out of — so it presupposes a binding and answers 400 `wechat_token_required` before one exists. The clear flag works like the others' (409 `messaging_disable_before_clear` while enabled; the cleared config keeps its row and its bot identity, and only a fresh scan makes it connectable again) |
-| POST | /messaging/wechat/state | Same contract as the other toggles (400 `wechat_token_required` without a stored token) |
-| DELETE | /messaging/wechat | Remove this channel's config entirely (bot token included). API completeness only |
-| POST | /messaging/wechat/test | Credential probe (`ilink/bot/getconfig` on behalf of the account that scanned) → `{ok, latencyMs?, error?}`. The only test here that takes NO body: nothing on this channel is typed, so the stored binding is the only thing to probe (400 `wechat_token_required` without one). No account label — the probe names neither the bot nor the person |
-| POST | /messaging/wechat/scan | Start scan-to-connect, which on this channel is the ONLY way to bind → `{taskId, qrUrl, pollMs}`. Render `qrUrl` as a QR code; it is opened by WeChat, never fetched. The platform's own poll handle — the thing that collects the bot token — stays on the server, and `taskId` is a handle this server mints in its place. 409 `messaging_disable_before_scan` while the connection is enabled; 502 `wechat_scan_failed` when the platform refuses |
-| POST | /messaging/wechat/scan/poll | `{taskId}` → `{status, botId?, binding?}`. `status` is one of `pending`, `scanned`, `need_verify_code`, `blocked`, `expired`, `already_bound`, `completed`. `completed` means the server already **saved** the binding (enabling stays separate); `already_bound` is not a failure — the bot is bound already and nothing new was issued. It does not say WHERE: the scan offers the platform no token list, so it cannot distinguish a binding on this server from one anywhere else. 404 `wechat_scan_task_unknown` for an unknown, foreign or already-resolved task. Unlike QQ's poll, an OVERLAPPING request answers `pending` rather than 404: the upstream call is a long poll and spans several client intervals |
-| POST | /messaging/wechat/scan/verify | `{taskId, verifyCode}` → 204. The pairing code WeChat showed on the phone. It rides the NEXT poll rather than a request of its own, because the platform takes it as a parameter of its status call, so this only records it — a wrong code surfaces as the next poll reporting `need_verify_code` again |
-| POST | /messaging/wechat/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its handle is forgotten now rather than at the sweep |
-| POST | /messaging/wechat/test-message | Send a short fixed text to the last known chat; 409 `wechat_no_chat` until the bot has been messaged once in WeChat |
-
-Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage`, `finalReplyOnly` and `renderMarkdown` are the three saved fields that are not credentials. With `linePerMessage` set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap). With `finalReplyOnly` set, a run relays only its LAST completed assistant message, delivered when the run ends, instead of mirroring each one as it completes — the working notes a run writes between tool calls stay in the web app, and the files that follow the reply are then read from that final message alone, since it is the only text the chat received. The two compose: with both set, the final reply is the one split per line. Both default to false, an omitted value on a PUT keeps the stored one, and neither applies to the notices or the test message — the approval reminder in particular is not a reply and arrives immediately whatever `finalReplyOnly` says. `renderMarkdown` renders a relayed reply's Markdown in the channel's own markup instead of sending its characters as written; it **defaults to true**, an omitted value on a PUT keeps the stored one, and it likewise never applies to the notices or the test message. Each channel shows what it can and degrades the rest deliberately rather than leaking the source: Telegram sends `parse_mode: "HTML"` and has no headings, lists or tables (a heading becomes a bold line, list markers become literal text, a table becomes a `<pre>` block); Feishu sends an interactive card carrying the JSON 2.0 rich-text component and renders everything, over-long tables becoming code blocks so no row is silently dropped; QQ sends `msg_type: 2` free-form markdown and has no code formatting and no tables (a fenced block becomes plain escaped lines, a table becomes its rows); WeChat reads Markdown itself, so rendering SUBTRACTS rather than translates — what the client will not show keeps its words and loses its markers (headings past the fourth level, emphasis around CJK, and inline images, which become links). Chunking follows the setting, cutting at block boundaries and re-fencing a code block that spans messages, so no message opens a construct it does not close. **A formatted send the channel refuses falls back to a plain-text send of the same message**, so the setting can cost formatting and never a reply. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation), and WeChat's is the bot id the scan returns. Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs. Inbound processing accepts text, images and files: an image becomes an ordinary `image_url` input part, capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. A file becomes the composer's other attachment shape — written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line, so its bytes never enter the conversation — under the same admin-settable per-file and per-message attachment caps an authenticated upload answers to, narrowed further by any tighter ceiling the channel itself has (Telegram serves a bot no file over 20MB). Feishu takes the `file` message type and Telegram the `document` field: a file the sender chose to send AS a file, which is also the only one of Telegram's media fields carrying the sender's own name. Video, audio and voice are deliberately not delivered on those two channels — nothing downstream decodes or transcribes them, and what a sender wants the Agent to have arrives as a file the moment they attach it as one. WeChat is the exception, and only because the platform does the work itself: it ships its own transcription with a voice message, and a video arrives as an ordinary file. The caption of a message whose attachment IS delivered (a photo, a document) is that message's text; a caption on any other media kind is not, since its bytes never arrive and running the model on the caption alone answers about a file it never received. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, as do a file over a cap, a batch over the per-message total and a file the channel refuses; none of them runs half a message, and a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). None of the ways a mentioned file does not arrive is posted in the chat. They are filed as error records under the Project, where the Cost Center's errors table shows them, one record per reply for each cause, naming every file it covers, the channel and the reason: `messaging_file_too_large` for the files over a cap, `messaging_files_skipped` for those past the count cap, and `messaging_file_send_failed` for uploads that were refused — one record for uploads the channel can never carry (any file on QQ), one for a missing permission (the scopes to grant and the console link listed once, in place of the channel's reason for each file) and one for any other refusal. The first two and the uploads a channel can never carry are `expected`; a missing permission and every other refusal are `unexpected`. A name that matches no file in the Workspace is only logged, and a file the run did not write is dropped silently, because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.
-**QQ is a reply-only channel, and it changes what delivery means.** The platform accepts no push this product may use: every outbound message is a *passive reply* carrying the `msg_id` of an inbound one, valid for a few minutes and capped at 4 replies per message in a single chat (5 in a group). Three consequences are visible through this API. A run that completes more assistant messages than the budget allows has them **coalesced** — the first `budget - 1` go out as they complete and the rest arrive combined in one final message, so nothing is dropped. `linePerMessage` is **clamped to that budget** rather than to the channel-neutral cap of 20, and a `renderMarkdown` send the platform refuses spends a second slot on its plain-text retry. `finalReplyOnly` cuts both ways here: it spends the least budget a run can spend — one reply — but the passive-reply window is only a few minutes wide, and holding the reply until the run ends spends that window on the run, so a run that outlives it delivers nothing at all where an every-message relay would have sent whatever completed inside it. And a send with nothing to reply to — a turn started in the web app, or any reply after the window closed — is **refused rather than pushed**, surfacing as 502 `qq_send_failed` on the test endpoint and as one `messaging_send_failed` error record for a relayed reply. QQ's account identity is the App ID. Outbound files are refused on this channel: the platform's rich-media path requires a publicly reachable URL for the bytes.
-**WeChat carries direct chats only, and the most media of the four.** The claw bot channel has no group inbound at all: a message addressed to the bot in a group never reaches this API, so a binding that answers a direct chat perfectly is silent in a group by design rather than by misconfiguration. In exchange it is the only channel here that carries text, images and files in BOTH directions — a reply's pictures and attachments are uploaded to the platform's CDN (AES-128-ECB under a per-file key) and arrive as real images and files rather than being refused. Two inbound kinds are folded: a voice message is relayed as WeChat's own transcription of it, and a video arrives as a file; a recording the platform could not transcribe reaches the chat as the shared not-supported notice.
-
-**Scan-to-connect never shows the browser the secret.** Whatever makes the flow safe stays on the server — the AES key that decrypts QQ's App Secret, and the poll handle that collects WeChat's bot token — generated, held, used and dropped there; the client is given only a task handle, a URL to draw, and a status. Tasks live in memory, are scoped to the Session that started them, are bounded per Session so one caller's scans cannot evict another's, and are claimed by the poll that resolves them, so a replay reads as 404 rather than as a second bind. On QQ a second concurrent poll of one task reads as 404 too; on WeChat it answers `pending`, because the upstream call is a long poll that spans several client intervals. Every scan route is owner-only, because the flow ends in a stored credential however little of it the caller types.
-
-### Preview on a separate origin
-
-Both the Files panel's rendered HTML view (an iframe) and "open in a new tab" go through `GET /files/preview-redirect?path=`, which authenticates the caller, then mints a short-lived HMAC token and 302s to a **different origin**:
-
-```text
-GET /api/sessions/:sessionId/files/preview-redirect?path=index.html
-302 Location: http://localhost:7364/preview/<token>/index.html
-GET /preview/<token>/<relative path> (unauthenticated; the token is the credential)
-```
-
-- **Why a separate origin.** The page needs a real origin to have working storage, cookies and third-party embeds — but it must not be the app's origin, or Agent-written HTML would run with the session cookie. Locally the app is canonicalized onto `localhost` and previews are served from `127.0.0.1`; cookies are keyed by host and ignore port, so those are separate cookie jars while a second port would not be. Otherwise `PENGUIN_PREVIEW_ORIGIN` applies; with neither (a wildcard or non-loopback bind, or the variable unset), the redirect falls back to the same-origin sandbox above and `previewIsolated` on `GET /api/me` reports `false` so the UI can say so first.
-- **In-app rendering rides the same URL.** The Files panel embeds the redirect URL in an iframe sandboxed with `allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads` — `allow-same-origin` grants the preview origin's identity, not the App's, so this stays strictly tighter than the sandbox-free new tab. Without a separate preview origin the panel instead falls back to inline `srcdoc` rendering (`allow-scripts` only, plus an in-memory storage shim), where relative subresources cannot load. Note that some browsers partition or block storage inside a cross-site iframe, so a page may behave slightly differently in the panel than in the top-level tab.
-- **The preview host serves only `/preview/*`.** It is the same process as the app, so it answers `/api` with `401` and `302`s every other route to the canonical app host. A session cookie is therefore never set or honored on the preview host, and Agent HTML there cannot reach the API same-origin. (For a deployed `PENGUIN_PREVIEW_ORIGIN`, the reverse proxy must enforce the equivalent: route only `/preview/*` to the app on that origin.)
-- **Path-based, not a query parameter**, so a page's relative subresources (`app.js`, `style.css`, images) resolve against the document and load under the same token.
-- **The token binds the Session, the preview host and an expiry.** The host binding is load-bearing: the same process also answers on the app origin, so `/preview/...` refuses to serve there — otherwise it would be a same-origin XSS. Access is read-only and scoped to that Session's Workspace, and the path is re-resolved server-side, so `..` and symlink escapes are rejected as before.
-- **Responses carry `Referrer-Policy: no-referrer`**, or the token-bearing URL would leak through `Referer` to every third party the page embeds — a risk that exists precisely because embeds now work.
-- Bad token, expired token, wrong host and out-of-bounds path all answer a bare 404: the endpoint is unauthenticated and must not confirm what exists.
-
-Key request bodies (explicit keys):
+| POST | `/tasks` | Starts a Task: `{input: TaskInputPart[], queueIfBusy?, goal?}` → 202 |
+| POST | `/steer` | Queues a steering message for the running Task: `{text, images?}` → 202 |
+| DELETE | `/steer/:steerId` | Recalls a steering message that has not been delivered yet |
+| DELETE | `/follow-ups/:followUpId` | Recalls a queued follow-up Task |
+| POST | `/approvals/:toolCallId` | Approval decision: `{decision}`, `allow` or `deny` → 204 |
+| POST | `/tool-calls/:toolCallId/background` | Moves one executing tool call to the background → 204 |
+| POST | `/subagents/:childSessionId/message` | Sends a message to one subagent child: `{text}` → `{outcome}` |
+| POST | `/subagents/:childSessionId/abort` | Stops one subagent child's current run |
+| POST | `/abort` | Interrupts the current Task: 202 when triggered, 204 when idle |
+| POST | `/retry-now` | Skips the reconnect countdown: → 200 `{skipped}` |
+| POST | `/compact` | Starts context compaction: 202 |
+
+- `POST /tasks` answers `{sessionId, queued?}`. With `queueIfBusy`, a busy Session holds the input as a follow-up (`queued: true`) and starts it as an ordinary next Task once the Session is idle; `task_state` events report the number queued. `file` input parts are written to the Session scratchpad and handed to the model as `[attached file: <path>]` lines (see [Request bodies](#request-bodies)).
+- `POST /tasks` with `goal: {budget?}` starts a goal loop instead. It returns 409 `goal_plugin_not_installed` unless the `goal` plugin is installed on the agent. The objective is the input's text, with any leading marker blocks removed, so the input must carry non-empty text (400 otherwise): an image alone states no objective. Images are sent in round 1 as ordinary input, and later rounds re-inject only the objective text. `file` parts are refused with 400, because nothing carries them into the objective that every round re-injects. See [Goal mode](/goal-mode).
+- `POST /steer` delivers the message between turns as a standalone `[user_steering]` user message, with its images right after it. Either field can carry the message on its own, but a request with neither returns 400. It returns 409 `not_running` when no Task is in progress.
+- `DELETE /steer/:steerId` takes an id from `pendingSteering` in `task_state` and withdraws that message from the queue. It answers 200 with the original content, `{text, images, files}`, so the composer can restore it for editing: files are read back from the scratchpad as data URLs, and their copies on disk are deleted. Once the message was delivered to the model, it returns 409 `not_pending`.
+- `DELETE /follow-ups/:followUpId` takes an id from `pendingFollowUps` in `task_state` and removes that follow-up before it starts. It answers 200 with the original content, `{text, images, files}`, which every queued follow-up carries however it was queued. It returns 409 `follow_up_started` once the follow-up has started or when the id is unknown.
+- `POST /tool-calls/:toolCallId/background` hands one executing tool call back as a background task, so the turn can close and the conversation can continue. The call ends as `completed` with its `process_id` or `subagent_id`, nothing is killed, and the result arrives later as the usual background-task notice. It returns 404 `tool_call_not_found` when nothing with that id is executing (the id is unknown, the call already finished, or the runtime is gone), and 409 `tool_not_detachable` when the call is running but its tool has no background form. Only `exec_command` and `run_subagent` have one.
+- `POST /subagents/:childSessionId/message` delivers the text as user input to the child, whatever its state. `outcome` is `steered` when the child was running and the message was queued as steering, `started` when the idle child began a follow-up run, and `resumed` when a released child was revived and began its next round. The child runs at its own context's thinking level, which you can pin with `PATCH` on the child Session. An empty `text` returns 400, 404 `subagent_gone` means the child's record does not exist or cannot be revived, and 409 `subagent_busy` means the child cannot take a message right now.
+- `POST /subagents/:childSessionId/abort` stops only the child's current run; the child Session stays available for steering and follow-ups. It returns 202 when a run was stopped, and 204 when the child is already idle or unknown.
+- `POST /retry-now` backs the **Retry now** button on the reconnect countdown. It skips the backoff wait in progress and fires the next retry immediately, without changing the attempt counter. `skipped: false` means no wait was in progress; it is not an error.
+- `POST /compact` returns 409 when there is nothing to compact, with the reason in the code: `compaction_not_configured` (the agent has no compaction configured), `nothing_to_compact` (the context has no completed conversation turn yet) or `already_compacted` (nothing new was said since the last compaction). A Session resumed after a server restart works this out from its Trace, so an existing conversation can be compacted without running a Task first.
+
+### Request bodies
```ts
// POST /api/sessions/:sessionId/tasks — start a Task
@@ -513,71 +755,378 @@ interface ApprovalDecisionRequest {
}
```
-The Web's `/model` switch has no dedicated endpoint: like the `/agent` handoff, it composes the ordinary APIs above — session creation opens a new Session for the same Agent (the chosen model, the source Workspace carried over), then POST /tasks sends a first message opening with a `[model_switch_from]` source block (the source session id, its `tracePath`, the Workspace, and the previous model pair); the model reads that Trace file itself when it needs the earlier history.
+The Web App's `/model` switch has no dedicated endpoint. Like the `/agent` handoff, it combines ordinary routes:
+
+1. Session creation opens a new Session for the same agent, with the chosen model and the source Workspace carried over.
+2. `POST /tasks` sends a first message that opens with a `[model_switch_from]` source block, naming the source session id, its `tracePath`, the Workspace and the previous model pair.
+3. The model reads that Trace file itself when it needs the earlier history.
+
+### Background processes
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | `/processes` | The background processes the conversation started |
+| POST | `/processes/:processId/kill` | Stops one background process |
+| DELETE | `/processes/:processId` | Removes one exited process from the list |
+
+- `GET /processes` lists the `exec_command` calls that moved to the background past their yield window. The list comes from the active runtime only, so a Session that was unloaded or never loaded correctly reports an empty list. A row carries `serviceUrl` when the server detected an address the process serves: the last local URL the output printed, or else a listening port found by probing the process group, refreshed on each request.
+- `POST /processes/:processId/kill` sends SIGTERM to the whole process group, then SIGKILL after a grace period, and the entry leaves the list. It returns 404 `process_not_found` when the process is already gone.
+- `DELETE /processes/:processId` returns 409 `process_running` while the process still runs (stop it instead) and 404 `process_not_found` when the entry is already gone. The entry leaves the runtime registry together with the output captured from it, so a later `input_command` on that `process_id` fails.
+
+### Workspace files
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | `/files?path=` | Browses a Workspace directory |
+| GET | `/files/content?path=&download=&preview=` | Reads a Workspace file (see [Workspace file responses](#workspace-file-responses)) |
+| GET | `/files/preview-redirect?path=` | Opens an HTML file on the separate preview origin: mints a signed token and redirects with 302 |
+| POST | `/files/stat` | Checks whether files exist: `{paths}` |
+| PUT | `/files/content?path=` | Uploads a file: `{dataBase64}`, up to 14MB |
+| POST | `/files/move` | Moves or renames one file: `{from, to, ifVersion?}` → 204 |
+| DELETE | `/files/content?path=&ifVersion=` | Deletes one file → 204 |
+| POST | `/files/reveal?path=` | Shows the file in the machine's own file manager → 204 |
+| GET | `/files/search?q=` | Searches the whole Workspace by entry name |
+| GET | `/scratchpad/:fileName` | Reads a scratch file of the Session, such as an input image or file attachment |
+
+- `GET /files/preview-redirect` backs **Open in new tab** and the rendered HTML view of the **Files** panel; see [Preview on a separate origin](#preview-on-a-separate-origin).
+- `POST /files/move` works on files only: a directory has no single version marker, so the precondition that protects the move cannot be expressed for one, and the route returns 400. Missing parent directories of `to` are created. It returns 404 `path_not_found` when `from` is gone, and 409 `file_changed` when `ifVersion` no longer matches (a source that disappeared while a marker was given counts as changed). It returns 409 `target_exists` when something is already at `to`, because the destination was never read and so is refused rather than overwritten, and 400 for a move onto the file's own path.
+- `DELETE /files/content` also works on files only (400 for a directory). It returns 404 `path_not_found` when the file is gone, and 409 `file_changed` when `ifVersion` no longer matches. The marker is optional, and without it the delete is unconditional, but the **Files** panel always sends the marker its read returned.
+- `POST /files/reveal` selects the file on macOS and Windows, and opens its directory on a Linux desktop. Only the desktop shell's own window may call it. It returns 404 `not_found` when the server was not started by a desktop shell, and 403 `desktop_shell_only` for a browser session against a desktop-mode server: such a session cannot be told apart from a remote one, and a folder opening on the server's machine helps nobody there. The path is confined the same way as for a read (400 out of bounds, 404 `path_not_found`), and 502 `reveal_failed` means the file manager would not start.
+- `GET /files/search` matches entry names only (a case-insensitive substring; the path is not matched) and answers `{hits: [{path, kind, sizeBytes, mtime}], truncated}`, each hit carrying what a directory listing entry carries. The search walks breadth-first from the root, so hits come shallowest first, and a capped result keeps the most relevant hits rather than whatever the first directory held. `truncated` means a cap stopped the walk: 200 hits, or 20000 directory entries visited. An empty `q`, or one longer than 100 characters, returns 400.
+
+### Workspace file responses
+
+Workspace files may be generated by an agent, so `GET /files/content` treats them as untrusted. Every response carries `X-Content-Type-Options: nosniff`, and the other headers depend on the two flags, where `download=1` wins over `preview=1`:
+
+| Query | Content-Type | Content-Disposition | Content-Security-Policy |
+| --- | --- | --- | --- |
+| neither | `text/plain; charset=utf-8` for `.html` / `.htm` / `.svg`, the real type otherwise | `inline` | — |
+| `preview=1` | the real type (`text/html`, `image/svg+xml`, …) | `inline` | `sandbox allow-scripts allow-popups allow-modals allow-forms`, sent only for `.html` / `.htm` / `.svg` |
+| `download=1` | the real type | `attachment` | — |
+
+The file name is always sent as `filename*=UTF-8''` with percent-encoding.
+
+`preview=1` is where the preview redirect falls back when no separate preview origin is available. The document keeps its real type and does render and run, but the sandbox deliberately omits `allow-same-origin`. The document therefore lands in an opaque origin and can reach neither this origin's cookies nor the API, which is also why `localStorage`, `document.cookie` and third-party embeds do not work there.
+
+`GET /scratchpad/:fileName` serves the same kind of untrusted bytes (uploads and temporary files an agent wrote) and is locked down the same way, without the flags:
+
+- `X-Content-Type-Options: nosniff` is always sent.
+- A fixed allowlist of five inert image types (`.png` / `.jpg` / `.jpeg` / `.gif` / `.webp`) is served inline, for the conversation's `<img>` tags.
+- Everything else is served as `application/octet-stream` with `Content-Disposition: attachment`, so nothing except those images can render as a document on the app's origin.
+
+### Preview on a separate origin
+
+The **Files** panel's rendered HTML view (an iframe) and **Open in new tab** both go through `GET /files/preview-redirect?path=`. This route authenticates the caller, mints a short-lived HMAC token, and redirects with 302 to a **different origin**:
+
+```text
+GET /api/sessions/:sessionId/files/preview-redirect?path=index.html
+302 Location: http://localhost:7364/preview/<token>/index.html
+GET /preview/<token>/<relative path> (unauthenticated; the token is the credential)
+```
+
+- Why a separate origin: the page needs a real origin for storage, cookies and third-party embeds to work, but it must not be the app's origin, or HTML an agent wrote would run with the session cookie. Locally, the app is canonicalized onto `localhost` and previews are served from `127.0.0.1`. Cookies are keyed by host and ignore the port, so those two hosts get separate cookie jars, which a second port would not. Otherwise `PENGUIN_PREVIEW_ORIGIN` applies. With neither (a wildcard or non-loopback bind, or the variable unset), the redirect falls back to the same-origin sandbox described above, and `previewIsolated` on `GET /api/me` reports `false` so the UI can tell the user first.
+- In-app rendering uses the same URL: the **Files** panel embeds the redirect URL in an iframe sandboxed with `allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads`. Here `allow-same-origin` grants the preview origin's identity, not the app's, so this stays strictly tighter than the new tab, which has no sandbox. Without a separate preview origin, the panel falls back to inline `srcdoc` rendering (`allow-scripts` only, plus an in-memory storage shim), where relative subresources cannot load. Some browsers partition or block storage inside a cross-site iframe, so a page may behave slightly differently in the panel than in a top-level tab.
+- The preview host serves only `/preview/*`. It is the same process as the app, so it answers `/api` with `401` and redirects every other route with `302` to the canonical app host. A session cookie is therefore never set or accepted on the preview host, and agent HTML there cannot reach the API from the same origin. For a deployed `PENGUIN_PREVIEW_ORIGIN`, the reverse proxy must enforce the same thing: route only `/preview/*` to the app on that origin.
+- The token sits in the path, not in a query parameter, so a page's relative subresources (`app.js`, `style.css`, images) resolve against the document and load under the same token.
+- The token binds the Session, the preview host and an expiry time. The host binding matters: the same process also answers on the app origin, so `/preview/...` refuses to serve there, which would otherwise be a same-origin XSS. Access is read-only and limited to that Session's Workspace, and the server resolves the path again, so `..` and symlink escapes are rejected as for any read.
+- Responses carry `Referrer-Policy: no-referrer`. Otherwise the URL, with its token, would leak through `Referer` to every third party the page embeds, a risk that exists precisely because embeds now work.
+- A bad token, an expired token, the wrong host and a path out of bounds all return a bare 404: the endpoint is unauthenticated and must not confirm what exists.
+
+### Traces
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | `/traces` | Lists this Session's Trace files |
+| GET | `/traces/:index` | Reads Trace events (paginated) |
+| GET | `/traces/:index/analysis` | Trace performance analysis |
+
+## Messaging Bindings (Feishu, Telegram, QQ, WeChat)
+
+A Session can be connected to a messaging bot. The channels today are Feishu, Telegram, QQ and WeChat, each under `/messaging/<channel>`. The paths below omit the `/api/sessions/:sessionId` prefix, like the Session-level tables.
+
+- A Session keeps at most one saved config per channel, and all its channels may be saved side by side. At most one of them is enabled, and the enabled channel holds the live connection.
+- Enabling binds the bot account to the Session, and disabling releases it. The same app or bot can therefore be saved on any number of Sessions; only enabling is exclusive.
+- Saving and connecting are separate: PUT only stores the credentials, and the `state` route owns the connection. New configs start disabled, and at startup the server connects only the enabled ones.
+- Messages sent to the bot start Tasks on the Session as ordinary user input, exactly as if typed into the web composer: no marker is added, and they queue as follow-ups while the Session is busy. Completed replies are relayed back to the chat, split into chunks of at most 4000 characters, which stays under Telegram's hard cap of 4096.
+- Feishu listens over the SDK's WebSocket long connection, Telegram long-polls `getUpdates`, QQ holds the platform's WebSocket gateway with the `GROUP_AND_C2C_EVENT` intent, and WeChat long-polls `ilink/bot/getupdates`. None of them needs a public callback URL.
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | `/messaging` | Every saved channel config of the Session |
+| GET | `/messaging/feishu` | The Feishu config, as `{binding, status}` (`null` when not saved) |
+| PUT | `/messaging/feishu` | Saves the Feishu credentials: `{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/feishu/state` | Turns the connection on or off: `{enabled}` |
+| DELETE | `/messaging/feishu` | Removes the Feishu config entirely, App Secret included |
+| POST | `/messaging/feishu/test` | Tests the credentials: → `{ok, latencyMs?, error?}` |
+| POST | `/messaging/feishu/test-message` | Sends a short fixed text to the last known chat |
+| GET | `/messaging/telegram` | The Telegram config in the same envelope (`botId`, `botTokenMasked`) |
+| PUT | `/messaging/telegram` | Saves the Telegram credential: `{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/telegram/state` | Turns the connection on or off: `{enabled}` |
+| DELETE | `/messaging/telegram` | Removes the Telegram config entirely, Bot Token included |
+| POST | `/messaging/telegram/test` | Tests the token with `getMe`: → `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}` |
+| POST | `/messaging/telegram/test-message` | Sends a short fixed text to the last known chat |
+| GET | `/messaging/qq` | The QQ config in the same envelope (`appId`, `appSecretMasked`) |
+| PUT | `/messaging/qq` | Saves the QQ credential pair: `{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/qq/state` | Turns the connection on or off: `{enabled}` |
+| DELETE | `/messaging/qq` | Removes the QQ config entirely, App Secret included |
+| POST | `/messaging/qq/test` | Tests the credentials with the app-access-token exchange: → `{ok, latencyMs?, error?}` |
+| POST | `/messaging/qq/scan` | Starts scan-to-connect: → `{taskId, qrUrl, pollMs}` |
+| POST | `/messaging/qq/scan/poll` | Polls a scan: `{taskId}` → `{status, appId?, binding?}` |
+| POST | `/messaging/qq/scan/cancel` | Drops a scan: `{taskId}` |
+| POST | `/messaging/qq/test-message` | Sends a short fixed text to the last known chat |
+| GET | `/messaging/wechat` | The WeChat config in the same envelope (`botId`, `botTokenMasked`) |
+| PUT | `/messaging/wechat` | Saves the delivery preferences only: `{clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/wechat/state` | Turns the connection on or off: `{enabled}` |
+| DELETE | `/messaging/wechat` | Removes the WeChat config entirely, bot token included |
+| POST | `/messaging/wechat/test` | Tests the stored binding with `ilink/bot/getconfig`: → `{ok, latencyMs?, error?}` |
+| POST | `/messaging/wechat/scan` | Starts scan-to-connect, the only way to bind WeChat: → `{taskId, qrUrl, pollMs}` |
+| POST | `/messaging/wechat/scan/poll` | Polls a scan: `{taskId}` → `{status, botId?, binding?}` |
+| POST | `/messaging/wechat/scan/verify` | Records the pairing code shown on the phone: `{taskId, verifyCode}` → 204 |
+| POST | `/messaging/wechat/scan/cancel` | Drops a scan: `{taskId}` |
+| POST | `/messaging/wechat/test-message` | Sends a short fixed text to the last known chat |
+
+### Configs and permissions
+
+- `GET /messaging` is the channel-agnostic read that the binding editor loads. Each row carries the `channel` discriminant, masked secrets, the `enabled` intent, `linePerMessage`, `finalReplyOnly`, `renderMarkdown`, the runtime status and `lastChatKnown`.
+- Masked secrets are omitted from responses when no secret is stored (a cleared config), and a config without a secret cannot be enabled. Secrets never go back to the client.
+- Reads and the two test routes are open to any Project member. PUT, the `state` toggle and DELETE are owner only, with the same semantics as the vault, because these writes carry or act on the secret. Every scan route is owner only too (see [Scan-to-connect](#scan-to-connect)).
+- DELETE removes one channel's config entirely and leaves the other channels untouched. It exists for API completeness; the Web App removes a secret with the clear flag instead. Deleting the Session removes all its configs.
+- The only rule across Sessions is per bot account per channel, and it applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu identifies the account by its `app_id`, Telegram by the numeric bot id before the token's colon (which survives token rotation), QQ by the App ID, and WeChat by the bot id the scan returns.
+
+### Saving and connecting
+
+- A PUT with an omitted or blank secret keeps the stored one. The clear flag (`clearAppSecret` or `clearBotToken`) drops the stored secret, but a secret typed in the same request wins. While the channel is enabled, clearing returns 409 `messaging_disable_before_clear`. A cleared config keeps its row and its non-secret fields, including a Telegram or WeChat bot's identity.
+- A PUT has no effect on the connection, with one exception: when the binding is enabled, its connector restarts with the new credentials, so the stored config and the live connection never diverge. A save therefore never conflicts across Sessions, except when it points an enabled binding at an account that another Session has enabled. That returns 409 `account_enabled_elsewhere`, because the restart would otherwise bring a second live connection onto the account without passing the enable check.
+- `POST …/state` with `{enabled: true}` connects with the stored credentials, and `{enabled: false}` disconnects. It returns 409 `another_channel_enabled` while another channel of this Session is enabled, and 409 `account_enabled_elsewhere` while another Session has the same account enabled. Both mean: turn that one off first. The second names nothing about the holder, which may be in a Project the caller cannot see. Without a stored secret, the toggle returns 400 `feishu_secret_required`, `telegram_token_required`, `qq_secret_required` or `wechat_token_required`.
+- The Feishu, Telegram and QQ test routes probe with the draft values in the request, each falling back to the stored config; the WeChat test takes no body (see below). A rejected credential is `ok: false`, not an HTTP error.
+- The test-message routes return 409 `feishu_no_chat`, `telegram_no_chat`, `qq_no_chat` or `wechat_no_chat` until someone has messaged the bot once in that app.
+
+### Per-channel details
+
+- Feishu: `baseDomain` defaults to `https://open.feishu.cn`.
+- Telegram: the whole credential is the one `<bot id>:<secret>` token that @BotFather issues. A token whose numeric id cannot be read returns 400 `telegram_token_invalid`. A successful test names the bot the token signs in as (`botUsername`) and reports `groupPrivacy: true` when @BotFather's Group Privacy is on, which it is by default. With Group Privacy on, the bot receives no ordinary messages in any group it does not administer.
+- QQ: the credentials are the App ID and App Secret from the development settings of the QQ open platform. There is no domain field, because API v2 has a single host. The test reports no account name, because the platform has no call that identifies the bot. The test message also returns 502 `qq_send_failed` when there is no recent QQ message to reply to; see [QQ](#qq).
+- WeChat: its PUT is the only one without a credential. A WeChat bot token exists only where a scan put it, and there is no console to copy one from, so the PUT requires an existing binding and returns 400 `wechat_token_required` before one exists. A cleared WeChat config can connect again only after a fresh scan. The test route is the only one that takes no body: nothing on this channel is typed in, so the stored binding is all there is to probe (400 `wechat_token_required` without one). The test names neither the bot nor the person who scanned.
+
+### QQ
+
+QQ is a reply-only channel, and that changes what delivery means. The platform offers no push this product may use: every outbound message is a passive reply that carries the `msg_id` of an inbound message, is valid for a few minutes, and is limited to 4 replies per message in a single chat (5 in a group). Three consequences show through this API:
+
+- A run that completes more assistant messages than the reply budget has them combined: the first `budget - 1` go out as they complete, and the rest arrive together in one final message, so nothing is dropped.
+- `linePerMessage` is limited to that budget rather than to the usual cap of 20 messages, and a `renderMarkdown` send the platform refuses uses a second reply for its plain-text retry. `finalReplyOnly` cuts both ways here. It uses the least budget a run can, one reply, but the passive-reply window is only a few minutes long. Holding the reply until the run ends spends that window on the run, so a run that outlasts the window delivers nothing, where relaying every message would have sent whatever completed inside it.
+- A send with nothing to reply to, such as a turn started in the Web App or any reply after the window closed, is refused rather than pushed. It shows up as 502 `qq_send_failed` on the test endpoint, and as one `messaging_send_failed` error record for a relayed reply.
+
+Outbound files are refused on QQ, because the platform's rich-media path requires a publicly reachable URL for the file.
+
+### WeChat
+
+WeChat carries direct chats only, and the most media of the four channels. The bot channel has no group inbound at all: a message addressed to the bot in a group never reaches this API, so a binding that works in a direct chat stays silent in a group by design, not because of a misconfiguration.
+
+In exchange, it is the only channel here that carries text, images and files in both directions. The images and attachments of a reply are uploaded to the platform's CDN (AES-128-ECB, with a key per file) and arrive as real images and files instead of being refused. Two inbound kinds are converted: a voice message arrives as WeChat's own transcription of it, and a video arrives as a file. A recording the platform could not transcribe gets the shared "not supported" notice in the chat.
+
+### Scan-to-connect
+
+Scan-to-connect never shows the secret to the browser. Everything that makes the flow safe stays on the server: the AES key that decrypts QQ's App Secret, and the platform poll handle that collects WeChat's bot token. The server generates, holds, uses and discards them, and the client only receives a task handle, a URL to draw and a status.
+
+- `POST …/scan` returns `{taskId, qrUrl, pollMs}`. Render `qrUrl` as a QR code: the QQ or WeChat app opens it, and nothing fetches it. For WeChat, `taskId` is a handle this server mints in place of the platform's poll handle. While the channel's connection is enabled, scan returns 409 `messaging_disable_before_scan`, because a scan replaces the whole credential under a live connector. When the platform refuses, it returns 502 `qq_scan_failed` or `wechat_scan_failed`.
+- QQ's `scan/poll` status `completed` means the server has decrypted the App Secret and saved the binding; `expired` means start a new task.
+- WeChat's `scan/poll` status is one of `pending`, `scanned`, `need_verify_code`, `blocked`, `expired`, `already_bound` and `completed`. `completed` means the server has saved the binding. `already_bound` is not a failure: the bot is already bound, and nothing new was issued. It does not say where, because the scan gives the platform no list of tokens, so it cannot tell a binding on this server from one anywhere else.
+- In both channels, saving a binding does not enable it; enabling stays a separate step.
+- `scan/verify` records the pairing code WeChat showed on the phone. The platform takes the code as a parameter of its status call, so the code rides along with the next poll instead of a request of its own. A wrong code shows up as the next poll reporting `need_verify_code` again.
+- `scan/cancel` drops a scan the user walked away from, so its key or handle is forgotten at once instead of at the next cleanup.
+- Tasks live in memory and belong to the Session that started them. Each Session has its own limit, so one caller's scans cannot push out another's. The poll that resolves a task claims it, so replaying that poll returns 404 (`qq_scan_task_unknown` or `wechat_scan_task_unknown`, also returned for an unknown task or another Session's task) rather than binding twice. A second concurrent poll of the same task also returns 404 on QQ, but `pending` on WeChat, because the upstream call there is a long poll that spans several client intervals.
+
+Every scan route is owner only, because the flow ends in a stored credential however little of it the caller types.
+
+### Delivery settings
+
+`linePerMessage`, `finalReplyOnly` and `renderMarkdown` are the three saved fields that are not credentials. On a PUT, an omitted value keeps the stored one. None of them applies to notices or to the test message; in particular, the approval reminder is not a reply and arrives immediately whatever `finalReplyOnly` says.
+
+- `linePerMessage` (default false) sends every non-blank line of a relayed assistant reply as its own message. Blank lines are dropped, each line is still split under the size cap, and past the cap of 20 messages per reply the remaining lines are combined into one last message. The messages go out 1 second apart.
+- `finalReplyOnly` (default false) relays only the last completed assistant message of a run, when the run ends, instead of relaying each message as it completes. The working notes a run writes between tool calls stay in the Web App. The files that follow the reply are then read from that final message alone, since it is the only text the chat received. With both settings on, the final reply is the one split into lines.
+- `renderMarkdown` (default true) renders the Markdown of a relayed reply in the channel's own markup instead of sending the characters as written. Chunking follows the setting: it cuts at block boundaries and re-opens a code block that spans messages, so no message opens a construct it does not close. If the channel refuses a formatted send, the same message is sent again as plain text, so the setting can cost formatting but never a reply.
+
+Each channel renders what it can and degrades the rest deliberately, rather than showing Markdown source:
+
+| Channel | How a reply is rendered |
+| --- | --- |
+| Telegram | `parse_mode: "HTML"`. No headings, lists or tables: a heading becomes a bold line, list markers stay as literal text, and a table becomes a `<pre>` block |
+| Feishu | An interactive card carrying the JSON 2.0 rich-text component, which renders everything. Over-long tables become code blocks, so no row is silently dropped |
+| QQ | `msg_type: 2` markdown. No code formatting and no tables: a fenced block becomes plain escaped lines, and a table becomes its rows |
+| WeChat | WeChat reads Markdown itself, so rendering removes rather than translates: what the client will not show keeps its words and loses its markers (headings deeper than the fourth level, emphasis around CJK text, and inline images, which become links) |
+
+### Inbound messages
+
+Inbound messages can carry text, images and files.
+
+- An image becomes an ordinary `image_url` input part. Each image is capped at the server's inline-image limit, and each binding has a rolling budget of image bytes: 40MB per 10 minutes, twice the inline-image cap. The budget exists because an inline image is written verbatim into the Trace, and unlike the composer, this path has no authentication in front of it.
+- A file takes the composer's other attachment shape: it is written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line, so its bytes never enter the conversation. It is subject to the same admin-configurable per-file and per-message caps as an authenticated upload, narrowed by any tighter limit of the channel itself: Telegram serves a bot no file over 20MB.
+- Feishu delivers files sent as the `file` message type, and Telegram files in the `document` field: a file the sender chose to send as a file, which is also the only Telegram media field that carries the sender's own file name.
+- On Feishu and Telegram, video, audio and voice are deliberately not delivered: nothing downstream decodes or transcribes them, and anything a sender wants the agent to have arrives as soon as they attach it as a file. WeChat is the exception, only because the platform does the work itself (see [WeChat](#wechat)).
+- The caption of a message whose attachment is delivered (a photo or a document) is that message's text. A caption on any other kind of media is not, because the media never arrives, and running the model on the caption alone would make it answer about a file it never received.
+- An image over the per-image limit, an image past the budget, and an image the channel refuses each get a different bilingual notice, as do a file over a cap, a batch over the per-message total, and a file the channel refuses. None of them runs half a message. When the bot's own permissions caused the refusal, the notice names the permission scopes to grant and links to the channel's console. On Feishu this is the usual case, because receiving messages and downloading their attachments are separate scopes.
+- Every other message type gets the bilingual "not supported" reply.
+
+### Outbound files
+
+After a run finishes, its reply is followed by the files the reply mentioned and the run produced: path-like tokens anywhere in the reply that resolve inside the Workspace, exist, and were written at or after the start of the run. The mention picks which output was the point. The modification time keeps a reply, which anyone in the chat can steer, from becoming a way to read files, since a reply that declines to paste a file still names it.
+
+- Images are sent as images and everything else as attachments, classified by the file actually read rather than by the name the reply wrote.
+- A run sends at most 5 files, at most 10MB per image and 30MB per file (the tighter of each channel's own limits).
+- A mentioned file that fails to arrive is never reported in the chat. It is filed under the Project as an error record instead, which the Cost Center's errors table shows: one record per reply for each cause, naming every file it covers, the channel and the reason.
+ - `messaging_file_too_large` covers the files over a cap, `messaging_files_skipped` those past the count cap. Both are `expected`.
+ - `messaging_file_send_failed` covers the uploads the channel refused, grouped by cause: uploads the channel can never carry (any file on QQ), a missing permission, and any other refusal. The permission record lists the scopes to grant and the console link once, in place of each file's own reason. Uploads the channel can never carry are `expected`; a missing permission and any other refusal are `unexpected`.
+ - A name that matches no file in the Workspace, and a file the run did not write, are skipped silently and only logged, because a reply that names a file it read or merely described is the ordinary case.
+
+### Connection status
+
+When it connects, Telegram first drains the backlog, skipping messages sent while no connection existed. That matches Feishu, where missed events are simply gone.
+
+Besides its state, a binding's runtime status reports what the live connection has actually seen:
+
+- `lastInboundAt`: when a message last arrived; absent while none has arrived since this connection opened.
+- `lastDeliveryError`: `{at, stage, detail}`, where `stage` is `inbound` when a message arrived but its Task never started, or `send` when a reply never reached the chat. A later success does not clear it.
+- `lastConnectionError`: `{at, detail}` for the last connection failure, kept after the connection recovers. By contrast, `lastError` belongs to the `error` state and disappears as soon as the state leaves it.
+
+All three live in the server process and reset on every connect or reconnect, and re-enabling the channel or saving credentials opens a new connection. An absent `lastInboundAt` therefore means "nothing since this connection opened", never "nothing ever". These fields exist because a channel that withholds messages still shows `connected` with no error.
+
+## Terminals
+
+Interactive shells on the server host. The Web App's terminals use these routes, and so can any client that needs to run a command and read the screen. Each terminal belongs to the user who opened it, and the other routes only find the caller's own terminals.
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | `/api/terminals` | Lists the caller's terminals: `{terminals}` |
+| POST | `/api/terminals` | Opens a terminal: `{cwd?, name?, shell?, cols?, rows?}` → 201 with the terminal's info |
+| GET | `/api/terminals/:id` | One terminal's info |
+| DELETE | `/api/terminals/:id` | Kills the terminal; 204 |
+| GET | `/api/terminals/:id/capture?start=&end=` | The screen contents as plain text |
+| POST | `/api/terminals/:id/keys` | Sends input: `{keys, literal?}` → `{ok: true}` |
+
+- `cwd` defaults to the home directory, and `shell` to the user's login shell.
+- `keys` is literal text or a key token: `Enter`, `Tab`, `Escape`, `Backspace`, `Space`, `Up`, `Down`, `Left`, `Right`, `Home`, `End`, `PageUp`, `PageDown`, `Delete`, or a control chord such as `C-c`. With `literal: true`, the text is sent exactly as given. A terminal whose shell has exited returns `409` `terminal_exited`.
+- The byte stream does not use these routes: it is a WebSocket at `GET /api/terminals/:id/stream` (an Upgrade request).
+- A request without a valid session or token returns `401` `unauthorized`.
+
+## Desktop Shell, Hot Update and Web Contributions
+
+Routes that serve the desktop shell, hot updates and the Web App's own module system rather than general clients.
+
+| Method | Path | Description |
+| --- | --- | --- |
+| POST | `/api/desktop/shutdown` | Shuts the server down gracefully, at the desktop shell's request; 202 |
+| GET | `/api/desktop/update` | The desktop app updater's status: `{status}` |
+| POST | `/api/desktop/update/check`, `/api/desktop/update/download`, `/api/desktop/update/install` | Relays the command to the desktop shell; 202 |
+| GET / PUT | `/api/desktop/tray` | Reads the tray-icon preference: `{status}` / relays a change: `{showTrayIcon?, locale?}` → 202 |
+| POST | `/api/hmr/assets/probe` | Hot update: reports which blobs the store lacks |
+| PUT | `/api/hmr/blobs/:sha` | Hot update: uploads one blob under its sha256 |
+| POST | `/api/hmr/upgrade` | Hot update: moves the platform, CLI and web bundles to a new version together |
+| GET | `/api/contributions` | The pages and tabs that server modules and plugins contribute to the Web App, as data |
+
+- Outside desktop mode, the desktop routes return `404` `not_found`.
+- `POST /api/desktop/shutdown` does not use the cookie session. It authenticates with the desktop shell's own Bearer token (`401` `unauthorized` otherwise), answers first, and starts the graceful shutdown right after.
+- The update and tray routes answer only the desktop shell's own window: any other session gets `403` `desktop_shell_only`. When the shell is not listening, they return `503` `shell_unreachable`. `PUT /api/desktop/tray` returns `400` `invalid_show_tray_icon` for a non-boolean `showTrayIcon`, `400` `invalid_locale` for a `locale` other than `zh` or `en`, and `400` `empty_tray_patch` when neither field is given. The PUT only acknowledges the change; read the result back with GET.
+- The `/api/hmr` routes are admin only (`403` `forbidden`). On a non-loopback bind they also require HTTPS and otherwise return `403` `hmr_disabled`. `X-Forwarded-Proto` counts only when `PENGUIN_TRUST_PROXY=1`. A completed upgrade sends `web_updated` to every connected client, so they reload.
## Streaming (SSE)
-Real-time delivery uses Server-Sent Events, not WebSocket, on two channels (the ordering semantics of what the channels carry are on [Message Flow & Ordering](/message-flow)):
+Real-time delivery uses Server-Sent Events, not WebSocket, on two kinds of channel. For the ordering semantics of what the channels carry, see [Message Flow & Ordering](/message-flow).
| Channel | Path | Contents |
| --- | --- | --- |
-| Per Session | GET /api/sessions/:sessionId/stream | The Session's message stream and run events |
-| Per user | GET /api/events | `hello` handshake and cross-Session notifications (session_state / session_background / schedule_fired / schedule_queued / session_created) |
+| Per Session | `GET /api/sessions/:sessionId/stream` | The Session's message stream and run events, including `session_created` for its subagent Sessions and the goal-mode events |
+| Per user | `GET /api/events` | The `hello` handshake and notifications across Sessions: `session_state`, `session_background`, `session_title`, `schedule_fired`, `schedule_queued`, `web_updated` and company mode's `org_*` events |
### Wire Format
-Default (unnamed) SSE events carry raw OmniMessage envelopes as single-line JSON — the same protocol the SDK yields and the Trace stores, see the [OmniMessage Protocol](/omni-message). Events named `server_event` carry the ServerEvent union:
+Default (unnamed) SSE events carry raw OmniMessage envelopes as single-line JSON: the same protocol the SDK yields and the Trace stores (see [OmniMessage Protocol](/omni-message)). Events named `server_event` carry the `ServerEvent` union:
```ts
export type ServerEvent =
| { type: "approval_request"; toolCall: OmniMessage<ToolCallPayload>; origin?: string[] }
- | { type: "task_state"; state: "idle" | "running" | "compacting" }
+ | {
+ type: "task_state";
+ state: "idle" | "running" | "compacting";
+ queued?: number;
+ pendingSteering?: PendingSteeringInfo[];
+ returnedSteering?: PendingSteeringInfo[];
+ pendingFollowUps?: PendingFollowUpInfo[];
+ subagents?: SubagentRuntimeInfo[];
+ }
| { type: "session_title"; sessionId: string; title: string }
| { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }
| { type: "session_background"; sessionId: string; processes: number; subagents: number }
| { type: "resync_required" }
| { type: "credentials_updated" }
| { type: "hello" }
+ | { type: "web_updated"; rev: string }
| { type: "session_created"; projectId: string; agentId: string; sessionId: string; source: SessionSource }
| { type: "schedule_fired"; projectId: string; agentId: string; name: string; sessionId: string }
- | { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string };
+ | { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string }
+ | { type: "goal_started"; sessionId: string; objective: string; budget: number }
+ | { type: "goal_round"; sessionId: string; round: number; used: number; budget: number }
+ | { type: "goal_finished"; sessionId: string; outcome: "complete" | "blocked" | "budget_limited" | "aborted"; rounds: number; used: number }
+ | { type: "org_run"; projectId: string; orgId: string; agentId: string; sessionId: string; kind: OrgTriggerKind }
+ | { type: "org_channel"; projectId: string; orgId: string; channelId: string; message: OrgChannelMessage }
+ | { type: "org_ticket"; projectId: string; orgId: string; ticketId: string; change: string }
+ | { type: "org_budget"; projectId: string; orgId: string; agentId: string; state: "warned" | "paused" | "resumed"; ratio: number };
```
| Event | Fired when |
| --- | --- |
-| approval_request | A tool call escalated to human approval: every call under always-ask, plus rw / unknown-permission calls under read-only; pending approvals are resent on reconnect |
-| task_state | The Session's run state flips (idle / running / compacting) |
-| session_title | The model-generated title after the first turn has been persisted |
-| session_state | The user-channel counterpart of `task_state`: the same run-state flip, named by `sessionId`, so a Session list stays live for every row and not only the conversation a client has open. Carries the row fields needed to redraw it without refetching — `lastActiveAt` as just stamped, and `hasTrace` (true whenever the state is running or compacting, since a Session that is running has by definition started a Task). Published to the user channels of the Project's owner and members |
-| session_background | A Session's background-task counts changed — a command promoted past its yield window or launched with `run_in_background`, a process that exited or was stopped, a background subagent starting, settling or being released. Carries `SessionInfo.backgroundTasks` as it now stands (`processes` = background command sessions still running, `subagents` = promoted subagent sessions mid-round), zeros included so a list can clear its mark without refetching; the list row and the single-session GET omit the field at zero. Same audience as `session_state` |
-| resync_required | The Last-Event-ID was evicted from the buffer; the client must refetch history |
-| credentials_updated | The Project's model credentials changed (`PUT /models`, or a completed key-minting flow): cached runtimes were invalidated, so the client clears any auth-dead composer state |
-| hello | Handshake on the user channel |
-| session_created | A new Session was registered (e.g. a subagent session) |
-| schedule_fired | A scheduled task fired and was delivered |
-| schedule_queued | The target Session is running; this firing was queued |
+| `approval_request` | A tool call needs human approval |
+| `task_state` | The Session's run state changes (`idle` / `running` / `compacting`) |
+| `session_title` | The model-generated title is saved after the first turn |
+| `session_state` | A Session's run state changes; the user-channel counterpart of `task_state` |
+| `session_background` | A Session's background-task counts change |
+| `resync_required` | The `Last-Event-ID` was evicted from the buffer; the client must refetch history |
+| `credentials_updated` | The Project's model credentials changed |
+| `hello` | Handshake on the user channel |
+| `web_updated` | A hot update replaced the served web assets; clients reload |
+| `session_created` | A new Session was registered, such as a subagent Session |
+| `schedule_fired` | A scheduled task fired and its prompt was delivered |
+| `schedule_queued` | The target Session is running, so this firing was queued |
+| `goal_started` | A goal run began, before its first round |
+| `goal_round` | A goal round is starting |
+| `goal_finished` | The goal reached a terminal state |
+| `org_run` | An organization's work run (desk session) or ticket session started |
+| `org_channel` | A new channel message was posted |
+| `org_ticket` | A ticket's status, owner, blocked state or contributing sessions changed |
+| `org_budget` | An employee's budget was warned, paused or resumed |
+
+- `approval_request` covers every call under `always-ask`, and calls with `rw` or unknown permission under `read-only`. Pending approvals are sent again on reconnect.
+- `task_state` also carries the number of queued follow-ups (`queued`), the steering messages still waiting for delivery (`pendingSteering`), steering that the run ended without delivering (`returnedSteering`), the queued follow-ups themselves (`pendingFollowUps`) and the live subagent children (`subagents`). An absent field means none.
+- `session_title` is sent on the Session's channel and on the user channels of the Project's owner and members.
+- `session_state` names the Session by `sessionId`, so every row of a Session list stays live, not only the conversation a client has open. It carries the row fields needed to redraw the row without refetching: `lastActiveAt` as just stamped, and `hasTrace`, which is true whenever the state is `running` or `compacting`, because a running Session has by definition started a Task. It is sent to the user channels of the Project's owner and members.
+- `session_background` fires when a command moves to the background past its yield window or starts with `run_in_background`, when a process exits or is stopped, and when a background subagent starts, settles or is released. It carries `SessionInfo.backgroundTasks` as it now stands (`processes` = background command sessions still running, `subagents` = subagent Sessions moved to the background and mid-round), zeros included, so a list can clear its mark without refetching. The list rows and the single-Session GET omit the field when both counts are zero. Its audience is the same as for `session_state`.
+- `credentials_updated` follows `PUT /models` or a completed key-minting flow. Cached runtimes were invalidated, so the client clears any composer state disabled by an auth failure.
+- `web_updated` carries the new web revision as `rev` and is sent to every user channel.
+- `session_created` is sent on the parent Session's channel.
+- `schedule_fired` names in `sessionId` the Session that received the prompt, which in new-Session mode is a new Session. A queued firing is sent once the Session is idle.
+- `goal_round` carries `used`, the tokens counted so far.
+- The `org_*` events are sent to the user channels of the Project's members. `org_channel` includes the message's mentions, so a client can tell whether it is addressed. These events are best effort; the organization routes carry the durable state.
### Delivery Guarantees
-- Event ids are monotonic per channel, shaped `<epoch>-<seq>`;
-- Each channel keeps a bounded replay buffer (most recent 10,000 events or 8MB);
-- Reconnecting with `Last-Event-ID` replays the gap on a buffer hit; on a miss the server first sends `resync_required`, and the client refetches `/messages` before continuing;
-- A heartbeat comment line is written every 20 seconds;
-- Event order: on a reconnect carrying `Last-Event-ID`, **the replayed gap (or `resync_required`) arrives first**, then the initial events — the authoritative `task_state` snapshot and still-pending approval_requests — then the live stream. A fresh connection (no `Last-Event-ID`) skips replay, so its first event is the `task_state` snapshot.
+- Event ids increase monotonically per channel and have the form `<epoch>-<seq>`.
+- Each channel keeps a bounded replay buffer: the most recent 10,000 events or 8MB.
+- On reconnect with `Last-Event-ID`, the server replays the gap if the id is still in the buffer. Otherwise it first sends `resync_required`, and the client refetches `/messages` before continuing.
+- A heartbeat comment line is written every 20 seconds.
+- Event order: on a reconnect that carries `Last-Event-ID`, the replayed gap (or `resync_required`) arrives first, then the initial events (the authoritative `task_state` snapshot and any still-pending `approval_request`s), then the live stream. A fresh connection without `Last-Event-ID` skips the replay, so its first event is the `task_state` snapshot.
### Recommended Client Pattern
-The order the bundled Web App uses:
+The bundled Web App connects in this order:
-1. Connect `/stream` first and buffer incoming events;
-2. GET `/messages` for the full history;
-3. If the response carries `live` (a Task is running), drop the buffered partials the cursor already covers and seed the `live.fragments` on top of history — the in-progress message reappears with its streamed prefix intact;
-4. Replay the buffer, deduplicating the overlap;
-5. Go live.
+1. Connect to `/stream` first and buffer the incoming events.
+2. GET `/messages` for the history.
+3. If the response carries `live` (a Task is running), drop the buffered partial events the cursor already covers and apply `live.fragments` on top of the history. The in-progress message reappears with its streamed prefix intact.
+4. Replay the buffer, removing the overlap.
+5. Continue with the live stream.
## Type Imports
-All DTO types are importable type-only from the server package's `@prismshadow/penguin-server/api` subpath:
+All DTO types can be imported, type-only, from the server package's `@prismshadow/penguin-server/api` subpath:
```ts
import type { ServerEvent, SessionInfo } from "@prismshadow/penguin-server/api";
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index dd96d46d..fe7bb6eb 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -1,507 +1,752 @@
---
title: Server API
-description: HTTP API 参考:认证机制、路由列表、SSE 流式协议与 DTO 类型导入。
+description: PenguinHarness 服务器的 HTTP API 参考:认证、全部路由分组、SSE 流式协议和 DTO 类型导入。
---
-PenguinHarness Server 提供一套同源 HTTP API,自带的 Web App 与其他 HTTP 客户端都通过它访问。本文是接口参考:认证机制、路由列表与 SSE 流式协议。服务启动方式见[快速开始](/quickstart)。
+PenguinHarness 服务器提供一组同源 HTTP API,内置 Web App 和其他任何 HTTP 客户端用的都是它。本页先讲认证,再按功能分组介绍路由(每组先给路由表,再补充细节),最后讲 SSE 流式协议。启动服务器的方法见[快速开始](/quickstart)。
-## 总览
+## 概览
-- 技术栈:Hono + @hono/node-server,要求 Node >= 24;
-- 存储:SQLite(内置 `node:sqlite`,WAL 模式)仅存放索引与聚合数据——用户、登录会话、Project 授权、Agent / Session 索引、用量、UI 偏好、错误记录与 Schedule 状态;Agent、Trace 与 Workspace 数据全部以文件形式存放在 `~/.penguin/data` 下,与 CLI / SDK 共享,见[配置参考](/configuration);
-- 监听:默认 `127.0.0.1:7364`,可用环境变量 `PORT` / `HOST` 调整;
-- 请求体:写请求仅接受 JSON(Content-Type 校验,CSRF 防线之一),其上限**由附件预算推导**而非固定值——附件以 base64 `data:` URL 随请求送达(膨胀 4/3),故上限为 `base64(attachmentTotalMb) + 一张内嵌图片与 JSON 外壳的余量`,在默认 120MB 合计下约 190MB,管理员调低附件上限时随之回落。按读取到的字节数统计,未声明长度(分块传输)的请求同样受限;
-- 错误响应统一为:
+- 技术栈:Hono 和 `@hono/node-server`,要求 Node >= 24。
+- 存储:SQLite(内置的 `node:sqlite`,WAL 模式)只保存索引和聚合数据:用户、认证会话、Project 授权、Agent 与 Session 索引、用量、UI 偏好、错误记录和定时任务状态。所有 Agent、Trace 和 Workspace 数据都以文件形式存放在 `~/.penguin/data` 下,与 CLI 和 SDK 共享;参见[配置参考](/configuration)。
+- 绑定地址:默认 `127.0.0.1:7364`,可通过 `PORT` / `HOST` 环境变量调整。
+- 请求体:写操作只接受 JSON,检查 Content-Type 是防 CSRF 的手段之一。请求体大小上限并非固定值,而是由附件额度推导出来的。附件以 base64 `data:` URL 的形式随请求传输,体积会膨胀 4/3,所以上限按 `base64(attachmentTotalMb)` 计算,再为一张内嵌图片和 JSON 封装留出余量。按默认 120MB 的总量计,约为 190MB;管理员调低总量,上限也会随之下降。服务器边读请求体边统计字节数,因此不声明长度(chunked)的请求同样受此限制。
+- 所有错误共用同一种结构:
```text
-{ "error": { "code": "<机器可读错误码>", "message": "<提示文案>" } }
+{ "error": { "code": "<machine-readable code>", "message": "<user-facing text>" } }
```
-## 目录结构
+## 源码结构
```text
packages/server/src
-├── index.ts / config.ts / app.ts # 启动入口 · 环境变量配置 · Hono 组装(运行时 app;业务路由由 src/modules 下的 http 模块装配,不绑端口,便于测试)
-├── api/types.ts # 对外 DTO 契约(经 "./api" 子路径供前端 type-only 引用)
-├── auth/ # scrypt 密码、admin 种子、cookie 会话、认证中间件
-├── db/ # node:sqlite 连接、建表 SQL、每表一个 repo
-├── http/ # 错误体、请求校验、SSE 适配、routes/ 全部路由
-├── runtime/ # session-manager(运行时驱动)· channel(SSE 环形缓冲)
-│ # approvals · usage-recorder · scheduler · title-generator
-└── services/ # 授权规则、TOML/YAML 配置读写、Session/Trace/用量/快照服务
+├── index.ts / config.ts / app.ts # startup entry · env config · the HMR layer's app (network guards, /api/hmr, the platform seam, static hosting; binds no port, testable)
+├── api/types.ts # the outward DTO contract (type-only import via the "./api" subpath)
+├── auth/ # scrypt passwords, admin seeding, cookie sessions, auth middleware
+├── db/ # node:sqlite connection, schema SQL, one repo per table
+├── hmr/ # hot update: the platform seam and the /api/hmr routes
+├── http/ # the business routes' assembly (app.ts), error bodies, request validation, SSE adapter, routes/
+├── machines/ # remote machines: ssh config, install and connect jobs, the /server/<machineId> proxy
+├── organization/ # company mode's files: chart, tickets, channels, handbook
+├── runtime/ # session-manager (runtime driving) · channel (SSE ring buffer)
+│ # approvals · usage-recorder · scheduler · title-generator · messaging/ · organization/
+├── services/ # authorization rules, TOML/YAML config IO, Session/Trace/usage/snapshot services
+└── terminal/ # terminals: /api/terminals and the byte-stream WebSocket
```
## 认证
-- Cookie 会话:`penguin_session`(HttpOnly、SameSite=Lax),有效期 30 天,滑动续期;
-- 密码以 scrypt 哈希存储;会话是 `auth_sessions` 表中的一行,以随机 Cookie 令牌的 sha256 为键(原始令牌从不落库);它跨重启存活、原地续期,logout 删除该行;
-- 不开放注册:启动时种子化内置管理员 `admin`,其初始密码随机生成、哈希后即丢弃,无人见过。在真正设置密码之前,每次启动都会打印一条首次登录链接用于认领账号(自动化场景可用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定一个已知密码)。其余账号由管理员创建;
-- 仅限同源访问,未启用 CORS 中间件。
+API 接受两种凭证:Cookie 会话和本地 API token。
+
+- Cookie 会话:`penguin_session`(HttpOnly,SameSite=Lax),有效期 30 天,滑动续期。
+- 密码以 scrypt 哈希存储。会话是 `auth_sessions` 表中的一行,以随机 Cookie token 的 sha256 为键;原始 token 从不存储。会话重启后依然有效,并在原地续期;登出则删除这一行。
+- 不开放注册。启动时,服务器会用一个随机密码初始化内置管理员 `admin`:密码哈希后保存,明文随即丢弃,没有任何人见过它。在设置密码之前,每次启动都会打印一条首次登录链接,用来认领账号。自动化场景可以改用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定一个已知密码。其余所有账号都由管理员创建。
+- 仅限同源:未启用任何 CORS 中间件。
+- 标为「仅管理员」的路由,对其他用户一律返回 `403` `admin_required`。
```bash
-# 密码用认领账号(首次登录链接)时设置的那个。
+# Use the password you set when claiming the account from the first-login link.
curl -c cookies.txt -H "Content-Type: application/json" \
- -d '{"userId":"admin","password":"<你的密码>"}' \
+ -d '{"userId":"admin","password":"<your password>"}' \
http://localhost:7364/api/auth/login
```
-### 本机 API token(Bearer)
+### 本地 API token(Bearer)
-所有受保护路由同时接受携带**本机 API token** 的 `Authorization: Bearer <token>`——这是 CLI(以及经 CLI 驱动 harness 的 Agent)用来替代登录的本机凭据:
+所有受保护的路由也接受携带**本地 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 请求同样生效。
+- 服务器每次启动都生成一个新 token,写入 `<root>/api-token`,文件权限仅限所有者(`0600`)。新 token 一经生成,上一次启动的 token 立即失效。
+- 有效的 Bearer token 以内置 `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 的 Content-Type 检查,对 Bearer 请求同样生效。
```bash
curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
http://127.0.0.1:7364/api/me
```
-## 路由参考
+## 认证与账号
-### 认证与账户
+登录、登出、账号认领,以及当前用户的密码、资料和偏好设置。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| POST | /api/auth/login | 登录:`{userId, password}` → `{user}` |
-| POST | /api/auth/logout | 退出登录,返回 204 |
-| GET | /api/auth/claim?token=… | 兑换登录链接(首次登录链接,或桌面 shell 的一次性 token):种下 Cookie 并跳转到 `/`;链接无效或已被使用时改为跳转 `/login?claimFailed=…`,由 Web App 说明如何获取新链接 |
-| GET | /api/install | 公开:`{installId}`——标识当前所服务数据根的不透明 id(`<root>/install-id`),在该根首次被使用时铸造。Web App 将其与自己存下的值比较,不一致时清除浏览器侧那些引用服务端实体的 UI 状态,因此更换数据根后不会再留下旧的 Workspace、草稿与置顶。`null` 表示服务端无法确定该 id,此时客户端不应改动任何内容。 |
-| GET | /api/me | 当前用户信息 |
-| PUT | /api/me/password | 修改密码:`{oldPassword, newPassword}`;桌面会话与首次登录会话可省略 `oldPassword`——其当前密码是随机生成且从未展示过的 |
-| PUT | /api/me/profile | 设置头像与昵称:`{displayName?, avatar?}` → `{user}`。为补丁语义——字段缺省表示保持原值,`null` 表示清除,两个字段都未出现则返回 `400`。`displayName` 去除首尾空白后须为 1–32 个字符(按字符计,因此中文昵称可以有 32 个)且不含控制字符;`avatar` 须是 `data:image/(png|jpeg|webp);base64,…` 形式的 data URL,长度不超过 131072 个字符且载荷可解码。任何已认证会话均可调用,含桌面 shell 的 token 会话——与上面的密码路由不同,个人资料没有需要校验的旧凭据 |
-| GET | /api/me/prefs | 读取 UI 偏好 |
-| PUT | /api/me/prefs | 写入 UI 偏好(浅合并) |
-
-### 用户管理(仅管理员)
+| POST | `/api/auth/login` | 登录:`{userId, password}` → `{user}` |
+| POST | `/api/auth/logout` | 登出,返回 `204` |
+| GET | `/api/auth/claim?token=…` | 兑换登录链接:设置 Cookie 并重定向到 `/` |
+| GET | `/api/install` | 公开:返回 `{installId}`,即当前数据根目录的 id |
+| GET | `/api/me` | 当前用户的信息 |
+| PUT | `/api/me/password` | 修改密码:`{oldPassword, newPassword}` |
+| PUT | `/api/me/profile` | 设置头像和昵称:`{displayName?, avatar?}` → `{user}` |
+| GET | `/api/me/prefs` | 读取 UI 偏好 |
+| PUT | `/api/me/prefs` | 写入 UI 偏好(浅合并) |
+
+- `GET /api/auth/claim` 用于兑换首次登录链接或桌面 shell 的一次性 token。链接无效或已被使用时,会改为重定向到 `/login?claimFailed=…`,Web App 会在那里说明如何获取一条有效链接。
+- `GET /api/install` 无需身份验证。`installId` 是一个不透明的 id,存储在 `<root>/install-id`,在数据根目录首次使用时生成。Web App 将它与本地保存的 id 比对,不一致时清空浏览器端引用服务器实体的 UI 状态,这样替换数据根目录后就不会残留旧的 Workspace、草稿和置顶项。返回 `null` 表示服务器无法确立 id,此时客户端不得改动任何状态。
+- `PUT /api/me/password`:桌面会话和首次登录会话可以省略 `oldPassword`,因为这类会话的当前密码是随机生成的,从未展示过。
+- `PUT /api/me/profile` 是补丁式更新:省略的字段保留原值,`null` 表示清除这个字段,请求体若两个字段都不含则返回 `400`。
+ - `displayName` 去除首尾空白后必须在 1–32 个字符之间,按字符计数(因此中文名可以满 32 个),且不能包含控制字符。
+ - `avatar` 必须是 `data:image/(png|jpeg|webp);base64,…` 形式的 URL,最长 131072 个字符,且其中的数据能够正常解码。
+ - 任何已认证的会话都可以调用,包括桌面 shell 的 token 会话。与修改密码的接口不同,修改资料没有旧凭证需要校验。
+
+## 用户管理(仅管理员)
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/admin/users | 用户列表。每行在账号设置了昵称时带上昵称;头像刻意不下发——该列表不分页,每个账号一份 data URL 会让响应体积远超这张表实际用到的内容 |
-| POST | /api/admin/users | 创建用户:`{userId, password}` |
-| POST | /api/admin/users/:userId/password | 重置密码(该用户全部登录会话失效) |
-| DELETE | /api/admin/users/:userId | 删除用户 |
+| GET | `/api/admin/users` | 列出用户 |
+| POST | `/api/admin/users` | 创建用户:`{userId, password}` |
+| POST | `/api/admin/users/:userId/password` | 重置密码,并使这个用户的所有登录会话失效 |
+| DELETE | `/api/admin/users/:userId` | 删除用户 |
+
+用户列表的每一行都会带上账号昵称(如果设置过)。列表中刻意不放头像:列表不分页,每个账号再附一个 data URL 会让响应体膨胀到淹没其他内容。
+
+桌面模式(由桌面应用拉起的服务器)下,这组路由一律返回 `403`,错误码为 `desktop_single_user`。桌面应用面向单用户,不提供用户管理;数据根目录中已有的用户不受影响。
-桌面模式下(server 由桌面应用拉起)整组路由返回 `403`、错误码 `desktop_single_user`:桌面应用是单用户形态,用户管理整体停用——数据根中已有的用户不受影响。
+## 服务器设置(仅管理员)
-### 服务端设置(仅管理员)
+服务器全局的代理、附件和公司模式设置。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/admin/settings | 服务端全局设置:`{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb}}` |
-| PUT | /api/admin/settings | 更新设置(字段可省略,省略即保持现值),返回更新后的完整设置 |
-| GET | /api/admin/settings/proxy-probe | 连通性测速的目标列表:`{targets: [{provider, url}]}`(不发起任何请求) |
-| POST | /api/admin/settings/proxy-probe/:provider | 沿服务端出站链路探测其中一个目标,不携带任何凭据:`{probe: {provider, url, outcome, ms, status?}}`;`outcome` 在收到任意 HTTP 响应时为 `reachable`,否则为 `timeout` / `dns` / `refused` / `tls` / `network`;列表之外的 id 返回 404 `probe_target_not_found` |
+| GET | `/api/admin/settings` | 服务器全局设置:`{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb, companyMode}}` |
+| PUT | `/api/admin/settings` | 更新设置;省略的字段保持当前值,任何字段非法都会拒绝整个 PUT。返回更新后的完整设置 |
+| GET | `/api/admin/settings/proxy-probe` | 可达性探测的目标:`{targets: [{provider, url}]}`。不发起任何请求 |
+| POST | `/api/admin/settings/proxy-probe/:provider` | 经服务器的出站链路探测其中一个目标,不发送任何凭证:`{probe: {provider, url, outcome, ms, status?}}` |
-代理设置为两个独立开关共享一个可选的显式地址;修改即时生效(对新发起的连接与新派生的子进程),无需重启:
+只要有 HTTP 响应返回,探测的 `outcome` 就是 `reachable`,否则为 `timeout`、`dns`、`refused`、`tls` 或 `network`。`:provider` 不在目标列表里时返回 `404` `probe_target_not_found`。
-- `proxyForApp`(「应用程序使用代理」,默认开)治理服务端自身出网(LLM 请求、更新检查、图片抓取):开且填写了 `proxyUrl` → http 与 https 流量都走该地址,**优先于代理环境变量**——无需配置任何环境变量;开但未填地址 → 遵循 HTTP_PROXY / HTTPS_PROXY / NO_PROXY 环境变量(大小写并存);关 → 一律直连。
-- `proxyForAgent`(「Agent 环境使用代理」,默认开)治理 Agent 命令子进程环境:开且填写了 `proxyUrl` → 注入 `HTTP_PROXY` / `HTTPS_PROXY`(含小写拼写)为该地址并附合并后的 NO_PROXY,覆盖继承值(`socks5://` 地址原样注入——各工具对这些变量中的 SOCKS URL 支持程度不一);开但未填地址 → 宿主环境原样透传;关 → 剥除代理变量(NO_PROXY 保留)。
-- `proxyUrl`(默认 null = 跟随环境变量)即两者共享的显式地址。PUT 校验:先 trim;空串或 null 即清除地址;接受 undici dispatcher 认可的代理 URL——`http://`、`https://` 与(undici 实验性支持的)`socks5://`/`socks://` 地址,允许携带凭据——以及裸 `主机[:端口]`(规范化为 `http://主机[:端口]`);只存储规范化后的值,响应回显存储形态。其余(无法解析,或 undici 拒绝的协议如 `socks4://`)一律 `400`,错误码 `invalid_proxy_url`,且被拒绝的 PUT 不写入任何字段。
+### 代理设置
-任一开启状态下生效的 NO_PROXY 恒包含 `localhost,127.0.0.1,::1`(回环不代理)。
+代理设置是两个相互独立的开关,共用一个可选的显式地址。改动立即作用于新建连接和新启动的进程,无需重启。
-上传限制是两个整数 MB,约束输入框的文件附件;二者均在下一次请求即生效、无需重启(校验与请求体上限都按请求读取):
+`proxyForApp`(即**应用程序使用代理**开关,默认开启)管理服务器自身的出站流量:LLM 请求、更新检查和图片拉取。
-- `attachmentMaxMb`(默认 100)为单个附件上限,超出返回 `413` `file_too_large`。
-- `attachmentTotalMb`(默认 120)为单条消息解码后的合计上限,超出返回 `413` `payload_too_large`。
-- PUT 校验:两者都必须是 1 到 200 之间的整数,且**生效后**的合计值(本次 PUT 给出的值,或本次不修改时的存量值)不得低于生效后的单个上限。其余一律 `400`,错误码 `invalid_attachment_limit`,且被拒绝的 PUT 不写入任何字段。
-- 不可配置项:单条消息的附件数量(20)与内嵌图片上限(20MB,超出返回 `413` `image_too_large`)。内嵌图片会写入轨迹,并在每次翻阅历史与恢复会话时被重新读取,因此刻意不随附件上限放宽;`GET /api/me` 会在 `uploadLimits` 下报告以上全部数值,客户端据此按当前生效的上限预先校验。
+- 开启且设置了 `proxyUrl`:http 和 https 都走这个地址,优先于代理环境变量,无需配置任何环境变量。
+- 开启但未设置地址:服务器遵循 `HTTP_PROXY`、`HTTPS_PROXY` 和 `NO_PROXY` 环境变量,大小写两种拼写都认。
+- 关闭:始终直连。
-### 机器(仅管理员)
+`proxyForAgent`(即 **Agent 环境使用代理**开关,默认开启)管理 Agent 命令子进程的环境。
-| 方法 | 路径 | 说明 |
-| --- | --- | --- |
-| GET | /api/projects/:projectId/machines | 本机,加上**服务端自身** `~/.ssh/config` 中的主机别名,附带**本 Project** 在每台上安装了什么、每台最近一次探测到的状态、本服务端会安装的版本,以及正在运行或最近一次的任务:`{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, status}], imageVersion, job}`。`elsewhere` 表示该主机由别的 Project 装过——可以纳入,不必重装 |
-| POST | /api/projects/:projectId/machines/probe | 询问本 Project 已安装的机器各自的状态(每台一次 ssh 往返,并发 5)并返回带有最新状态的列表 |
-| POST | /api/projects/:projectId/machines/:machineId/install | 在该主机上安装当前构建,并把它归入本 Project;返回 `202` 与同样的响应体,此时任务已在运行。请求体 `{replaceProgram: true}` 用于回答任务给出的那个提议:即便版本已一致也照装不误,并重启它 |
-| POST | /api/projects/:projectId/machines/:machineId/connect | 把该机器的服务端拉起来,并**持有**对它的那唯一一条连接——一个 `ssh -T -D` 会话,不会因空闲而关闭,断了会自行重建,服务端重启或热推之后也会恢复;返回 `202` 与同样的响应体,此时连接任务已在运行。Windows 机器返回 `409` `connect_unsupported`:那边没有可以持有会话的 shell |
-| POST | /api/projects/:projectId/machines/:machineId/disconnect | 断开连接。远端服务端**保持运行**——那是那台机器自己的服务端,别人可能正在上面 |
-| POST | /api/projects/:projectId/machines/:machineId/restart | 停止该机器的服务端并在同一端口重新启动;返回 `202`,若已有任务在跑则 `409`。它值得成为一个独立操作,是因为一台机器的**文件**可以在它运行时被更新,而只有重启才能让进程与之相符 |
-| GET | /api/projects/:projectId/machines/:machineId/dirs?path= | 该机器上 `path` 的子目录,经由持有的连接读取——工作区选择器浏览的就是它。与代理一样,按机器**自身的 id** 寻址。机器未连接时返回 `404`:读取从不自行打开 ssh |
-| POST | /api/projects/:projectId/machines/:machineId/release | 把该机器移出本 Project;机器上已安装的程序保持不动 |
+- 开启且设置了 `proxyUrl`:注入 `HTTP_PROXY` 和 `HTTPS_PROXY`(含对应的小写变量),值为这个地址,同时注入合并后的 `NO_PROXY`,覆盖继承来的值。`socks5://` 地址原样注入;各工具能否在这些变量中接受 SOCKS URL 并不一致。
+- 开启但未设置地址:宿主环境原样透传。
+- 关闭:移除代理变量,保留 `NO_PROXY`。
-无论个人服务端还是多用户服务端都仅限管理员:安装会以**服务端账户**的密钥派生 ssh,并在另一台机器上写入程序目录——这是所有者的能力,而非访客的。ssh 配置只读不写,也从不解析:列表就是配置的文本(无论声明了几百台主机都只是一次文件读取),而别名原样交给 ssh——它的含义由 ssh 自己按自己的配置、每次都重新决定。
+`proxyUrl` 是共用的显式地址,默认为 `null`,即跟随环境变量。PUT 按如下规则校验:
-`imageVersion` 是将被推送的版本;为 `null` 表示本服务端根本没有安装镜像(只有从未被热推过的源码检出会是这种形态),此时任何安装都会以 `409` `no_install_image` 拒绝。该版本取自当前运行的安装自身:热推过的服务端推送它正在运行的 bundle(`0.0.0-hmr.<cli>.<web>`),tarball 或打包安装则推送自己的程序树,因此两端的一致是构造性的。
+- 先去除首尾空白,空值或 `null` 表示清除这个地址。
+- 可接受的值是 undici dispatcher 支持的代理 URL(`http://`、`https://`,以及实验性的 `socks5://` / `socks://`,允许带凭证),另外也接受裸的 `host[:port]`,并归一化为 `http://host[:port]`。只存储归一化后的值,响应返回的也是这个值。
+- 其他任何值——无论是无法解析,还是 undici 不接受的协议(如 `socks4://`)——都返回 `400`,错误码为 `invalid_proxy_url`,且这次 PUT 不会写入任何内容。
-`installed` 是**本服务端**最近一次在该机器上完成的安装——`{version, at}`,从未安装过则为 `null`。它持久化在数据根目录下,因此能跨重启、跨热推、跨「在别的机器上安装」而保留;它记录的是本端做过什么,而非对远端的实地探查,所以被手工清空的远端仍显示为已安装,直到下一次安装将其修正。安装失败不写入任何记录。
+无论哪种开启状态,最终生效的 `NO_PROXY` 都包含 `localhost,127.0.0.1,::1`,所以回环流量永远不会走代理。
-`machineId` 是该机器**自身**的 id——由运行在那里的服务端铸造的 16 位 base64url 字符(其 `machine` 表),跨改名、改别名与重装都保持不变,是所有存储引用应当指向的东西。该机器上的服务端尚未启动过时为 `null`,因为还没有任何东西铸造过它;它与 `status` 在同一次往返中获取,并记录在安装记录旁。同一主机的两个别名会报告相同的 `machineId`。
+### 附件上限
-`local` 标记服务端自身所在的机器。它始终出现在列表中、始终是已安装、始终在运行——它就是正在应答的那一个——并且永远不是安装目标:对它 `POST …/install` 返回 `409` `self_install`。
+输入框中的文件附件由两个以整数 MB 为单位的值控制。两者都从下一个请求起生效,无需重启,因为校验逻辑和请求体上限在每次请求时都会读取它们。
-`status` 为 `{state, checkedAt, port?, detail?}`,`state` 取 `running` / `stopped` / `unreachable` 之一;该机器尚未被探测时为 `null`。没有单独的 ssh 状态:ssh 是传输方式,因此连不上的机器就是 `unreachable`,并在 `detail` 中保留 OpenSSH 自己的原话。`GET` 从不发起探测——它只报告最近一次的答案——因为一次探测是每台机器一次 ssh 往返,而列表本身只是配置文件的文本。真正花费这些往返的是 `POST /api/machines/probe`,且只针对安装过的机器。
+- `attachmentMaxMb`(默认 100)是单个文件的大小上限,超过则返回 `413` `file_too_large`。
+- `attachmentTotalMb`(默认 120)是单条消息解码后字节总数的上限,超过则返回 `413` `payload_too_large`。
-已连接机器的 API 可通过本源上的 `/server/<machineId>/api/…` 访问,经由本服务端持有的那一条 ssh 会话拨达——是该会话内部的一个 channel(走它的 SOCKS 端口),从不是第二条连接。以机器自身的 id 而非它被访问时所用的 ssh 别名寻址:别名只存在于某一份配置文件中,若以它为键,一旦有人重命名主机,该机器的 URL 就会随之改变;而 id 是 base64url,放在路径中无需任何百分号编码。**仅限管理员**,且只有一个身份:请求在对端以那台机器的管理员身份发出,会话由本服务端通过自己的 ssh 权限铸造(在机器上执行 `penguin auth token`)——浏览器的 cookie 不会过去,机器的 cookie 也不会回来。只有 `/api` 会被转发——前端始终是本地的。
+PUT 按如下规则校验:
-安装是任务而非请求:它要探测对端,可能下载并校验一份 Node 运行时,再经 scp 复制镜像——最坏情况以分钟计。`POST` 启动后立即返回,客户端轮询 `GET` 读取 `job.log`,其中是对端自己的原话(ssh 的诊断、远端安装器的输出)。连接(`POST …/connect`)与重启(`POST …/restart`)是同一形状的任务,以 `job.kind`(`install` / `connect` / `restart`)区分。运行期间 `job.result` 为 `null`,结束后安装为 `{ok: true, installed: "installed" | "already-installed", version}`、连接与重启为 `{ok: true, connected: true}`,失败为 `{ok: false, step, message, canReplaceProgram?}`——`canReplaceProgram` 标记一种下一步是「无论如何都安装程序」的失败(`POST …/install` 带 `{replaceProgram: true}`),只提供选项而不自动执行,因为它会重启一个别人可能正在用的服务端。同一时刻只允许一个任务;任务存于内存,热推与重启都不保留,重跑即是恢复手段——每一步都是幂等的。
+- 两者都必须是 1–200 之间的整数。
+- 生效的总量(本次 PUT 传入的值;若本次未修改,则为已存储的值)不得低于生效的单文件上限。
+- 其余情况返回 `400`,错误码为 `invalid_attachment_limit`,且这次 PUT 不会写入任何内容。
-在任何 ssh 运行之前就能判定的拒绝各有错误码:`409` `install_running`、`404` `unknown_machine`、`409` `no_install_image`,以及 `409` `self_install`——本服务端不会把这份构建盖到自己正在运行的程序目录上。除 `local` 那一行之外,指回本机的别名(`Host localhost`、本机的第二个名字)一旦被探测到报出本服务端自己的 id,同样会被拒绝。
+有两项限制不可更改:每条消息的文件数量上限(20)和内嵌图片上限(20MB,超限返回 `413` `image_too_large`)。内嵌图片会写入 Trace,之后每次分页加载历史、每次恢复会话都要重新读取,因此刻意不随附件上限一同调大。`GET /api/me` 会在 `uploadLimits` 中返回上述全部限制,客户端发送文件前可以先对照实际生效的限制检查文件。
-### 版本与在线更新
+### 公司模式开关
-| 方法 | 路径 | 说明 |
-| --- | --- | --- |
-| GET | /api/version | 当前运行构建的身份,外加该根目录被推送的 harness:`{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}`,与 `penguin version --json` 输出同一份记录。`harness` 描述该数据根目录的 HMR store(`{source, pushedAt, bundles}`,其中 `source` 为推送方 checkout 的 `{repo, revision}`),从未被推送过时为 null。`describe` 是单行身份(发布版为 `v0.2.3`,源码构建为 `v0.2.3-14-g9e8f7d6-dirty`);`channel` 取 `release` 或 `source`;`buildDate`(UTC yyyy-mm-dd)与 `commit` 在构建时打入、无需联网,源码构建以及打入机制之前的发布版为 null;`branch` 与 `dirty` 记录源码构建的 git 位置,发布版为 null |
-| GET | /api/version/update-check | 对比 GitHub 最新 Release 与当前版本:`{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`;`?force=1`(手动「检查更新」)绕过 TTL 缓存,结果照常写入缓存 |
-| GET | /api/version/update | **仅管理员。**在线更新任务的状态:`{state: idle \| running \| done, targetVersion, phase?, percent?, output, result?, startedAt?, finishedAt?}`——运行中带 `phase`(`resolving` / `downloading` / `installing`)与 `percent`(从安装器的进度条读出);结束后带 `result`(`{status, reason?, output, needsRestart}`)。更新弹窗在任务运行期间轮询它 |
-| POST | /api/version/update | **仅管理员。**启动在线更新任务——在服务器上后台运行 `penguin update --yes`——已有任务在跑则并入;应答与 GET 完全一致。已结束的任务可以再次启动(即重试) |
-| POST | /api/version/restart | **仅管理员。**请求进程在优雅关闭后以托管进程约定的重启退出码退出,由 `penguin server \| penguin web` 在已安装的版本上重新拉起:`{restarting: true}`;没有托管进程时为 `{restarting: false, reason: "no_supervisor"}` |
+`companyMode` 是服务器的**启用公司模式**开关,默认关闭。修改无需重启即生效:开关关闭期间,所有组织路由都返回 `404` `company_mode_off`,组织的调度器也不会触发任何事件。
-`update-check` 是服务端唯一自动发起的对外网络请求,并且严格失败兜底:查询失败仍返回 200,只是设置 `error`(`network` / `rate_limited` / `bad_response`)且 `latestVersion` 为 null;结果在内存中缓存(成功 1 小时、失败 10 分钟);设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭该查询(返回 `disabled: true`,不发起任何网络请求)。Owner 主动发起的供应商 Key 授权会另外产生对外请求。更新的 `status` 为 `updated`(需重启服务才能运行新版本)、`failed` 或 `unsupported` —— 后者包括服务不是通过 `penguin server|web` 启动(`reason: "not_launched_via_cli"`),以及 CLI 自身拒绝执行(源码运行、无法识别的安装方式、Windows);`output` 携带 CLI 输出的末尾片段。
+## 机器(仅管理员)
-### Project 与成员
+通过 ssh 在其他主机上安装本服务器的构建,并管理与这些主机的连接。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/projects | 当前用户可见的 Project 列表 |
-| POST | /api/projects | 创建 Project |
-| DELETE | /api/projects/:projectId | 删除 Project |
-| POST | /api/projects/:projectId/suggest-id | 为新建对象的显示名提议一个语义 id:`{name, kind, taken?}`,`kind` 为 `project`、`agent`、`benchmark`、`org` 或 `channel`,`taken` 为提议须避开的 id → `{id, source, reason?}`。路径中 Project 的缺省 Model 把名称译成该 kind 拼写的英文 id(`source: model`)——新建 Project 的对话框借用打开它的那个 Project;首次回答拼不出 id 时,会带上「只回答标识符本身」的格式要求再问一次;未配置 Model 或两次回答都无法用时,以名称的 ASCII slug 兜底(`source: fallback`);两条路都命名不了的名称回一个带日期的占位 id(`source: placeholder`),并带上 `reason`:`no_default_model`、`model_failed`、`unusable_answer` 或 `no_ascii`。该路由不会因为「名称译不出来」而失败——问了 id 的对话框一定拿得到一个。各 kind 只在 id 的形状、服务端自行避开的 id 与调用权限上不同:`project` 在 admin 名下是 snake_case,其他用户是 `<用户名>-<后缀>`,避开服务器上已有的全部 Project id;`agent` 是 snake_case,避开该 Project 的 Agent;`benchmark` 是 kebab-case,避开该 Project 的 Benchmark,仅 Owner 可调用;`org` 与 `channel` 带 `co_` / `ch_` 前缀,模型的回答本就带前缀时不会加第二遍,公司模式关闭时回 404 `company_mode_off`。其余调用者须是该 Project 的成员。服务端自行避开的是该 kind 的创建路由会以「已占用」拒绝的全部名称——列表里看不到的残留目录(如没有配置文件的 Benchmark 目录)也算在内——它们不写进提示词,撞名时只加 `_2` / `-2` 后缀;以数字开头或只有一个字符、因而不合规则的 id 前面补上类型名(如 `agent_3d_viewer`);占位 id 为 `project_<yyyymmdd>`、`agent_<yyyymmdd>`、`benchmark-<yyyymmdd>`、`co_org_<yyyymmdd>` 与 `ch_channel_<yyyymmdd>`(非 admin 的 Project 带用户名前缀)。Model 一侧的每一次落空都记为 `id_suggest_failed` 错误,`org` / `channel` 的来源为 `organization`,其余为 `id_suggest`;该次补全关闭思考、使用共享的元请求预算,不属于任何 Session,也不计量 |
-| GET | /api/projects/:projectId/members | 成员列表 |
-| POST | /api/projects/:projectId/members | 添加成员:`{userId}` |
-| DELETE | /api/projects/:projectId/members/:userId | 移除成员 |
+| GET | `/api/projects/:projectId/machines` | 本机以及服务器自身 `~/.ssh/config` 中的主机别名,连同本 Project 的安装记录、最近状态和当前任务:`{machines: [{id, alias, machineId, installed, elsewhere?, local, connection, api, status}], imageVersion, job}` |
+| POST | `/api/projects/:projectId/machines/probe` | 逐台询问本 Project 已安装机器正在做什么(每台一次 ssh 往返,最多 5 台并发),返回携带最新状态的列表 |
+| POST | `/api/projects/:projectId/machines/:machineId/install` | 开始在这台主机上安装当前构建,并将这台主机分配给本 Project;任务运行期间返回 `202`,响应体相同 |
+| POST | `/api/projects/:projectId/machines/:machineId/connect` | 启动那台机器的服务器,并维持那条唯一的连接;connect 任务运行期间返回 `202`,响应体相同 |
+| POST | `/api/projects/:projectId/machines/:machineId/disconnect` | 断开连接,远端服务器继续运行 |
+| POST | `/api/projects/:projectId/machines/:machineId/restart` | 停止那台机器的服务器,并在同一端口重新启动;返回 `202`,任务运行期间返回 `409` |
+| GET | `/api/projects/:projectId/machines/:machineId/dirs?path=` | 那台机器上 `path` 的子目录,经由保持中的连接读取;Workspace 选择器浏览的就是这些目录 |
+| POST | `/api/projects/:projectId/machines/:machineId/release` | 将那台机器移出本 Project;机器上的安装保持不变 |
+
+无论个人服务器还是多用户服务器,这组路由都仅限管理员:安装会以服务器账号的密钥运行 ssh,并在另一台机器上写入程序目录——这是所有者才有的能力,不是访客该有的。服务器从不写入自己的 ssh 配置,也从不解析它。机器列表就是配置文件的原文,不管声明了多少台主机都只读取一次;每个别名都按原样传给 ssh,因此每次都由 ssh 套用自己的配置。
+
+- `POST …/install` 可以携带请求体 `{replaceProgram: true}`,用来回应任务过程中提出的这个要求:即使版本已经一致,服务器也会重新安装程序并重启它。
+- `POST …/connect` 维持一条 `ssh -T -D` 会话:空闲时永不超时,断开后自动重连,服务器重启或热推送后也会自动恢复。Windows 机器返回 `409` `connect_unsupported`,因为没有 shell 可以维持会话。
+- `POST …/disconnect` 断开后远端服务器继续运行:它属于那台机器,其他人可能还在使用。
+- `POST …/restart` 之所以是独立操作,是因为机器上的文件可以在运行期间更新,只有重启才能让进程与文件保持一致。
+- `GET …/dirs` 与下文的 API 代理一样,用机器自身的 id 寻址。机器未连接时返回 `404`,因为读取操作绝不会自行建立 ssh 连接。
+
+### 机器字段
+
+- `elsewhere`:这台主机已由其他 Project 安装,可以直接接管,而不必重新安装。
+- `imageVersion`:将要推送的版本;本服务器完全没有安装镜像时为 `null`。只有从未接收过热推送的开发检出属于这种情况,此时每次安装都会失败,返回 `409` `no_install_image`。这个版本就是当前运行安装自身的版本:热推送的服务器发送它正在运行的 bundle(`0.0.0-hmr.<cli>.<web>`),tarball 或打包安装则发送自己的目录树,所以两端天然一致。
+- `installed`:本服务器最近一次在那台机器上执行的安装,格式为 `{version, at}`;从未安装过则为 `null`。它保存在数据根目录下,因此重启、热推送和其他机器上的安装都不会使它丢失。它记录的是实际执行过的操作,并不核对远端状态,所以手动清空过的机器仍会显示为已安装,直到下一次安装把它纠正过来。安装失败不会留下任何记录。
+- `machineId`:机器自身的 id,由运行在那台机器上的服务器生成(记录在它的 `machine` 表中),共 16 个 base64url 字符。重命名、修改别名和重新安装都不会改变它,持久化引用应指向它。在那台机器上启动过服务器之前,它为 `null`,因为还没有任何东西生成过它。本服务器在与 `status` 同一次往返中获知它,并把它与安装记录存放在一起。同一主机的两个别名报告相同的 `machineId`。
+- `local`:标记本服务器所在的机器。由于应答请求的正是它,这条记录始终在列表中,始终显示为已安装且正在运行;它也永远不会成为安装目标:对它调用 `POST …/install` 返回 `409` `self_install`。
+- `status`:`{state, checkedAt, port?, detail?}`,其中 `state` 为 `running`、`stopped` 或 `unreachable`;从未探测过的机器为 `null`。没有单独的 ssh 状态。ssh 就是传输通道,连不上的机器即为 `unreachable`,`detail` 携带 OpenSSH 自己的报错信息。`GET` 从不主动探测,只报告最近一次的结果,因为每探测一台机器都要花费一次 ssh 往返,而列表本身只是配置文本。只有 `POST …/machines/probe` 会付出这些往返开销,而且只针对已安装的机器。
+
+### 已连接机器的 API
+
+已连接机器的 API 可以通过本服务器 origin 上的 `/server/<machineId>/api/…` 访问。请求经由本服务器与那台机器之间唯一的那条 ssh 会话传输,走的是会话内部经由它的 SOCKS 端口的一条通道,绝不另开第二条连接。
+
+URL 使用机器自身的 id,而不是连接所用的 ssh 别名。别名只存在于某个配置文件里,若以别名为准,主机一改名,机器的 URL 就会跟着变。id 采用 base64url 编码,放进路径无需百分号转义。
+
+该代理仅限管理员,且只使用单一身份:请求在对端以那台机器的管理员身份执行,所用会话由本服务器凭借自身的 ssh 访问能力签发(在那台机器上执行 `penguin auth token`)。浏览器的 Cookie 不会传到对端,机器上的 Cookie 也不会带回本地。只有 `/api` 会转发,前端仍在本地运行。
+
+### 任务
+
+安装是一个任务,而不是单次请求。它要探测对端,可能还要下载并校验 Node 运行时,再通过 scp 复制镜像,整个过程可能耗时数分钟。`POST` 启动任务后立即返回。客户端轮询 `GET` 获取 `job.log`,其中是对端自己的输出(ssh 的诊断信息和远端安装器的输出)。
+
+连接(`POST …/connect`)和重启(`POST …/restart`)也是同样形式的任务,通过 `job.kind`(`install`、`connect` 或 `restart`)区分。任务运行期间 `job.result` 为 `null`,结束后为以下之一:
-成员写操作仅限 Owner。成员路由在桌面模式下同样返回 `403 desktop_single_user`(见上文「用户管理」)。
+- 安装:`{ok: true, installed: "installed" | "already-installed", version}`
+- 连接或重启:`{ok: true, connected: true}`
+- 失败:`{ok: false, step, message, canReplaceProgram?}`
-### 模型
+`canReplaceProgram` 表示这次失败的后续步骤可以是强行安装程序:调用 `POST …/install` 并附带 `{replaceProgram: true}`。服务器只提供这一步而不擅自执行,因为它会重启一台可能还有其他人在使用的服务器。
+
+同一时刻只运行一个任务。任务只存于内存,热推送或重启后就会丢失。要恢复就重新执行一遍:每一步都是幂等的。
+
+### 拒绝情形
+
+这些拒绝在运行任何 ssh 命令之前就已判定,每个都有专属错误码:
+
+- `409` `install_running`
+- `404` `unknown_machine`
+- `409` `no_install_image`
+- `409` `self_install`:本服务器不会把自己的构建推送覆盖到自身正在运行的程序目录上。除了 `local` 这一行,指回本主机的别名(例如 `Host localhost` 或本主机的另一个名字)同样会拒绝,前提是某次探测已从它那里读到本服务器自己的 id。
+
+## 版本与自更新
+
+查看当前运行的构建,检查 GitHub 上是否有更新的 release,并执行自更新。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/projects/:projectId/models | 模型列表(api_key 掩码显示);有促销的行以 `discount` 携带其折扣 |
-| PUT | /api/projects/:projectId/models | 全表替换,条目以 `(provider, modelId)` 为键;条目的 `discount` 写入或清除其促销折扣(见下文) |
-| POST | /api/projects/:projectId/models/test | 连通性测试:`{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
-| POST | /api/projects/:projectId/models/detect | 自定义 base URL 的协议自动检测:按 `openai-responses` → `ant-messages` → `openai-chat` 顺序探测,先用整理后的 URL(整段端点路径会先被剥掉),再用它增删 `/v1` 后的形式,返回第一个被提供的协议与实际应答的 base URL:`{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}` |
-| POST | /api/projects/:projectId/models/list | 新增分组导入所用的端点模型列表:按检测出的协议列出端点服务的全部模型 id:`{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |
-| POST | /api/projects/:projectId/models/detect-vision | 视觉能力探测:用该模型的凭据发送一张 1x1 图片(一次真实计费的补全):`{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported\|unsupported\|failed, message?}` |
+| GET | `/api/version` | 当前构建的标识,以及这个数据根目录收到的 harness 推送 |
+| GET | `/api/version/update-check` | 将 GitHub 上的最新 release 与当前运行版本对比 |
+| GET | `/api/version/update` | 仅管理员。自更新任务的状态 |
+| POST | `/api/version/update` | 仅管理员。启动自更新任务 |
+| POST | `/api/version/restart` | 仅管理员。通过托管进程重启该进程 |
+
+### GET /api/version
+
+返回当前构建的标识以及这个数据根目录收到的 harness 推送:`{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}`。与 `penguin version --json` 打印的记录完全一致。
+
+- `describe` 是一行式的版本标识:release 构建形如 `v0.2.3`,源码检出的构建形如 `v0.2.3-14-g9e8f7d6-dirty`。
+- `channel` 为 `release` 或 `source`。
+- `buildDate`(UTC yyyy-mm-dd)和 `commit` 在构建时写入,读取时无需联网。源码构建,以及早于这一写入机制的 release,这两项为 null。
+- `branch` 和 `dirty` 记录源码构建的 git 位置,release 中为 null。
+- `harness` 以 `{source, pushedAt, bundles}` 描述数据根目录的 HMR 存储,其中 `source` 是执行推送的检出的 `{repo, revision}`。这个数据根目录从未接收过推送时为 null。
+
+### GET /api/version/update-check
+
+将 GitHub 上的最新 release 与当前运行版本对比:`{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`。手动**检查更新**发送的 `?force=1` 可绕过 TTL 缓存,结果仍按常规缓存。
+
+这次查询失败时平稳降级:
+
+- 查询失败仍返回 200,只是 `error` 会带值(`network`、`rate_limited` 或 `bad_response`),且 `latestVersion` 为 null。
+- 结果缓存在内存中:成功后缓存 1 小时,失败后缓存 10 分钟。
+- `PENGUIN_UPDATE_CHECK=off` 可彻底关闭查询:响应带 `disabled: true`,且不发起任何网络请求。
+
+这个开关只关掉这一项检查。无论它取什么值,模型请求、已启用的远程控制连接、由所有者发起的供应商 Key 授权和代理测试都照常出站。
+
+### GET /api/version/update
+
+仅管理员。返回自更新任务的状态:`{state: idle | running | done, targetVersion, phase?, percent?, output, result?, startedAt?, finishedAt?}`。更新运行期间,更新对话框会轮询这个接口。
+
+- 任务运行期间,`phase` 为 `resolving`、`downloading` 或 `installing`,`percent` 取自安装器的进度条。
+- 任务完成后,`result` 为 `{status, reason?, output, needsRestart}`。
-所有涉及模型的接口都要求完整的 `(provider, modelId)` 二元组,不做任何推断:只带一半的请求一律 400,绝不会退化为一次查找。模型引用本身可省略的场景(创建 Session、定时任务)省略的是整对,两半都不给即选用 Project 默认模型。
+`result` 中的 `status` 为以下之一:
-行上的 `pricing` 恒为牌价。促销折扣是从牌价中扣除的比例,取值在 0 与 1 之间(不含两端),不写入 `.project_config.toml`,而由服务端按行存于 `web.db`、在计算成本时扣除。`PUT /models` 时,条目带 `discount` 即按其写入:数字写入,`null` 清除,其他取值在写入任何内容之前即返回 400。省略 `discount` 的条目保留已存折扣,但若条目改名(`renamedFrom` 指向另一对引用)或 `pricing` 与已存价格不同,则一并清除;新表中不再出现的行,折扣随之删除。
+- `updated`:重启服务即可运行新版本。
+- `failed`。
+- `unsupported`:要么服务器不是通过 `penguin server` 或 `penguin web` 启动的(`reason: "not_launched_via_cli"`),要么 CLI 拒绝更新(源码检出、无法识别的安装布局,或 Windows)。
-`PUT /models` 同时会使该 Project 已缓存的 Session 运行时失效(与 vault 更新同一套生效语义):进行中的运行不做热替换,但该 Project 下任何 Session 的下一个 Task 都会重新装载并读到新的 `api_key` / `base_url`。它还会向该 Project 已打开的 Session 通道发布 `credentials_updated` 事件(见下文「流式推送」),且模型响应携带 `updatedAt`(配置文件 mtime)——Web App 用它与最近一次鉴权失败的时间比较,决定鉴权失败的输入框是否继续禁用。
+`output` 保存 CLI 自身输出的最后一段。
-#### Penguin Go Key 授权
+### POST /api/version/update
-以下路由全部仅限 Owner。浏览器只会得到本地 flow id 与授权 URL,不会得到设备密钥、中转站交付的 API Key 或其他平台响应字段。PenguinHarness 在服务端校验平台模型清单,把交付的 Key 写入 `penguin-go` 既有条目,并按平台元数据创建本地缺失模型;已有模型会刷新平台牌价和客户端协议,端点及其他由 Project 管理的配置不会被覆盖,模型也不会被删除。Project 模型表写入后,平台返回的折扣会整体替换该分组存于 `web.db` 的促销折扣,从不写入 `.project_config.toml`。
+仅管理员。启动自更新任务,任务会在服务器主机后台运行 `penguin update --yes`。如果已有任务在运行,这个请求会并入其中。响应即任务状态,与 `GET /api/version/update` 的返回完全一致。已完成的任务可以重新启动,作为重试。
+
+### POST /api/version/restart
+
+仅管理员。让进程在优雅关闭后以托管进程的重启码退出,`penguin server` 或 `penguin web` 随即会在已安装的 release 上重新拉起它。返回 `{restarting: true}`;如果没有托管进程在管理这个进程,则返回 `{restarting: false, reason: "no_supervisor"}`。
+
+## Project 与成员
+
+Project、Project 成员,以及保存在 `.project_config.toml` 中的 Project 级设置。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| POST | /api/projects/:projectId/platform-auth/start | 开启一次性授权流程;按平台截止时间过期,本地最长保留十分钟 |
-| POST | /api/projects/:projectId/platform-auth/sync | 使用已保存的 Key 获取平台模型清单,新增本地缺失模型并刷新已有模型的平台元数据;响应以 `added` / `updated` 返回数量,Key 无效时返回 `platform_reauthorization_required` |
-| GET | /api/projects/:projectId/platform-auth/:flowId/status | 由服务端轮询中转站,把已交付 Key 写入模型组并新增平台模型 |
-| POST | /api/projects/:projectId/platform-auth/:flowId/retry | 写入失败时仅重试本地原子写,不重复请求一次性交付 |
-| POST | /api/projects/:projectId/platform-auth/:flowId/cancel | 取消本地流程;中转站的 pending 记录按自身 TTL 过期 |
+| GET | `/api/projects` | 当前用户可见的 Project |
+| POST | `/api/projects` | 创建 Project:`{projectId, name?}` → 201 `{project}` |
+| PATCH | `/api/projects/:projectId` | 重命名 Project:`{name}` → `{project}` |
+| DELETE | `/api/projects/:projectId` | 删除 Project |
+| GET | `/api/projects/:projectId/members` | 列出成员 |
+| POST | `/api/projects/:projectId/members` | 添加成员:`{userId}` |
+| DELETE | `/api/projects/:projectId/members/:userId` | 移除成员 |
+| GET / PUT | `/api/projects/:projectId/chat-defaults` | 读取 / 替换新建对话的默认值 |
+| GET / PUT | `/api/projects/:projectId/command-policy` | 读取 / 替换沙箱命令策略 |
+| POST | `/api/projects/:projectId/suggest-id` | 为正在创建的对象的显示名提议一个语义化 id |
+
+- `PATCH /api/projects/:projectId` 仅限所有者,且只能修改显示名称(1–100 个字符)。Project id 就是它的目录名,永不改变。
+- `DELETE /api/projects/:projectId` 仅限所有者。`default_project` 与 CLI 共享,无法删除:返回 `409` `cannot_delete_default_project`。
+- 成员的写操作仅限所有者。桌面模式下,成员相关路由同样返回 `403 desktop_single_user`;参见[用户管理(仅管理员)](#用户管理仅管理员)。
+- `chat-defaults` 对应 `[default_chat]` 配置块:`{agentId?, workspace?, approvalMode?, thinkingLevel?}`。任何成员都可以读取,只有所有者可以替换。PUT 会替换整个块:省略的键清除对应默认值,空请求体则移除整个块。`agentId` 必须指向 Project 中已存在的 Agent(否则返回 `400` `unknown_agent`)。`workspace` 只是预填值,创建 Session 时才会校验;留空表示临时 Workspace。`thinkingLevel` 用作未在自身配置里设置思考等级的 Agent 的兜底值,不接受 `none`。默认模型不属于这个块,由模型相关路由管理。
+- `command-policy` 对应 `[command_policy]` 配置块:`{enabled?, rules: [{name, pattern, description?, enabled?}]}`。任何成员都可以读取,只有所有者可以替换。PUT 必须携带完整的规则列表(空数组表示没有任何规则),规则最多 64 条。每条规则需要名称(最多 64 个字符)和 pattern(最多 512 个字符,且必须能编译为正则表达式),description 最多 300 个字符。pattern 编译失败返回 `400` `invalid_rule_pattern`,其他格式错误的规则返回 `400` `invalid_rules`,`enabled` 不是布尔值返回 `400` `invalid_enabled`。参见[命令策略](/configuration#命令策略)。
+
+### 语义化 id 提议
+
+`POST /api/projects/:projectId/suggest-id` 接收 `{name, kind, taken?}`,返回 `{id, source, reason?}`。`kind` 取 `project`、`agent`、`benchmark`、`org` 或 `channel`,`taken` 是提议必须避开的一批 id。id 输入框旁边的**用 AI 生成**按钮,背后都是这一条路由。
+
+- 路径里这个 Project 的默认模型把名称翻译成一个符合该 kind 拼写风格的英文 id(`source: model`);**新建 Project** 对话框借用的是打开它时所在的那个 Project。回答没有得出 id 时,会带着明确的格式要求再问模型一次。
+- 没有配置模型,或两次回答都不可用时,改用名称生成的 ASCII slug(`source: fallback`)。
+- 两条路径都生成不出 id 时,给出一个带日期的占位 id(`source: placeholder`),`reason` 为 `no_default_model`、`model_failed`、`unusable_answer` 或 `no_ascii`:`project_<yyyymmdd>`、`agent_<yyyymmdd>`、`benchmark-<yyyymmdd>`、`co_org_<yyyymmdd>` 或 `ch_channel_<yyyymmdd>`;非管理员的 Project id 前面还带用户名。
+- 各个 kind 的差别只有三处:id 的形状、服务端自己要避开的 id,以及谁可以请求。`project` 对管理员是 snake_case,对其他人是 `<username>-<后缀>`,要避开服务器上的每一个 Project id;`agent` 是 snake_case,要避开这个 Project 的 Agent;`benchmark` 是 kebab-case,要避开这个 Project 的 Benchmark,且仅限所有者;`org` 和 `channel` 带 `co_`、`ch_` 前缀,回答里已有前缀时不会重复添加,公司模式关闭时返回 `404` `company_mode_off`。其余情况下调用者必须是这个 Project 的成员。
+- 服务端自己要避开的,是该 kind 的创建路由会以「已占用」拒绝的那些名称,包括任何列表都不显示的残留目录。它们不会进入提示词;发生冲突时只会加上 `_2` / `-2` 后缀。核心词因为以数字开头或只有一个字符而被该 kind 的规则拒绝时,会放到这个 kind 的名词后面再试一次(`3D Viewer` → `agent_3d_viewer`)。
+- 名称翻译不出来时路由也不会失败,因此请求 id 的对话框总能拿到结果。模型侧的每一次失败都会记录为 `id_suggest_failed` 错误,`org` 和 `channel` 记在 `organization` 来源下,其余记在 `id_suggest` 下。这次补全关闭思考运行,使用共享的元请求预算,不属于任何 Session,也不计量。
+
+## 模型
+
+管理 Project 的模型表,并探测模型端点。模型表对所有成员开放读取;本节其余路由仅限所有者。
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | `/api/projects/:projectId/models` | 列出模型(`api_key` 做掩码处理);正在促销的条目会带上促销折扣 `discount` |
+| PUT | `/api/projects/:projectId/models` | 整表替换,以 `(provider, modelId)` 为键;条目的 `discount` 用来保存或清除它的促销 |
+| PUT | `/api/projects/:projectId/models/default` | 设置默认模型:`{provider, modelId}` → `{defaultModel}` |
+| POST | `/api/projects/:projectId/models/test` | 测试连通性:`{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
+| POST | `/api/projects/:projectId/models/detect` | 检测自定义 base URL 使用的协议 |
+| POST | `/api/projects/:projectId/models/list` | 列出端点提供的模型 id,供添加分组时导入 |
+| POST | `/api/projects/:projectId/models/detect-vision` | 探测模型是否接受图片 |
+
+凡是指定模型的路由都要求完整的 `(provider, modelId)` 组合,不做任何推断:只带一半的请求一律返回 400,绝不会退化为一次查找。在模型引用本身可选的场景(创建 Session、定时任务)里,两个都不填则使用 Project 的默认模型。
+
+条目的 `pricing` 记的始终是牌价。促销是一个大于 0、小于 1 的折扣率,从牌价中扣除,但从不写进 `.project_config.toml`:服务端按条目把它保存在 `web.db` 里,计算用量成本时再扣除。`PUT /models` 里,条目带的 `discount` 说了算——数字表示保存这个促销,`null` 表示清除,其他取值会在写入任何内容之前返回 `400`。条目不带 `discount` 时保留已存的促销,除非它改名(`renamedFrom` 指向另一对引用)或 `pricing` 与已存的不同,这两种情况下促销会被清除。新表里没有的条目,其促销随之删除。
-成功写入后会使该 Project 的缓存运行时失效,并发布 `credentials_updated`。只要平台返回非空模型清单,分组不存在时也可以直接创建;`apply_failed` 表示通过校验的交付内容未能写入本地配置,重试接口只会再次执行这一步本地写入。
+- `PUT /models` 还会使 Project 缓存的 Session 运行时失效,生效值的语义与 vault 更新相同。已经开始的运行不会切换,但 Project 内任何 Session 的下一个 Task 都会重新加载运行时,读取新的 `api_key` / `base_url`。这条路由还会向 Project 已打开的 Session 通道发布 `credentials_updated` 事件(参见[流式传输(SSE)](#流式传输sse))。模型响应带有 `updatedAt`,即配置文件的修改时间;Web App 拿它和最近一次认证失败的时间对比,决定那次失败导致禁用的输入框是否继续保持禁用。
+- `PUT /models/default` 只修改默认模型,无需重发模型表或凭证。这对组合必须指向一条已配置的条目,否则返回 400。已有的 Session 沿用创建时的模型,因此这条路由既不会使运行时失效,也不会发布 `credentials_updated`。
+- `POST /models/detect` 依次探测 `openai-responses`、`ant-messages`、`openai-chat`。先按输入原样尝试 URL(做归一化,去掉粘贴进来的端点路径),再尝试为同一 URL 加上或去掉 `/v1`,并报告第一个命中的协议及提供这个协议的 base URL:`{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}`。
+- `POST /models/list` 返回端点在检测到的协议下提供的模型 id:`{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}`。
+- `POST /models/detect-vision` 用这个模型的凭证发送一张 1x1 图片,这是一次真实计费的补全请求:`{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported|unsupported|failed, message?}`。
-#### 授权新建 API key
+### 签发供应商 API key
-仅限 Owner,但供应商跳回的 `GET /callback` 例外——它无需会话即可应答,且只能把跳回时带来的授权码存到流程上,详见下文。若某个供应商分组在内置目录中声明了授权流程,用户可以在浏览器里授权并**新建**一个 API key,不必再去控制台复制。
+内置模型目录中发布了授权流程的供应商分组,可以在浏览器里直接为用户签发新的 API key,用户不必再去控制台复制。这些路由仅限所有者使用,唯一的例外是重定向接收端 `GET /callback`:它无需会话即可响应,且只能把跳转带来的授权码交给对应流程(见下文)。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| POST | /api/projects/:projectId/model-oauth/start | 开启一次流程:`{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |
-| GET | /api/projects/:projectId/model-oauth/callback | 供应商跳回的地址(`?flow=&code=`):把授权码存到流程上,并返回一个 HTML 页面;`HEAD` 返回 405 |
-| GET | /api/projects/:projectId/model-oauth/:flowId | 轮询流程状态,并顺带兑换已存下的授权码、写入 key:`{status: pending\|done\|error, provider, error?}` |
-| POST | /api/projects/:projectId/model-oauth/:flowId/code | 兑换用户粘贴的授权码:`{code}` → `{ok, applied?, error?}` |
+| POST | `/api/projects/:projectId/model-oauth/start` | 发起流程:`{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |
+| GET | `/api/projects/:projectId/model-oauth/callback` | 供应商跳转回来的地址(`?flow=&code=`):把授权码存到流程上,并返回一个 HTML 页面。`HEAD` 返回 405 |
+| GET | `/api/projects/:projectId/model-oauth/:flowId` | 轮询流程,兑换已存下的授权码并写入 key:`{status: pending\|done\|error, provider, error?}` |
+| POST | `/api/projects/:projectId/model-oauth/:flowId/code` | 兑换用户粘贴的授权码:`{code}` → `{ok, applied?, error?}` |
-PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不下发到客户端;新建出的 key 直接写入该分组的模型,不回传、不记录日志、也不出现在 URL 中。一次流程只属于某个 Project 下的某个用户且只能用一次:第二次兑换会被拒绝,`/start`、`/:flowId`、`/:flowId/code` 也拒绝该 Owner 以外的任何人。
+PKCE verifier 由服务器生成,只在内存中保存 10 分钟,从不发送给客户端。签发出的 key 直接写入这个供应商分组的模型配置,从不返回、从不记录日志,也从不放进 URL。一个流程只属于一个 Project 中的一个用户,且只能使用一次:不接受第二次兑换,除这个用户外,任何人都无法调用 `/start`、`/:flowId` 和 `/:flowId/code`。
-`GET /callback` 是唯一的例外,且只能如此。环回地址上的 OAuth 跳转由供应商所跳转的那个浏览器送达,而它未必就是发起流程的那一个——桌面端 shell 会把授权页交给**系统**浏览器打开,系统浏览器并不持有该应用来源的 Cookie。因此这一条路径挂载在会话校验之外,改以 flow id 作为凭据:32 字节随机数,十分钟有效,只能存入一次,只对开启该流程的那个 Project 生效,且只服务于确实要了跳回地址的流程(`manual` 流程会被拒绝,它压根没拿到过跳回地址)。
+`GET /callback` 必须是例外。回环地址上的 OAuth 跳转,由供应商跳转到的那个浏览器接收,而它未必是发起流程的浏览器。比如桌面 shell 会在*系统*浏览器中打开授权页,而系统浏览器没有这个应用的源的 Cookie。因此只有这一条路径挂在会话校验之外,改用 flow id 鉴权:32 个随机字节,10 分钟内有效,且只允许存入一次。授权码只能存入发起这个流程的 Project,而且只有要求过回调的流程才接受:`manual` 流程一律拒绝,因为它从未拿到过回调 URL。
-这条路由能做的事还有第二重边界:它只把授权码存到流程上,此外什么都不做。与供应商的兑换、以及写入该 Project 模型的动作,都发生在 `GET /:flowId`——Owner 自己的轮询,仍在会话校验之内。因此没有 Owner 主动查询流程状态,就不会有 key 落进任何 Project;兑换失败也在那里以 `{status: error, error}` 报出,而不是显示在跳回页面上。周边的一切同样不在豁免之内:更长的路径、其它任何请求方法(该字面路径上的 `HEAD` 返回 405),以及另外三条同级路由,仍然都需要会话。
+回调能做的事还有第二重限制:它只把授权码存到流程上,此外什么都不做。与供应商的兑换、写入 Project 模型,都发生在 `GET /:flowId`,也就是所有者自己的轮询里,仍在会话校验之后。除非所有者主动查询流程状态,否则任何 key 都进不了 Project;兑换失败也在那里以 `{status: error, error}` 报告,而不是显示在跳转页面上。回调周边的一切同样不在豁免之列:更长的路径、其他任何请求方法(这一路径本身的 `HEAD` 返回 405),以及另外三条同组路由,都仍然需要会话。
-`mode: manual` 不传回调地址,授权页改为显示一次性授权码供用户手动带回,适用于跳转回不来的部署。无论由哪条路由完成兑换,流程完成后同样会使缓存的运行时失效并发布 `credentials_updated`,与 `PUT /models` 一致。
-### 插件注册表
+`mode: manual` 不发送回调 URL,授权页会显示一个一次性授权码,由用户手动粘贴回来,适用于跳转回不来的部署。无论由哪条路由兑换授权码,流程完成后都会使缓存的运行时失效并发布 `credentials_updated`,与 `PUT /models` 完全一致。
-| Method | Path | Description |
+### Penguin Go Key 授权
+
+Penguin Go 的 key 通过服务端轮询的设备授权交付,而不是浏览器跳转,因此它有自己的一组路由。这些路由都仅限所有者。浏览器只拿到本地的 flow id 和授权 URL,拿不到设备密钥、交付的 key,也拿不到平台返回的其他内容。
+
+| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/plugins/registry | 插件市场页的插件索引:`{plugins: PluginIndexEntry[]}`——所有已配置注册表(当前仅内置注册表)合并后的索引 |
-| GET | /api/plugins/registry/readme?name=… | 某个已列出条目的说明文档:`{name, readme}`(注册表没有时 `readme` 为 null);索引未列出的名字返回 404 |
-| GET | /api/projects/:projectId/plugins/installed | 该 Project 要求的插件,并联上进程实际在跑的状态:`{plugins: [{specifier, active, builtin, modules, replaces, error?}], shipped, file, restartPending}`(成员即可) |
-| POST | /api/projects/:projectId/plugins/installed | `{specifier}`——为该 Project 要求一个随构建发布的插件(否则 400 `plugin_not_shipped`),无需重启即生效,App 自行重组——这会中止所有 Project 正在进行的 Agent 运行;启动失败的改动会被撤销(管理员) |
-| PUT | /api/projects/:projectId/plugins/installed | `{plugins}`——重写该 Project 的列表并应用;新增的名字须是随构建发布的包(管理员) |
-| DELETE | /api/projects/:projectId/plugins/installed?specifier=… | 从该 Project 的列表中去掉并应用;磁盘上什么都不变(管理员) |
+| POST | `/api/projects/:projectId/platform-auth/start` | 开启一次性授权流程,平台给出的截止时间在本地最多按十分钟计:→ 201 `{flowId, authorizeUrl, expiresAt}` |
+| POST | `/api/projects/:projectId/platform-auth/sync` | 用已存的 key 拉取平台模型目录,补齐 Project 缺少的模型并刷新平台维护的字段:→ 模型表,外加 `added` 与 `updated` 计数 |
+| GET | `/api/projects/:projectId/platform-auth/:flowId/status` | 由服务端向 Penguin Go 轮询,随后把交付的 key 写入整个分组并补齐平台的模型:`{status: pending\|applying\|completed\|cancelled\|apply_failed\|error, error?, applied?}` |
+| POST | `/api/projects/:projectId/platform-auth/:flowId/retry` | 本地写入失败后重试写入;不会再次索取这次一次性交付,流程处于其他状态时返回 `409 platform_auth_not_retryable` |
+| POST | `/api/projects/:projectId/platform-auth/:flowId/cancel` | 取消本地流程;平台侧的待处理记录按自己的 TTL 过期 |
-索引格式沿用 typst/packages 的 `index.json` 模式:扁平数组,每个元素是插件的一个版本条目(`name`、`version`、`description`、`authors`、`license`,可选 `repository` / `homepage` / `keywords` / `categories` / `updatedAt`)。注册表仅用于发现,不会导入任何插件代码;Project 通过上面的路由要求某个条目,其列表存在自己的 `.project_config.toml` 的 `[plugins]` 表里——包名 → 要求,形状同 Cargo 的 `[dependencies]`(`"@scope/name" = "*"`、版本字符串,或 `{ version = "…" }`)。进程运行的是所有 Project 表的并集。
+服务端先校验交付的 key、端点和模型目录,然后才写入任何内容。校验通过后,它把 key 写入 `penguin-go` 分组下已有的每个条目,创建平台提供而 Project 没有的模型,刷新已有模型的牌价与客户端协议,并用平台的促销替换这个分组已存的促销。端点和其他由 Project 自己维护的字段保持不变,任何模型都不会被删除;目录非空时,分组不存在也会被建出来。写入完成后会使缓存的运行时失效并发布 `credentials_updated`,与 `PUT /models` 完全一致。
-### Agent
+flow id 指向的流程不存在时返回 `404 platform_auth_flow_not_found`。`sync` 在没有已存 key 或平台拒绝这把 key 时返回 `409 platform_reauthorization_required`,平台拒绝提供目录或返回的目录无法解析时返回 `502 platform_sync_failed`,平台不可达则是 `502 platform_unreachable`。交付的 key 未能写入本地时,流程停在 `apply_failed`,重试路由正是为此准备的。
-以下路径均省略前缀 `/api/projects/:projectId`。
+## Agent
+
+下面的路径省略了 `/api/projects/:projectId` 前缀,只有两个全局的 `/api/plugins` 路由是例外。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET / POST | /agents | Agent 列表 / 创建 |
-| DELETE | /agents/:agentId | 删除 Agent |
-| GET / PUT | /agents/:agentId/config | 读写配置(AGENTS.md + system_config.yaml,PUT 保留 YAML 注释) |
-| GET / PUT | /agents/:agentId/vault | Vault 环境变量(值掩码显示;PUT 全表替换) |
-| GET | /agents/:agentId/memory | 记忆总览:开关、模板是否含 `{{MEMORY}}`,以及各作用域条目——用户作用域(`user`,`kind: "user"`)在前,其后为各 Workspace |
-| POST | /agents/:agentId/memory/template-placeholder | 向提示词模板插入 `{{MEMORY}}` 占位符(幂等;创建于记忆功能之前的 Agent 的显式采用路径) |
-| GET | /agents/:agentId/memory/scopes/:key/files | 列出单个作用域的主题文件(frontmatter + 文件信息);`:key` 为 workspace key 或 `user` |
-| GET / DELETE | /agents/:agentId/memory/scopes/:key/files/:name | 读取单个主题文件 / 删除它(并同步清理其 `MEMORY.md` 索引行) |
-| GET | /agents/:agentId/memory/scopes/:key/export | 把整个作用域导出为一份 JSON 文档:全部主题文件加它的 `MEMORY.md`,以附件形式下载 |
-| POST | /agents/:agentId/memory/scopes/:key/import | 把这样一份文档写回(仅 owner):`{payload, mode?, confirm?}`。`mode` 为 `skip`(缺省,只添加作用域尚未有的名字)、`overwrite`(覆盖同名文件)或 `replace`(并删除文档中没有的文件);任何会覆盖或删除的操作都需要 `confirm`,否则返回 409 `memory_import_confirm_required` |
-| GET | /agents/:agentId/export | 导出 Agent State 快照(tar.gz 下载) |
-| POST | /agents/:agentId/import | 导入快照:`{dataBase64, confirm?}`;版本冲突且未确认时返回 409 |
-| GET | /agents/:agentId/skills | 已安装 Skill 列表(从库安装走 `/plugins`) |
-| DELETE | /agents/:agentId/skills/:name | 卸载 Skill |
-| POST | /agents/:agentId/plugins | 按名称安装库内插件——各自的 Skill 与钩子包,重装即更新。`{ names }` → 201 `{ skills, hooks }`;404 `unknown_plugin` 时什么都不写 |
-| GET | /agents/:agentId/hooks | 已安装钩子包:名称、描述、版本、钩子点、所属插件的图标 |
-| POST | /agents/:agentId/hooks/archive | 从 zip 安装钩子包:`{dataBase64, overwrite?}`——hooks.json 与脚本在根目录或唯一顶层目录内,清单列出的每条命令都须指向包内文件;未带 overwrite 而同名已装时 409 `hook_exists` |
-| GET | /agents/:agentId/hooks/:name/archive | 把已安装的钩子包导出为 zip(可原样经 POST 导回) |
-| GET | `/api/plugins`(全局) | 按分类列出插件库——每个插件带其 Skill 元数据与钩子点(任意已登录用户) |
-| GET | `/api/plugins/:plugin/files`(全局) | 单个库内插件携带的全部文件,按路径键入的文本——各 Skill 的可安装 SKILL.md 与参考文件在 `skills/<name>/` 下,钩子脚本在 `hooks/` 下——供插件详情弹窗的文件浏览器使用(任意已登录用户) |
-| DELETE | /agents/:agentId/hooks/:name | 卸载钩子包 |
-
-### Schedule
+| GET / POST | `/agents` | 列出 Agent / 创建 Agent |
+| DELETE | `/agents/:agentId` | 删除一个 Agent(仅所有者) |
+| GET / PUT | `/agents/:agentId/config` | 读取 / 写入配置(`AGENTS.md` 和 `system_config.yaml`;PUT 保留 YAML 注释) |
+| POST | `/agents/:agentId/config/mcp-test` | 测试一条 MCP 服务器配置:`{name, config}` → `{ok, tools?, error?, latencyMs?}` |
+| POST | `/agents/:agentId/config/kernel-update` | 将配置合并升级到当前默认值:→ `{advanced, kept, kernelVersion}` |
+| POST | `/agents/:agentId/config/reset` | 用当前默认值覆盖 `system_config.yaml`,并返回新生成的配置 |
+| GET / PUT | `/agents/:agentId/vault` | Vault 环境变量(值做掩码处理;PUT 替换全部值,仅限所有者) |
+| POST | `/agents/:agentId/vault/template-placeholder` | 在 Prompt 模板中插入 `{{VAULT}}` 占位符(仅所有者) |
+| GET | `/agents/:agentId/memory` | 记忆概览 |
+| POST | `/agents/:agentId/memory/template-placeholder` | 在 Prompt 模板中插入 `{{MEMORY}}` 占位符 |
+| GET | `/agents/:agentId/memory/scopes/:key/files` | 列出一个作用域的主题文件 |
+| GET / DELETE | `/agents/:agentId/memory/scopes/:key/files/:name` | 读取 / 删除一个主题文件 |
+| GET | `/agents/:agentId/memory/scopes/:key/export` | 将一个作用域导出为单个 JSON 文档 |
+| POST | `/agents/:agentId/memory/scopes/:key/import` | 将导出的作用域写回(仅所有者) |
+| GET | `/agents/:agentId/export` | 导出 Agent State 快照(tar.gz 下载) |
+| POST | `/agents/:agentId/import` | 导入快照:`{dataBase64, confirm?}`;不带 `confirm` 且版本冲突时返回 409 |
+| GET | `/agents/:agentId/skills` | 已安装的 Skill(从插件库安装需通过 `/plugins`) |
+| POST | `/agents/:agentId/skills/template-placeholder` | 在 Prompt 模板中插入 `{{SKILLS}}` 占位符 |
+| POST | `/agents/:agentId/skills/archive` | 从 zip 安装 Skill:`{dataBase64, overwrite?}` → 返回 201 和 Skill 列表 |
+| GET | `/agents/:agentId/skills/:name/archive` | 将已安装的 Skill 导出为 zip |
+| DELETE | `/agents/:agentId/skills/:name` | 卸载一个 Skill |
+| POST | `/agents/:agentId/plugins` | 按名称从插件库安装插件:`{names}` → 201 `{skills, hooks}` |
+| GET | `/agents/:agentId/hooks` | 已安装的钩子包 |
+| POST | `/agents/:agentId/hooks/archive` | 从 zip 安装钩子包:`{dataBase64, overwrite?}` |
+| GET | `/agents/:agentId/hooks/:name/archive` | 将已安装的钩子包导出为 zip |
+| DELETE | `/agents/:agentId/hooks/:name` | 卸载一个钩子包 |
+| GET | `/api/plugins`(全局) | 按分类返回插件库(任何已登录用户) |
+| GET | `/api/plugins/:plugin/files`(全局) | 单个插件库插件自带的所有文件,以路径为键返回文本(任何已登录用户) |
+
+### Agent 路由
+
+- `POST /agents` 接受 `{agentId, name?, description?, plugins?, skillsDirectory?, directorySkills?, dataBase64?}`,返回 201 和 `{agent}`。`plugins` 指定要预装的插件库插件;遇到未知名称会拒绝请求,且不会创建 Agent 目录。`skillsDirectory` 和 `directorySkills` 从用户选择的目录导入 Skill(参见 [Session 创建与目录浏览](#session-创建与目录浏览)中的 `GET /dir-skills`),两者必须一起发送。`dataBase64` 让 Agent 从导出的快照启动,而不是使用默认模板。
+- `POST …/config/mcp-test` 从本机连接一条 MCP 服务器配置,列出它的工具后断开,不写入任何 Agent State。配置条目格式有误时返回 400。服务器连不上不算 HTTP 错误,照常返回 `{ok: false, error}`。
+- `POST …/config/kernel-update` 是 `reset` 的无损版本。它把缺失或仍保持旧默认值的设置标签页升级到当前默认值(记入 `advanced`),完整保留已自定义的标签页(记入 `kept`),并写入新的默认值版本(`kernelVersion`)。
+- `template-placeholder` 路由都是幂等的。Vault 和 Skills 两个路由会在 Prompt 模板中插入 `{{VAULT}}` 或 `{{SKILLS}}`;如果模板里是旧版硬编码的 `# Vault` 或 `# Skills` 小节,则替换成对应的占位符。记忆路由插入 `{{MEMORY}}`,在记忆功能推出之前创建的 Agent 就是通过它接入记忆的。
+- `POST …/skills/archive` 接受最大 14MB 的 zip。不带 `overwrite` 时,同名 Skill 已安装会返回 409 `skill_exists`。`GET …/skills/:name/archive` 导出的文件名为 `<name>.zip`;如果 Skill 的 `SKILL.md` 声明了版本,则为 `<name>-v<version>.zip`。Skill 未安装时,导出和卸载路由都返回 404 `not_found`。
+
+### 记忆
+
+- `GET …/memory` 返回记忆开关、Prompt 模板是否带有 `{{MEMORY}}`,以及每个作用域的条目:用户作用域(`user`,`kind: "user"`)排在最前,随后是各个 Workspace。
+- 在这些作用域路由中,`:key` 是某个 Workspace 的 key 或 `user`。
+- `GET …/scopes/:key/files` 列出一个作用域的主题文件,包括各自的 frontmatter 和文件统计信息。
+- `DELETE …/scopes/:key/files/:name` 删除一个主题文件,并从 `MEMORY.md` 索引中删掉对应的行。
+- `GET …/scopes/:key/export` 把作用域的全部主题文件连同 `MEMORY.md` 合成一个 JSON 文档返回,以附件形式下载。
+- `POST …/scopes/:key/import` 接受 `{payload, mode?, confirm?}`。`mode` 取 `skip`(默认值,只添加作用域缺少的文件)、`overwrite`(替换同名文件)或 `replace`(还会删除文档中没有包含的文件)。凡会覆盖或删除文件的模式都需要 `confirm`,否则路由返回 409 `memory_import_confirm_required`。
+
+### 插件与钩子
+
+- `POST …/plugins` 会安装每个指定插件的 Skill 和钩子包;再次安装即更新。名称不存在时返回 404 `unknown_plugin`,且不做任何写入。
+- `GET …/hooks` 返回每个已安装钩子包的名称、描述、版本、钩子点和插件图标。
+- `POST …/hooks/archive` 要求 `hooks.json` 及其脚本位于 zip 根目录或同一个顶层目录内,且列出的每条命令都必须指向包内的文件。不带 `overwrite` 时,同名钩子包已安装会返回 409 `hook_exists`。`GET …/hooks/:name/archive` 导出的 zip 可以再通过这个路由安装。
+- `GET /api/plugins` 按分类返回插件库的全部插件,包括每个插件的 Skill 元数据和钩子点。
+- `GET /api/plugins/:plugin/files` 返回单个插件库插件自带的全部文件,以路径为键返回文本:`skills/<name>/` 下是每个 Skill 可安装的 `SKILL.md` 和参考文件,`hooks/` 下是钩子脚本。插件详情页的文件浏览器用的就是这个路由。
+
+## 插件注册表与 Project 插件
+
+本节的插件是服务端的包:由服务器加载进自身模块树的模块,例如沙箱后端。它们不是安装在 Agent 上的插件库插件,后者见[插件与钩子](#插件与钩子)。注册表路由是全局的,任何已登录用户都可以访问;已安装插件路由属于单个 Project。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /schedules | 一次列出 Project 内所有 Agent 的定时任务,每条带所属 `agentId`(任意成员) |
-| GET / POST | /agents/:agentId/schedules | 定时任务列表 / 创建(重名返回 409) |
-| GET / PUT / DELETE | /agents/:agentId/schedules/:name | 读取 / 更新 / 删除单个任务 |
+| GET | `/api/plugins/registry` | 插件索引:`{plugins: PluginIndexEntry[]}` |
+| GET | `/api/plugins/registry/readme?name=…` | 索引中一个条目的说明文档:`{name, readme}` |
+| GET | `/api/projects/:projectId/plugins/installed` | 该 Project 要求的插件,连同进程的实际运行情况:`{plugins, shipped, file, restartPending}` |
+| POST | `/api/projects/:projectId/plugins/installed` | 仅管理员。添加一个随构建发布的插件:`{specifier}` |
+| PUT | `/api/projects/:projectId/plugins/installed` | 仅管理员。替换整个列表:`{plugins}` |
+| DELETE | `/api/projects/:projectId/plugins/installed?specifier=…` | 仅管理员。从列表中移除一个插件 |
-Schedule 写操作仅限 Owner。新建 Session 模式的任务,`modelId` 与 `provider` 要么成对给出、要么都不给;该二元组会在任务保存时以及调度器对账时对照 Project 模型表校验。
+- 索引沿用 typst/packages 的 `index.json` 格式:扁平数组,每个元素是一个版本条目,包含 `name`、`version`、`description`、`authors` 和 `license`,可选 `repository`、`homepage`、`keywords`、`categories` 和 `updatedAt`。条目的 `name` 就是 Project 列表里使用的包名。目前索引只来自服务器内置的一个注册表,其中列出了四个沙箱后端。注册表只用于发现,从不导入插件代码。
+- `GET …/readme` 返回包自带的 `README.md`,从本机上的副本读取;没有时 `readme` 为 `null`。索引未列出的名称返回 `404` `not_found`,缺少 `name` 的请求返回 `400` `bad_request`。
+- `GET …/installed` 对该 Project 的任何成员开放。`plugins` 的每个元素是 `{specifier, active, builtin, modules, replaces, error?}`:`active` 表示进程已加载这个包,`builtin` 表示它随本次构建发布,`modules` 和 `replaces` 是其生成的 `ifaces.json` 声明的节点,`error` 说明它为什么没有运行,例如本机上没有这个包,或加载失败。`shipped` 列出构建发布的全部插件包,无论是否被要求。`file` 是保存列表的文件名。已列出的插件既没有运行、也没有加载失败时,`restartPending` 为 true,重启服务器即可解决。Project 的 `.project_config.toml` 无法读取时返回 `400` `invalid_plugins_file`。
+- 写操作返回与 GET 相同的响应体。specifier 必须是包名,不能是路径、URL 或版本范围(`400` `bad_request`)。加入列表的名称必须是构建发布的包,否则路由返回 `400` `plugin_not_shipped`:不会下载任何东西。`PUT` 只发送名称,留在列表中的名称保留文件为它记录的要求。`DELETE` 只修改列表,不删除磁盘上的任何东西。
+- 写操作无需重启即可生效:App 围绕新列表[自行重组](/server-boot#重组),效果与热替换相同。所有 Project 中正在进行的 Agent 运行都会被中止,因为所有 Project 共用同一棵模块树。新 App 启动失败时,改动会被撤销,之前的 App 随之恢复。
+- 列表就是 Project 的 `.project_config.toml` 中的 `[plugins]` 表(见 [Project 配置](/configuration#project-配置))。进程加载所有 Project 表的并集,因此任何一个 Project 要求的插件,都会为所有 Project 加载。
-### Benchmark
+## 定时任务
-Benchmark 挂在 Project 上而非某个 Agent 上:一个 Benchmark 评测过哪些 Agent 由使用者决定,每条 evaluation 记录本轮被测的 Agent(`agentId`,记录中没有时为 `null`)。汇总项的 `agentIds` 按首次出现顺序列出这些 Agent。以下路径同样省略前缀 `/api/projects/:projectId`。
+下面的路径省略了 `/api/projects/:projectId` 前缀。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /benchmarks | Benchmark 评分数据——只返回带 `benchmark_config.toml` 的目录;缺少该文件的目录(评测运行期间删除 Benchmark 所留下的残留)会被跳过;每条带 `status`(技能仍在构建时为 `draft`,校准未能完成时为 `failed`,否则 `published`) |
-| POST | /benchmarks | 手动新建 Benchmark(仅 owner):`{ id, title, description?, runs?, cases: [{ id, title, statement, rubric }] }` → 201 `{ benchmark }`。服务端写入 `benchmark_config.toml`(其中 `status = "published"`)、内容为 `evaluations: []` 的 `scoreboard.yaml`,以及每道题的 `statement/README.md`(标题为其一级标题)与 `rubric/README.md`;id 沿用 Agent id 的字符规则,题目 id 以 `CASE-` 开头;目录已存在时返回 409 `benchmark_exists` |
-| DELETE | /benchmarks/:benchmarkId | 整目录删除一个 Benchmark——题目、配置与记分板(仅 owner;204,不存在返回 404) |
-| GET | /benchmarks/:benchmarkId/cases | 单个 Benchmark 的题目列表:题目 id 与题干 README 的一级标题;评分细则永不返回 |
-| GET | /benchmarks/:benchmarkId/cases/:caseId/files | 浏览某道题的 `statement/`;在 `/files` 前加 `/rubric` 即评分细则一侧 |
-| GET | /benchmarks/:benchmarkId/cases/:caseId/files/content | 读取该材料下的单个文件(`?path=`、`?preview=1`、`?download=1`),内联渲染的加固规则与 Workspace 文件一致 |
+| GET | `/schedules` | Project 内所有 Agent 的定时任务合并为一个列表,每条都标注所属的 `agentId`(任何成员) |
+| GET / POST | `/agents/:agentId/schedules` | 列出定时任务 / 创建定时任务(名称已存在时返回 409) |
+| POST | `/agents/:agentId/schedules/template-placeholder` | 在 Prompt 模板中插入 `{{SCHEDULES}}` 占位符(幂等) |
+| GET / PUT / DELETE | `/agents/:agentId/schedules/:name` | 读取 / 更新 / 删除单个任务 |
+
+定时任务的写操作仅限所有者。新建 Session 模式的任务,`modelId` 和 `provider` 要么同时携带,要么都不带。保存任务时会对照 Project 的模型表校验这对值;调度器核对任务时还会再校验一次。
-### 组织(公司模式)
+## Benchmark
-以下路径都在 `/api/projects/:projectId/organizations` 之下。管理员的公司模式总开关关闭时所有路由回 404。Project 成员可读写。没有删除组织的路由:`status`(`active` / `paused`)就是它的开关,暂停的组织仍保留其对话、员工、工位与工单。写入体可带 `agentId` 与 `sessionId`——调用方所在的员工与会话,CLI 从 `PENGUIN_AGENT_ID` 与 `PENGUIN_SESSION_ID` 填入——文件里记录的就是该员工而不是 token 的用户;`agentId` 指向某名员工时以它为准,否则看会话。频道的读取与成员 DELETE 没有请求体,同样两项改由 `?agentId=` / `?sessionId=` 传入。两者都仅对携带本机 API token 的请求生效,员工因此被当作它自己而不是登录的那个人来应答。这些路由背后的文件见[公司模式](/company-mode)。
+Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估任意多个 Agent,每次评估都会记录它测试的 Agent(`agentId`;没有对应 Agent 的记录为 `null`)。汇总中的 `agentIds` 按这些 Agent 首次出现的顺序排列。下面的路径同样省略了 `/api/projects/:projectId` 前缀。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET / POST | / | 列出组织 / 新建:`{orgId, mission, name?, timezone?, workspace?, model?, ceoBudget?, language?}` → 201 并返回组织详情(创建即生成 CEO Agent 并以初始化会话打开其工位;id 或 CEO 的 Agent id 已被占用则 409)。CEO 的组织图条目写入 `workspace: ceo`,与其他员工一样是公共工作区下的一个分区。`ceoBudget` 是 CEO 的月预算(美元),写入其 `org_chart.yaml` 条目的 `budget`——非负,不给则为 100;按累计线比较,即整家公司的上限。`language` 取 `zh` 或 `en`,是组织书写一切内容所用的工作语言;不给则从使命判定 |
-| GET / PATCH | /:orgId | 概览(设置、看板计数、今日日程、待处理、全员频道最近消息、`inbox`、告警;设置里的 `language` 一律是生效值,文件里没有该字段时从使命读出)/ 修改名称、使命、`status`(`active` / `paused`——暂停即停止一切自动触发)、`approvalMode`、`timezone`、`language` 与阈值 |
-| GET | /:orgId/chart | 员工树,含每位员工的实况状态、工位与本周期支出 |
-| POST | /:orgId/employees | 招募:任用已有 Agent 传 `{agentId}`,或新建 `{newAgent: {agentId, name?, description?, plugins?}}`,再加 `title`、`reportsTo`、`workspace?`、`budget?`、`duties?`、`model?`。`workspace` 不给则缺省为以该员工 Agent id 命名的子目录——公共工作区的根目录放共享输入,不是任何人的工位。相对 `workspace` 会归一化(`./hr` → `hr`)并在公共工作区下创建,绝对路径必须已经存在,用 `..` 爬出公共工作区的写法回 400 `invalid_workspace` |
-| PATCH / DELETE | /:orgId/employees/:agentId | 改头衔、汇报对象、工作区(校验与创建同招募)、预算(`null` 清除)、职责、Model / 离任(下属上移到其上级;CEO 不可离任) |
-| GET / POST | /:orgId/employees/:agentId/desk | 工位会话(无则创建)/ 换新的工位会话 |
-| GET / PUT | /:orgId/handbook | 组织手册索引(`handbook/README.md`) |
-| GET | /:orgId/handbook/files | 知识库文件清单,索引在前 |
-| GET / PUT / DELETE | /:orgId/handbook/files/\<path\> | 按相对路径读写、删除一份文档;索引不可删 |
-| GET / POST | /:orgId/calendar | 全员日程项及运行状态 / 新建:`{agentId, name, prompt, enabled, startAt, period?, endAt?, title?}` → 除写下的事件外还带一组建议性的 `warnings`(每条一行):同一起始分钟上已有另一位员工的常设日程项、同一员工已有同周期的常设日程项、常设日程项以 `now` 起算。写入绝不因此被拒 |
-| GET / PUT / DELETE | /:orgId/calendar/:agentId/:name | 单个日程项;`PUT` 的响应与上面的新建相同,同样带 `warnings` |
-| GET / POST | /:orgId/tickets | 按列的看板(含无法解析的文件)/ 新建:`{title, goal?, acceptanceCriteria?, body?, owner?, parent?, notify?, priority?, due?, slug?}`。`owner` 是这张工单**唯一**的责任人——本组织的员工(裸 Agent id 或 `agent:<id>`)或 Project 成员(`user:<id>`),缺省为调用方;没有 `notify` 时它成为整个 `notify`,但仅限它是员工时,人不会因为自己名下的工单被 @。谁创建的记在工单 `history` 的 `created` 条目里。id 的 slug 优先取 `slug`(小写英文单词以连字符连接,否则 400),否则由标题推导;标题推不出两个词时交给 Project 的模型来取,模型也取不出则回 400 `slug_required`,请调用方自己取 |
-| GET / PUT | /:orgId/tickets/:ticketId | 工单详情(frontmatter 字段、正文各节、`progress` 为纯句子、`history`、贡献会话、子工单、上卷成本)/ 更新 `{title?, owner?, parent?, notify?, priority?, due?, goal?, acceptanceCriteria?, result?}`。`owner` 不接受 `null`:工单永远有负责人,只能改派、不能清空;`parent` 与 `due` 仍可传 `null` 清除 |
-| POST | /:orgId/tickets/:ticketId/move | `{status, reason?}`——移入 `rejected` 须给理由 |
-| POST | /:orgId/tickets/:ticketId/block | `{reason, by?}`——`by` 为工单 id 或主体;工单留在所在列 |
-| POST | /:orgId/tickets/:ticketId/unblock | 解除阻塞 |
-| POST | /:orgId/tickets/:ticketId/progress | `{text}`——往 `## Progress` 追加一句大白话;谁写的、什么时候写的记为 `history` 里的一条 `progress` |
-| POST | /:orgId/tickets/:ticketId/start | `{agentId?, message?, workspace?}` → 202 `{sessionId}`:该员工的一个工单会话,记入工单的 `sessions` 与 `history`。本路由是唯一一个 `agentId` 不表示调用方身份的路由——它指的是这个会话以谁的身份运行。谁能发起取决于调用方:人可以为任何工单发起(`agentId` 指定员工,缺省取负责人);而以员工身份写入的调用方——工位会话或工单会话在请求体里带上自己的 `sessionId`——只能为**自己名下**的工单发起,对别人的工单或没有员工负责人的工单一律回 403 `not_ticket_owner`。负责人仍可用 `agentId` 把同事拉进自己名下的工单 |
-| POST | /:orgId/tickets/:ticketId/attach | `{sessionId}`——把既有会话记为贡献会话 |
-| GET / POST | /:orgId/channels | 调用方可见的全部频道(人:全部;员工:自己所在的),`default_channel` 在前 / 新建:`{channelId, name?, purpose?}` → 201,初始成员只有创建者(id 被占用则 409) |
-| GET / PATCH | /:orgId/channels/:channelId | 频道及其成员 / 改名称、改 `purpose`、设 `archived`(仅限人,且 `default_channel` 不可归档) |
-| POST | /:orgId/channels/:channelId/members | `{principal}`——任一成员可邀请 `agent:<id>` 员工或 `user:<id>` Project 成员;人可以自行加入,员工不可。重复添加已有成员为幂等的 201 |
-| DELETE | /:orgId/channels/:channelId/members/:principal | 移出成员:任何人都可移出自己,人可移出任何人,员工只能移出自己;移出非成员为幂等的 204 |
-| GET / POST | /:orgId/channels/:channelId/messages | 某一天的消息(`?date=yyyy-mm-dd`,缺省为组织时区的今天)及调用方的未读与 @ 计数 / 发送 `{text, refs?}`;@ 从正文解析,且必须都是频道成员。`system` 消息在英文 `text` 之外还带 `notice`——一个 `kind`(`employee_joined`、`employee_left`、`channel_created`、`channel_archived`、`channel_unarchived`、`channel_joined`、`channel_invited`、`channel_left`、`channel_removed`、`budget_warned`、`budget_paused`,以及遗留的 `ticket_blocked`、`ticket_done`、`ticket_rejected`——这三种已不再写入,保留只是为了让磁盘上已有的行仍能渲染)与一组字符串 `params`——客户端据此按读者的语言渲染该句;该字段出现之前写下的消息没有它 |
-| POST | /:orgId/channels/:channelId/read | `{upTo}`——调用方在该频道的已读游标 |
-| GET | /:orgId/finance | 按员工(本人与沿汇报线累计)、按工单(沿 `Parent` 上卷)的支出、逐日趋势与告警;`?period=yyyy-mm` |
-| GET | /:orgId/sessions | 组织的工位会话与按工单分组的工单会话;工位会话启用了消息渠道绑定时带 `messagingChannel`,与该 Session 自身的列表行一致 |
-
-频道相关错误:`channel_not_found`(404,频道 id 不合法时同样如此)、`channel_exists`(409)、`channel_archived`(409,归档频道在取消归档前不接受写入)、`not_a_member`(403,无成员身份的读取、发言与邀请,以及员工尝试仅限人的操作)、`all_hands_immutable`(400,归档 `default_channel` 或编辑其成员)、`mention_not_member`(400,消息提及了不在该频道的对象,整条不写入)、`invalid_principal`(400)。
-
-`GET /api/events` 上的用户级事件:`org_run`(工作轮或工单会话开始)、`org_channel`(新消息,带 `channelId` 与 @ 名单)、`org_ticket`(工单的状态、负责人、阻塞或会话变化)、`org_budget`(告警 / 暂停 / 解除)。
-
-驱动工位会话的只有三样:日程项、频道里的 @ 提及、直接同它说话的人(CEO 创建时的初始化运行是唯一例外)。**工单写入不会启动任何一轮运行。** `move`、`block`、`unblock` 以及经 `PUT /:orgId/tickets/:ticketId` 设定负责人,都只被记录——写进工单文件、该变化在全员频道有系统消息时写进全员频道、并发出 `org_ticket` 事件——同时排入相关员工的队列;每人的下一条日程项在正文的 `## Since your last sweep` 一节里带上它们,一条变化一行。组织或员工被暂停期间队列照常积累,由此后真正触发的那次巡检送达;员工离职时,尚未送达的行随之删除。
-
-### Session 创建与目录浏览
+| GET | `/benchmarks` | Benchmark 的分数数据 |
+| POST | `/benchmarks` | 手动创建 Benchmark(仅所有者) |
+| DELETE | `/benchmarks/:benchmarkId` | 删除 Benchmark 目录,包括其中的题目、配置和计分板(仅所有者;返回 204,不存在时返回 404) |
+| GET | `/benchmarks/:benchmarkId/cases` | Benchmark 的题目:每道题的 id 和题干 README 的标题。评分标准永远不会返回 |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/files` | 浏览一道题的 `statement/` 目录 |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/files/content` | 读取题干中的一个文件(`?path=`、`?preview=1`、`?download=1`) |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/rubric/files` | 浏览一道题的 `rubric/` 目录 |
+| GET | `/benchmarks/:benchmarkId/cases/:caseId/rubric/files/content` | 读取评分标准中的一个文件,参数与上一条相同 |
+
+- `GET /benchmarks` 只列出含有 `benchmark_config.toml` 的目录;评估过程中删除 Benchmark 留下的目录没有这个文件,因此不会出现在列表里。每个条目都带 `status`:Skill 还在构建 Benchmark 时为 `draft`,校准未能完成时为 `failed`,其余情况为 `published`。
+- `POST /benchmarks` 接受 `{id, title, description?, runs?, cases: [{id, title, statement, rubric}]}`,返回 201 和 `{benchmark}`。服务器会写入 `benchmark_config.toml`(其中 `status = "published"`)、一份 `evaluations: []` 的 `scoreboard.yaml`,以及每道题的 `statement/README.md`(以 title 为标题)和 `rubric/README.md`。id 的字符规则与 Agent id 相同,题目 id 以 `CASE-` 开头。如果目录已存在,路由返回 409 `benchmark_exists`。
+- 这些读取文件内容的路由采用与 Workspace 文件相同的内联加固;参见 [Workspace 文件响应](#workspace-文件响应)。
+
+## 组织(公司模式)
+
+以下所有路径都位于 `/api/projects/:projectId/organizations` 之下。服务器的公司模式开关关闭时,每条路由都返回 `404` `company_mode_off`(参见[公司模式开关](#公司模式开关))。任何 Project 成员都可以读写。没有任何路由会删除组织:`status`(`active` / `paused`)就是关闭开关,暂停的组织会保留自己的对话、员工、工位和工单。这些路由背后的文件见[公司模式](/company-mode)。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /agents/:agentId/sessions | Session 列表(含运行状态);无论由哪个客户端创建,所有行都会列出;带 `excludeOrg=1` 时只列用户自己的行——组织的工位会话、工单会话及其派生的子会话同时从分页与 `counts=1` 的统计中剔除(开发模式的会话列表即以此请求) |
-| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201。`client` 是存入索引行的创建客户端标记(CLI 传 `"cli"`,缺省 `"web"`)——仅作来源信息,绝不参与列表过滤;`source` 只接受 `"benchmark"`(Benchmark 评估或优化创建),`subagent` 与 `schedule` 由服务端自己写入 `org` 是服务端为组织的工位与工单会话(公司模式)自行写入的值,客户端不能传。 |
-| GET | /dirs?path= | 服务器端目录浏览(Workspace 选择器数据源) |
+| GET / POST | `/` | 列出组织 / 创建组织 |
+| GET / PATCH | `/:orgId` | 组织概览 / 修改组织设置 |
+| GET | `/:orgId/chart` | 员工树,含每名员工的实时状态、工位和本期花费 |
+| POST | `/:orgId/employees` | 招聘员工:已有 Agent 或新建 Agent |
+| PATCH / DELETE | `/:orgId/employees/:agentId` | 修改员工 / 将员工移出组织 |
+| GET / POST | `/:orgId/employees/:agentId/desk` | 工位会话(缺失时自动打开)/ 续期后的工位会话 |
+| GET / PUT | `/:orgId/handbook` | 手册索引(`handbook/README.md`) |
+| GET | `/:orgId/handbook/files` | 知识库文件,索引排在最前 |
+| GET / PUT / DELETE | `/:orgId/handbook/files/<path>` | 按相对路径访问单个文档;索引不可删除 |
+| GET / POST | `/:orgId/calendar` | 全体员工的事件和运行状态 / 创建事件 |
+| GET / PUT / DELETE | `/:orgId/calendar/:agentId/:name` | 单个事件 |
+| GET / POST | `/:orgId/tickets` | 按列组织的看板,附无法解析的文件 / 创建工单 |
+| GET / PUT | `/:orgId/tickets/:ticketId` | 工单详情 / 更新工单 |
+| POST | `/:orgId/tickets/:ticketId/move` | `{status, reason?}`;移动到 `rejected` 时必须给出原因 |
+| POST | `/:orgId/tickets/:ticketId/block` | `{reason, by?}`,`by` 是工单 id 或主体;工单仍留在原列 |
+| POST | `/:orgId/tickets/:ticketId/unblock` | 解除阻塞 |
+| POST | `/:orgId/tickets/:ticketId/progress` | `{text}`:向 `## Progress` 追加一句纯文本 |
+| POST | `/:orgId/tickets/:ticketId/start` | `{agentId?, message?, workspace?}` → 202 `{sessionId}`:启动工单会话 |
+| POST | `/:orgId/tickets/:ticketId/attach` | `{sessionId}`:把已有会话登记为贡献会话 |
+| GET / POST | `/:orgId/channels` | 调用者可见的频道,`default_channel` 在最前 / 打开一个频道 |
+| GET / PATCH | `/:orgId/channels/:channelId` | 频道和成员 / 重命名、修改 `purpose`、设置 `archived` |
+| POST | `/:orgId/channels/:channelId/members` | `{principal}`:添加成员 |
+| DELETE | `/:orgId/channels/:channelId/members/:principal` | 移除成员 |
+| GET / POST | `/:orgId/channels/:channelId/messages` | 一天的消息,附调用者的未读数和提及数 / 发送消息 |
+| POST | `/:orgId/channels/:channelId/read` | `{upTo}`:调用者在此频道的已读游标 |
+| GET | `/:orgId/finance` | 每名员工的花费(自身及沿汇报线累计)和每个工单的花费(沿 `Parent` 逐级汇总)、每日趋势和告警;`?period=yyyy-mm` |
+| GET | `/:orgId/sessions` | 组织的工位会话,以及按工单分组的工单会话。工位会话启用了消息绑定时,这一行也带上它的 `messagingChannel`,与会话自己的行一致 |
+
+### 调用者身份
+
+写操作的请求体可以携带 `agentId` 和 `sessionId`,分别对应发起调用的员工和会话;CLI 会从 `PENGUIN_AGENT_ID` 和 `PENGUIN_SESSION_ID` 自动填入这两个值。文件里因此记录的是员工,而不是 token 对应的用户:`agentId` 指向员工时以 `agentId` 为准,否则由会话决定。频道读取和成员 DELETE 没有请求体,所以改用查询参数 `?agentId=` / `?sessionId=` 传入同一对值。只有携带本地 API token 的请求,服务器才会认可这两个字段;员工就是这样以自己的身份、而不是以登录者的身份得到响应的。
+
+### 组织
+
+- `POST /` 接收 `{orgId, mission, name?, timezone?, workspace?, model?, ceoBudget?, language?}`,返回 201 和组织详情。创建组织的同时会创建 CEO Agent,并以一次初始化运行打开它的工位。id 或 CEO 的 Agent id 已被占用时,路由返回 409。CEO 的组织架构条目以 `workspace: ceo` 写入,也就是共享 Workspace 下的一个分区,其他员工也都是这样。
+- `ceoBudget` 是 CEO 的月度预算,单位为美元,写入 CEO 在 `org_chart.yaml` 中条目的 `budget`。不能为负数,默认 100。预算沿累计线比较,所以这个值是全公司的上限。
+- `language` 取 `zh` 或 `en`,是组织所有产出内容的工作语言。省略时根据使命判断。
+- `GET /:orgId` 返回概览:设置、看板计数、今日日程、待办事项、全员频道的最近消息、`inbox` 和告警。设置里始终带有生效的 `language`;文件里没有记录时,从使命推断得出。
+- `PATCH /:orgId` 修改名称、使命、`status`(`active` / `paused`;暂停会停止所有自动触发器)、`approvalMode`、`timezone`、`language` 和各项阈值。
+
+组织和频道的 id 提议由 Project 级路由给出,即带 `kind: org` 或 `kind: channel` 的 `POST /api/projects/:projectId/suggest-id`,见[语义化 id 提议](#语义化-id-提议)。
+
+### 员工
+
+- `POST /:orgId/employees` 招聘已有 Agent 时传 `{agentId}`,新建 Agent 时传 `{newAgent: {agentId, name?, description?, plugins?}}`;另外还可以带 `title`、`reportsTo`、`workspace?`、`budget?`、`duties?` 和 `model?`。
+- `workspace` 缺省为以员工 Agent id 命名的子目录,因为共享 Workspace 的根目录存放共享输入,不属于任何人的工位。相对路径 `workspace` 会先规范化(`./hr` → `hr`),再在共享 Workspace 下创建。绝对路径必须已经存在。包含 `..` 而逃出共享 Workspace 的路径返回 400 `invalid_workspace`。
+- `PATCH /:orgId/employees/:agentId` 修改职位、上级、Workspace(创建与校验规则和招聘时相同)、预算(传 `null` 即清除)、职责和模型。
+- `DELETE /:orgId/employees/:agentId` 将员工移出组织:下属上移,改归这名员工的上级管理。CEO 不能移出组织。
+
+### 日程
+
+`POST /:orgId/calendar` 接收 `{agentId, name, prompt, enabled, startAt, period?, endAt?, title?}`,返回保存后的事件,外加提示性的 `warnings`,每条警告一行:
+
+- 另一名员工有周期事件的开始时间落在同一分钟
+- 同一员工已有相同周期的第二个周期事件
+- 周期事件从 `now` 时刻开始
+
+警告不会阻止写入。`PUT /:orgId/calendar/:agentId/:name` 的响应与创建时一致,同样包含 `warnings`。
+
+### 工单
+
+- `POST /:orgId/tickets` 接收 `{title, goal?, acceptanceCriteria?, body?, owner?, parent?, notify?, priority?, due?, slug?}`。
+- `owner` 是唯一的责任主体:员工(直接写 Agent id,或 `agent:<id>`)或 Project 成员(`user:<id>`)。缺省为调用者。不传 `notify` 时,负责人一人就是整份 `notify` 列表,但前提是负责人为员工,这样人不会因为自己名下的工单被 @。谁提交了工单,记录在 `history` 的 `created` 条目里。
+- id 的 slug 优先取 `slug`,它必须是由连字符连接的小写英文单词(否则返回 400)。不传 `slug` 时从标题提取。标题凑不出两个单词时,交给 Project 的模型处理;模型也失败时,返回 400 `slug_required`,让调用者自己指定 slug。
+- `GET /:orgId/tickets/:ticketId` 返回 frontmatter 字段、正文各节、纯文本形式的 `progress`、`history`、贡献会话、子工单和逐级汇总的成本。
+- `PUT /:orgId/tickets/:ticketId` 接收 `{title?, owner?, parent?, notify?, priority?, due?, goal?, acceptanceCriteria?, result?}`。`owner` 不接受 `null`:工单始终有负责人,负责人可以更换,但不能取消。`parent` 和 `due` 接受 `null`,用于清空这两项。
+- `POST …/progress` 会记录这句话是谁写的、何时写的,并在 `history` 末尾追加一条 `progress` 条目。
+
+`POST /:orgId/tickets/:ticketId/start` 为一名员工启动工单会话,并记入工单的 `sessions` 和 `history`。这是唯一一条 `agentId` 不代表调用者身份的路由:它指定会话以哪名员工的身份运行。谁可以启动会话,取决于调用者:
+
+- 人可以在任何工单上启动会话。`agentId` 指定员工,缺省为负责人。
+- 以员工身份写入的调用者(用自己的 `sessionId` 发请求的工位会话或工单会话),只能为自己负责的工单启动会话。对别人的工单,或没有员工负责人的工单,会收到 403 `not_ticket_owner`。
+- 负责人也可以传 `agentId`,把一位同事拉进自己负责的工单。
+
+### 频道
+
+- `GET /:orgId/channels` 列出调用者能看到的所有频道:人可以看到全部,员工只看到自己加入的。
+- `POST /:orgId/channels` 接收 `{channelId, name?, purpose?}`,返回 201 和新建的频道,创建者是唯一成员;id 已被占用时返回 409。
+- `PATCH /:orgId/channels/:channelId` 只有人可以设置 `archived`,`default_channel` 则任何人都不能归档。
+- `POST …/members` 允许任何成员邀请 `agent:<id>` 员工或 `user:<id>` Project 成员。人可以添加自己,员工不行。添加的已是成员时不做任何改动,返回 201。
+- `DELETE …/members/:principal` 允许任何人移除自己,人还可以移除任何人;员工只能移除自己。移除非成员时不做任何改动,返回 204。
+- `GET …/messages` 接收 `?date=yyyy-mm-dd`,缺省为组织时区的今天。`POST …/messages` 发送 `{text, refs?}`;提及对象从文本中解析,且必须都是频道成员。
+
+`system` 消息在英文 `text` 之外还带一个 `notice`:包含 `kind` 和字符串 `params`,客户端据此用读者的语言渲染这句话。在这个字段出现之前写入的消息没有 `notice`。`kind` 取 `employee_joined`、`employee_left`、`channel_created`、`channel_archived`、`channel_unarchived`、`channel_joined`、`channel_invited`、`channel_left`、`channel_removed`、`budget_warned`、`budget_paused` 之一,或遗留的 `ticket_blocked`、`ticket_done`、`ticket_rejected` 之一。现在已经没有任何代码会写入遗留 kind,保留它们只是为了让磁盘上已有的消息仍能正常渲染。
+
+频道错误:
+
+| 代码 | 状态码 | 含义 |
+| --- | --- | --- |
+| `channel_not_found` | 404 | 频道不存在;不可能属于任何频道的 id 也返回这个错误 |
+| `channel_exists` | 409 | 频道 id 已被占用 |
+| `channel_archived` | 409 | 频道已归档,取消归档前不接受写入 |
+| `not_a_member` | 403 | 非成员却读取、发言或邀请,或员工尝试只有人才能执行的操作 |
+| `all_hands_immutable` | 400 | 归档 `default_channel` 或修改它的成员 |
+| `mention_not_member` | 400 | 消息提及的主体不是频道成员;不写入任何内容 |
+| `invalid_principal` | 400 | 主体格式不正确 |
-创建 Session 时,`modelId` 与 `provider` 要么成对给出、要么都不给:给出完整二元组即指定模型,两个都省略则取 Project 默认模型,只给一个返回 400。Workspace 默认自动创建临时工作区,审批模式默认 `allow-all`。
+### 事件与触发
-### 用量与 Trace(Agent 级)
+公司模式会在用户事件流 `GET /api/events` 上发布 `org_run`、`org_channel`、`org_ticket` 和 `org_budget`;参见[流式传输(SSE)](#流式传输sse)。
+
+只有三件事会驱动工位会话:日程事件、频道里的 @ 提及,以及有人跟它说话。CEO 在创建时的初始化运行是唯一的例外。
+
+写工单不会触发运行。`move`、`block`、`unblock` 以及通过 `PUT /:orgId/tickets/:ticketId` 变更负责人,都会记入工单文件,并以 `org_ticket` 事件发布,同时排入相关员工的队列。员工的下一次日程事件触发时,会在正文的 `## Since your last sweep` 之下逐行列出这些变更,一条变更占一行。组织或员工暂停时,队列依然保留,由最终触发的那次巡检送达。员工离开组织时,它尚未投递的行也随之删除。
+
+## Session 创建与目录浏览
+
+以下路径省略了 `/api/projects/:projectId` 前缀。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /usage | 用量统计,查询参数 `from`、`to`、`fromTs`/`toTs`(ISO 时间戳界定的滑动窗口,须成对给出;`minute` 精度必需)、`groupBy`、`granularity`(时间序列精度 `minute` / `hour` / `day` / `week` / `month`,默认 `day`;范围 × 精度过大的组合会被拒绝)、`agentId`、`provider`、`modelId` |
-| GET | /usage/errors | 异常明细表分页(按时间倒序):`offset`、`limit`,以及与看板一致的 `from` / `to` / `fromTs` / `toTs` / `agentId` 过滤,另可选 `kind`(`unexpected` / `expected`)→ `{items, total}` |
-| DELETE | /usage/errors | 清空当前筛选下的异常明细:`from` / `to` / `fromTs` / `toTs` / `agentId`,与读取所用的同一组(不接受 `kind`,面板没有该控件)→ `{deleted}`。此处 `from` 与 `to` 必填(缺一即 400)——开区间等于整段历史而非一次筛选。仅 Project owner;删除的触及范围与调用者的读取范围相同,故管理员的清空同时带走其读取所含的无归属异常,成员的清空从不涉及 |
-| GET | /agents/:agentId/traces | Trace 文件的日期 → Session 下钻结构 |
-| GET | /agents/:agentId/traces/:sessionId/:index | 读取 Trace 事件(`offset` / `limit` 分页) |
-| GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace 性能分析结果 |
-| GET | /agents/:agentId/traces/:sessionId/:index/download | 下载 Trace 原始文件(JSONL 附件) |
-| POST | /agents/:agentId/traces/import | 导入 Trace 文件:`{dataBase64}` → `{sessionId, index, date}` |
+| GET | `/agents/:agentId/sessions` | 列出 Agent 的 Session 及运行状态,不论由哪个客户端创建;`excludeOrg=1` 则只要用户自己的那些 |
+| POST | `/agents/:agentId/sessions` | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201 `{session}` |
+| GET | `/dirs?path=` | Workspace 选择器背后的服务器端目录浏览器 |
+| GET | `/dir-skills?path=` | 目录所带的 Skill,用于导入到新 Agent |
-Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入,上限 14MB)。导入文件必须是合法的 Trace JSONL,且首条记录为携带文件名安全 `session_id` 的 `session_meta`;若该 Agent 已存在同名 Session,导入将被拒绝(409 `trace_session_exists`),因此导入文件总是成为一个新 Session 的 001 号文件,并按首条记录时间戳的本地日期落入对应日期目录。
+- Session 列表接受可选查询参数。`limit` 和 `offset` 用于分页(`offset` 必须搭配 `limit`)。`category`(`active`、`subagent`、`schedule`、`benchmark` 或 `archived`)先过滤再分页;`workspaceGroup` 只保留一个 Workspace 的会话。`counts=1` 会在响应里附加 `counts`(整个列表按类别的总数)、`workspaceCounts`(按 Workspace 路径统计的同类总数)和 `workspaceLatest`(每个 Workspace 最新的 Session)。不带分页参数时,返回完整列表。
+- `excludeOrg=1` 会把组织的工位会话、工单会话和子 Session 一并移出这一页以及 `counts=1` 的总数,这正是开发模式的列表所要的。取其他值返回 400。
+- 创建时 `modelId` 和 `provider` 必须成对出现:要指定模型就传完整一对,两个都省略则使用 Project 的默认模型。只传一个返回 400。
+- 显式传入的 `workspace` 必须是已存在的目录,永远不会自动创建。省略时自动创建一个临时 Workspace。审批模式默认 `allow-all`。
+- `client` 是记录在数据行上的来源提示:CLI 发起的请求为 `"cli"`,默认 `"web"`。组织的工位会话和工单会话由服务器自己写入 `"org"`,客户端不能发送这个值。只有 `excludeOrg` 会把它当作过滤条件,而且只用来剔除这些行。
+- `source` 只接受 `"benchmark"`,用于 Benchmark 评估或优化创建的 Session。`subagent` 和 `schedule` 由服务器自己设置。
+- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries}`,只包含子目录;读不了的目录按空列表返回,用户仍然可以向上返回。
+- `GET /dir-skills` 只读取绝对路径下的 `<path>/.agents/skills` 和 `<path>/.claude/skills`,响应为 `{path, skills}`。没有 Skill 的目录返回空列表。参见 [Agent](#agent) 一节中的 `POST /agents`。
-### Session 级接口
+## 用量与 Trace(Agent 级别)
-以下路径均省略前缀 `/api/sessions/:sessionId`。Trace 与 Session 的存储模型见 [Session 与 Trace](/sessions-and-traces)。
+以下路径省略了 `/api/projects/:projectId` 前缀。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | / | Session 信息(单会话 GET 额外携带 `tracePath`:最新 Trace 文件的绝对路径;列表行不含)。`orgId` 标出被公司模式缓存认领的会话——工位会话,或参与该组织某个工单的会话——普通会话没有这个字段;列表路由同样带上它 |
-| PATCH | / | 更新:`{approvalMode?, thinkingLevel?, archived?, title?}`。`thinkingLevel` 将思考等级钉在该 Session 上并持久化,自下一次 LLM 请求起生效——思考等级是软限制参数:允许中途更换,代价是提供商的缓存失效,因此选择器会建议先压缩;读取时由 `SessionInfo.thinkingLevel` 返回(缺省即从未钉住:按 Agent 配置生效) |
-| DELETE | / | 删除 Session(连同 Trace 与暂存文件) |
-| GET | /messages | 无参数时返回完整 OmniMessage 历史;`tailLimit=n` 或 `before=<游标>&limit=n` 改为读取一个按 Task 切分的窗口(自带 Web App 打开对话只读最近 50 轮,滚动到顶部再续载),此时响应携带 `page`(下一页游标 `before`、窗口前的轮数 `earlierTurns` 与累计统计 `prior`)。Task 运行期间响应额外携带 `live`(进行中的流式尾部,见下) |
-| POST | /fork | 从一条已完成的模型回复分叉空闲 Session:`{position:{fileIndex,ordinal}}` → `{session}` |
-| GET | /stream | SSE 事件流(见下节) |
-| POST | /tasks | 发起 Task:`{input: TaskInputPart[], queueIfBusy?}` → 202。带 `queueIfBusy` 时,运行中的 Session 会把输入暂存为跟进消息(`queued: true`),空闲后按序自动作为普通 Task 发出;`task_state` 事件携带排队数。`file` 类型的输入会写入 Session scratchpad,以 `[attached file: <路径>]` 行交给模型(见下方请求体)。带 `goal: {budget?}` 时该输入转为发起目标循环(Agent 未安装 `goal` 插件则 409 `goal_plugin_not_installed`):必须含非空文字(一张图说明不了目标),随行的图片一律折叠成 scratchpad 路径行写入目标文本、与模型是否支持视觉无关,而 `file` 会被拒绝——没有东西能把它折进每轮重注入的目标里——见[目标模式](/goal-mode) |
-| POST | /steer | 运行中插话:`{text, images?}` 为运行中的 Task 排队一条消息(作为独立的 `[user_steering]` 用户消息随下一轮送达,图片紧随其后)→ 202;两个字段任一非空即可成消息,都为空则 400;无 Task 运行返回 409 `not_running` |
-| DELETE | /steer/:steerId | 撤回一条尚未送达的插话(id 随 `task_state` 的 `pendingSteering` 下发):从队列中撤出 → 200,返回其原始内容 `{text, images, files}`(文件从 scratchpad 读回为 data URL,磁盘副本随之删除),供输入框恢复编辑;已送达模型则 409 `not_pending` |
-| DELETE | /follow-ups/:followUpId | 撤回一条排队中的跟进消息(id 随 `task_state` 的 `pendingFollowUps` 下发):在自动发出前移除 → 200,返回其原始内容 `{text, images, files}`——排队中的跟进消息一律带有该内容,与其入队路径无关;已自动发出则 409 `follow_up_started` |
-| POST | /approvals/:toolCallId | 审批决定:`{decision}` 取 `allow` 或 `deny` → 204 |
-| POST | /tool-calls/:toolCallId/background | 把一个**正在执行**的工具调用交还为后台任务,使本轮可以结束、对话继续进行:204。调用带着 `process_id` / `subagent_id` 以 `completed` 结束,不杀任何进程,任务完成后仍以一贯的后台任务通知送回。该 id 没有正在执行的调用时(未知、已结束,或运行时已不存在)返回 404 `tool_call_not_found`;调用在运行但其工具没有后台形态时返回 409 `tool_not_detachable`(只有 `exec_command` 与 `run_subagent` 具备后台形态) |
-| POST | /abort | 中断当前 Task:已触发返回 202,无任务返回 204 |
-| POST | /retry-now | 重连倒计时上的「立即重试」:跳过进行中的退避等待、立刻发起下一次重试(重试计数不变)→ 200 `{skipped}`——`skipped:false` 表示当前没有等待可跳过(良性空操作,非错误) |
-| POST | /compact | 触发上下文压缩:202;无可压缩内容返回 409,具体原因由 code 承载——`compaction_not_configured`(该 Agent 没有配置压缩)、`nothing_to_compact`(当前上下文尚未完成一轮对话)、`already_compacted`(上次压缩后还没有新的对话)。服务重启后恢复的 Session 依据 Trace 判断可压缩性,因此已有对话无需先跑一次 Task 即可压缩 |
-| GET | /processes | 对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`)。仅来自活跃运行时——被回收或从未装载的会话如实返回空列表。检测到进程所服务地址时行内附 `serviceUrl`(取输出打印的最后一个本机 URL,否则按进程组做监听端口探测,每次拉取时刷新) |
-| POST | /processes/:processId/kill | 停止一个后台进程(对整个进程组先 SIGTERM、宽限期后 SIGKILL),条目随之从列表消失;已不存在时 404 `process_not_found` |
-| DELETE | /processes/:processId | 从列表移除一个**已退出**的进程条目:仍在运行时 409 `process_running`(应改用停止),已不存在时 404 `process_not_found`。条目连同该进程已捕获的输出一起离开运行时注册表,此后对该 `process_id` 调用 `input_command` 会失败 |
-| GET | /files?path= | 浏览 Workspace 目录 |
-| GET | /files/content?path=&download=&preview= | 读取 Workspace 文件(`download=1` 时作为附件下载,`preview=1` 以沙箱方式预览 —— 见下) |
-| GET | /files/preview-redirect?path= | html 的“新页面打开”:签发令牌并 302 跳转到独立预览源 |
-| POST | /files/stat | 批量存在性检查:`{paths}` |
-| PUT | /files/content?path= | 上传文件:`{dataBase64}`,上限 14MB |
-| POST | /files/move | 移动或重命名单个 Workspace 文件:`{from, to, ifVersion?}` → 204。**仅限文件**——目录没有单一的版本标记,无法为其表达保护该操作的前置条件,因此返回 400。`to` 的父目录缺失时自动创建。`from` 不存在时 404 `path_not_found`;`ifVersion` 与文件不再匹配时 409 `file_changed`(带标记时源文件消失同样算作已变化);`to` 已被占用时 409 `target_exists`——目的地从未被读取过,因此只拒绝、不覆盖;移动到文件自身路径返回 400 |
-| DELETE | /files/content?path=&ifVersion= | 删除单个 Workspace 文件:204。仅限文件(目录返回 400);文件不存在时 404 `path_not_found`,`ifVersion` 不再匹配时 409 `file_changed`。该标记在协议上可选——不带即为无条件删除——而 Files 面板总是回传其读取时拿到的那一枚 |
-| POST | /files/reveal?path= | 在本机的系统文件管理器里显示该文件(macOS 与 Windows 选中文件,Linux 桌面打开其所在目录)→ 204。仅桌面端自己的窗口可以请求:服务端非由 shell 启动时 404 `not_found`,桌面模式下的浏览器会话 403 `desktop_shell_only`——服务端分不清它与远程浏览器,而在服务端所在机器上弹出目录对那边的用户毫无用处。路径按读取的同一道规则限域(越界 400,不存在 404 `path_not_found`);文件管理器起不来时 502 `reveal_failed` |
-| GET | /files/search?q= | 按条目**名称**搜索整个 Workspace(大小写不敏感的子串匹配,不匹配路径)→ `{hits: [{path, kind, sizeBytes, mtime}], truncated}`,每条命中携带的字段与目录列表中的条目一致。自根目录广度优先遍历,因此命中按层级由浅至深排列,被截断时留下的是最相关的命中,而不是最先遍历到的那个目录里的内容;`truncated` 表示遍历触及上限——200 条命中,或访问 20000 个目录条目。`q` 为空或超过 100 字符返回 400 |
-| GET | /traces | 本 Session 的 Trace 文件列表 |
-| GET | /traces/:index | 读取 Trace 事件(分页) |
-| GET | /traces/:index/analysis | Trace 性能分析结果 |
-| GET | /scratchpad/:fileName | 读取会话暂存文件(如输入图片、文件附件) |
-
-通用约定:无权访问的 Session 一律返回 404,不泄露其存在性;每个 Session 同时只允许一个 Task 或压缩在运行,冲突时返回 409(`task_in_progress` / `compacting`)。
-
-#### GET /messages 的 `live` 字段
-
-Trace 只存完整消息(流式 `partial_*` 永远不落盘),所以仅靠历史无法呈现一条正在流式输出的消息。因此当 Session 处于运行/压缩状态时,messages 响应额外携带进行中的流式尾部:
+| GET | `/usage` | 用量统计 |
+| GET | `/usage/model-totals` | 每个模型的历史累计 Token 总量;不接受任何过滤参数 |
+| GET | `/usage/errors` | 错误详情表的一页,按时间倒序:→ `{items, total}` |
+| DELETE | `/usage/errors` | 按当前过滤条件清空错误表:→ `{deleted}`(仅限 Project 所有者) |
+| GET | `/agents/:agentId/traces` | Trace 文件,按日期 → Session 逐级下钻 |
+| GET | `/agents/:agentId/traces/:sessionId/:index` | 读取 Trace 事件(`offset` / `limit` 分页) |
+| GET | `/agents/:agentId/traces/:sessionId/:index/analysis` | Trace 性能分析 |
+| GET | `/agents/:agentId/traces/:sessionId/:index/download` | 下载原始 Trace 文件(JSONL 附件) |
+| POST | `/agents/:agentId/traces/import` | 导入 Trace 文件:`{dataBase64}` → `{sessionId, index, date}` |
+
+`GET /usage` 接受以下查询参数:
+
+| 参数 | 说明 |
+| --- | --- |
+| `from`、`to` | 日期范围,格式 `yyyy-mm-dd` |
+| `fromTs`、`toTs` | 限定滑动窗口起止的 ISO 时间戳。必须成对传入;`minute` 粒度时必填 |
+| `groupBy` | `date`、`agent`、`model` 或 `session`;默认 `date` |
+| `granularity` | 时间序列精度:`minute`、`hour`、`day`、`week` 或 `month`;默认 `day`。范围与精度的组合过大时会拒绝请求 |
+| `agentId`、`provider`、`modelId` | 过滤条件 |
+
+- `GET /usage/errors` 接受 `offset`、`limit`、同样的 `from` / `to` / `fromTs` / `toTs` / `agentId` 过滤条件,以及可选的 `kind`(`unexpected` 或 `expected`)。
+- `DELETE /usage/errors` 接受与读取相同的过滤条件(`from` / `to` / `fromTs` / `toTs` / `agentId`),但不接受 `kind`,因为面板上没有这个控件。这里 `from` 和 `to` 都必填(否则返回 400),因为少一个边界,清空的就是整段历史,而不是过滤后的一部分。清空的范围与调用者读取的范围完全一致:管理员清空时,也会删掉只有管理员读取才能看到的未归属行;成员清空时则永远不会。
+- `GET /agents/:agentId/traces` 还接受 `limit` 和 `offset` 分页,以及 `category`(必须搭配 `limit`),用于只列出某一类别的 Session。
+- 任何成员都可以下载 Trace。导入只有所有者能做,与 Agent State 快照导入一样,上限 14MB。导入的文件必须是有效的 Trace JSONL,首条记录必须是 `session_meta`,`session_id` 须可安全用作文件名。session id 与 Agent 已有的重复时拒绝导入(409 `trace_session_exists`),所以导入的文件总是成为新 Session 的 index 001,按首条记录的时间戳存入对应的本地日期目录。
+
+## Session 级端点
+
+下面这些路径省略了 `/api/sessions/:sessionId` 前缀。Session 和 Trace 背后的存储模型见 [Session 与 Trace](/sessions-and-traces)。
+
+这里的每条路由都遵循两条约定。调用方无权访问的 Session 一律返回 `404` `session_not_found`,因此不会暴露它是否存在。一个 Session 同一时间只能运行一个 Task 或一次压缩:冲突的请求返回 409(`task_in_progress` / `compacting`)。
+
+### Session 与历史
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | `/` | Session 信息 |
+| PATCH | `/` | 更新 Session:`{approvalMode?, thinkingLevel?, archived?, title?}` |
+| DELETE | `/` | 删除 Session,连同它的 Trace 和暂存文件 |
+| GET | `/messages` | OmniMessage 历史,全量或按 Task 窗口 |
+| POST | `/fork` | 在一条已完成的助手回复之后分叉空闲的 Session:`{position: {fileIndex, ordinal}}` → `{session}` |
+| GET | `/stream` | SSE 事件流;见[流式传输(SSE)](#流式传输sse) |
+| GET | `/context` | 当前模型上下文的组成,以及压缩将从哪里开始 |
+| GET | `/goal` | 当前 Session 最近一次目标运行 |
+
+- `GET /` 返回 Session 的信息。与列表行不同,单个 Session 的响应还带 `tracePath`,即最新 Trace 文件的绝对路径。`orgId` 标记公司模式缓存持有的会话(工位会话,或这个组织某个工单的贡献会话);普通 Session 一律不带这个字段,列表路由同样会设置它。
+- `PATCH /` 带 `thinkingLevel` 会把这个思考等级持久地固定到这个 Session,从下一次 LLM 请求开始生效。思考等级是软性限制:可以在上下文中途更改,代价是损失供应商已缓存的上下文,因此等级选择器会建议先压缩。固定后的等级以 `SessionInfo.thinkingLevel` 返回;没有这个字段说明从未固定等级,此时采用 Agent 配置。
+- `GET /messages` 不带参数时返回完整的 OmniMessage 历史。`tailLimit=n` 改为读取最新的 n 个按 Task 对齐的单元,`before=<cursor>&limit=n` 读取某个游标之前的 n 个单元。两种形式互斥,`n` 在 1 到 1000 之间,`limit` 默认为 200。内置 Web App 打开一段对话时先显示最近 50 轮,滚动时再加载更早的内容。窗口式响应带 `page`,包含下一页的游标(`before`)、窗口之前的轮数(`earlierTurns`)和此前累计的统计(`prior`)。Task 运行期间,响应还会带 `live`;见 [GET /messages 上的 live 字段](#get-messages-上的-live-字段)。
+- `GET /context` 返回当前模型上下文的各个组成部分,外加 `compactionThreshold`:上下文达到多大(以 Token 计)时,Session 的下一个请求会开始压缩。这个阈值就是 Agent 的 `compaction.max_context_length`,上限不超过模型上下文窗口的剩余空间。压缩未启用、读不到 Agent 配置,或阈值不低于窗口时,这个值是 `null`。这条路由每次调用都读取最新的 Trace 文件,所以数值是快照,不是实时计数器。
+- `GET /goal` 返回 `{goal}`:Session 从未跑过目标时为 `null`,否则为 `{objective, status, budget, used, rounds}`。`status` 取值为 `active`、`complete`、`blocked`、`budget_limited` 或 `aborted`,`budget` 为 -1 表示不限制。目标只存活在它的运行期间,所以 Session 已停止运行、目标却仍是 active 时,会报告为 `aborted`。见[目标模式](/goal-mode)。
+
+### GET /messages 上的 `live` 字段
+
+Trace 只存储完整的消息,流式的 `partial_*` 消息从不落盘,所以光靠历史看不到一条仍在流式输出的消息。Session 运行或压缩期间,messages 响应会额外带上进行中的流尾部:
```ts
interface MessagesResponse {
messages: (OmniMessage & { tracePosition?: { fileIndex: number; ordinal: number } })[];
live?: {
- // Session 通道最近分配的 SSE 事件 id(`<epoch>-<seq>`):
- // 截至该 id(含)发布的所有事件都已累积进 `fragments`。
+ // The Session channel's most recently assigned SSE event id (`<epoch>-<seq>`):
+ // every event published up to and including this id is already reflected in `fragments`.
cursor: string;
- // 每个未闭合流式片段对应一条合成的 `partial_* start` OmniMessage,其 payload 携带
- // 迄今累积的全部内容(文本/思考前缀、工具调用名 + 已累积参数、工具输出前缀 + 图片),
- // 并保留原始 `origin` 链(子智能体片段同样覆盖)。
+ // One synthetic `partial_* start` OmniMessage per open streaming fragment, whose
+ // payload carries the full accumulated content so far (text/thinking prefix,
+ // tool-call name + accumulated arguments, tool-output prefix + images), with the
+ // original `origin` chain preserved (subagent fragments included).
fragments: OmniMessage[];
};
}
```
-`cursor` 与 `fragments` 在 Trace 读取开始前原子采集。使用先连接模式(见下)的客户端在应用完历史后处理它们:当 cursor 的 epoch 与本连接已缓冲事件的 epoch 一致时,丢弃 seq ≤ cursor 的已缓冲 **partial** 事件(其内容已累积在 `fragments` 里),把 `fragments` 按正常归约路径喂入,再重放剩余缓冲。已缓冲的**完整**消息从不按 cursor 丢弃 —— 仍由常规重叠去重裁决。空闲时不携带 `live`。
-
-`tracePosition` 只是历史响应元数据,不进入持久化 OmniMessage。Web App 将一轮最后一条模型文本的不可变坐标提交给 `/fork`,服务端再校验它确实闭合了一个完整 Task。分叉会克隆保留范围内的 Trace 分片,并把源 Session 的 scratchpad 快照到新 Session id 下;系统生成的本地附件路径同步改写,因此以后删除任一 Session 都不会破坏另一方。同一源 Session 在任意回复位置产生的分支共用持久编号,标题使用不依赖界面语言的后缀,依次为 `原标题 (1)`、`原标题 (2)`;删除旧分支不会复用编号。源 Session 正在运行或压缩时返回 409。
+`cursor` 和 `fragments` 在 Trace 读取开始之前一并原子捕获。先连接事件流的客户端(见[推荐的客户端模式](#推荐的客户端模式))在历史之后应用它们:游标的 epoch 与已缓冲 SSE 事件的 epoch 一致时,丢弃所有 seq 不高于游标的缓冲 partial 事件,因为 `fragments` 已经包含那些内容。接着客户端把 `fragments` 送入正常的 reducer,再重放缓冲中剩下的部分。游标从不丢弃缓冲中的完整消息;那些交给常规的重叠去重处理。Session 空闲时不返回 `live`。
-Workspace 文件可能由 Agent 生成,`GET /files/content` 一律按不可信内容处理:所有响应都带 `X-Content-Type-Options: nosniff`,其余响应头取决于两个开关(`download=1` 优先于 `preview=1`):
+### 分叉
-| 查询参数 | Content-Type | Content-Disposition | Content-Security-Policy |
-| --- | --- | --- | --- |
-| 都不带 | `.html` / `.htm` / `.svg` 降级为 `text/plain; charset=utf-8`,其余为真实类型 | `inline` | 无 |
-| `preview=1` | 真实类型(`text/html`、`image/svg+xml` 等) | `inline` | `sandbox allow-scripts allow-popups allow-modals allow-forms`,仅对 `.html` / `.htm` / `.svg` 下发 |
-| `download=1` | 真实类型 | `attachment` | 无 |
-
-`GET /scratchpad/:fileName` 提供的同样是不可信字节(用户上传与 Agent 写下的临时文件),防护口径一致,只是没有那两个开关:始终带 `nosniff`;仅五种可安全内联的图片类型(`.png` / `.jpg` / `.jpeg` / `.gif` / `.webp`)按真实类型内联,供对话里的 `<img>` 使用;其余一律 `application/octet-stream` 并带 `Content-Disposition: attachment` —— 非图片内容无法在 App 所在源上作为文档渲染。
+`tracePosition` 是历史响应的元数据,不属于持久化的 OmniMessage 信封。Web App 把这条回复最后一条助手记录的不可变位置发给 `/fork`,服务器检查这条记录确实结束了一个已完成的 Task。
-文件名始终以 `filename*=UTF-8''` 形式携带(百分号编码)。`preview=1` 是预览跳转在没有独立预览源时的回退目标:文档保留真实类型,可以正常渲染并执行脚本,但沙箱刻意不含 `allow-same-origin`,因此它落在一个不透明源里,既拿不到本源的 Cookie,也调不动 API。这份隔离也正是那里 `localStorage`、`document.cookie` 与第三方 embed 全都不可用的原因。
+分叉会克隆保留的 Trace 文件,并把源暂存区按新 Session id 拍快照,同时改写系统生成的本地附件标记,因此以后无论删除哪个 Session,分叉都能继续工作。从同一个源 Session 的任意回复创建的分叉,共用一套与界面语言无关的持久标题序号(`Source title (1)`、`Source title (2)`);删除较早的分叉也不会释放它的序号。源 Session 正在运行或压缩时返回 409。
-### 消息绑定(飞书、Telegram、QQ、微信)
-
-Session 可以接入消息软件机器人——目前的渠道是飞书、Telegram、QQ 与微信,各自挂在 `/messaging/<channel>` 之下。一个 Session **每个渠道至多保存一份配置**(多份可同时保存),其中**至多一个渠道处于启用状态**——启用的渠道持有在线连接。启用即把机器人账号绑定到该 Session,停用即解除绑定,因此同一个应用或机器人可以同时保存在任意多个 Session 上,只有启用是互斥的。发给机器人的消息以普通用户输入在该 Session 上发起 Task——与在网页输入框里输入完全一致(无标记块;忙碌时排入 follow-up 队列)——完成的回复再转发回对应会话,并按渠道文本上限分段(Telegram 硬上限 4096 字符)。飞书经 SDK 的 WebSocket 长连接接收事件,Telegram 用 `getUpdates` 长轮询,QQ 以 `GROUP_AND_C2C_EVENT` intent 保持平台的 WebSocket 网关连接,微信用 `ilink/bot/getupdates` 长轮询——四者都无需公网回调地址。保存与连接是两件事:PUT 只保存凭据,连接由独立的 state 接口开关。路径同上表,省略 `/api/sessions/:sessionId` 前缀。
+### Task 与插话
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + `linePerMessage` + `finalReplyOnly` + `renderMarkdown` + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 |
-| GET | /messaging/feishu | `{binding, status}` 形态下的飞书配置(未保存时为 null) |
-| PUT | /messaging/feishu | 保存凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`。`appSecret` 省略或留空则保持已存值;`clearAppSecret: true` 清除已存密钥(新输入的密钥优先于清除标记;启用中返回 409 `messaging_disable_before_clear`——清除后配置行与非密钥字段保留);`baseDomain` 默认 `https://open.feishu.cn`。不带连接副作用——唯一例外:**已启用**绑定的连接器会用新凭据重启,保证存储配置与在线连接永不背离。保存不会与其他 Session 冲突,唯一例外正源于这次重启:把**已启用**的绑定改指到另一个 Session 已启用的账号上,返回 409 `account_enabled_elsewhere`,否则那次重启就会绕过启用闸门、把第二条在线连接接到同一账号上 |
-| POST | /messaging/feishu/state | 连接开关:`{enabled}`——启用即用**已存凭据**建立连接,停用即断开。该 Session 另一渠道已启用时返回 409 `another_channel_enabled`,同一账号已在**其他 Session** 上启用时返回 409 `account_enabled_elsewhere`(两者都是「先停用那一个」——后者不透露持有方的任何信息,它可能位于调用方看不到的 Project);已存配置没有密钥时返回 400 `feishu_secret_required`。新配置默认停用;服务端启动只连接已启用的配置 |
-| DELETE | /messaging/feishu | 整体删除该渠道的配置(含 App Secret;另一渠道不受影响)。仅为 API 完整性保留——Web 界面的移除入口是清除标记 |
-| POST | /messaging/feishu/test | 用请求携带的草稿值做凭据探测,缺省字段回落到已存配置 → `{ok, latencyMs?, error?}`(凭据被拒是 `ok: false`,不是 HTTP 错误) |
-| POST | /messaging/feishu/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在飞书里给机器人发过消息之前返回 409 `feishu_no_chat` |
-| GET | /messaging/telegram | 同一形态下的 Telegram 配置(`botId`、`botTokenMasked`) |
-| PUT | /messaging/telegram | 保存凭据:`{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`——整份凭据就是 @BotFather 签发的一条 `<机器人 id>:<密钥>` Token(省略或留空则保持已存值;读不出数字 id 时返回 400 `telegram_token_invalid`;清除标记与飞书同口径,清除后配置保留其机器人身份)。保存与启用的分离一致;把已启用绑定的 Token 换成另一个 Session 已启用的机器人时,同样返回 409 `account_enabled_elsewhere`,其余情况不存在跨 Session 的保存冲突 |
-| POST | /messaging/telegram/state | 与飞书开关同一契约(无已存 Token 时返回 400 `telegram_token_required`) |
-| DELETE | /messaging/telegram | 整体删除该渠道的配置(含 Bot Token)。仅为 API 完整性保留 |
-| POST | /messaging/telegram/test | 凭据探测(`getMe`),草稿 Token 缺省回落到已存值 → `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}`——成功时报出 Token 登录到的机器人;当 @BotFather 的 Group Privacy 处于开启状态(默认如此,此时机器人在它不担任管理员的群里收不到任何普通消息)时报出 `groupPrivacy: true` |
-| POST | /messaging/telegram/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 Telegram 里给机器人发过消息之前返回 409 `telegram_no_chat` |
-| GET | /messaging/qq | 同一形态下的 QQ 配置(`appId`、`appSecretMasked`) |
-| PUT | /messaging/qq | 保存凭据对:`{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`——QQ 开放平台「开发设置」页的 App ID 与 App Secret。留空保持、清除标记、保存与启用分离都与飞书 PUT 同口径;把一条已启用绑定的 App ID 换成另一个 Session 已启用的账号时,同样返回 409 `account_enabled_elsewhere`,此外保存不会跨 Session 冲突;没有域名字段,因为 API v2 只有一个接口域名 |
-| POST | /messaging/qq/state | 与其他开关同一契约(无已存密钥时返回 400 `qq_secret_required`) |
-| DELETE | /messaging/qq | 整体删除该渠道的配置(含 App Secret)。仅为 API 完整性保留 |
-| POST | /messaging/qq/test | 凭据探测(换取 app access token)→ `{ok, latencyMs?, error?}`。不报出账号名:平台没有能识别机器人身份的接口 |
-| POST | /messaging/qq/scan | 发起扫码连接:服务端用新生成、且不外传的 AES 密钥注册一个绑定任务 → `{taskId, qrUrl, pollMs}`。把 `qrUrl` 渲染成二维码;它由 QQ 客户端打开,浏览器不会请求它。该 Session 的 QQ 连接处于启用状态时返回 409 `messaging_disable_before_scan`——扫码会在在线连接器底下换掉整对凭据;平台拒绝时返回 502 `qq_scan_failed` |
-| POST | /messaging/qq/scan/poll | `{taskId}` → `{status, appId?, binding?}`。`completed` 表示服务端已解密 App Secret 并**保存**了绑定(启用仍是独立动作);`expired` 表示需重新建任务。未知、属于其他 Session 或已完成的任务返回 404 `qq_scan_task_unknown` |
-| POST | /messaging/qq/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其密钥,而不是等待过期清扫 |
-| POST | /messaging/qq/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 QQ 里给机器人发过消息之前返回 409 `qq_no_chat`;没有可回复的近期消息时返回 502 `qq_send_failed`(见下) |
-| GET | /messaging/wechat | 同一形态下的微信配置(`botId`、`botTokenMasked`) |
-| PUT | /messaging/wechat | **只**保存投递偏好:`{clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`。这是本组唯一不携带凭据的 PUT——微信机器人的 Bot Token 只能由扫码产生,没有可供复制的后台——因此它以已有绑定为前提,绑定不存在时返回 400 `wechat_token_required`。清除开关与其他渠道一致(启用中返回 409 `messaging_disable_before_clear`;被清除的配置保留行与机器人身份,只有重新扫码才能再次连接) |
-| POST | /messaging/wechat/state | 与其他开关同一契约(无已存 Token 时返回 400 `wechat_token_required`) |
-| DELETE | /messaging/wechat | 整体删除该渠道的配置(含 Bot Token)。仅为 API 完整性保留 |
-| POST | /messaging/wechat/test | 凭据探测(以扫码账号身份调用 `ilink/bot/getconfig`)→ `{ok, latencyMs?, error?}`。这是唯一**不接受请求体**的探测:本渠道没有可填写的字段,只能探测已存绑定(没有则返回 400 `wechat_token_required`)。不报出账号名——该探测既不识别机器人,也不识别人 |
-| POST | /messaging/wechat/scan | 发起扫码连接——在本渠道这是**唯一**的绑定方式 → `{taskId, qrUrl, pollMs}`。把 `qrUrl` 渲染成二维码;它由微信打开,服务端从不请求它。平台自身的轮询句柄——也就是能换取 Bot Token 的那个——留在服务端,`taskId` 是服务端另行签发的替代句柄。连接启用中返回 409 `messaging_disable_before_scan`;平台拒绝时返回 502 `wechat_scan_failed` |
-| POST | /messaging/wechat/scan/poll | `{taskId}` → `{status, botId?, binding?}`。`status` 取值为 `pending`、`scanned`、`need_verify_code`、`blocked`、`expired`、`already_bound`、`completed`。`completed` 表示服务端已**保存**绑定(启用仍是独立动作);`already_bound` 不是失败——该机器人已被绑定,没有签发新凭据。它并不说明绑定在**哪里**:本流程不向平台提供任何已持有的 token 列表,因此无法区分「绑定在本服务」与「绑定在别处」。任务未知、属于其他 Session 或已结算时返回 404 `wechat_scan_task_unknown`。与 QQ 不同,**重叠的**轮询返回 `pending` 而非 404:上游是长轮询,一次调用会跨越客户端的多个轮询间隔 |
-| POST | /messaging/wechat/scan/verify | `{taskId, verifyCode}` → 204。微信在手机上显示的配对码。平台把它作为状态查询的参数,因此它随**下一次**轮询携带而不单独发起请求,本接口只做记录——配对码错误会表现为下一次轮询再次返回 `need_verify_code` |
-| POST | /messaging/wechat/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其句柄,而不是等待过期清扫 |
-| POST | /messaging/wechat/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在微信里给机器人发过消息之前返回 409 `wechat_no_chat` |
-
-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage`、`finalReplyOnly` 与 `renderMarkdown` 是仅有的三个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。开启 `renderMarkdown` 后,转发回复中的 Markdown 按各渠道自身的标记语言渲染,而不是把字符原样发出;它**默认为 true**,PUT 省略同样保持已存值,同样不作用于通知与测试消息。各渠道各自渲染力所能及的部分,其余按既定方式降级而非泄漏源码:Telegram 使用 `parse_mode: "HTML"`,没有标题、列表和表格(标题渲染为一行粗体,列表符号作为文本保留,表格改用 `<pre>` 块);飞书发送携带 JSON 2.0 富文本组件的交互卡片,全部构件均可渲染,超长表格改为代码块以免整行被静默丢弃;QQ 使用 `msg_type: 2` 自定义 markdown,没有代码格式也没有表格(代码块按转义后的普通文本行发出,表格按其行发出);微信自己就读 Markdown,因此渲染是**做减法**而不是翻译——客户端不会呈现的部分保留文字、去掉标记(四级以上的标题、CJK 两侧的强调,以及内联图片,后者改为链接)。分段随该设置改变:在块边界切分,跨消息的代码块会重新加围栏,因此任何一条消息都不会打开一个它没有闭合的构件。**渠道拒绝的格式化发送会退回为同一条消息的纯文本发送**,因此该设置只可能损失排版,绝不会损失回复。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变),微信则是扫码返回的机器人 id。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本、图片与文件:图片按普通 `image_url` 输入部分送入,单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。文件按输入框的另一种附件形态送入——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型,其字节不进入对话——上限沿用管理员可设的单个文件与单条消息附件上限(与经过鉴权的上传同一组数值),并再取渠道自身更紧的那个上限(Telegram 不向机器人提供超过 20MB 的文件)。飞书取 `file` 消息类型,Telegram 取 `document` 字段:发送者主动**以文件形式**发出的那一个,也是 Telegram 各媒体字段中唯一携带发送者原始文件名的。在这两个渠道上,视频、音频与语音有意不予送达——下游没有任何环节能解码或转写它们,而发送者真正想交给智能体的东西,只要按文件发送就会到达。微信是例外,且仅仅因为解码由平台自己完成:语音消息随附它自己的转写文本,视频则作为普通文件到达。附件**确实会被送达**的消息(图片、文件),其说明文字即该消息的文本;其他媒体类型的说明文字则不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈。图片超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示;文件超过单个上限、一条消息的文件总量超限与渠道拒绝下载同样各有其提示。它们都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件没送到时,聊天里不会出现任何说明。它们记为该 Project 下的错误记录,显示在成本中心的异常表中:每条回复按原因各记一条,写明其涵盖的每个文件、渠道与原因——超过上限的文件记 `messaging_file_too_large`,超出数量上限的记 `messaging_files_skipped`,被拒绝的上传记 `messaging_file_send_failed`,其中渠道根本无法承载的上传(QQ 上的任何文件)、缺少权限(所需权限与控制台授权链接只列一次,取代渠道对每个文件给出的原因)与其余拒绝各记一条。前两种与渠道无法承载的上传记为 `expected`;缺少权限与其余拒绝记为 `unexpected`。Workspace 内对不上任何文件的名字只写入服务端日志,本次运行没有写过的文件则静默跳过,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。
-**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20;被平台拒绝的 `renderMarkdown` 发送,其纯文本重试会再占用一次额度。`finalReplyOnly` 在这里有利有弊:它把一次运行的额度消耗压到最低——只发一条;但被动回复的有效期只有几分钟,把回复扣到运行结束才发,等于把这个窗口花在了运行本身上,运行时长超过窗口时将什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。
-**微信只承载单聊,但媒体能力是四个渠道里最全的。** 该机器人渠道完全不接收群消息:在群里 @机器人的消息根本不会到达本 API,因此单聊正常、群聊沉默是渠道形态而非配置错误。作为交换,它是这里唯一能**双向**传输文字、图片与文件的渠道——回复中的图片与附件会上传到平台 CDN(每个文件一把 AES-128-ECB 密钥),以真正的图片和文件到达,而不是被拒绝。两类入站消息被折叠处理:语音消息按微信自带的语音转文字结果进入对话,视频按文件到达;微信没能转写的语音则以共用的「不支持」提示回到聊天。
-
-**扫码连接不会把机密交给浏览器。** 让这套流程安全的东西都留在服务端——解密 QQ App Secret 的 AES 密钥,以及换取微信 Bot Token 的轮询句柄——在服务端生成、持有、使用并丢弃;客户端只拿到任务句柄、待绘制的 URL 与状态。任务只存在于内存,归属发起它的 Session,按 Session 单独限量(一个调用方的扫码任务挤不掉另一个调用方的),并被「解决它的那一次轮询」认领掉,因此重放得到的是 404 而不是第二次绑定。对同一任务的并发轮询在 QQ 上同样是 404;在微信上返回 `pending`,因为上游是一次跨越客户端多个轮询间隔的长轮询。所有扫码路由都仅限 Project 所有者——无论调用方实际输入了多少内容,这个流程的终点都是一份存下来的凭据。
-
-### 独立源预览
-
-Files 面板内的 HTML 渲染视图(iframe)与“新页面打开”都走 `GET /files/preview-redirect?path=`:先鉴权,再签发一枚短时效 HMAC 令牌,然后 302 跳转到**另一个源**:
-
-```text
-GET /api/sessions/:sessionId/files/preview-redirect?path=index.html
-302 Location: http://localhost:7364/preview/<token>/index.html
-GET /preview/<token>/<相对路径> (不鉴权,令牌即凭证)
-```
-
-- **为什么要独立源。** 页面需要一个真实的源,才能有可用的 storage、Cookie 与第三方 embed;但它不能是应用自己的源,否则 Agent 写出来的 HTML 就带着会话 Cookie 在跑。本地把 App 固定在规范主机 `localhost`,预览用 `127.0.0.1`——Cookie 按主机划分且不区分端口,所以这两者天然是两个 Cookie jar,而只换端口做不到。其余情况用 `PENGUIN_PREVIEW_ORIGIN`;两者都没有时(通配或非回环绑定,或变量未设)回退到上面的同源沙箱,并由 `GET /api/me` 的 `previewIsolated` 返回 `false`,界面据此提前说明。
-- **面板内渲染共用同一 URL。** Files 面板把该跳转 URL 嵌入 iframe,沙箱为 `allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads`——`allow-same-origin` 赋予的是预览源而非应用源的身份,因此仍严格紧于不带沙箱的新标签页。没有独立预览源时,面板回退为内联 `srcdoc` 渲染(仅 `allow-scripts`,附内存版 storage 垫片),相对子资源在那里无法加载。另注意部分浏览器会对跨站 iframe 内的 storage 做分区或屏蔽,页面在面板内的行为可能与顶层标签页略有差异。
-- **预览主机只服务 `/preview/*`。** 它与 App 是同一个进程,故其 `/api` 一律 401,其余路径一律 302 回规范 App 主机——会话 Cookie 因此永远不会落在预览主机上,也不被其接受,那里的 Agent HTML 无法同源调用 API。(部署 `PENGUIN_PREVIEW_ORIGIN` 时,反向代理须做等价保证:该源上只把 `/preview/*` 路由到 App。)
-- **路径式而非查询参数**,页面里的相对子资源(`app.js`、`style.css`、图片)才能相对文档解析,并在同一个令牌下加载。
-- **令牌绑定 Session、预览主机与过期时间。** 其中主机绑定是承重的:同一个进程也在应用源上应答,因此 `/preview/...` 在应用源上一律拒绝服务——否则那就是一个同源 XSS。权限只读、限定该 Session 的 Workspace,路径仍在服务端重新解析,`..` 与符号链接逃逸照旧拒绝。
-- **响应带 `Referrer-Policy: no-referrer`**,否则带令牌的 URL 会经 `Referer` 泄漏给页面内嵌的每一个第三方——而这个风险恰恰是因为 embed 现在能用了才出现的。
-- 令牌无效、过期、主机不符与路径越界一律返回裸 404:该端点不鉴权,不能确认任何东西是否存在。
-
-关键请求体(明确键名):
+| POST | `/tasks` | 启动一个 Task:`{input: TaskInputPart[], queueIfBusy?, goal?}` → 202 |
+| POST | `/steer` | 为正在运行的 Task 排入一条插话消息:`{text, images?}` → 202 |
+| DELETE | `/steer/:steerId` | 撤回一条尚未投递的插话消息 |
+| DELETE | `/follow-ups/:followUpId` | 撤回一个排队的后续 Task |
+| POST | `/approvals/:toolCallId` | 审批决定:`{decision}`,`allow` 或 `deny` → 204 |
+| POST | `/tool-calls/:toolCallId/background` | 把一个执行中的工具调用移入后台 → 204 |
+| POST | `/subagents/:childSessionId/message` | 向一个子 Agent 会话发送消息:`{text}` → `{outcome}` |
+| POST | `/subagents/:childSessionId/abort` | 停止一个子 Agent 会话的当前运行 |
+| POST | `/abort` | 中断当前 Task:触发时返回 202,空闲时返回 204 |
+| POST | `/retry-now` | 跳过重连倒计时:→ 200 `{skipped}` |
+| POST | `/compact` | 开始上下文压缩:202 |
+
+- `POST /tasks` 响应 `{sessionId, queued?}`。带 `queueIfBusy` 时,忙碌的 Session 会把输入存为后续 Task(`queued: true`),等 Session 空闲后作为普通的下一个 Task 启动;`task_state` 事件报告排队的数量。`file` 输入部分写入 Session 暂存区,并以 `[attached file: <path>]` 行的形式交给模型(见[请求体](#请求体))。
+- `POST /tasks` 带 `goal: {budget?}` 时改为启动目标循环。Agent 没有安装 `goal` 插件时返回 409 `goal_plugin_not_installed`。目标就是输入里的文本(去掉开头的标记块),所以输入必须带非空文本(否则返回 400):只有图片说明不了目标。图片作为普通输入随第 1 轮发送,之后各轮只重新注入目标文本。`file` 部分一律以 400 拒绝,因为没有办法把文件带进每一轮都重新注入的目标。见[目标模式](/goal-mode)。
+- `POST /steer` 在轮次之间把消息作为一条独立的 `[user_steering]` 用户消息投递,图片紧随其后。`text` 和 `images` 任一字段都能单独携带消息,但两者都缺时返回 400。没有 Task 在运行时返回 409 `not_running`。
+- `DELETE /steer/:steerId` 接收 `task_state` 里 `pendingSteering` 的 id,把那条消息从队列撤回。响应 200,带原始内容 `{text, images, files}`,便于输入框恢复消息供编辑:文件以 data URL 的形式从暂存区读回,磁盘上的副本随之删除。消息已经投递给模型时返回 409 `not_pending`。
+- `DELETE /follow-ups/:followUpId` 接收 `task_state` 里 `pendingFollowUps` 的 id,在后续 Task 启动前把它移除。响应 200,带原始内容 `{text, images, files}`;无论以哪种方式排队,每个排队的后续 Task 都带这些内容。后续 Task 已经启动、或 id 未知时返回 409 `follow_up_started`。
+- `POST /tool-calls/:toolCallId/background` 把一个执行中的工具调用转成后台任务交回,当前轮次得以收尾,对话得以继续。调用以 `completed` 结束并附带 `process_id` 或 `subagent_id`,进程一律不终止,结果稍后通过常规的后台任务通知送达。没有这个 id 的调用在执行时返回 404 `tool_call_not_found`(id 未知、调用已结束、或运行时已不存在);调用还在运行、但它的工具没有后台形态时返回 409 `tool_not_detachable`。只有 `exec_command` 和 `run_subagent` 有后台形态。
+- `POST /subagents/:childSessionId/message` 无论子 Agent 处于什么状态,都把文本作为用户输入投递给它。子 Agent 正在运行、消息作为插话排队时,`outcome` 为 `steered`;空闲的子 Agent 启动一次后续运行时为 `started`;已释放的子 Agent 重新拉起并开始下一轮时为 `resumed`。子 Agent 以自己上下文的思考等级运行,可以用子 Session 上的 `PATCH` 固定它。空 `text` 返回 400;404 `subagent_gone` 表示子 Agent 的记录不存在或无法复活;409 `subagent_busy` 表示子 Agent 目前无法接收消息。
+- `POST /subagents/:childSessionId/abort` 只停止子 Agent 当前的运行;子 Session 仍可用于插话和后续 Task。成功停止一次运行时返回 202;子 Agent 已空闲或未知时返回 204。
+- `POST /retry-now` 对应重连倒计时上的**立即重试**按钮。它跳过当前的退避等待,立即发起下一次重试,不改动尝试计数。`skipped: false` 表示当时没有等待在进行,这不是错误。
+- `POST /compact` 在没有可压缩内容时返回 409,原因写在错误码里:`compaction_not_configured`(Agent 没有配置压缩)、`nothing_to_compact`(上下文还没有完整的对话轮次)或 `already_compacted`(上次压缩之后没有新内容)。服务器重启后恢复的 Session 会从自己的 Trace 推导出这些状态,所以已有对话无需先跑一个 Task 也能压缩。
+
+### 请求体
```ts
-// POST /api/sessions/:sessionId/tasks —— 发起一个 Task
+// POST /api/sessions/:sessionId/tasks — start a Task
interface TaskCreateRequest {
input: TaskInputPart[];
- // 思考等级不是 Task 参数:它属于模型上下文——用 PATCH 钉在 Session 上,此后开启的每个上下文都以钉住的等级运行
+ // The thinking level is not a task parameter: it belongs to the model context — pin it on
+ // the Session with PATCH, and each context the Session opens runs at the pinned level
}
type TaskInputPart =
| { type: "text"; text: string }
- | { type: "image_url"; imageUrl: string } // 粘贴图片以 data URL 上送,≤20MB(超出返回 413 image_too_large)
- // 文件附件:base64 data: URL,默认单个 ≤100MB(超出返回 413 file_too_large),单次请求最多 20 个、
- // 解码后合计 ≤120MB(超出返回 413 too_many_files / payload_too_large;三项校验都在落盘前完成)。
- // 两个尺寸均可由管理员调整(PUT /api/admin/settings),并由 GET /api/me 下发。
- // 服务端将其写入该 Session 的 scratchpad,并在消息文本末尾追加一行
- // `[attached file: <path>]`——模型按路径读取该文件。`fileName` 不得含路径分隔符;落盘时保留
- // 原有词形(`报告 2026.pdf` → `报告-2026.pdf`:非 ASCII 字符原样保留,对 shell 不友好的
- // ASCII 字符替换为 `-`),既便于在消息中辨认,也可安全地拼进命令。
+ | { type: "image_url"; imageUrl: string } // pasted images arrive as data URLs, ≤20MB (413 image_too_large)
+ // File attachment: base64 data: URL, by default ≤100MB each (413 file_too_large beyond that),
+ // at most 20 per request and 120MB of decoded bytes in total (413 too_many_files /
+ // payload_too_large; all three are checked before anything is written). The two sizes are
+ // admin-settable (PUT /api/admin/settings) and reported by GET /api/me. The server writes it into the Session
+ // scratchpad and appends an `[attached file: <path>]` line to the message text — the model
+ // opens the file by path. `fileName` carries no path separators; on disk it keeps its own
+ // words (`报告 2026.pdf` → `报告-2026.pdf`: non-ASCII survives, shell-hostile ASCII becomes
+ // `-`), so a name is readable in the message and safe to paste into a command.
| { type: "file"; fileName: string; dataUrl: string };
// POST /api/sessions/:sessionId/approvals/:toolCallId
@@ -510,71 +755,378 @@ interface ApprovalDecisionRequest {
}
```
-Web 的 `/model` 模型切换没有专用接口:它按 `/agent` 交接的方式复用上面的普通接口——先用会话创建接口在同一 Agent 下新建 Session(选定新模型并沿用源 Workspace),再 POST /tasks 发送以 `[model_switch_from]` 源块开头的首条消息(源会话 id、其 `tracePath`、Workspace 与原模型二元组),模型需要早前历史时自行读取该 Trace 文件。
+Web App 的 `/model` 切换没有专用端点。和 `/agent` 交接一样,它把几条普通路由组合起来:
+
+1. 创建 Session:为同一个 Agent 打开新 Session,沿用所选模型和源 Workspace。
+2. `POST /tasks` 发送第一条消息,开头是 `[model_switch_from]` 来源块,写明源 session id、它的 `tracePath`、Workspace 以及之前的模型组合。
+3. 需要更早的历史时,模型自己去读那个 Trace 文件。
+
+### 后台进程
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | `/processes` | 对话启动的后台进程 |
+| POST | `/processes/:processId/kill` | 停止一个后台进程 |
+| DELETE | `/processes/:processId` | 把一个已退出的进程从列表移除 |
+
+- `GET /processes` 列出超出让出窗口而转入后台的 `exec_command` 调用。列表只来自当前活跃的运行时,所以未加载、或从未正确加载的 Session 报告空列表。当服务器检测到进程对外服务的地址时,行会带 `serviceUrl`:它是输出打印的最后一个本地 URL;找不到时,是探测进程组发现的监听端口,每次请求都会刷新。
+- `POST /processes/:processId/kill` 先向整个进程组发送 SIGTERM,宽限期后发送 SIGKILL,条目随即移出列表。进程已不存在时返回 404 `process_not_found`。
+- `DELETE /processes/:processId` 在进程仍在运行时返回 409 `process_running`(应该改用停止接口),在条目已不存在时返回 404 `process_not_found`。条目连同已捕获的输出一起移出运行时注册表,之后再对那个 `process_id` 执行 `input_command` 会失败。
+
+### Workspace 文件
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | `/files?path=` | 浏览一个 Workspace 目录 |
+| GET | `/files/content?path=&download=&preview=` | 读取一个 Workspace 文件(见 [Workspace 文件响应](#workspace-文件响应)) |
+| GET | `/files/preview-redirect?path=` | 在独立的预览源上打开 HTML 文件:签发签名 token 并以 302 重定向 |
+| POST | `/files/stat` | 检查文件是否存在:`{paths}` |
+| PUT | `/files/content?path=` | 上传文件:`{dataBase64}`,最大 14MB |
+| POST | `/files/move` | 移动或重命名一个文件:`{from, to, ifVersion?}` → 204 |
+| DELETE | `/files/content?path=&ifVersion=` | 删除一个文件 → 204 |
+| POST | `/files/reveal?path=` | 在机器自带的文件管理器中显示文件 → 204 |
+| GET | `/files/search?q=` | 按条目名搜索整个 Workspace |
+| GET | `/scratchpad/:fileName` | 读取 Session 的一个暂存文件,例如输入图片或文件附件 |
+
+- `GET /files/preview-redirect` 支撑**新页面打开**和**文件浏览**面板里的 HTML 渲染视图;见[独立源上的预览](#独立源上的预览)。
+- `POST /files/move` 只对文件生效:目录没有单一的版本标记,保护移动的前置条件无法对目录表达,所以对目录返回 400。`to` 缺失的父目录会自动创建。`from` 不存在时返回 404 `path_not_found`;`ifVersion` 不再匹配时返回 409 `file_changed`(带着标记时源文件却已消失,也算作已变化)。`to` 位置已有内容时返回 409 `target_exists`——目标从未读取过,所以选择拒绝而不是覆盖;移动到文件自身路径返回 400。
+- `DELETE /files/content` 同样只对文件生效(对目录返回 400)。文件已不存在时返回 404 `path_not_found`;`ifVersion` 不再匹配时返回 409 `file_changed`。这个标记是可选的,不带标记时删除是无条件的,但**文件浏览**面板总是发送它读取时拿到的标记。
+- `POST /files/reveal` 在 macOS 和 Windows 上选中文件,在 Linux 桌面上打开文件所在目录。只有桌面 shell 自己的窗口可以调用它。服务器不是由桌面 shell 启动时返回 404 `not_found`;浏览器会话访问桌面模式服务器时返回 403 `desktop_shell_only`:这种会话无法与远程会话区分,而在服务器所在的机器上打开文件夹,对那头的用户毫无用处。路径的限制与读取相同(越界 400,不存在 404 `path_not_found`);502 `reveal_failed` 表示文件管理器未能启动。
+- `GET /files/search` 只匹配条目名(不区分大小写的子串;不匹配路径),响应为 `{hits: [{path, kind, sizeBytes, mtime}], truncated}`,每条命中都带有目录列表条目的全部字段。搜索从根目录开始广度优先遍历,所以浅层结果先出现;结果达到上限时,保留的是最相关的命中,而不是最先遍历到的那个目录里的内容。`truncated` 表示遍历因达到上限而停止:命中 200 条,或访问了 20000 个目录条目。`q` 为空或超过 100 个字符时返回 400。
+
+### Workspace 文件响应
+
+Workspace 文件可能由 Agent 生成,所以 `GET /files/content` 把它们当作不可信内容。每个响应都带 `X-Content-Type-Options: nosniff`,其余响应头取决于两个标志,`download=1` 优先于 `preview=1`:
+
+| 查询参数 | Content-Type | Content-Disposition | Content-Security-Policy |
+| --- | --- | --- | --- |
+| 两者都不带 | `.html` / `.htm` / `.svg` 用 `text/plain; charset=utf-8`,其他用真实类型 | `inline` | — |
+| `preview=1` | 真实类型(`text/html`、`image/svg+xml` 等) | `inline` | `sandbox allow-scripts allow-popups allow-modals allow-forms`,仅对 `.html` / `.htm` / `.svg` 发送 |
+| `download=1` | 真实类型 | `attachment` | — |
+
+文件名一律以 `filename*=UTF-8''` 的形式加百分号编码发送。
+
+没有可用的独立预览源时,预览重定向就回退到 `preview=1`。文档保留真实类型,会正常渲染和执行,但沙盒有意省略 `allow-same-origin`。于是文档落在一个不透明源里,既拿不到本源的 cookie,也访问不到 API;`localStorage`、`document.cookie` 和第三方嵌入在那里都不起作用,原因也在于此。
+
+`GET /scratchpad/:fileName` 提供同类不可信内容(上传的文件以及 Agent 写入的临时文件),以同样的方式加固,但不接受那两个标志:
+
+- 始终发送 `X-Content-Type-Options: nosniff`。
+- 固定白名单中的五种惰性图片类型(`.png` / `.jpg` / `.jpeg` / `.gif` / `.webp`)以内联方式提供,供对话里的 `<img>` 标签使用。
+- 其余内容一律以 `application/octet-stream` 加 `Content-Disposition: attachment` 提供,因此除这些图片外,任何东西都无法在应用的源上渲染成文档。
+
+### 独立源上的预览
+
+**文件浏览**面板里的 HTML 渲染视图(一个 iframe)和**新页面打开**都经过 `GET /files/preview-redirect?path=`。这条路由先验证调用方,再签发一个短时效的 HMAC token,然后以 302 重定向到一个**不同的源**:
+
+```text
+GET /api/sessions/:sessionId/files/preview-redirect?path=index.html
+302 Location: http://localhost:7364/preview/<token>/index.html
+GET /preview/<token>/<relative path> (unauthenticated; the token is the credential)
+```
+
+- 为什么需要独立的源:页面要有真实的源,存储、cookie 和第三方嵌入才能工作;但这个源不能是应用的源,否则 Agent 写的 HTML 会带着会话 cookie 运行。本地运行时,应用地址规范化为 `localhost`,预览由 `127.0.0.1` 提供。cookie 按主机名隔离、忽略端口,所以这两个主机拥有各自独立的 cookie jar;换成第二个端口就做不到这一点。其他情况则使用 `PENGUIN_PREVIEW_ORIGIN`。两者都没有时(通配或非回环绑定,或变量未设置),重定向回退到前文所述的同源沙盒,同时 `GET /api/me` 上的 `previewIsolated` 报告 `false`,UI 得以提前告知用户。
+- 应用内渲染用同一个 URL:**文件浏览**面板把重定向 URL 嵌入 iframe,沙盒标志为 `allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads`。这里的 `allow-same-origin` 授予的是预览源的身份,不是应用的,所以这套配置仍然严格比新标签页收紧——新标签页没有沙盒。没有独立预览源时,面板回退到内联 `srcdoc` 渲染(只给 `allow-scripts`,外加一个内存版 storage 垫片),相对子资源无法加载。部分浏览器会对跨站 iframe 内的存储做分区或阻止,所以同一个页面在面板里的行为可能与顶层标签页略有差异。
+- 预览主机只服务 `/preview/*`。它与应用是同一个进程,所以对 `/api` 返回 `401`,把其余所有路由以 `302` 重定向到规范的应用主机。因此,预览主机从不设置、也不接受会话 cookie,那里的 Agent HTML 无法从同一源访问 API。部署了 `PENGUIN_PREVIEW_ORIGIN` 时,反向代理必须执行同样的约束:只把 `/preview/*` 路由到这个源上的应用。
+- token 放在路径里,而不是查询参数里,这样页面的相对子资源(`app.js`、`style.css`、图片)相对文档解析,并在同一个 token 下加载。
+- token 绑定 Session、预览主机和过期时间。主机绑定很关键:同一个进程也在应用源上应答,所以 `/preview/...` 拒绝在那个源上服务,否则会构成同源 XSS。访问是只读的,限于这个 Session 的 Workspace;服务器会重新解析路径,对 `..` 和符号链接逃逸的拒绝方式与任何读取相同。
+- 响应带 `Referrer-Policy: no-referrer`。否则 URL 连同其中的 token 会通过 `Referer` 泄露给页面嵌入的每一个第三方——正因为嵌入如今可以工作,这个风险才随之而来。
+- 无效 token、过期 token、错误主机和越界路径一律返回裸 404:这个端点不经认证,绝不能确认任何路径是否存在。
+
+### Trace
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | `/traces` | 列出当前 Session 的 Trace 文件 |
+| GET | `/traces/:index` | 读取 Trace 事件(分页) |
+| GET | `/traces/:index/analysis` | Trace 性能分析 |
+
+## 消息渠道绑定(飞书、Telegram、QQ、微信)
+
+Session 可以连接消息机器人。目前支持的渠道是飞书、Telegram、QQ 和微信,路由都在 `/messaging/<channel>` 下。与 Session 级别的表格一样,下面的路径省略了 `/api/sessions/:sessionId` 前缀。
+
+- 每个 Session 对每个渠道最多保存一份配置,多个渠道的配置可以并存。同一时刻最多启用其中一个,启用的那个渠道持有活跃连接。
+- 启用会把机器人账号绑定到 Session,停用则解除绑定。因此,同一个应用或机器人可以保存到任意多个 Session 上;只有启用是独占的。
+- 保存和连接是两回事:PUT 只存储凭据,连接由 `state` 路由负责。新配置默认停用,服务器启动时只连接已启用的配置。
+- 发到机器人的消息会变成普通用户输入,在 Session 上启动 Task,和在 Web App 输入框里打字完全一样:不添加任何标记,Session 忙碌时排入后续消息队列。回复完成后会转发回聊天,按块发送,每块最多 4000 字符,低于 Telegram 4096 字符的硬性上限。
+- 飞书通过 SDK 的 WebSocket 长连接监听消息,Telegram 长轮询 `getUpdates`,QQ 以 `GROUP_AND_C2C_EVENT` intent 持有平台的 WebSocket 网关,微信长轮询 `ilink/bot/getupdates`。这些渠道都不需要公网回调 URL。
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | `/messaging` | Session 已保存的全部渠道配置 |
+| GET | `/messaging/feishu` | 飞书配置,格式为 `{binding, status}`(未保存时为 `null`) |
+| PUT | `/messaging/feishu` | 保存飞书凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/feishu/state` | 打开或关闭连接:`{enabled}` |
+| DELETE | `/messaging/feishu` | 完全删除飞书配置,包括 App Secret |
+| POST | `/messaging/feishu/test` | 测试凭据:→ `{ok, latencyMs?, error?}` |
+| POST | `/messaging/feishu/test-message` | 向最近已知的聊天发送一段简短的固定文本 |
+| GET | `/messaging/telegram` | Telegram 配置,格式同上(`botId`、`botTokenMasked`) |
+| PUT | `/messaging/telegram` | 保存 Telegram 凭据:`{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/telegram/state` | 打开或关闭连接:`{enabled}` |
+| DELETE | `/messaging/telegram` | 完全删除 Telegram 配置,包括 Bot Token |
+| POST | `/messaging/telegram/test` | 用 `getMe` 测试 Token:→ `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}` |
+| POST | `/messaging/telegram/test-message` | 向最近已知的聊天发送一段简短的固定文本 |
+| GET | `/messaging/qq` | QQ 配置,格式同上(`appId`、`appSecretMasked`) |
+| PUT | `/messaging/qq` | 保存 QQ 凭据对:`{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/qq/state` | 打开或关闭连接:`{enabled}` |
+| DELETE | `/messaging/qq` | 完全删除 QQ 配置,包括 App Secret |
+| POST | `/messaging/qq/test` | 通过换取 app-access-token 测试凭据:→ `{ok, latencyMs?, error?}` |
+| POST | `/messaging/qq/scan` | 发起扫码绑定:→ `{taskId, qrUrl, pollMs}` |
+| POST | `/messaging/qq/scan/poll` | 轮询扫码任务:`{taskId}` → `{status, appId?, binding?}` |
+| POST | `/messaging/qq/scan/cancel` | 丢弃扫码任务:`{taskId}` |
+| POST | `/messaging/qq/test-message` | 向最近已知的聊天发送一段简短的固定文本 |
+| GET | `/messaging/wechat` | 微信配置,格式同上(`botId`、`botTokenMasked`) |
+| PUT | `/messaging/wechat` | 只保存投递偏好:`{clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` |
+| POST | `/messaging/wechat/state` | 打开或关闭连接:`{enabled}` |
+| DELETE | `/messaging/wechat` | 完全删除微信配置,包括 bot token |
+| POST | `/messaging/wechat/test` | 用 `ilink/bot/getconfig` 测试已存储的绑定:→ `{ok, latencyMs?, error?}` |
+| POST | `/messaging/wechat/scan` | 发起扫码绑定,这是绑定微信的唯一方式:→ `{taskId, qrUrl, pollMs}` |
+| POST | `/messaging/wechat/scan/poll` | 轮询扫码任务:`{taskId}` → `{status, botId?, binding?}` |
+| POST | `/messaging/wechat/scan/verify` | 记录手机上展示的配对码:`{taskId, verifyCode}` → 204 |
+| POST | `/messaging/wechat/scan/cancel` | 丢弃扫码任务:`{taskId}` |
+| POST | `/messaging/wechat/test-message` | 向最近已知的聊天发送一段简短的固定文本 |
+
+### 配置与权限
+
+- `GET /messaging` 是与渠道无关的读取接口,绑定编辑器加载的就是它。每行包含 `channel` 判别字段、掩码后的密钥、`enabled` 的期望值、`linePerMessage`、`finalReplyOnly`、`renderMarkdown`、运行时状态和 `lastChatKnown`。
+- 没有存储密钥时(即已清除的配置),响应里省略掩码密钥;没有密钥的配置无法启用。密钥永远不会回传给客户端。
+- 读取接口和两个测试路由对任何 Project 成员开放。PUT、`state` 开关和 DELETE 仅限所有者,语义与 vault 相同,因为这些写操作携带密钥或作用于密钥。所有扫码路由同样仅限所有者(见[扫码绑定](#扫码绑定))。
+- DELETE 会完全删除一个渠道的配置,不影响其他渠道。这个路由只是为了 API 完整性而保留;Web App 实际用清除标志来移除密钥。删除 Session 会删除它的全部配置。
+- 跨 Session 只有唯一一条规则,按渠道内的机器人账号计算,而且只约束连接:一个账号只有一条事件流,因此最多只能有一个 Session 启用它。飞书按 `app_id` 识别账号,Telegram 按 Token 冒号前的数字 bot id(换发 Token 后依然不变),QQ 按 App ID,微信按扫码返回的 bot id。
+
+### 保存与连接
+
+- PUT 省略密钥或密钥为空白时,保留已存储的密钥。清除标志(`clearAppSecret` 或 `clearBotToken`)会删除已存储的密钥,但同一请求里输入的新密钥优先。渠道处于启用状态时执行清除,会返回 409 `messaging_disable_before_clear`。清除后的配置仍保留这条记录和非密钥字段,包括 Telegram 或微信机器人的身份标识。
+- PUT 不影响连接,只有一个例外:绑定为启用状态时,连接器会用新凭据重启,因此已存储的配置和活跃连接永远不会出现偏差。也正因为如此,保存操作不会在 Session 之间产生冲突,除非它把一个已启用的绑定指向了另一个 Session 已启用的账号。这种情况返回 409 `account_enabled_elsewhere`——否则重启会让这个账号出现第二条活跃连接,等于绕过了启用检查。
+- `POST …/state` 传入 `{enabled: true}` 时用已存储的凭据建立连接,传入 `{enabled: false}` 时断开。本 Session 的另一个渠道处于启用状态时,返回 409 `another_channel_enabled`;另一个 Session 已启用同一账号时,返回 409 `account_enabled_elsewhere`。两种情况的含义相同:先把那一个停用。第二种错误不会透露占用者是谁,对方可能位于调用者看不到的 Project 里。没有已存储的密钥时,开关操作返回 400 `feishu_secret_required`、`telegram_token_required`、`qq_secret_required` 或 `wechat_token_required`。
+- 飞书、Telegram 和 QQ 的 test 路由用请求中的草稿值探测,缺少的值回退到已存储的配置;微信的 test 不接受请求体(见下文)。凭据未通过验证时返回 `ok: false`,而不是 HTTP 错误。
+- test-message 路由在有人在对应应用里给机器人发过消息之前,返回 409 `feishu_no_chat`、`telegram_no_chat`、`qq_no_chat` 或 `wechat_no_chat`。
+
+### 各渠道细节
+
+- 飞书:`baseDomain` 默认为 `https://open.feishu.cn`。
+- Telegram:凭据就是 @BotFather 签发的那一个 `<bot id>:<secret>` 格式的 Token。解析不出数字 id 的 Token 返回 400 `telegram_token_invalid`。测试成功时会给出 Token 登录的机器人名(`botUsername`),并在 @BotFather 的 Group Privacy 开启时报告 `groupPrivacy: true`,这个选项默认开启。Group Privacy 开启时,机器人收不到自己不担任管理员的群里的普通消息。
+- QQ:凭据是 QQ 开放平台开发设置中的 App ID 和 App Secret。没有域名字段,因为 API v2 只有一个主机。测试不报告账号名,因为平台没有能识别机器人的调用。没有最近的 QQ 消息可回复时,test-message 还会返回 502 `qq_send_failed`;见 [QQ](#qq)。
+- 微信:微信的 PUT 是唯一不含凭据的。微信 bot token 只存在于扫码写入的地方,也没有控制台可供复制,因此 PUT 要求已存在绑定,绑定存在之前返回 400 `wechat_token_required`。清除后的微信配置只有重新扫码才能再次连接。test 路由是唯一不接受请求体的:这个渠道没有任何手动输入的内容,已存储的绑定就是全部可探测的对象(没有绑定时返回 400 `wechat_token_required`)。测试既不给出机器人名,也不给出扫码者信息。
+
+### QQ
+
+QQ 是只能回复的渠道,这一点改变了投递的含义。平台没有本产品可用的推送:每条出站消息都是被动回复,必须携带一条入站消息的 `msg_id`,有效期只有几分钟,而且每条消息在单聊中最多回复 4 条(群聊 5 条)。这个 API 上能看到三个后果:
+
+- 一次运行完成的助手消息超过回复额度时,消息会合并:前 `budget - 1` 条一完成就发出,其余的一起并入最后一条消息,不会丢掉任何一条。
+- `linePerMessage` 受这个额度而不是通常每条回复 20 条上限的约束;平台拒绝 `renderMarkdown` 发送时,纯文本重试会占用第二条回复。`finalReplyOnly` 在这里有利有弊。它让一次运行只消耗最少的额度——一条回复;但被动回复的窗口只有几分钟。把回复留到运行结束才发,窗口就消耗在运行上:运行时间一旦超过窗口,什么都发不出去,而逐条转发至少能把窗口内完成的消息发出去。
+- 没有可回复对象的发送不会推送出去,而是直接拒绝——比如在 Web App 里发起的一轮对话,或窗口关闭后的任何回复。这种情况在 test 端点上表现为 502 `qq_send_failed`,在转发的回复上表现为一条 `messaging_send_failed` 错误记录。
+
+在 QQ 上,出站文件一律拒收,因为平台的富媒体路径要求文件有一个公网可达的 URL。
+
+### 微信
+
+微信只承载单聊,但它是四个渠道中媒体支持最多的一种。这个 bot 渠道完全没有群聊入站:群里发给机器人的消息永远到不了这个 API,所以在单聊中正常的绑定在群里保持沉默,这是设计使然,不是配置错误。
+
+换来的是,它是这里唯一支持文本、图片、文件双向传输的渠道。回复中的图片和附件会上传到平台 CDN(AES-128-ECB 加密,每个文件一把密钥),以真正的图片和文件送达,而非遭到拒收。两类入站消息会经过转换:语音消息到达时是微信自己的转写文本,视频到达时是一个文件。平台无法转写的录音会在聊天中收到统一的「不支持」提示。
+
+### 扫码绑定
+
+扫码绑定从不把密钥暴露给浏览器。保证流程安全的一切都留在服务器上:解密 QQ App Secret 的 AES 密钥,以及收集微信 bot token 的平台轮询句柄。生成、保管、使用和销毁这些内容都是服务器的事,客户端只会拿到任务句柄、一个待渲染的 URL 和一个状态。
+
+- `POST …/scan` 返回 `{taskId, qrUrl, pollMs}`。把 `qrUrl` 渲染成二维码:由 QQ 或微信 App 打开它,任何一方都不需要去请求这个 URL。对微信来说,`taskId` 是本服务器自己生成的一个句柄,代替平台的轮询句柄。渠道的连接处于启用状态时,scan 返回 409 `messaging_disable_before_scan`,因为扫码会整体替换活跃连接器使用的全部凭据。平台拒绝时,scan 返回 502 `qq_scan_failed` 或 `wechat_scan_failed`。
+- QQ 的 `scan/poll` 状态为 `completed` 表示服务器已解密 App Secret 并保存了绑定;`expired` 表示重新发起一个任务。
+- 微信的 `scan/poll` 状态是 `pending`、`scanned`、`need_verify_code`、`blocked`、`expired`、`already_bound`、`completed` 之一。`completed` 表示服务器已保存绑定。`already_bound` 不算失败:机器人已经绑定过,没有签发任何新东西。它不会说明绑定在哪里——扫码不会给出 Token 列表,因此无法区分绑定是在本服务器上还是在别处。
+- 两个渠道都一样:保存绑定并不会启用它;启用仍是单独的一步。
+- `scan/verify` 记录微信在手机上展示的配对码。平台把配对码当作状态调用的参数,因此配对码随下一次轮询捎带发送,而不是单独发一次请求。配对码错误时,下一次轮询会再次报告 `need_verify_code`。
+- `scan/cancel` 丢弃用户中途放弃的扫码任务,对应的密钥或句柄立即从内存中丢弃,而不是等到下次清理。
+- 扫码任务保存在内存中,属于发起它们的 Session。每个 Session 有自己的数量上限,一个调用者的扫码任务不会把另一个调用者的挤出去。拿到最终结果的那个轮询会认领任务,因此重放这个轮询会返回 404(`qq_scan_task_unknown` 或 `wechat_scan_task_unknown`;未知任务或其他 Session 的任务也返回同样的错误),而不是重复绑定。同一任务的第二个并发轮询在 QQ 上同样返回 404,在微信上则返回 `pending`,因为微信一侧的上游调用是长轮询,会跨越多个客户端轮询间隔。
+
+所有扫码路由仅限所有者调用,因为无论调用者实际输入多少,整个流程最终都会落成一条存储的凭据。
+
+### 投递设置
+
+`linePerMessage`、`finalReplyOnly` 和 `renderMarkdown` 是三个与凭据无关的保存字段。PUT 时省略的字段保留已存储的值。这三个字段对通知和测试消息都不生效;特别是审批提醒,它不是回复,无论 `finalReplyOnly` 取什么值都会立即送达。
+
+- `linePerMessage`(默认 false)把转发的助手回复里每个非空行单独发成一条消息。空行直接丢弃,每行超出大小上限时仍会拆分,超过每条回复 20 条消息的上限后,剩余的行合并成最后一条消息。消息之间间隔 1 秒发出。
+- `finalReplyOnly`(默认 false)只在运行结束时转发这次运行最后一条完成的助手消息,而不是每完成一条就转发一条。运行在工具调用之间写下的工作笔记只保留在 Web App 中。此后跟随回复的文件也只从这条最终消息里读取,因为聊天收到的文本只有这一条。两个设置同时开启时,按行拆分的是最终回复。
+- `renderMarkdown`(默认 true)用渠道自己的标记格式渲染转发回复中的 Markdown,而不是原样发送字符。分块遵循这个设置:在块边界切分,跨消息的代码块会重新打开,因此任何一条消息都不会开启自己不闭合的结构。渠道拒绝带格式的发送时,同一条消息会以纯文本再次发送,所以这个设置最多损失格式,绝不会损失回复。
+
+每个渠道渲染自己支持的部分,其余刻意降级,而不是显示 Markdown 源码:
+
+| 渠道 | 回复的渲染方式 |
+| --- | --- |
+| Telegram | `parse_mode: "HTML"`。没有标题、列表和表格:标题变成一行加粗文本,列表符号保留为字面文本,表格变成 `<pre>` 块 |
+| 飞书 | 交互卡片,承载 JSON 2.0 富文本组件,能渲染全部内容。过长的表格转成代码块,不会悄悄丢掉任何一行 |
+| QQ | `msg_type: 2` markdown。没有代码格式,也没有表格:围栏代码块变成逐行转义的普通文本,表格变成逐行文本 |
+| 微信 | 微信自己解析 Markdown,所以渲染是做减法而不是转换:客户端不会显示的内容保留文字、去掉标记(层级深于四级的标题、CJK 文本两侧的强调标记,以及内联图片,后者变成链接) |
+
+### 入站消息
+
+入站消息可以携带文本、图片和文件。
+
+- 图片会变成普通的 `image_url` 输入部分。每张图片受服务器内联图片上限的约束,每个绑定还有一个滚动的图片字节预算:每 10 分钟 40MB,即内联图片上限的两倍。设这个预算是因为内联图片会原样写入 Trace,而这条路径与输入框不同,前面没有身份验证把关。
+- 文件采用输入框的另一种附件形态:先写入 Session scratchpad,再以 `[attached file: <path>]` 一行的形式交给模型,因此文件字节不会进入对话。它与经过身份验证的上传一样,受管理员可配置的单文件、单消息上限约束;渠道自身若有更严格的限制,则以更严者为准:Telegram 不向机器人提供超过 20MB 的文件。
+- 飞书投递以 `file` 消息类型发送的文件;Telegram 投递 `document` 字段里的文件,也就是发送者选择以文件形式发送的内容——这也是唯一携带发送者原始文件名的 Telegram 媒体字段。
+- 在飞书和 Telegram 上,视频、音频和语音刻意不投递:下游没有任何环节会解码或转写它们;发送者想让 Agent 拿到的内容,附成文件即可送达。微信是例外,只是因为平台自己做了这些处理(见[微信](#微信))。
+- 附件会投递的消息(照片或文档),说明文字就是这条消息的文本。其他类型媒体上的说明文字则不然:媒体根本不会到达,只凭说明文字运行模型,会让它谈论一个从未收到过的文件。
+- 超过单图上限的图片、超出预算的图片和渠道拒收的图片,各有一条不同的双语提示;超过上限的文件、超过单消息总量的批次和渠道拒收的文件也是如此。任何一种情况都不会发出半条消息。如果拒绝是机器人自身权限导致的,提示会写明需要授予的权限范围,并附上渠道控制台的链接。在飞书上这是常见情况,因为接收消息和下载附件是两个不同的权限范围。
+- 其余所有消息类型都会收到双语「不支持」回复。
+
+### 出站文件
+
+运行结束后,回复后面会跟着回复提到、且由运行产出的文件:回复中任意位置出现、形如路径的片段,只要解析后落在 Workspace 内、文件确实存在、且写入时间不早于运行开始,就会随回复发出。「提及」挑出哪个产物才是重点。写入时间条件防止回复变成读取文件的手段——聊天里的任何人都能引导回复,而一条拒绝粘贴文件的回复照样会提到文件名。
+
+- 图片以图片形式发送,其余以附件形式发送;分类依据是实际读取的文件,而不是回复里写的名字。
+- 一次运行最多发送 5 个文件:每张图片最多 10MB,每个文件最多 30MB(取各渠道自身限制中更严的一个)。
+- 提及的文件未能送达时一律不在聊天中报告,而是作为异常记录挂在这个 Project 下,由成本中心的异常表展示:同一次回复里每个原因一条记录,写明它覆盖的每个文件、渠道和原因。
+ - `messaging_file_too_large` 覆盖超过大小上限的文件,`messaging_files_skipped` 覆盖超过数量上限的那些。两者都属于 `expected`。
+ - `messaging_file_send_failed` 覆盖渠道拒绝的上传,按原因分组:渠道根本承载不了的上传(QQ 上的任何文件)、缺少权限,以及其他任何拒绝。缺少权限的那条只列一次要授予的权限范围和控制台链接,取代每个文件各自的原因。渠道根本承载不了的上传属于 `expected`;缺少权限和其他任何拒绝属于 `unexpected`。
+ - Workspace 中对不上文件的名字,以及运行没有写过的文件,静默跳过、只写服务端日志,因为回复提到自己读过或只是描述过的文件是常态。
+
+### 连接状态
+
+Telegram 连接时会先清空积压,跳过无连接期间发送的消息。这一点与飞书一致:飞书错过的事件就彻底丢失了。
+
+除了状态本身,绑定的运行时状态还会报告活跃连接实际看到的情况:
+
+- `lastInboundAt`:最后一条消息到达的时间;本次连接建立后还没有消息到达时,这个字段不存在。
+- `lastDeliveryError`:`{at, stage, detail}`。`stage` 为 `inbound` 表示消息到达了但对应的 Task 从未启动,为 `send` 表示回复从未到达聊天。之后的成功不会清除这个字段。
+- `lastConnectionError`:`{at, detail}`,记录最近一次连接失败,连接恢复后仍保留。相比之下,`lastError` 属于 `error` 状态,状态一离开它就消失。
+
+这三个字段都保存在服务器进程中,每次连接或重连都会重置;重新启用渠道或保存凭据都会开启新连接。因此 `lastInboundAt` 缺失意味着「本次连接建立以来没有消息」,绝不是「从来没有过消息」。提供这些字段,是因为一个扣着消息不投递的渠道,照样显示 `connected`,而且没有任何报错。
+
+## 终端
+
+服务器主机上的交互式 shell。Web App 的终端使用这些路由,任何需要运行命令并读取屏幕的客户端也可以使用。每个终端属于打开它的用户,其余路由只能找到调用者自己的终端。
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | `/api/terminals` | 列出调用者的终端:`{terminals}` |
+| POST | `/api/terminals` | 打开一个终端:`{cwd?, name?, shell?, cols?, rows?}` → 201,返回终端信息 |
+| GET | `/api/terminals/:id` | 单个终端的信息 |
+| DELETE | `/api/terminals/:id` | 终止终端;204 |
+| GET | `/api/terminals/:id/capture?start=&end=` | 以纯文本返回屏幕内容 |
+| POST | `/api/terminals/:id/keys` | 发送输入:`{keys, literal?}` → `{ok: true}` |
+
+- `cwd` 默认为用户主目录,`shell` 默认为用户的登录 shell。
+- `keys` 是字面文本或按键名:`Enter`、`Tab`、`Escape`、`Backspace`、`Space`、`Up`、`Down`、`Left`、`Right`、`Home`、`End`、`PageUp`、`PageDown`、`Delete`,或 `C-c` 这样的组合键。设置 `literal: true` 时,文本按原样发送。shell 已退出的终端返回 `409` `terminal_exited`。
+- 字节流不走这些路由:它是一个 WebSocket,地址为 `GET /api/terminals/:id/stream`(一个 Upgrade 请求)。
+- 缺少有效会话或 token 的请求返回 `401` `unauthorized`。
+
+## 桌面 shell、热更新与 Web 贡献
+
+这组路由服务于桌面 shell、热更新和 Web App 自己的模块系统,而不是一般客户端。
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| POST | `/api/desktop/shutdown` | 应桌面 shell 的请求优雅关闭服务器;202 |
+| GET | `/api/desktop/update` | 桌面应用更新器的状态:`{status}` |
+| POST | `/api/desktop/update/check`、`/api/desktop/update/download`、`/api/desktop/update/install` | 把命令转发给桌面 shell;202 |
+| GET / PUT | `/api/desktop/tray` | 读取系统托盘图标偏好:`{status}` / 转发更改:`{showTrayIcon?, locale?}` → 202 |
+| POST | `/api/hmr/assets/probe` | 热更新:报告存储缺少哪些 blob |
+| PUT | `/api/hmr/blobs/:sha` | 热更新:按 sha256 上传一个 blob |
+| POST | `/api/hmr/upgrade` | 热更新:把 platform、CLI 和 web bundle 一并升到新版本 |
+| GET | `/api/contributions` | 以数据形式返回服务器模块和插件贡献给 Web App 的页面和标签页 |
+
+- 非桌面模式下,桌面路由返回 `404` `not_found`。
+- `POST /api/desktop/shutdown` 不使用 cookie 会话。它用桌面 shell 专有的 Bearer token 认证(否则返回 `401` `unauthorized`),先应答,再立即开始优雅关闭。
+- update 和 tray 路由只响应桌面 shell 自己的窗口:其他任何会话都会得到 `403` `desktop_shell_only`。shell 未监听时,返回 `503` `shell_unreachable`。`showTrayIcon` 不是布尔值时,`PUT /api/desktop/tray` 返回 `400` `invalid_show_tray_icon`;`locale` 不是 `zh` 或 `en` 时返回 `400` `invalid_locale`;两个字段都未提供时返回 `400` `empty_tray_patch`。PUT 只确认收到更改;请用 GET 读回实际结果。
+- `/api/hmr` 路由仅限管理员(`403` `forbidden`)。绑定在非环回地址上时还要求 HTTPS,否则返回 `403` `hmr_disabled`。只有 `PENGUIN_TRUST_PROXY=1` 时 `X-Forwarded-Proto` 才生效。升级完成后,每个已连接的客户端都会收到 `web_updated` 并重新加载。
-## 流式接口(SSE)
+## 流式传输(SSE)
-实时通道采用 Server-Sent Events 而非 WebSocket,共两条(通道内承载的消息顺序语义见[消息流转与时序](/message-flow)):
+实时投递使用 Server-Sent Events 而不是 WebSocket,分为两类通道。通道所载内容的顺序语义见[消息流与顺序](/message-flow)。
| 通道 | 路径 | 内容 |
| --- | --- | --- |
-| Session 级 | GET /api/sessions/:sessionId/stream | 该 Session 的消息流与运行事件 |
-| 用户级 | GET /api/events | `hello` 握手与跨 Session 通知(session_state / session_background / schedule_fired / schedule_queued / session_created) |
+| 每个 Session | `GET /api/sessions/:sessionId/stream` | Session 的消息流和运行事件,包括子 Agent Session 的 `session_created` 以及目标模式事件 |
+| 每个用户 | `GET /api/events` | `hello` 握手和跨 Session 的通知:`session_state`、`session_background`、`session_title`、`schedule_fired`、`schedule_queued`、`web_updated` 以及公司模式的 `org_*` 事件 |
### 传输格式
-默认(未命名)SSE 事件承载原始 OmniMessage 信封(单行 JSON)——与 SDK 产出、Trace 落盘是同一套协议,见 [OmniMessage 协议](/omni-message);命名为 `server_event` 的事件承载 ServerEvent 联合类型:
+默认(未命名)的 SSE 事件以单行 JSON 携带原始 OmniMessage 信封:SDK 产出、Trace 存储的就是这个协议(见 [OmniMessage 协议](/omni-message))。名为 `server_event` 的事件携带 `ServerEvent` 联合类型:
```ts
export type ServerEvent =
| { type: "approval_request"; toolCall: OmniMessage<ToolCallPayload>; origin?: string[] }
- | { type: "task_state"; state: "idle" | "running" | "compacting" }
+ | {
+ type: "task_state";
+ state: "idle" | "running" | "compacting";
+ queued?: number;
+ pendingSteering?: PendingSteeringInfo[];
+ returnedSteering?: PendingSteeringInfo[];
+ pendingFollowUps?: PendingFollowUpInfo[];
+ subagents?: SubagentRuntimeInfo[];
+ }
| { type: "session_title"; sessionId: string; title: string }
| { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }
| { type: "session_background"; sessionId: string; processes: number; subagents: number }
| { type: "resync_required" }
| { type: "credentials_updated" }
| { type: "hello" }
+ | { type: "web_updated"; rev: string }
| { type: "session_created"; projectId: string; agentId: string; sessionId: string; source: SessionSource }
| { type: "schedule_fired"; projectId: string; agentId: string; name: string; sessionId: string }
- | { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string };
+ | { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string }
+ | { type: "goal_started"; sessionId: string; objective: string; budget: number }
+ | { type: "goal_round"; sessionId: string; round: number; used: number; budget: number }
+ | { type: "goal_finished"; sessionId: string; outcome: "complete" | "blocked" | "budget_limited" | "aborted"; rounds: number; used: number }
+ | { type: "org_run"; projectId: string; orgId: string; agentId: string; sessionId: string; kind: OrgTriggerKind }
+ | { type: "org_channel"; projectId: string; orgId: string; channelId: string; message: OrgChannelMessage }
+ | { type: "org_ticket"; projectId: string; orgId: string; ticketId: string; change: string }
+ | { type: "org_budget"; projectId: string; orgId: string; agentId: string; state: "warned" | "paused" | "resumed"; ratio: number };
```
| 事件 | 触发时机 |
| --- | --- |
-| approval_request | 工具调用升级为人工审批时发出:always-ask 下的所有调用,以及 read-only 下 rw / 未知权限的调用;重连时未决审批会重发 |
-| task_state | Session 运行状态翻转(idle / running / compacting) |
-| session_title | 首轮后模型生成的标题已持久化 |
-| session_state | `task_state` 在用户通道上的对应事件:同一次运行状态翻转,带上 `sessionId`,因此会话列表的每一行都能保持实时,而不只是客户端当前打开的那个会话。事件还携带重绘该行所需的行字段,无需重新拉取列表 —— 刚刚写入的 `lastActiveAt`,以及 `hasTrace`(状态为 running 或 compacting 时必为 true,因为正在运行的会话必然已经启动过 Task)。仅发往该 Project 拥有者与成员的用户通道 |
-| session_background | 某个 Session 的后台任务计数发生变化——命令超过 yield 窗口转入后台或以 `run_in_background` 启动、进程退出或被停止、后台子智能体开始一轮、结束一轮或被释放。携带此刻的 `SessionInfo.backgroundTasks`(`processes` = 仍在运行的后台命令会话数,`subagents` = 已转后台、正在跑一轮的子会话数),归零时同样推送,列表据此即可撤下标记而无需重新拉取;列表行与单条查询在计数为零时省略该字段。受众与 `session_state` 相同 |
-| resync_required | Last-Event-ID 已被缓冲区淘汰,客户端须重新拉取历史 |
-| credentials_updated | Project 模型凭据已变更(`PUT /models`,或一次完成的授权新建 key 流程):缓存运行时已失效,客户端应清除鉴权失败的输入框禁用态 |
-| hello | 用户通道连接握手 |
-| session_created | 新 Session 注册(如子 Agent 会话) |
-| schedule_fired | 定时任务已触发并发送 |
-| schedule_queued | 目标 Session 正在运行,本次触发已排队 |
+| `approval_request` | 工具调用需要人工审批 |
+| `task_state` | Session 的运行状态变化(`idle` / `running` / `compacting`) |
+| `session_title` | 第一轮对话后,模型生成的标题已保存 |
+| `session_state` | Session 的运行状态变化;`task_state` 在用户通道上的对应事件 |
+| `session_background` | Session 的后台任务计数变化 |
+| `resync_required` | `Last-Event-ID` 已被挤出缓冲区;客户端必须重新拉取历史 |
+| `credentials_updated` | Project 的模型凭据发生变化 |
+| `hello` | 用户通道上的握手 |
+| `web_updated` | 热更新替换了对外提供的 web 资源;客户端需重新加载 |
+| `session_created` | 注册了一个新 Session,例如子 Agent Session |
+| `schedule_fired` | 定时任务已触发,Prompt 已投递 |
+| `schedule_queued` | 目标 Session 正在运行,这次触发已排队 |
+| `goal_started` | 目标运行开始,在第一轮之前 |
+| `goal_round` | 一轮目标运行即将开始 |
+| `goal_finished` | 目标达到终止状态 |
+| `org_run` | 组织的工作运行(工位会话)或工单会话已启动 |
+| `org_channel` | 频道里有新消息 |
+| `org_ticket` | 工单的状态、负责人、阻塞状态或贡献会话发生变化 |
+| `org_budget` | 员工的预算进入警告、暂停或恢复状态 |
+
+- `approval_request` 覆盖 `always-ask` 模式下的每个调用,以及 `read-only` 模式下带 `rw` 或未知权限的调用。待处理的审批会在重连时重新发送。
+- `task_state` 还携带排队的后续消息数量(`queued`)、仍在等待投递的插话消息(`pendingSteering`)、运行结束时没能投递的插话消息(`returnedSteering`)、排队的后续消息本身(`pendingFollowUps`)以及活跃的子 Agent(`subagents`)。字段缺失表示没有。
+- `session_title` 发送到 Session 的通道,以及 Project 所有者和成员的用户通道。
+- `session_state` 用 `sessionId` 指明是哪个 Session,因此 Session 列表的每一行都能保持实时,而不只是客户端当前打开的那个会话。事件携带重绘这一行所需的字段,无需重新拉取:刚写入的 `lastActiveAt`,以及 `hasTrace`。状态为 `running` 或 `compacting` 时 `hasTrace` 必为 true,因为正在运行的 Session 必然已经启动过 Task。它发送到 Project 所有者和成员的用户通道。
+- 以下情况会触发 `session_background`:命令超过让出窗口转入后台,或以 `run_in_background` 启动;进程退出或停止;后台子 Agent 开始一轮、结束一轮或释放。事件携带 `SessionInfo.backgroundTasks` 的当前值(`processes` = 仍在运行的后台命令会话数,`subagents` = 已转入后台、正处于一轮中的子 Agent Session 数),归零时同样发送,列表无需重新拉取就能撤下标记。两个计数都为零时,列表行和单个 Session 的 GET 会省略这个字段。受众与 `session_state` 相同。
+- `credentials_updated` 在 `PUT /models` 或签发 API key 的流程完成之后发送。缓存的运行时已失效,客户端应清除因认证失败而禁用的输入框状态。
+- `web_updated` 以 `rev` 携带新的 web 修订号,发送到每个用户通道。
+- `session_created` 发送到父 Session 的通道。
+- `schedule_fired` 的 `sessionId` 是接收 Prompt 的 Session,在新建 Session 模式下是一个新 Session。排队的触发会在 Session 空闲后发送。
+- `goal_round` 携带 `used`,即目前累计的 Token 数。
+- `org_*` 事件发送到 Project 成员的用户通道。`org_channel` 包含消息里的提及信息,客户端可据此判断消息是否指向自己。这些事件是尽力而为的;持久状态以组织路由为准。
### 投递保证
-- 事件 id 按通道单调递增,形如 `<epoch>-<seq>`;
-- 每通道维护有界重放缓冲(最近 10,000 条事件或 8MB);
-- 携带 `Last-Event-ID` 重连时,命中缓冲则补发缺口;未命中则先发 `resync_required`,客户端重新拉取 `/messages` 后继续消费;
-- 每 20 秒写一条心跳注释行;
-- 事件次序:带 `Last-Event-ID` 重连时,**补发的缺口(或 `resync_required`)最先送达**,随后才是初始事件——权威的 `task_state` 快照与未决的 approval_request,再进入实时流;全新连接(无 `Last-Event-ID`)不重放缓冲,首个事件即为 `task_state` 快照。
+- 事件 id 在每个通道内单调递增,格式为 `<epoch>-<seq>`。
+- 每个通道保留一个有界的重放缓冲区:最近 10,000 个事件或 8MB。
+- 携带 `Last-Event-ID` 重连时,如果 id 仍在缓冲区内,服务器会重放缺失的事件;否则先发送 `resync_required`,客户端重新拉取 `/messages` 后再继续。
+- 每 20 秒写入一行心跳注释。
+- 事件顺序:携带 `Last-Event-ID` 重连时,先到达重放的缺失部分(或 `resync_required`),然后是初始事件(权威的 `task_state` 快照和所有仍待处理的 `approval_request`),最后是实时流。不带 `Last-Event-ID` 的新连接跳过重放,第一个事件就是 `task_state` 快照。
-### 推荐客户端模式
+### 推荐的客户端模式
-自带 Web App 的接入顺序:
+内置的 Web App 按以下顺序连接:
-1. 先连接 `/stream` 并缓冲收到的事件;
-2. 再 GET `/messages` 拉取完整历史;
-3. 若响应携带 `live`(有 Task 在运行),丢弃 cursor 已覆盖的缓冲 partial 事件,并把 `live.fragments` 播种到历史之上 —— 进行中的消息连同已流式输出的前缀一起回到画面;
-4. 回放缓冲区并对重叠消息去重;
-5. 转入实时消费。
+1. 先连接 `/stream`,把收到的事件缓存起来。
+2. 用 GET 请求 `/messages` 获取历史。
+3. 如果响应带有 `live`(有 Task 正在运行),丢弃缓存中游标已覆盖的 partial 事件,把 `live.fragments` 应用在历史之上。进行中的消息会重新出现,已流式输出的前缀原样保留。
+4. 重放缓存的事件,去掉重叠部分。
+5. 之后继续处理实时流。
## 类型导入
-全部 DTO 类型可从服务端包的子路径 `@prismshadow/penguin-server/api` 以 type-only 方式导入:
+所有 DTO 类型都能以仅类型导入的方式,从服务器包的 `@prismshadow/penguin-server/api` 子路径引入:
```ts
import type { ServerEvent, SessionInfo } from "@prismshadow/penguin-server/api";
diff --git a/packages/docs/content/server-boot.en.md b/packages/docs/content/server-boot.en.md
index cdfc1526..f4f30aec 100644
--- a/packages/docs/content/server-boot.en.md
+++ b/packages/docs/content/server-boot.en.md
@@ -1,116 +1,224 @@
---
title: Server Boot and Subsystems
-description: The assembly order from process entry to HTTP listen, each subsystem's external surface, and where plugins sit in the two-level process/App lifecycle.
+description: The assembly order from process entry to a serving App, each subsystem's external surface, and where plugins sit in the two-level process/App lifecycle.
---
-`server/src/index.ts` is a side-effecting module: importing it starts the server — the contract the CLI relies on to run a server inside its own process. The startup order is written out in `main()`, one `PenguinServer` method per step, the method name being the step name. Assembly itself is split in two — `bootAppDeps(config)` builds the runtime core, publishes its capabilities and boots the platform (the business surface is assembled inside it), while `createApp(deps)` assembles the runtime shell's Hono route table without listening — so tests can take the full app and drive it via `app.request(...)` with no port involved and without going through `index.ts` at all.
+`server/src/index.ts` is a side-effecting module: importing it starts the server. That is the contract the CLI relies on to run a server inside a Node process of its own choosing.
-This page answers two questions: in what order does the process bring each subsystem up, from entry to listen; and what is each subsystem's **external surface** — the way others depend on it: exported types, HTTP routes, events, or the context members plugins receive.
+The startup order is written out in `main()`: one `PenguinServer` method per step, and the method name is the step name. Assembly itself is split in two:
+
+- `bootAppDeps(config)` builds the process core: the database, the channel hub and the HMR host. It publishes them into the resource registry and boots the platform. The business surface is assembled inside the platform.
+- `createApp(boot)` assembles the layer's own Hono app: network guards, the platform seam and static hosting. It does not listen. Tests can take the full app and drive it via `app.request(...)`, with no port involved and without going through `index.ts` at all.
+
+This page answers two questions:
+
+- In what order does the process bring each subsystem up, from entry to a serving App? See [Process entry](#process-entry) and [Boot sequence](#boot-sequence).
+- What is each subsystem's **external surface**, meaning the way others depend on it: exported types, HTTP routes, events, or the interfaces plugin modules may require? See [Subsystem inventory](#subsystem-inventory).
## Process entry
-| Entry | Mechanism |
-| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Direct | `node dist/index.js` (`start` in `server/package.json`) |
-| CLI (`penguin server` / `penguin web`) | Sets `PORT`/`HOST` env vars, then `import("@prismshadow/penguin-server")` **in the same process** — no fork; `penguin web` additionally polls for readiness and opens the browser |
-| Desktop | `utilityProcess.fork` launches a **separate** server process, injecting `PENGUIN_HOME`, `PORT`, `PENGUIN_DESKTOP_TOKEN`, `PENGUIN_PORT_FILE` via env |
+Four mechanisms start the server. All of them converge: the same env vars drive the same module.
+
+| Entry | Mechanism |
+| --- | --- |
+| Direct | `node dist/index.js` (`start` in `server/package.json`) |
+| CLI (`penguin server` / `penguin web`) | Sets `PORT`/`HOST` and exports `PENGUIN_CLI_ENTRY`, then runs the server as a **supervised child process** that imports `@prismshadow/penguin-server` |
+| CLI auto-start | A CLI command that finds no running server spawns a detached `server` subcommand with `PORT=0` and attaches once the root's lock is live |
+| Desktop | `utilityProcess.fork` launches a separate server process with the server's env injected |
+
+The supervised child runs as `node <entry> server …`, marked `PENGUIN_SERVE_CHILD=1` and told `PENGUIN_SUPERVISED=1`. The parent forwards the terminal's signals, exits with the child's code, and relaunches the child when it exits with the restart code that **Restart to update** asks for. A dev run through tsx cannot be re-spawned by node, so the CLI imports the server in-process instead. `penguin web` additionally polls for readiness and opens the browser.
-All three converge: the same env vars drive the same module. The server's own configuration comes from environment variables only (`server/src/config.ts`); `system_config.yaml` is Agent-level state, read when a Session runs — it plays no part in server boot.
+Auto-start output goes to `<root>/logs/server-auto-<date>.log`.
+
+The desktop process injects `PENGUIN_HOME`, `HOST`, `PORT`, `PENGUIN_DESKTOP_TOKEN` and `PENGUIN_PORT_FILE` via env, plus `PENGUIN_WEB_DIST` and `PENGUIN_CLI_ENTRY` when the app pins them.
+
+> [!NOTE]
+> The server's own configuration comes from environment variables only (`server/src/config.ts`). `system_config.yaml` is agent-level state, read when a Session runs; it plays no part in server boot.
## Boot sequence
+`main()` writes the order out, one `PenguinServer` method per line:
+
```text
main() —— one PenguinServer method per line
│
├─ ① loadEnv · installProxy dotenv first (.env may define HTTP_PROXY itself), then the proxy takes over fetch
├─ ② readConfig env only: PENGUIN_HOME, PORT, HOST, PENGUIN_WEB_DB …
├─ ③ ensureSoleInstance data root held by another live instance → exit code 3 (before the DB opens)
-├─ ④ loadPlugins a SHIM for a platform older than the move below: the platform loads its own plugins
-├─ ⑤ buildDeps = bootAppDeps open the DB → runtime core (auth, ChannelHub, HmrHost) → publish the
-│ capabilities (db/auth/channels/config/proxy/desktop/plugin host) →
-│ hmr.ensure() boots the platform: its create() assembles the WHOLE
-│ business surface (services, routes, scheduler) and delivers the hooks
-├─ ⑥ applyPersistedProxy the DB is open: align the dispatcher with the persisted settings
-├─ ⑦ buildApp the runtime shell: guards, /api/auth, /api/desktop, /api/hmr, seam, static
-├─ ⑧ seedAdmin built-in admin seed (initial-Project provisioning late-binds via the registry)
-├─ ⑨ listen listening starts; the callback writes back the real port, takes the lock, writes the port file, opens the ::1 companion
-└─ ⑩ installProcessHandlers signals, the desktop quit path, the process-level error fallback
+├─ ④ listen bind the port now; answer 503 "starting" until ⑧. The callback writes back
+│ the real port, takes the lock, and opens the ::1 companion on a loopback bind
+├─ hmrMain(createHost(), replace, start) the HMR layer's entry runs start, then makes the first generation current
+│ ├─ ⑤ loadPlugins a shim for platforms that predate loading their own plugins: import what the
+│ │ Projects' [plugins] tables name into a host the first App can reuse
+│ ├─ ⑥ buildDeps = bootAppDeps open the DB → process core (ChannelHub, auth state + local API token, CLI shim) →
+│ │ publish the capabilities (interfaces descriptor, config, db, auth state, channels,
+│ │ proxy, HMR host + control, desktop, lifecycle, plugin host) → hmr.ensure() boots
+│ │ the platform: its create() assembles the WHOLE business surface
+│ ├─ ⑦ applyPersistedProxy the DB is open: align the dispatcher with the persisted settings
+│ ├─ ⑧ buildApp the layer's app: guards, the platform seam, static hosting; terminal WS on each listener
+│ ├─ ⑨ seedAdmin built-in admin seed; decides whether a first-login link is due
+│ ├─ ⑩ installProcessHandlers signals, the desktop quit path, restart-to-update, the process-level error fallback
+│ └─ ⑪ printFirstLoginNotice the one-time sign-in link, when one is due
+└─ ⑫ announce write the port to PENGUIN_PORT_FILE: the App is up
```
-The order is not arbitrary — four of its constraints are hard: the proxy takes over global `fetch` before any outbound request can happen; the instance lock is checked **before** the database opens, because `web.db` is single-writer; the plugin host enters the registry with the other capabilities before the platform boots, so what an earlier App imported is there for the next one to reuse; and the platform — the whole business surface with it — finishes booting before `listen`, so **no request is ever served before business and plugins are in place**. `installProcessHandlers` comes last, after `listen`, so shutdown can never fire before there is a listener for it to close.
+The order is not arbitrary, and its constraints are hard:
+
+- The proxy takes over global `fetch` before any outbound request can happen.
+- The instance lock is checked **before** the database opens, because `web.db` is single-writer.
+- The plugin host enters the registry with the other capabilities before the platform boots, so the plugin objects ⑤ imported are there for the first App to reuse, as each App's are for the next.
+- The platform, with the whole business surface in it, finishes booting before ⑧ hands the listener its app.
+- The port is bound early on purpose. Until ⑧, every request gets `503 penguin-server is starting` with `retry-after: 1`, so a client that arrives early sees "starting" rather than a refused connection. **No business request is ever served before the platform and plugins are in place.**
+- The port announcement comes last, because the desktop shell opens its window on it.
+- `installProcessHandlers` comes after `listen`, so shutdown can never fire before there is a listener for it to close.
+
+Plugin loading sits after `ensureSoleInstance` by design as well: a process about to exit with code 3 has no business importing third-party modules and running their top-level side effects first.
-Plugin loading sitting after `ensureSoleInstance` is deliberate too: a process about to exit with code 3 has no business importing third-party modules and running their top-level side effects first.
+## Process and App lifecycles
-## Two lifecycles: process and App
+The process core is built once and lives until the process exits. It contains the SQLite handle, the ChannelHub, the process-scoped auth values such as the local API token, and the HMR host with its resource registry.
-The runtime core (the DB, auth, the ChannelHub, the HmrHost) is built once and lives until the process exits. **Everything else is platform-level**: the whole business surface — services, routes, the SessionManager, the Scheduler — together with the terminal manager, plugin delivery and workflow instances is rebuilt at every App creation (every boot and every hot swap, a new bundle pushed via `POST /api/hmr/upgrade`).
+Everything else is platform-level. The whole business surface — services, routes, the AuthService, the SessionManager, the Scheduler — is rebuilt at every App creation, together with the terminal manager, the plugin host and the plugin modules. An App creation happens at every boot, at every hot swap, where a new bundle is pushed via `POST /api/hmr/upgrade`, and at every change to a Project's plugin list, where the App [re-assembles itself](#re-assembly) from the same bundle.
```text
-Process-level (runtime mechanism, once) App-level (the business surface, re-run per boot + per hot swap)
-─────────────────────────── ─────────────────────────────────────────────────
-SQLite · auth (AuthService) every business service and route (services + http/routes)
-ChannelHub (SSE survives swaps) SessionManager · Scheduler
+Process-level (HMR layer, once) App-level (the business surface, re-run per boot + per hot swap + per re-assembly)
+─────────────────────────────── ─────────────────────────────────────────────────
+SQLite · auth state (API token …) every business service and route (AuthService included)
+ChannelHub (SSE survives swaps) SessionManager · Scheduler · messaging bridge
HmrHost · the resource registry TerminalManager (adopts parked ptys)
-the plugin host (imported objects) plugin closure read + imported, modules created as children of the tree
+the plugin host (imported objects) plugin lists read + imported, modules created as children of the tree
```
-**Swap semantics: unparked state HARD-STOPS** — pending approvals are denied, active runs abort, the scheduler dies with its App, and the next App rebuilds everything from the claimed capabilities. Only resources that implement park/adopt (terminal ptys) ride across.
+The dividing line between the two levels is the **resource registry**. It sits outside the reloadable platform tree, so it survives across Apps. The pty processes are parked in it, and a new App merely reclaims their handles; that is why a hot swap is invisible to whoever is typing in a terminal. The DB handle, the auth state and the SSE hub travel the same road: published by the process, claimed by each App. The plugin host is handed on the same way: each App registers the host it built, and the next App claims it to reuse the plugin objects it holds.
+
+### Swap semantics
+
+**Unparked state HARD-STOPS** at a swap. Pending approvals are denied and active runs abort. The scheduler, the messaging bridge and machine connections stop with their App, and the next App rebuilds them from the claimed capabilities. Between the old App's dispose and the new App's boot, the kernel waits for the aborted runs to drain, for up to 5 s.
+
+What rides across:
+
+| What survives | How |
+| --- | --- |
+| Terminal ptys | Parked in the registry; the new App reclaims their handles |
+| Machine tunnels | ssh child processes the successor adopts by pid |
+| Process-level singletons | Live in the process core, outside every App |
+
+### Resource interface contracts
+
+Resources carry an interface contract of their own, but the contract does not live on the kernel iface. The declaration is itself a registry entry, `platform.resourceInterfaces`. It is a descriptor that names a family, `penguin`, and, per ID-prefix group, the members its adopters use. The `terminal` group lists every member a parked pty is reached through. Each App's `create()` writes the declaration and leaves it for its successor.
+
+Before adopting anything, the new App reads its predecessor's declaration and compares it with its own compiled-in one:
+
+- A group declared in the same family that offers every member this build needs integrates, and its resources ride across.
+- Any other group — a different family, a missing member, or a group this build no longer declares — is disposed entry by entry in **reverse registration order** and rebuilt fresh.
+
+Live objects cannot be strict-parsed the way the context document is, so declaration agreement is the integration criterion.
-Resources carry an interface contract of their own — but it does not live on the kernel iface: the declaration is itself a registry entry (`resource-interfaces`, group→version by ID prefix, e.g. `{ terminal: 1, platform: 1 }`), written by each App's `create()` and left for its successor. Before adopting anything, the new App reads its predecessor's declaration and compares it with its own compiled-in one: a group both declare at the same version integrates and rides across; a group whose versions differ, or that this build stops declaring, is disposed entry by entry in **reverse registration order** and rebuilt fresh (live objects cannot be strict-parsed the way the context document is, so declaration agreement is the integration criterion). The kernel's park/validate/swap mechanism neither participates in nor knows about this convention — which means the reconciliation policy itself evolves by platform push. Runtime capabilities (`runtime:*`) get the symmetric defense on their side: a bundle carries the capability-contract version it was compiled against, and `claimRuntimeCapabilities` handshakes it against the runtime's published one before trusting any claim — a mismatch declines the whole set and degrades to terminals-only instead of a TypeError at use time.
+The decision is taken first but acted on only once the new App is fully built. A boot that fails midway can therefore still hand the live resources back to the previous generation.
-The dividing line is the **resource registry**: it sits outside the reloadable platform tree, so it survives across Apps. The pty processes are parked in it and the new App merely reclaims their handles, which is why a hot swap is invisible to whoever is typing in a terminal; the PluginHost, the DB handle, the auth service and the SSE hub travel the same road — published by the runtime, claimed by each App.
+The kernel's park/validate/swap mechanism neither participates in nor knows about this convention. The reconciliation policy itself therefore evolves by platform push.
-This is not merely tidiness. A pushed bundle is compiled **standalone** — a self-contained ESM file (`bundle: true`, no externals) with its own module graph — so a module-level host singleton on the platform side would, after a push, be that bundle's own empty host, and every configured plugin would silently vanish on the first hot push. Claiming rather than importing is what makes the packaged App and the pushed App drive the same host. When the runtime published none, the fallback is an empty host — the honest reading of "this runtime knows nothing about plugins". The same reasoning is spelled out in `terminal/identity.ts`.
+### Capability claims
-## App creation: where plugins run
+The process capabilities get the symmetric defense on their side. The process publishes a descriptor, `platform.interfaces`, naming per capability the members a claimer reaches for. Before trusting a claim, `claimHmrCapabilities` checks the descriptor, and the live objects behind it, against the copy compiled into the bundle.
-The full App-creation order is `platformImpl.create` in `server/src/hmr/platform.ts`:
+A mismatch refuses the claim, so the boot fails and the push is rolled back, instead of surfacing as a `TypeError` at use time. A descriptor of the same family that offers none of the capabilities declares a bare kernel, which boots terminals only.
+
+Claiming from the registry, rather than importing, is not merely tidiness. A pushed bundle is compiled **standalone**: a self-contained ESM file (`bundle: true`, no externals) with its own module graph. A module-level singleton on the platform side would, after a push, be that bundle's own fresh copy, holding none of what the process built. Claiming rather than importing is what makes the packaged App and the pushed App drive the same database, channel hub and auth state. The plugin host follows the same rule: a pushed App can reuse the plugin objects an earlier App imported only because it claims them. When nothing was published, the claim yields an empty host — the honest reading of "this runtime knows nothing about plugins".
+
+## App creation
+
+App creation lives in `server/src/hmr/platform.ts`. `platformImpl.create` boots the App proper, `createInner`, as an inner instance behind a shell the runtime holds, which is what lets the App [re-assemble itself](#re-assembly). The full order of `createInner`:
```text
-platformImpl.create
+createInner
│
-├─ caps = claimRuntimeCapabilities(resources) # db/auth-state/channels/config/proxy/hmr/desktop
-├─ plugins = pluginHostFrom(resources) # claim the host the runtime loaded in ④ (empty host if none was published)
-├─ tree = bootModules(platformTree(caps, …, plugin modules), { ifaces, parked: context.modules })
+├─ claim = claimHmrCapabilities(resources) # refused → throw (the boot fails); bare → terminals only
+├─ migrate(caps.db, { swapPath: true }) # a pushed platform brings its own migrations
+├─ decide which parked resource groups to adopt (platform.resourceInterfaces)
+├─ plugins = loadPluginHost(resources, root, assetsDir)
+│ # read the Projects' [plugins] tables and import what they name, reusing the objects of the
+│ # host an earlier App registered; a bare kernel keeps the claimed host (empty if none)
+├─ tree = bootModules(platformDef(caps, adoptable, plugin modules, replacements, reassemble), { ifaces, resources, parked })
│ # THE TREE (server/src/platform.ts): every service and repo is a @Component
│ # (a class that exports itself), the session runtime, the terminal manager and the
│ # http assembly are @Modules (classes that export others). Their manifests (read off
│ # the decorators by gen-ifaces) are checked first — requires resolved by signature,
│ # contributions validated against their slots — then setup() runs in dependency
│ # order. Plugin modules (a package's ifaces.json) are children of the same tree.
-└─ ctx.effect: tree.dispose() (every module's effects, reverse order) + manager.shutdown drain
+├─ ctx.effect: manager.shutdown drain + tree.dispose() (every module's effects, reverse order)
+└─ commit: dispose the groups not adopted, register this build's resource declaration and this App's plugin host
```
-A plugin is a set of modules — the unit the harness itself is built from, written the same way: `@Component` / `@Module` classes with `@Use` / `@Provide` / `@Bind` fields. Its manifests are generated, not written — the package's build runs `gen-ifaces` over its own tsconfig and ships the `ifaces.json` beside its `package.json` — the table is the package's module payload, and a plugin is a plugin by being listed; the default export is `{ modules?: [<class>, …], replaces?: [<class>, …] }` — `modules` the nodes it adds, `replaces` the nodes it stands in for (a class of the replaced node's name: a component, a module, or a whole group) — each class checked against its manifest in that table at load. A stand-in is not checked when it is put in place; the tree it results in is checked as one before any node runs, and refused by name if the stand-in offers less than its consumers need. Split by frequency:
-| Moment | Frequency | What happens |
-| --------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Load | Once per App | The platform's `create()` reads the closure — the union of every Project's `[plugins]` table — and resolves and imports each specifier, reads the `ifaces.json` beside its `package.json` (absent = no modules), and checks each class the default export names against its manifest there. A package that names classes without a table (never built), or one whose class and table disagree (a stale build), is skipped with its reason; a Project whose config cannot be read or parsed contributes nothing and its list view says so. An entry the previous App imported from the same, unchanged file is reused rather than imported again |
-| Check + create | Once per App | The platform adds the plugin modules to its tree; the whole tree is checked as data first (requirements resolved by signature, contributions validated against their slots), then created in dependency order — so a module is created fresh per boot and per hot swap |
-| Dispose | Once per App | A module's `effect()` registrations run in reverse creation order when the App is disposed; nothing of a plugin survives into the next generation |
+### What a plugin is
+
+A plugin is a set of modules: the unit the harness itself is built from, written the same way. Plugin code uses `@Component` / `@Module` classes with `@Use` / `@Provide` / `@Bind` fields.
+
+A package's manifests are generated, not written. The package's build runs `gen-ifaces` over its own tsconfig and ships the resulting `ifaces.json` beside its `package.json`. That table is the package's module payload, and a package is a plugin by being listed in a Project's `[plugins]` table.
+
+The default export is `{ modules?: [<class>, …], replaces?: [<class>, …] }`:
+
+- `modules` — the nodes the package adds.
+- `replaces` — the nodes it stands in for: a class of the replaced node's name, which can be a component, a module, or a whole group.
+
+Each class named in the default export is checked against its manifest in the table at load. A stand-in is not checked when it is put in place. The tree it results in is checked as one before any node runs, and it is refused by name if the stand-in offers less than its consumers need.
+
+### The plugin lifecycle
+
+Split by frequency:
+
+| Moment | Frequency | What happens |
+| --- | --- | --- |
+| Load | Once per App | The platform's `create()` reads the closure, the union of every Project's `[plugins]` table. It resolves each specifier (from the data root's `plugins/` prefix, the plugins shipped with the version being booted, or the installation) and imports it, reads the `ifaces.json` beside its `package.json` (absent = no modules), and checks each class the default export names against its manifest there. An entry an earlier App imported from the same, unchanged file is reused instead of imported again. A package that names classes without a table (never built), or one whose class and table disagree (a stale build), is skipped with its reason, which the Project's plugin list reports; a Project whose `.project_config.toml` cannot be read or parsed contributes nothing |
+| Check + create | Once per App | The platform adds the plugin modules to its tree; the whole tree is checked as data first (requirements resolved by signature, contributions validated against their slots), then created in dependency order — so a module is created fresh per boot, per hot swap and per re-assembly |
+| Dispose | Once per App | A module's `effect()` registrations run in reverse creation order when the App is disposed; nothing of a plugin survives into the next generation |
+
+### Re-assembly
+
+A change to a Project's plugin list applies without restarting the process. The runtime holds the shell that `platformImpl.create` returns, and every member of its API forwards to the inner App of the moment. `reassemble()` runs the kernel's own `upgrade` over that inner instance with the same bundle and the same parked document: the swap a hot push performs, without a new bundle. Everything under [Swap semantics](#swap-semantics) applies, so agent runs in progress are stopped in every Project.
+
+The plugin routes hand their edit to the re-assembly, which writes it in its own queue, so two edits of one file never interleave. When the new App fails to boot, the edit is undone first and the previous App is booted again from its document, so the list reads as it did before the change. Nothing in `packages/hmr` takes part, which is why re-assembly works on every runtime. The routes are listed in [Server API](/server-api#plugin-registry-and-project-plugins).
+
+### The plugin contract
+
+The plugin contract — `Plugin`, the decorators, and the sandbox vocabulary — is declared in the SDK at `@prismshadow/penguin-core/plugin`. `@prismshadow/penguin-server/plugin` exports the interfaces a plugin module may require (`Sandbox`, `Terminals`, `Sessions`, `AgentService`, `Messaging`, `Http`, …), types only.
+
+The decorators are the SDK's only runtime a plugin carries. They record on the class itself, so the copy in a plugin's bundle and the host's read the same thing.
+
+Which plugins run is decided by the Projects' `[plugins]` tables, which the Web App's **Plugins** page writes; the harness itself imports no plugin.
-The plugin contract (`Plugin`, the decorators, plus the sandbox vocabulary) is declared in the SDK, at `@prismshadow/penguin-core/plugin`; `@prismshadow/penguin-server/plugin` re-exports the interfaces a plugin module may require (`Sandbox`, `Terminals`, `SessionManager`, `Agents`, …), types only. The decorators are the SDK's only runtime a plugin carries — they record on the class itself, so the copy in a plugin's bundle and the host's read the same thing. Which plugins run is the closure over the Projects' `[plugins]` tables (`.project_config.toml`), written from the Plugins page; the harness itself imports no plugin. A component's interface is its class's public surface; a module's provisions and a consumer's narrow requirements are abstract classes (`extends Interface<…>()`) declared beside the code that owns them. `pnpm gen:ifaces` projects both into `src/ifaces.json` (generated, not committed — `typecheck`, `build` and `test` regenerate it), the table the tree is checked against.
+A component's interface is its class's public surface. A module's provisions and a consumer's narrow requirements are abstract classes (`extends Interface<…>()`) declared beside the code that owns them. `pnpm gen:ifaces` projects both into `src/ifaces.json` — generated, not committed; `typecheck`, `build` and `test` regenerate it. That is the table the tree is checked against.
## Subsystem inventory
-Each subsystem's construction site and external surface (step numbers refer to the boot sequence above):
-
-| Subsystem | Constructed | External surface |
-| -------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
-| Config | `config.ts` `resolveServerConfig` (②) | `ServerConfig`; its only post-listen mutation writes back the real port |
-| Single-instance lock | `lock.ts` (③ pre-check, ⑨ acquire) | Package subpath `@prismshadow/penguin-server/lock`; the CLI and Desktop use it for pre-launch probing |
-| Database | `db/database.ts` `openDatabase` (first step of ⑤)| Repo classes under `db/repos/*`; WAL, foreign keys, additive `ensureColumn` migrations |
-| Auth | `auth/service.ts` (⑤, runtime mechanism) | `/api/auth/*`, the cookie `authMiddleware`, and authentication of terminal WS upgrades |
-| Project / Session | `services/*` — **App-level** (assembled in create)| `/api/projects/**`, `/api/sessions/**` (route details in [Server API](/server-api)) |
-| Agent runtime | `runtime/session-manager.ts` — **App-level** | Task / approval / abort / compact routes and SSE `GET /:sessionId/stream`; delegates to core via `createAgent` |
-| Events | `runtime/channel.ts` `ChannelHub` (⑤, runtime; SSE streams survive swaps)| User-level SSE `GET /api/events`; the `ServerEvent` type family |
-| Scheduler | `runtime/scheduler.ts` — **App-level** (started/stopped by create)| The schedules routes; publishes results into the ChannelHub |
-| HMR host / platform | `hmr/host.ts` (end of ⑤) | `PlatformApi` (`park` / `info` / `http` / `terminals` / `attachStream`); `POST /api/hmr/upgrade` is a runtime-owned route, never offered to the platform |
-| Terminals | `terminal/` — **App-level** | `/api/terminals*` route group (registered into the platform's one Hono app), WS `GET /api/terminals/:id/stream`; ptys are parked and survive swaps |
-| Plugin host | built by the platform's `create()`, published to the registry for the next App | an npm package: its generated `ifaces.json` (the module payload), a default export `{ modules: [<class>, …] }`; the configuration surface is the `[plugins]` table of each Project's `.project_config.toml` |
-| Sandbox | `sandbox/service.ts` — **App-level** (a module; backends contribute to its `providers` slot) | a `SandboxModule.providers` contribution from a plugin module; enforcement reaches commands through core's spawn seam |
-| Module tree | `src/platform.ts` — **App-level** (booted by create over the claimed capabilities) | `@Component()` on each service / repo class (a node is named by its class) with `@Use()` fields for its dependencies; `@Module({ children, exports })` groups (`IdentityModule`, `ProjectsModule`, …) whose exports are what their children offer the rest of the tree; `@Module({ … })` classes with `@Provide()` fields where one class builds several things; narrow consumer interfaces as abstract classes beside their consumer (`extends Interface<…>()`); no `modules/` directory — each node lives in the file of the thing it is; `src/ifaces.json` generated; `GET /api/contributions` lists what reached the web slots |
-| Model catalog | No boot-time construction — static core data | `/api/projects/:projectId/models`; the catalog itself lives in `core/src/state/model-catalog.ts` |
-
-One request-time path is worth knowing: the platform's HTTP seam offers every request to the current App's `http(request)` first, and only a `null` return falls through to the runtime's own routes; while a hot swap is in flight, requests queue at the seam for the new App instead of hitting a half-disposed one.
-
-For the overall layering and the core engine boundary see the [Architecture overview](/architecture); for the HTTP route details see the [Server API](/server-api).
+Each subsystem's construction site and external surface. Step numbers ① to ⑫ refer to the [boot sequence](#boot-sequence) above.
+
+| Subsystem | Constructed | External surface |
+| --- | --- | --- |
+| Config | `config.ts` `resolveServerConfig` (②) | `ServerConfig`; its only post-listen mutation writes back the real port |
+| Single-instance lock | `lock.ts` (③ pre-check, ④ acquire in the listen callback) | Package subpath `@prismshadow/penguin-server/lock`; the CLI and Desktop use it for pre-launch probing |
+| Database | `db/database.ts` `openDatabase` (first step of ⑥) | Repo classes under `db/repos/*`; WAL, foreign keys, ordered versioned migrations (`db/migrations.ts`, stamped in `PRAGMA user_version`) |
+| Auth | `auth/service.ts` — **App-level** (built per App); the process-scoped values (`auth/runtime-state.ts`, the local API token among them) are published in ⑥ | `/api/auth/*`, the cookie and Bearer-token `authMiddleware`, and authentication of terminal WS upgrades |
+| Project / Session | `services/*` — **App-level** (assembled in create) | `/api/projects/**`, `/api/sessions/**` (route details in [Server API](/server-api)) |
+| Agent runtime | `runtime/session-manager.ts` — **App-level** | Task / approval / abort / compact routes and SSE `GET /api/sessions/:sessionId/stream`; delegates to core via `createAgent` |
+| Events | `runtime/channel.ts` `ChannelHub` (⑥, process-level; SSE streams survive swaps) | User-level SSE `GET /api/events`; the `ServerEvent` type family |
+| Scheduler | `runtime/scheduler.ts` — **App-level** (started/stopped by create) | The schedules routes; publishes results into the ChannelHub |
+| HMR host / platform | `@prismshadow/penguin-hmr` (`HmrHost`, `hmrMain`) and `hmr/platform.ts` (the platform) | `PlatformApi` (`info` / `log` / `http` / `terminals` / `attachStream` / `business` / `shutdown` / `drained`, plus the kernel's `park`); `/api/hmr/*`, including `POST /api/hmr/upgrade`, is a route group the platform contributes — a pushed generation that does not serve it is refused before commit |
+| Terminals | `terminal/` — **App-level** | `/api/terminals*` route group, WS `GET /api/terminals/:id/stream`; ptys are parked and survive swaps |
+| Plugin host | built by each App's `create()` and registered at its commit for the next App to reuse; ⑤ `loadPlugins` publishes one in ⑥ for platforms that predate this | an npm package: its generated `ifaces.json` (the module payload), a default export `{ modules?: [<class>, …], replaces?: [<class>, …] }`; the configuration surface is the `[plugins]` table of each Project's `.project_config.toml`, written through `/api/projects/:projectId/plugins/installed` |
+| Sandbox | `sandbox/service.ts` — **App-level** (a module; backends contribute to its `providers` slot) | a `SandboxModule.providers` contribution from a plugin module; enforcement reaches commands through core's spawn seam |
+| Module tree | `src/platform.ts` — **App-level** (booted by create over the claimed capabilities) | `@Component()` on each service / repo class (a node is named by its class) with `@Use()` fields for its dependencies; `@Module({ children, exports })` groups (`IdentityModule`, `ProjectsModule`, …) whose exports are what their children offer the rest of the tree; `@Module({ … })` classes with `@Provide()` fields where one class builds several things; narrow consumer interfaces as abstract classes beside their consumer (`extends Interface<…>()`); no `modules/` directory — each node lives in the file of the thing it is; `src/ifaces.json` generated; `GET /api/contributions` lists what reached the web slots |
+| Model catalog | No boot-time construction — static core data | `/api/projects/:projectId/models`; the catalog itself lives in `core/src/state/model-catalog.ts` |
+
+### The HTTP seam at request time
+
+The platform's HTTP seam offers every request to the current App's `http(request)` first. Behavior by case:
+
+| Case | Behavior |
+| --- | --- |
+| The current App returns `null` | Falls through to the layer's own tail: static hosting and the SPA fallback |
+| The current App throws | Answered `500` rather than falling through |
+| No generation is current | Answered `503` |
+| A hot swap is in flight | Requests wait at the seam for the new App instead of hitting a half-disposed one |
+
+For the overall layering and the core engine boundary, see the [Architecture overview](/architecture). For the HTTP route details, see the [Server API](/server-api).
diff --git a/packages/docs/content/server-boot.zh.md b/packages/docs/content/server-boot.zh.md
index 65d54d14..c85ba2f8 100644
--- a/packages/docs/content/server-boot.zh.md
+++ b/packages/docs/content/server-boot.zh.md
@@ -1,114 +1,224 @@
---
title: Server 启动与子系统
-description: 从进程入口到 HTTP 监听的组装顺序、各子系统的对外表面,以及插件在进程级与 App 级两层生命周期中的位置。
+description: 从进程入口到 App 开始服务的组装顺序、各子系统的对外表面,以及插件在进程级与 App 级两层生命周期中的位置。
---
-`server/src/index.ts` 是一个副作用模块:import 它即启动服务——CLI 就是靠这一条契约在自己进程里跑起 server 的。启动次序写在 `main()` 里,每一步是 `PenguinServer` 的一个方法,方法名即步骤名。组装本身又拆成两个函数——`bootAppDeps(config)` 构建运行时核心、发布能力并启动平台(业务面在平台内组装),`createApp(deps)` 组装运行时壳层的 Hono 路由表但不监听——因此测试可以拿到完整的 app 直接 `app.request(...)`,不占端口,也不经过 `index.ts`。
+`server/src/index.ts` 是一个带副作用的模块:导入它,Server 就会启动。CLI 正是依赖这一约定,才能把 Server 跑在自己选定的 Node 进程里。
-本页回答两个问题:进程从入口到监听按什么顺序把子系统立起来;每个子系统的**对外表面**(surface)是什么——即别人依赖它的方式:导出类型、HTTP 路由、事件,或插件拿到的 context 成员。
+启动顺序写在 `main()` 里:每一步对应一个 `PenguinServer` 方法,方法名就是步骤名。组装本身分成两部分:
+
+- `bootAppDeps(config)` 构建进程核心(数据库、ChannelHub、HMR host),把它们发布进资源注册表,然后启动平台;业务面在平台内部组装。
+- `createApp(boot)` 组装这一层自己的 Hono 应用(网络守卫、平台接缝、静态托管),但不监听端口。因此测试可以拿到完整的应用,直接用 `app.request(...)` 驱动,不占端口,也完全不经过 `index.ts`。
+
+本页回答两个问题:
+
+- 进程从入口到 App 开始服务,按什么顺序把各个子系统立起来?见[进程入口](#进程入口)和[启动时序](#启动时序)。
+- 每个子系统的**对外表面**是什么,即别人依赖它的方式:导出类型、HTTP 路由、事件,或插件模块可以 require 的接口?见[子系统一览](#子系统一览)。
## 进程入口
-| 进入方式 | 机制 |
-| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
-| 直接运行 | `node dist/index.js`(`server/package.json` 的 `start`) |
-| CLI(`penguin server` / `penguin web`)| 设好 `PORT`/`HOST` 环境变量后**同进程** `import("@prismshadow/penguin-server")`,不 fork;`penguin web` 额外轮询就绪后打开浏览器 |
-| Desktop | `utilityProcess.fork` 拉起**独立** server 进程,经环境变量注入 `PENGUIN_HOME`、`PORT`、`PENGUIN_DESKTOP_TOKEN`、`PENGUIN_PORT_FILE` |
+启动 Server 的机制有四种,殊途同归:同一组环境变量驱动同一个模块。
+
+| 入口 | 机制 |
+| --- | --- |
+| 直接运行 | `node dist/index.js`(`server/package.json` 里的 `start`) |
+| CLI(`penguin server` / `penguin web`) | 设好 `PORT`/`HOST` 并导出 `PENGUIN_CLI_ENTRY`,然后以**受监管的子进程**运行 Server,由子进程导入 `@prismshadow/penguin-server` |
+| CLI 自动启动 | CLI 命令发现没有运行中的 Server 时,以 `PORT=0` 派生一个分离的 `server` 子命令,等数据根的锁生效后再接入 |
+| 桌面应用 | `utilityProcess.fork` 拉起一个**独立**的 Server 进程,并注入它需要的环境变量 |
+
+受监管的子进程以 `node <entry> server …` 运行,带有 `PENGUIN_SERVE_CHILD=1` 标记,并通过 `PENGUIN_SUPERVISED=1` 得知有监管者。父进程转发终端的信号,以子进程的退出码退出;子进程以 **重启以更新** 所要求的重启码退出时,父进程重新拉起它。用 tsx 运行的开发实例无法由 node 重新派生,CLI 就改为在本进程内导入 Server。`penguin web` 还会轮询到就绪后打开浏览器。
-三种方式殊途同归:都以同一份环境变量驱动同一个模块。Server 自身的配置只来自环境变量(`server/src/config.ts`);`system_config.yaml` 是 Agent 级状态,在 Session 运行时才被读取,与 server 启动无关。
+自动启动的输出写入 `<root>/logs/server-auto-<date>.log`。
+
+桌面应用经环境变量注入 `PENGUIN_HOME`、`HOST`、`PORT`、`PENGUIN_DESKTOP_TOKEN` 和 `PENGUIN_PORT_FILE`;应用指定了 `PENGUIN_WEB_DIST` 和 `PENGUIN_CLI_ENTRY` 时,也一并注入。
+
+> [!NOTE]
+> Server 自身的配置只来自环境变量(`server/src/config.ts`)。`system_config.yaml` 是 Agent 级状态,在 Session 运行时读取,与 Server 启动无关。
## 启动时序
+`main()` 把顺序写了出来,每行一个 `PenguinServer` 方法:
+
```text
-main() —— 每行一个 PenguinServer 方法
+main() —— one PenguinServer method per line
│
-├─ ① loadEnv · installProxy dotenv 先行(.env 自己可能定义 HTTP_PROXY),随后全局代理接管 fetch
-├─ ② readConfig 仅环境变量:PENGUIN_HOME、PORT、HOST、PENGUIN_WEB_DB …
-├─ ③ ensureSoleInstance 数据根被另一存活实例持有 → 退出码 3(先于开库)
-├─ ④ loadPlugins 给比下述改动更旧的平台留的垫片:平台在自己的 create() 里加载插件
-├─ ⑤ buildDeps = bootAppDeps 开库 → 运行时核心(auth、ChannelHub、HmrHost)→ 发布能力(db/auth/
-│ channels/config/proxy/desktop/插件 host)→ hmr.ensure() 启动平台:
-│ 其 create() 组装整个业务面(服务、路由、scheduler)并投递插件钩子
-├─ ⑥ applyPersistedProxy 库已打开,用持久化的代理设置校准 dispatcher
-├─ ⑦ buildApp 运行时壳层:守卫、/api/auth、/api/desktop、/api/hmr、seam、静态托管
-├─ ⑧ seedAdmin 内置 admin 种子(初始 Project 供给经注册表晚绑定到当前业务面)
-├─ ⑨ listen 开始监听;回调里回填真实端口、取实例锁、写端口文件、开 ::1 伴随监听
-└─ ⑩ installProcessHandlers 信号、Desktop 退出路径、进程级错误兜底
+├─ ① loadEnv · installProxy dotenv first (.env may define HTTP_PROXY itself), then the proxy takes over fetch
+├─ ② readConfig env only: PENGUIN_HOME, PORT, HOST, PENGUIN_WEB_DB …
+├─ ③ ensureSoleInstance data root held by another live instance → exit code 3 (before the DB opens)
+├─ ④ listen bind the port now; answer 503 "starting" until ⑧. The callback writes back
+│ the real port, takes the lock, and opens the ::1 companion on a loopback bind
+├─ hmrMain(createHost(), replace, start) the HMR layer's entry runs start, then makes the first generation current
+│ ├─ ⑤ loadPlugins a shim for platforms that predate loading their own plugins: import what the
+│ │ Projects' [plugins] tables name into a host the first App can reuse
+│ ├─ ⑥ buildDeps = bootAppDeps open the DB → process core (ChannelHub, auth state + local API token, CLI shim) →
+│ │ publish the capabilities (interfaces descriptor, config, db, auth state, channels,
+│ │ proxy, HMR host + control, desktop, lifecycle, plugin host) → hmr.ensure() boots
+│ │ the platform: its create() assembles the WHOLE business surface
+│ ├─ ⑦ applyPersistedProxy the DB is open: align the dispatcher with the persisted settings
+│ ├─ ⑧ buildApp the layer's app: guards, the platform seam, static hosting; terminal WS on each listener
+│ ├─ ⑨ seedAdmin built-in admin seed; decides whether a first-login link is due
+│ ├─ ⑩ installProcessHandlers signals, the desktop quit path, restart-to-update, the process-level error fallback
+│ └─ ⑪ printFirstLoginNotice the one-time sign-in link, when one is due
+└─ ⑫ announce write the port to PENGUIN_PORT_FILE: the App is up
```
-这个顺序不是随意排的,其中四条是硬约束:代理在任何出站请求可能发生之前接管全局 `fetch`;单实例锁在开库**之前**预检,因为 `web.db` 是单写者;插件 host 随其他能力一起在平台 boot 前进入注册表,因此上一个 App import 过的对象可供下一个复用;平台(连同整个业务面)在 `listen` 之前完成启动,因此**没有任何请求会在业务与插件就位之前被服务**。收尾的 `installProcessHandlers` 排在 `listen` 之后,这样关停流程不会在监听器存在之前被触发。
+这个顺序不是随意排的,其中的约束都是硬性的:
+
+- 代理必须在任何出站请求发出之前接管全局 `fetch`。
+- 实例锁在数据库打开**之前**检查,因为 `web.db` 只允许一个写入者。
+- 插件宿主随其他能力在平台启动前进入注册表,因此 ⑤ 导入的插件对象可供首个 App 复用,每个 App 的插件对象也同样留给下一个 App。
+- 平台(连同整个业务面)在 ⑧ 把应用交给监听器之前完成启动。
+- 端口是刻意提前绑定的。⑧ 之前的每个请求都得到 `503 penguin-server is starting`(带 `retry-after: 1`),早到的客户端看到的是「启动中」,而不是连接被拒。**没有任何业务请求会在平台与插件就位之前被处理。**
+- 端口公告放在最后,因为桌面外壳在收到它之后才打开窗口。
+- `installProcessHandlers` 排在 `listen` 之后,这样关停流程不会在监听器存在之前被触发。
+
+插件加载排在 `ensureSoleInstance` 之后也是有意的:一个即将以退出码 3 退出的进程,不应该先去导入一堆第三方模块、执行它们的顶层副作用。
-插件加载排在 `ensureSoleInstance` 之后也是有意的:一个即将以退出码 3 退出的进程不应该先去 import 一堆第三方模块、执行它们的顶层副作用。
+## 进程与 App 两级生命周期
-## 两级生命周期:进程与 App
+进程核心只构建一次,活到进程退出,包括 SQLite 句柄、ChannelHub、进程级的认证值(例如本地 API token),以及带资源注册表的 HMR host。
-运行时核心(DB、认证、ChannelHub、HmrHost)随进程构建一次、活到进程退出。**其余全部是平台层**:整个业务面——服务、路由、SessionManager、Scheduler——连同终端管理器、插件投递、workflow 实例,都在每次 App 创建时重建(每次启动 + 每次热更新,`POST /api/hmr/upgrade` 推送新 bundle)。
+其余全部是平台级的:整个业务面(服务、路由、AuthService、SessionManager、Scheduler)连同终端管理器、插件宿主和插件模块,在每次创建 App 时重建。每次启动、每次热替换、每次修改 Project 的插件列表都会创建 App:热替换时,新的 bundle 经 `POST /api/hmr/upgrade` 推送进来;修改插件列表时,App 用同一个 bundle [自行重组](#重组)。
```text
-进程级(运行时机制,构建一次) App 级(业务面,每次启动 + 每次热更新重跑)
-────────────────────────── ────────────────────────────────
-SQLite · 认证(AuthService) 全部业务服务与路由(services + http/routes)
-ChannelHub(SSE 跨 swap 存活) SessionManager · Scheduler
-HmrHost · 资源注册表 TerminalManager(接管寄存的 pty)
-插件 host(已 import 的对象) 读插件闭包并 import,插件模块作为树的子节点创建
+Process-level (HMR layer, once) App-level (the business surface, re-run per boot + per hot swap + per re-assembly)
+─────────────────────────────── ─────────────────────────────────────────────────
+SQLite · auth state (API token …) every business service and route (AuthService included)
+ChannelHub (SSE survives swaps) SessionManager · Scheduler · messaging bridge
+HmrHost · the resource registry TerminalManager (adopts parked ptys)
+the plugin host (imported objects) plugin lists read + imported, modules created as children of the tree
```
-**swap 语义:未实现 park 的状态一律硬中止**——待审批全部拒绝、运行中任务中止、scheduler 随旧 App 死掉,新 App 从认领的能力重建一切。只有实现了 park/adopt 的资源(终端 pty)跨 swap 存活。
+两级之间的分界线是**资源注册表**。它位于可重载的平台树之外,因此跨 App 存活。pty 进程寄存在里面,新 App 只是取回句柄,所以正在终端里打字的人感觉不到热替换。数据库句柄、认证状态和 SSE hub 走的是同一条路:由进程发布,由每个 App 认领。插件宿主也以同样的方式传递:每个 App 登记自己构建的宿主,下一个 App 认领它,复用其中的插件对象。
+
+### 热替换语义
+
+**未寄存的状态在热替换时一律硬中止**:待审批全部拒绝,运行中的任务中止,调度器、消息桥和机器连接随旧 App 一起停止,由下一个 App 从认领的能力重建。旧 App 销毁之后、新 App 启动之前,内核会等已中止的运行收尾,最多 5 秒。
+
+跨热替换存续的有:
+
+| 存续内容 | 方式 |
+| --- | --- |
+| 终端 pty | 寄存在注册表里,新 App 取回句柄 |
+| 机器隧道 | ssh 子进程,由后继 App 按 pid 接管 |
+| 进程级单例 | 属于进程核心,在所有 App 之外 |
+
+### 资源接口契约
+
+资源本身也有接口契约,但它不进内核的 iface:声明本身就是注册表里的一个条目 `platform.resourceInterfaces`。这个描述符写明所属家族(`penguin`),并按 ID 前缀分组,列出接管者会用到的成员;`terminal` 组列出了使用一个寄存 pty 时会碰到的全部成员。每一代 App 的 `create()` 写入声明,留给继任者。
+
+新 App 在接管任何东西之前,先读前任的声明,与自己编译期内置的声明比对:
+
+- 同一家族、且提供了本构建所需全部成员的组,整组集成,资源跨代存续。
+- 其他组(家族不同、缺少成员,或本构建不再声明)按**逆注册序**逐条销毁后重建。
+
+活对象无法像上下文文档那样严格解析,所以声明一致就是集成的判据。
-资源本身也有接口契约,但它不进 kernel 的 iface——声明本身就是注册表里的一个条目(`resource-interfaces`,按 ID 前缀组记版本,如 `{ terminal: 1, platform: 1 }`),由每代 App 的 `create()` 写入并留给继任者。新 App 在 adopt 任何东西之前读前任的声明、与自己编译期的声明比对:同版本的组整体集成存续;版本不同或本代不再声明的组,按**逆注册序**逐一 dispose 后重建(活对象无法像 context 文档那样 strict-parse,声明一致就是集成的判据)。kernel 的 park/validate/swap 机制不参与也不感知这套约定,因此调和策略本身也随平台热推送演进。运行时能力(`runtime:*`)走另一条对称防线:bundle 编译期携带能力契约版本,`claimRuntimeCapabilities` 先与运行时发布的版本握手,不符则整组拒领、退化为 terminals-only,而不是在使用时抛 TypeError。
+判定先做,但要等新 App 完全建好才执行,因此中途失败的启动仍能把活着的资源交还给上一代。
-分界线是**资源注册表**:它位于可重载的平台树之外,因此跨 App 存活。pty 进程本身寄存在里面,新 App 只是接管句柄——所以热更新对正在敲终端的人不可见;PluginHost、DB 句柄、认证服务、SSE hub 走的是同一条路:运行时发布进注册表,每个 App 认领同一份。
+内核的 park/validate/swap 机制不参与、也不感知这套约定,因此调和策略本身也随平台推送演进。
-这一点不只是整洁问题。推送的 bundle 是**独立编译**的自包含 ESM(`bundle: true`,无 external),拥有自己的模块图;若平台侧持有一个模块级 host 单例,推送后拿到的会是 bundle 自己那个空 host,所有已配置插件都会在第一次热推送时静默消失。认领而非导入,正是为了让打包的 App 与推送的 App 驱动同一个 host。运行时未发布 host 时回退为空 host——「这个运行时不认识插件」的诚实读法。同样的理由见 `terminal/identity.ts`。
+### 能力认领
-## App 创建:插件的舞台
+进程能力一侧有对称的防线:进程发布描述符 `platform.interfaces`,为每项能力列出认领方会用到的成员。在信任任何认领之前,`claimHmrCapabilities` 先把描述符及其背后的活对象,与 bundle 编译期内置的副本比对。
-App 创建的完整顺序在 `server/src/hmr/platform.ts` 的 `platformImpl.create`:
+对不上就拒绝认领:启动失败、推送回滚,而不是在使用时才抛出 `TypeError`。同一家族却不提供任何能力的描述符,声明的是裸内核,只启动终端。
+
+从注册表认领而不是导入,不只是图整洁。推送的 bundle 是**独立编译**的自包含 ESM 文件(`bundle: true`,无 externals),拥有自己的模块图。若平台侧持有模块级单例,推送后拿到的会是 bundle 自己那份全新的副本,进程构建的东西一样也没有。认领而非导入,才让打包的 App 与推送的 App 驱动同一个数据库、ChannelHub 和认证状态。插件宿主遵循同一规则:推送的 App 能复用之前的 App 导入的插件对象,正是因为它认领了这些对象。没有任何发布时,认领得到的是空宿主,这是「这个运行时不认识插件」的如实表达。
+
+## App 创建
+
+App 创建写在 `server/src/hmr/platform.ts` 里。`platformImpl.create` 把真正的 App(`createInner`)作为内层实例启动,外面是一层由运行时持有的外壳,App 因此能够[自行重组](#重组)。`createInner` 的完整顺序:
```text
-platformImpl.create
+createInner
│
-├─ caps = claimRuntimeCapabilities(resources) # db/auth-state/channels/config/proxy/hmr/desktop
-├─ plugins = pluginHostFrom(resources) # 认领运行时在 ④ 加载好的那个 host(未发布则为空 host)
-├─ tree = bootModules(platformTree(caps, …, 插件模块), { ifaces, parked: context.modules })
-│ # 模块树(server/src/platform.ts):
-│ # 每个服务和 repo 是一个 @Component(导出自己的 class),session 运行时、终端管理器和
-│ # http 装配是 @Module(导出别人的 class)。先校验它们的 manifest(gen-ifaces 从装饰器
-│ # 读出)——requires 按签名解析、contribution 按槽位校验——再按依赖顺序执行 setup()。
-│ # 插件模块(包里生成的 ifaces.json)是同一棵树的子节点。
-└─ ctx.effect:tree.dispose()(每个模块的 effect,逆序)+ manager.shutdown 排空
+├─ claim = claimHmrCapabilities(resources) # refused → throw (the boot fails); bare → terminals only
+├─ migrate(caps.db, { swapPath: true }) # a pushed platform brings its own migrations
+├─ decide which parked resource groups to adopt (platform.resourceInterfaces)
+├─ plugins = loadPluginHost(resources, root, assetsDir)
+│ # read the Projects' [plugins] tables and import what they name, reusing the objects of the
+│ # host an earlier App registered; a bare kernel keeps the claimed host (empty if none)
+├─ tree = bootModules(platformDef(caps, adoptable, plugin modules, replacements, reassemble), { ifaces, resources, parked })
+│ # THE TREE (server/src/platform.ts): every service and repo is a @Component
+│ # (a class that exports itself), the session runtime, the terminal manager and the
+│ # http assembly are @Modules (classes that export others). Their manifests (read off
+│ # the decorators by gen-ifaces) are checked first — requires resolved by signature,
+│ # contributions validated against their slots — then setup() runs in dependency
+│ # order. Plugin modules (a package's ifaces.json) are children of the same tree.
+├─ ctx.effect: manager.shutdown drain + tree.dispose() (every module's effects, reverse order)
+└─ commit: dispose the groups not adopted, register this build's resource declaration and this App's plugin host
```
-插件是一组模块——与 harness 自身的构成单位相同,写法也相同:`@Component` / `@Module` 类,字段上是 `@Use` / `@Provide` / `@Bind`。它的 manifest 是生成的,不是手写的——包的 build 对自己的 tsconfig 跑 `gen-ifaces`,把 `ifaces.json` 随 `package.json` 一起发布——这张表就是包的模块载荷,包是不是插件由它被列出决定;默认导出是 `{ modules?: [<class>, …], replaces?: [<class>, …] }`——`modules` 是它新增的节点,`replaces` 是它顶替的节点(以被顶替节点为名的类:组件、模块或整个组)——加载时每个类对照表中自己的 manifest 核对。替身放入时不做检查;组装出的树在任何节点运行前作为整体校验,替身提供的少于消费者所需就按名字拒绝。按频率拆开:
-| 时机 | 频率 | 发生什么 |
-| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
-| 加载 | 每 App 一次 | platform 的 `create()` 读闭包——所有 Project 的 `[plugins]` 表的并集——解析并 import 每个 specifier、读它 `package.json` 旁的 `ifaces.json`(没有即没有模块),把默认导出点名的每个类对照表中自己的 manifest 核对。点名了类却没有表的包(没构建过)、类与表不一致的包(构建陈旧)会带原因被跳过;配置读不了或解析不了的 Project 不贡献任何插件,其列表视图会说明。上一个 App 从同一个、未改动的文件 import 过的条目直接复用,不再 import |
-| 校验 + 创建 | 每 App 一次 | platform 把插件模块加入它的树;整棵树先作为数据校验(requires 按签名解析、contribution 按槽位校验),再按依赖顺序创建——所以模块在每次启动、每次热替换时都是全新创建的 |
-| 释放 | 每 App 一次 | 模块通过 `effect()` 登记的清理在 App 释放时按创建逆序执行;插件的任何东西都不会进入下一代 |
+### 插件是什么
+
+插件是一组模块,与 harness 自身的构成单位相同,写法也相同:`@Component` / `@Module` 类,字段上是 `@Use` / `@Provide` / `@Bind`。
+
+包的 manifest 是生成的,不是手写的:包的构建对自己的 tsconfig 运行 `gen-ifaces`,把生成的 `ifaces.json` 放在 `package.json` 旁一起发布。这张表就是包的模块载荷;一个包列进某个 Project 的 `[plugins]` 表,就是插件。
+
+默认导出是 `{ modules?: [<class>, …], replaces?: [<class>, …] }`:
+
+- `modules`——包新增的节点。
+- `replaces`——它顶替的节点:一个以被顶替节点命名的类,可以是组件、模块或整个组。
+
+加载时,默认导出点名的每个类都要对照表中自己的 manifest 核对。替身放入时不做检查;组装出的树在任何节点运行之前作为整体校验,替身提供的少于消费者所需时,按名字拒绝。
+
+### 插件生命周期
+
+按频率划分:
+
+| 时机 | 频率 | 发生什么 |
+| --- | --- | --- |
+| 加载 | 每 App 一次 | 平台的 `create()` 读取闭包,即所有 Project 的 `[plugins]` 表的并集。它解析每个 specifier(从数据根的 `plugins/` 前缀、随正在启动的版本发布的插件或安装目录中查找)并导入,读取它 `package.json` 旁的 `ifaces.json`(没有即没有模块),把默认导出点名的每个类对照表中的 manifest 核对。之前的 App 从同一个未改动的文件导入过的条目直接复用,不再重新导入。点名了类却没有表的包(没构建过)、类与表不一致的包(构建陈旧)会带原因被跳过,原因显示在该 Project 的插件列表里;`.project_config.toml` 无法读取或解析的 Project 不贡献任何插件 |
+| 校验 + 创建 | 每 App 一次 | 平台把插件模块加入自己的树;整棵树先作为数据校验(requires 按签名解析、contribution 按槽位校验),再按依赖顺序创建,所以模块在每次启动、每次热替换、每次重组时都是全新创建的 |
+| 释放 | 每 App 一次 | App 释放时,模块通过 `effect()` 登记的清理按创建逆序执行;插件的任何东西都不会进入下一代 |
+
+### 重组
+
+修改 Project 的插件列表无需重启进程即可生效。运行时持有 `platformImpl.create` 返回的外壳,外壳 API 的每个成员都转发给当下的内层 App。`reassemble()` 在这个内层实例上运行内核自己的 `upgrade`,bundle 和寄存文档都不变:这正是热推送执行的那次替换,只是没有新的 bundle。[热替换语义](#热替换语义)中的一切照样适用,因此所有 Project 中正在进行的 Agent 运行都会被中止。
+
+插件路由把改动交给重组,由重组在自己的队列里写入,因此对同一个文件的两次修改不会交错。新 App 启动失败时,先撤销改动,再从之前的文档重新启动上一个 App,列表因此回到修改之前的样子。`packages/hmr` 不参与其中,所以重组在任何运行时上都能工作。相关路由见 [Server API](/server-api#插件注册表与-project-插件)。
+
+### 插件契约
+
+插件契约(`Plugin`、各装饰器,以及沙箱词汇表)声明在 SDK 里,即 `@prismshadow/penguin-core/plugin`;`@prismshadow/penguin-server/plugin` 导出插件模块可以 require 的接口(`Sandbox`、`Terminals`、`Sessions`、`AgentService`、`Messaging`、`Http` 等),只有类型。
+
+装饰器是插件随身携带的唯一一段 SDK 运行时。它们把记录写在类自身上,所以插件 bundle 里的那份和宿主读到的是同一样东西。
+
+哪些插件运行由各 Project 的 `[plugins]` 表决定,这些表由 Web App 的**插件市场**页写入;harness 自身不导入任何插件。
-插件契约(`Plugin`、装饰器,加上沙箱词汇表)声明在 SDK 里,即 `@prismshadow/penguin-core/plugin`;`@prismshadow/penguin-server/plugin` 再导出插件模块可以 require 的接口(`Sandbox`、`Terminals`、`SessionManager`、`Agents`……),只有类型。装饰器是插件带走的唯一一段 SDK 运行时——它们把记录写在类自身上,所以插件 bundle 里的那份和宿主读的是同一样东西。哪些插件运行由各 Project 的 `[plugins]` 表(`.project_config.toml`,在插件页写入)的闭包决定,harness 自身不 import 任何插件。组件的接口是它 class 的公开表面;模块的 provides 与消费者的窄 requires 是声明在归属代码旁边的抽象类(`extends Interface<…>()`)。`pnpm gen:ifaces` 把两者投影进 `src/ifaces.json`(生成物,不进版本库——`typecheck`、`build`、`test` 都会重新生成),即模块树据以校验的表。
+组件的接口是它的类的公开表面;模块的 provides 与消费者的窄 requires 是声明在所属代码旁边的抽象类(`extends Interface<…>()`)。`pnpm gen:ifaces` 把两者投影进 `src/ifaces.json`(生成物,不进版本库;`typecheck`、`build`、`test` 都会重新生成),模块树就依据这张表校验。
## 子系统一览
-各子系统的构建位置与对外表面(时序编号对应上文启动时序):
-
-| 子系统 | 构建位置 | 对外表面 |
-| -------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
-| 配置 | `config.ts` `resolveServerConfig`(②) | `ServerConfig`;监听后唯一一次改写是回填真实端口 |
-| 单实例锁 | `lock.ts`(③ 预检、⑨ 取锁) | 包子路径 `@prismshadow/penguin-server/lock`;CLI 与 Desktop 用它做启动前探测 |
-| 数据库 | `db/database.ts` `openDatabase`(⑤ 首步) | `db/repos/*` 仓储类;WAL、外键、增量 `ensureColumn` 迁移 |
-| 认证 | `auth/service.ts`(⑤,运行时机制) | `/api/auth/*`、cookie `authMiddleware`、终端 WS 升级的鉴权 |
-| Project / Session | `services/*`——**App 级**(平台 create 内组装)| `/api/projects/**`、`/api/sessions/**`(路由细目见 [Server API](/server-api)) |
-| Agent 运行时 | `runtime/session-manager.ts`——**App 级** | 任务 / 审批 / 中止 / 压缩路由与 SSE `GET /:sessionId/stream`;内部经 `createAgent` 委托给 core |
-| 事件 | `runtime/channel.ts` `ChannelHub`(⑤,运行时;SSE 流跨 swap 存活)| 用户级 SSE `GET /api/events`;`ServerEvent` 类型族 |
-| Scheduler | `runtime/scheduler.ts`——**App 级**(create 内启停)| schedules 路由;执行结果发布进 ChannelHub |
-| HMR 宿主 / 平台 | `hmr/host.ts`(⑤ 末尾) | `PlatformApi`(`park` / `info` / `http` / `terminals` / `attachStream`);`POST /api/hmr/upgrade` 为运行时自留路由,不经平台 |
-| 终端 | `terminal/`——**App 级** | `/api/terminals*` 路由组(注册进平台唯一的 Hono app)、WS `GET /api/terminals/:id/stream`;pty 寄存跨热更新存活 |
-| 插件宿主 | platform 的 `create()` 构建,发布进注册表供下一个 App 复用 | 一个 npm 包:生成的 `ifaces.json`(模块载荷)、默认导出 `{ modules: [<class>, …] }`;配置面是各 Project `.project_config.toml` 的 `[plugins]` 表 |
-| 模块树 | `src/platform.ts`——**App 级**(create 在认领的能力之上启动) | 每个服务 / repo class 上 `@Component()`(节点以 class 命名),依赖是 `@Use()` 字段;`@Module({ children, exports })` 分组(`IdentityModule`、`ProjectsModule`……),exports 是组内 children 向树的其余部分提供的接口;一个 class 造出多个东西时用带 `@Provide()` 字段的 `@Module({ … })`;消费者的窄接口是紧挨消费者声明的抽象类(`extends Interface<…>()`);没有 `modules/` 目录——每个节点就住在它所是的那个东西的文件里;生成的 `src/ifaces.json`;`GET /api/contributions` 列出到达 web 槽位的内容 |
-| 沙盒 | `sandbox/service.ts`——**App 级**(一个模块;后端向它的 `providers` 槽位投递) | 插件模块向 `SandboxModule.providers` 投递的一条 contribution;约束经 core 的 spawn seam 落到命令上 |
-| 模型目录 | 无启动期构建——core 静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |
-
-请求期还有一条固定路径值得知道:平台的 HTTP seam 把每个请求先交给当前 App 的 `http(request)`,返回 `null` 才落到运行时自己的路由;热更新进行中时请求在 seam 上排队等新 App 就绪,而不是打到半旧的实例上。
+各子系统的构建位置与对外表面。步骤编号 ① 到 ⑫ 对应上文的[启动时序](#启动时序)。
+
+| 子系统 | 构建位置 | 对外表面 |
+| --- | --- | --- |
+| 配置 | `config.ts` 的 `resolveServerConfig`(②) | `ServerConfig`;监听后唯一一次改写是回填真实端口 |
+| 单实例锁 | `lock.ts`(③ 预检,④ 在监听回调中取锁) | 包子路径 `@prismshadow/penguin-server/lock`;CLI 与桌面应用用它做启动前探测 |
+| 数据库 | `db/database.ts` 的 `openDatabase`(⑥ 首步) | `db/repos/*` 仓储类;WAL、外键、按版本顺序执行的迁移(`db/migrations.ts`,版本记在 `PRAGMA user_version`) |
+| 认证 | `auth/service.ts`——**App 级**(每个 App 各建一份);进程级的值(`auth/runtime-state.ts`,含本地 API token)在 ⑥ 发布 | `/api/auth/*`、支持 cookie 与 Bearer token 的 `authMiddleware`、终端 WS 升级的鉴权 |
+| Project / Session | `services/*`——**App 级**(在 create 内组装) | `/api/projects/**`、`/api/sessions/**`(路由细目见 [Server API](/server-api)) |
+| Agent 运行时 | `runtime/session-manager.ts`——**App 级** | 任务 / 审批 / 中止 / 压缩路由与 SSE `GET /api/sessions/:sessionId/stream`;内部经 `createAgent` 委托给 core |
+| 事件 | `runtime/channel.ts` 的 `ChannelHub`(⑥,进程级;SSE 流跨热替换存活) | 用户级 SSE `GET /api/events`;`ServerEvent` 类型族 |
+| Scheduler | `runtime/scheduler.ts`——**App 级**(随 create 启停) | schedules 路由;执行结果发布进 ChannelHub |
+| HMR 宿主 / 平台 | `@prismshadow/penguin-hmr`(`HmrHost`、`hmrMain`)与 `hmr/platform.ts`(平台) | `PlatformApi`(`info` / `log` / `http` / `terminals` / `attachStream` / `business` / `shutdown` / `drained`,外加内核的 `park`);`/api/hmr/*`(含 `POST /api/hmr/upgrade`)是平台贡献的路由组,推送的新一代若不提供这组路由,会在提交前被拒 |
+| 终端 | `terminal/`——**App 级** | `/api/terminals*` 路由组、WS `GET /api/terminals/:id/stream`;pty 寄存在注册表中,跨热替换存活 |
+| 插件宿主 | 每个 App 的 `create()` 构建,在提交时登记进注册表供下一个 App 复用;⑤ `loadPlugins` 为早于这一改动的平台构建一份,在 ⑥ 发布 | 一个 npm 包:生成的 `ifaces.json`(模块载荷)、默认导出 `{ modules?: [<class>, …], replaces?: [<class>, …] }`;配置面是各 Project 的 `.project_config.toml` 中的 `[plugins]` 表,经 `/api/projects/:projectId/plugins/installed` 写入 |
+| 沙箱 | `sandbox/service.ts`——**App 级**(一个模块;后端向它的 `providers` 槽位投递) | 插件模块向 `SandboxModule.providers` 投递的一条 contribution;约束经 core 的 spawn 接缝落到命令上 |
+| 模块树 | `src/platform.ts`——**App 级**(create 在认领的能力之上启动它) | 每个服务 / repo 类用 `@Component()` 标注(节点以类命名),依赖写成 `@Use()` 字段;`@Module({ children, exports })` 组(`IdentityModule`、`ProjectsModule` 等),exports 就是子节点向树里其余部分提供的东西;一个类要构建多个东西时,用带 `@Provide()` 字段的 `@Module({ … })` 类;消费方的窄接口是抽象类,声明在消费方旁边(`extends Interface<…>()`);没有 `modules/` 目录——每个节点就住在它对应事物所在的文件里;`src/ifaces.json` 为生成文件;`GET /api/contributions` 列出到达 web 槽位的内容 |
+| 模型目录 | 无启动期构建——core 的静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |
+
+### 请求时的 HTTP 接缝
+
+平台的 HTTP 接缝把每个请求先交给当前 App 的 `http(request)`,各情形的处理:
+
+| 情形 | 行为 |
+| --- | --- |
+| 当前 App 返回 `null` | 落到这一层自己的末端:静态托管与 SPA 回退 |
+| 当前 App 抛出异常 | 直接返回 `500`,不再向下传 |
+| 当前没有任何一代 App | 返回 `503` |
+| 热替换进行中 | 请求在接缝上排队等新 App 就绪,而不是打到半释放的旧 App 上 |
整体分层与 core 引擎的边界见[架构总览](/architecture);HTTP 路由细目见 [Server API](/server-api)。
diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.md
index 2b13df61..f64ecf2f 100644
--- a/packages/docs/content/sessions-and-traces.en.md
+++ b/packages/docs/content/sessions-and-traces.en.md
@@ -1,28 +1,28 @@
---
title: Sessions & Traces
-description: The six-level run model, local data directory layout, Trace file design, and Session recovery.
+description: The six-level run model, the data layout on disk, how the append-only Trace is written, and how a Session is recovered from it.
---
-All PenguinHarness runtime data lives on the local file system: configuration is editable files, history is append-only Traces. This page defines each level of the run model and explains how the Trace serves as history, recovery source, and statistics source at once.
+All PenguinHarness runtime data lives on the local file system. Configuration is editable files, and history is an append-only **Trace**. This page defines each level of the run model and the layout on disk, then explains how the Trace serves as history, recovery source and statistics source at once.
## Run model
-Six levels: Project → Agent → Workspace → Session → Task → Request.
+The run model has six levels: Project → Agent → Workspace → Session → Task → Request.
| Concept | Definition |
| --- | --- |
-| Project | Top-level unit organizing Agents; owns the model and credential configuration; in the multi-user Web setup, users and Projects are many-to-many |
-| Agent | The executing subject; has exactly one Agent State (a persistent directory); one Agent can serve many Workspaces |
-| Workspace | The working directory of one run — the only file scope the model sees; an explicit `workspaceDir` must already exist, otherwise a temporary Workspace `workspaces/tmp-<8hex>` is created |
+| Project | Top-level unit that organizes agents; owns the model and credential configuration; in a multi-user Web deployment, users and Projects are many-to-many |
+| Agent | The executing subject; has exactly one Agent State (a persistent directory); one agent can serve many Workspaces |
+| Workspace | The working directory of one run — the only file scope the model sees; an explicit `workspaceDir` must already exist; when none is given, a temporary Workspace `workspaces/tmp-<8hex>` is created |
| Session | A continuous conversation under one (Agent, Workspace); model and Workspace are locked at Session creation; ids look like `session-YYYY-MM-DD-HH-mm-ss-<8hex>` |
| Task | One execution goal started by one Prompt; consists of one or more consecutive Requests |
| Request | One LLM API call: context and tool definitions in, streamed output out |
-See the [Architecture](/architecture) page for how the levels cooperate, and the [Agent Loop](/agent-loop) for how Requests advance within a Task.
+For how the levels work together, see [Architecture](/architecture). For how Requests advance within a Task, see [The Agent Loop](/agent-loop).
## Data layout
-The data root is the `PENGUIN_HOME` environment variable, defaulting to `~/.penguin/data`. The layout is defined in one place, `packages/core/src/state/paths.ts`:
+The data root is the `PENGUIN_HOME` environment variable, `~/.penguin/data` by default. The layout is defined in one place, `packages/core/src/state/paths.ts`:
```text
<root>/<project>/
@@ -32,7 +32,7 @@ The data root is the `PENGUIN_HOME` environment variable, defaulting to `~/.peng
└── agents/
└── <agent>/
├── agent_state/ # system_config.yaml, AGENTS.md, .vault.toml,
- │ # tools/, skills/, schedule/
+ │ # tools/, skills/, hooks/, schedule/
│ └── memory/ # Memory: user/ plus one directory per Workspace,
│ # each with its own MEMORY.md index
├── traces/
@@ -47,58 +47,129 @@ The data root is the `PENGUIN_HOME` environment variable, defaulting to `~/.peng
└── snapshots/ # Agent State version snapshots
```
-See the [Configuration Reference](/configuration) for the fields of each config file.
+For the fields of each config file, see the [Configuration Reference](/configuration).
## Trace design
-A Trace is an append-only JSON Lines file; each line is one OmniMessage envelope (see the [OmniMessage Protocol](/omni-message)). History is only ever appended, never modified in place.
+A Trace is an append-only JSON Lines file. Each line is one OmniMessage envelope; see the [OmniMessage Protocol](/omni-message). History is only ever appended, never modified in place.
-- One Trace file corresponds to one complete model context. When compaction produces a new context segment, the writer rotates to a new file — `_002`, `_003`, … — with an incrementing index.
+- One Trace file corresponds to one complete model context. When compaction produces a new context segment, the writer rotates to a new file with an incrementing index: `_002`, `_003`, …
- Recorded: `session_meta`, complete `model_msg`, and all `event_msg`.
-- Not recorded: streaming `partial_*` fragments (the producer appends the complete message once the segment ends), and nested messages tagged with `origin` — a subagent's messages go to the child Session's own Trace, while the parent Trace keeps a single `subagent` pointer event at the spawn site recording the child Session id.
-- `request_begin` and `request_end(status)` come in pairs delimiting one Request; replay uses `request_end.status === "completed"` as the commit criterion for that turn.
-- Appends are serialized inside the writer: records from concurrent producers (the model stream, parallel tool executions) land strictly one after another, each as a single uninterrupted line — a multi-megabyte record such as a base64 image Data URL can never be torn apart by a concurrent append, and file rotation never splits a record.
-- Each record is appended with a single `write(2)` (not `fs.appendFile`, which splits payloads larger than 512 KiB into multiple underlying writes), so an abnormal process exit can at most truncate the last record — it can never tear one apart in the middle. Before Session resumption continues an existing file, the writer probes the file tail: if a previous crash left a torn line (no trailing newline), the next record is preceded by a newline, so the torn line never swallows the records appended after it.
+- Not recorded:
+ - Streaming `partial_*` fragments. The producer appends the complete message once the segment ends.
+ - Nested messages tagged with `origin`. A subagent's messages go to the child Session's own Trace. The parent Trace keeps a single `subagent` pointer event at the spawn site, recording the child Session id.
+- `request_begin` and `request_end(status)` come in pairs and delimit one Request. Replay uses `request_end.status === "completed"` as the commit criterion for that turn.
+- Appends are serialized inside the writer. Records from concurrent producers (the model stream, parallel tool executions) land strictly one after another, each as a single uninterrupted line. A multi-megabyte record, such as a base64 image Data URL, can never be torn apart by a concurrent append. File rotation never splits a record.
+- Each record is appended with a single `write(2)`, not `fs.appendFile`, which splits payloads larger than 512 KiB into several underlying writes. An abnormal process exit can therefore at most truncate the last record; it can never tear one apart in the middle.
+- Before Session resumption continues an existing file, the writer probes the file tail. If a previous crash left a torn line (no trailing newline), the next record is preceded by a newline, so the torn line never swallows the records appended after it.
See `packages/core/src/trace/writer.ts` for the implementation.
-The head of a Trace (illustrative; one OmniMessage envelope per line):
+### Head of a Trace
+
+An illustrative Trace head follows, one OmniMessage envelope per line. Note the order:
+
+- The user's input is written before the `request_begin` it is sent with.
+- On the first run, the toolset follows the input as a `tool_list_ready` event, after an `mcp_connect_begin` / `mcp_connect_end` pair when MCP servers are configured. `session_meta` does not carry the tool definitions.
```jsonl
-{"timestamp":"2026-07-18T03:10:22.531Z","type":"session_meta","payload":{"session_id":"session-2026-07-18-11-10-22-3f8a1c2d","provider":"deepseek","model_id":"deepseek-v4-pro","model_context_window":1000000,"system_prompt":"…","tools":[…],"agent_state":"/home/u/.penguin/data/default_project/agents/default_agent/agent_state","workspace":"/home/u/work"}}
-{"timestamp":"…","type":"event_msg","payload":{"type":"request_begin"}}
+{"timestamp":"2026-07-18T03:10:22.531Z","type":"session_meta","payload":{"session_id":"session-2026-07-18-11-10-22-3f8a1c2d","provider":"deepseek","model_id":"deepseek-v4-pro","model_context_window":1000000,"system_prompt":"…","agent_state":"/home/u/.penguin/data/default_project/agents/default_agent/agent_state","workspace":"/home/u/work"}}
{"timestamp":"…","type":"model_msg","payload":{"type":"text","role":"user","text":"Create hello.txt"}}
-{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call","role":"assistant","name":"exec_command","arguments":"{\"cmd\":\"printf hi > hello.txt\"}","tool_call_id":"call_0"}}
+{"timestamp":"…","type":"event_msg","payload":{"type":"tool_list_ready","tools":[…]}}
+{"timestamp":"…","type":"event_msg","payload":{"type":"request_begin"}}
+{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call","role":"assistant","name":"exec_command","arguments":"{\"cmd\":\"printf hi > hello.txt\"}","tool_call_id":"call_0","stop_reason":"completed"}}
{"timestamp":"…","type":"event_msg","payload":{"type":"approval_decision","decision":"allow","tool_call_id":"call_0"}}
-{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call_output","role":"user","output":"[no output]","tool_call_id":"call_0"}}
-{"timestamp":"…","type":"event_msg","payload":{"type":"request_end","status":"completed"}}
{"timestamp":"…","type":"event_msg","payload":{"type":"token_usage","session":{…},"request":{…}}}
+{"timestamp":"…","type":"event_msg","payload":{"type":"request_end","status":"completed"}}
+{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call_output","role":"user","output":"[no output]","tool_call_id":"call_0","stop_reason":"completed"}}
```
-When tool output exceeds `maxOutputLength`, Trace records the same bounded head, truncation marker, and absolute Session recovery path seen by Web/CLI and the model; it does not separately duplicate the archived text. The path exposes the host data-root layout but remains valid across Tasks and Session resume because the unredacted recovery file lives in that Session's scratchpad. The existing explicit Session-deletion path removes the scratchpad and recovery file together. Trace replay therefore faithfully restores both what the model saw and a usable pointer for later follow-up.
+### Truncated tool output
+
+When tool output exceeds `maxOutputLength`, the Trace records what the model, the Web App and the CLI see: the bounded head, the truncation marker and the absolute Session recovery path. It does not store a second copy of the archived text.
+
+The path exposes the host's data-root layout. It stays valid across Tasks and Session resume, because the unredacted recovery file lives in that Session's scratchpad, and deleting the Session removes the scratchpad and the recovery file together. Replaying the Trace therefore restores both what the model saw and a usable pointer for later follow-up.
## Session recovery
-The Trace is the single source of truth for recovery — there is no separate session database to keep in sync. `resumeSession` works as follows:
+The Trace is the single source of truth for recovery. There is no separate session database to keep in sync. `resumeSession` works as follows:
-1. Locate the highest-index Trace file of the Session;
-2. Read the runtime configuration from its `session_meta` — the model and the Workspace, immutable for the lifetime of the Session, and the system prompt and thinking level that context opened with;
-3. Replay the committed history into a fresh LLM context;
-4. Reconstruct the carry-over (undelivered tool outputs, interruption markers) plus turn and Token counters;
+1. Locate the highest-index Trace file of the Session.
+2. Read the runtime configuration from its `session_meta`:
+ - the model and the Workspace, which are immutable for the lifetime of the Session;
+ - the system prompt that the context opened with.
+3. Replay the committed history into a fresh LLM context.
+4. Reconstruct the carry-over (undelivered tool outputs, interruption markers) and the turn and Token counters.
5. Continue appending to the same Trace file.
-Recovery requires that the Workspace and the model still exist. What recovery guarantees is structural legality: only committed turns are replayed, with `tool_call` / `tool_call_output` pairing intact; incomplete model output (thinking, text) is allowed to be lost. A truncated last line left by an abnormal process exit is tolerated and ignored; a malformed line in the middle of a file (e.g. in a file damaged before writer appends were serialized) is skipped with a diagnostic on stderr, and every parseable record is kept. See `packages/core/src/trace/resume.ts`.
+> [!NOTE]
+> The thinking level is not part of `session_meta`. It resolves again from the Session's pin, else the agent config, else the Project default.
+
+### Requirements and guarantees
+
+Recovery requires that the Workspace still exists and the model is still configured in the Project.
+
+Recovery guarantees structural legality:
+
+- Only committed turns are replayed, with `tool_call` / `tool_call_output` pairing intact.
+- Incomplete model output (thinking, text) is allowed to be lost.
+
+### Damaged files
+
+- A truncated last line left by an abnormal process exit is tolerated and ignored.
+- A malformed line in the middle of a file, for example in a file damaged before the writer serialized appends, is skipped with a diagnostic on stderr. Every parseable record is kept.
+
+See `packages/core/src/trace/resume.ts`.
+
+### After a completed compaction
-Special case: if the latest Trace file ends with a completed compaction, that context is closed as a whole — resume starts from an empty context; in summarize mode the `[context_summary]` is reconstructed and prepended to the first input after resume (old Traces using the earlier angle-bracket `<summary>` form are still understood). That empty context is opened like any context a compaction opens: assembled whole from the current Agent State — prompt, toolset, vault and run settings — rather than from the closed file's recorded prompt (see [Compaction](/agent-loop)). An open context, by contrast, keeps the prompt its file recorded; its tools, Environment and vault can only come from the current Agent State, since the Trace records no executable configuration.
+If the latest Trace file ends with a completed compaction, that context is closed as a whole. Resume starts from an empty context.
+
+In summarize mode, the `[context_summary]` is reconstructed and prepended to the first input after resume. Older Traces using the earlier angle-bracket `<summary>` form are still understood.
+
+The empty context is opened like any context a compaction opens. It is assembled whole from the current Agent State (prompt, toolset, vault and run settings), not from the closed file's recorded prompt. See [Compaction](/agent-loop).
+
+An open context behaves differently: it keeps the prompt its file recorded. Its tools, Environment and vault can only come from the current Agent State, because the Trace records no executable configuration.
## Model switch (/model)
-The Web's `/model` command changes models the way the `/agent` handoff does: picking a model stages it in the composer, and sending creates a new Session under the same Agent via the ordinary session-creation API (the chosen model, **the source session's Workspace** — so files stay reachable), and the first message opens with a `[model_switch_from]` source block — the source session id, the absolute path of its latest Trace file, the Workspace, and the previous model pair — followed by whatever the user typed. The history is **not injected** into the new context: some models require thinking payloads and `fidelity` byte-for-byte when history is replayed, which cannot cross models — instead the model reads the source Trace file itself (JSONL, one message envelope per line) when it needs the earlier context. The source session and its Trace are untouched.
+In the Web App, the `/model` command changes models the way the `/agent` handoff does:
+
+1. Picking a model stages it in the composer.
+2. Sending creates a new Session under the same agent through the ordinary session-creation API. The new Session uses the chosen model and the source session's Workspace, so files stay reachable.
+3. The first message opens with a `[model_switch_from]` source block, followed by whatever the user typed. The block records the source session id, the absolute path of its latest Trace file, the Workspace, and the previous model pair.
+
+The history is not injected into the new context. Some models require thinking payloads and `fidelity` byte-for-byte when history is replayed, and that cannot cross models. Instead, the model reads the source Trace file itself (JSONL, one message envelope per line) when it needs the earlier context; see [Field fidelity](#field-fidelity). The source session and its Trace are untouched. For how to use the command, see [Switch the model](/chat#switch-the-model).
## Field fidelity
-Each content message's opaque provider `fidelity` payload (thinking signatures, phase labels, encrypted reasoning, …) is preserved verbatim in the Trace and sent back verbatim — some models require it byte-for-byte on history replay, and any rewriting would break compatibility. This is one reason the Trace stores raw OmniMessage envelopes rather than a post-processed format.
+Each content message carries an opaque provider `fidelity` payload: thinking signatures, phase labels, encrypted reasoning, and similar data. The Trace preserves this payload verbatim and sends it back verbatim.
+
+- Some models require it byte-for-byte on history replay.
+- Any rewriting would break compatibility.
+
+This is one reason the Trace stores raw OmniMessage envelopes rather than a post-processed format.
## Observability
-Every approval decision (`approval_decision`), abort (`abort`), compaction (`compaction_begin` / `compaction_end`), and `token_usage` lands in the Trace as an event. The Web Trace view and the usage/cost statistics are both derived from this same data — there is no second source of truth — and priced by the same rule: the Project's current rates for the model, at the tier each request's own timestamp fell in, so a Trace file's per-turn costs add up to what the conversation toolbar and the cost center show for the same requests; see the [Web App Guide](/web-app). The approval mechanism itself is covered in [Tools & Approval](/tools). Trace files can also be moved across deployments: a conversation's Trace panel exports the selected file (downloaded verbatim as JSONL), and System settings → General imports one back under an Agent — an import whose session id already exists under that Agent is rejected, so an imported file always becomes index 001 of a new Session.
+Every approval decision, abort, compaction, and Token usage lands in the Trace as an event:
+
+| Occurrence | Event |
+| --- | --- |
+| Approval decision | `approval_decision` |
+| Abort | `abort` |
+| Compaction | `compaction_begin` / `compaction_end` |
+| Token usage | `token_usage` |
+
+The Web App's Trace views and the usage and cost statistics are all derived from this data. There is no second source of truth.
+
+Both are priced by the same rule: the Project's current rates for the model, at the tier each request's own timestamp fell in. A Trace file's per-turn costs therefore add up to what the conversation header and the Cost Center show for the same requests. See [Conversations](/chat) and the [Cost Center](/usage).
+
+The approval mechanism itself is covered in [Tools & Approval](/tools).
+
+### Moving Trace files across deployments
+
+- **Export:** in a conversation's Trace panel, **Export** downloads the selected file verbatim as JSONL.
+- **Import:** in [System settings](/settings#import-a-trace) → **General**, **Import Trace** adds a file to the Project and agent you choose, as a new conversation. Files can be up to 14 MB.
+
+An import whose session id already exists anywhere in this installation is rejected, so an imported file always becomes index 001 of a new Session.
diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.md
index 895474f8..13eeac1a 100644
--- a/packages/docs/content/sessions-and-traces.zh.md
+++ b/packages/docs/content/sessions-and-traces.zh.md
@@ -1,102 +1,175 @@
---
title: Session 与 Trace
-description: 运行模型的六层结构、本地数据目录布局、Trace 文件设计与 Session 恢复机制。
+description: 六层运行模型、磁盘上的数据布局、只追加的 Trace 如何写入,以及 Session 如何从中恢复。
---
-PenguinHarness 的全部运行数据都落在本地文件系统:配置是可编辑文件,历史是 append-only 的 Trace。本页定义运行模型的各层概念,并说明 Trace 如何同时充当历史记录、恢复依据与统计来源。
+PenguinHarness 的全部运行时数据都存放在本地文件系统上。配置是可编辑的文件,历史是只追加的 **Trace**。本页逐层定义运行模型和磁盘上的数据布局,然后说明 Trace 如何同时充当历史记录、恢复来源和统计来源。
## 运行模型
-六层结构:Project → Agent → Workspace → Session → Task → Request。
+运行模型分六层:Project → Agent → Workspace → Session → Task → Request。
| 概念 | 定义 |
| --- | --- |
-| Project | 组织 Agent 的顶层单位,持有模型与凭证配置;Web 多用户部署中,用户与 Project 是多对多关系 |
-| Agent | 执行主体,恰好拥有一份 Agent State(持久化目录);一个 Agent 可服务多个 Workspace |
-| Workspace | 一次运行的工作目录,是模型可见的唯一文件范围;显式指定的 `workspaceDir` 必须已存在,未指定时自动创建临时 Workspace `workspaces/tmp-<8hex>` |
-| Session | 同一(Agent、Workspace)下的一段连续对话;模型与 Workspace 在 Session 创建时锁定,id 形如 `session-YYYY-MM-DD-HH-mm-ss-<8hex>` |
-| Task | 由一条 Prompt 发起的一个执行目标,由一个或多个连续的 Request 组成 |
-| Request | 一次 LLM API 调用:上下文与工具定义送入,流式输出返回 |
+| Project | 组织 Agent 的顶层单位;持有模型和凭证配置;在多用户 Web 部署中,用户与 Project 多对多 |
+| Agent | 执行主体;有且仅有一个 Agent State(一个持久化目录);一个 Agent 可以服务多个 Workspace |
+| Workspace | 一次运行的工作目录,也是模型唯一能看到的文件范围;显式指定的 `workspaceDir` 必须已经存在,未指定时会创建临时 Workspace `workspaces/tmp-<8hex>` |
+| Session | 同一(Agent、Workspace)下的一段连续对话;模型和 Workspace 在 Session 创建时锁定;id 形如 `session-YYYY-MM-DD-HH-mm-ss-<8hex>` |
+| Task | 由一个 Prompt 启动的一个执行目标;由一个或多个连续 Request 组成 |
+| Request | 一次 LLM API 调用:输入上下文和工具定义,输出流式结果 |
-各层组件如何协作见[架构总览](/architecture);Task 内部 Request 如何推进见 [Agent 运行循环](/agent-loop)。
+各层如何协同工作,见[架构总览](/architecture)。Request 如何在 Task 内推进,见 [Agent 运行循环](/agent-loop)。
## 数据目录
-数据根目录取环境变量 `PENGUIN_HOME`,缺省 `~/.penguin/data`。目录布局由 `packages/core/src/state/paths.ts` 统一定义:
+数据根目录由环境变量 `PENGUIN_HOME` 指定,默认为 `~/.penguin/data`。目录布局统一定义在 `packages/core/src/state/paths.ts` 中:
```text
<root>/<project>/
-├── .project_config.toml # Project 级模型与凭证(隐藏文件,0600)
-├── benchmarks/ # 能力评测题库与得分,每个 Benchmark 一个目录——与各 Agent
-│ # 平级,可评测其中任意一个
+├── .project_config.toml # Project-level models & credentials (hidden file, 0600)
+├── benchmarks/ # capability Benchmark cases and scores, one directory per
+│ # Benchmark — a peer of the Agents, evaluating any of them
└── agents/
└── <agent>/
- ├── agent_state/ # system_config.yaml、AGENTS.md、.vault.toml、
- │ # tools/、skills/、schedule/
- │ └── memory/ # 记忆:user/ 加每个 Workspace 一个目录,
- │ # 各自带一份 MEMORY.md 索引
+ ├── agent_state/ # system_config.yaml, AGENTS.md, .vault.toml,
+ │ # tools/, skills/, hooks/, schedule/
+ │ └── memory/ # Memory: user/ plus one directory per Workspace,
+ │ # each with its own MEMORY.md index
├── traces/
│ └── <yyyy-mm-dd>/<sessionId>_<index3>.jsonl
- ├── scratchpad/ # 临时文件,按 Session id 建子目录(如粘贴的图片)
- ├── shared_env/ # 共享的解释器/工具环境(虚拟环境、pipx、各类缓存),由 Agent
- │ # 按需创建——属于系统提示词约定而非代码创建的路径,使工具在任何
- │ # 任务中都只装一次;项目自身的依赖仍留在项目内
- ├── workspaces/ # 临时 Workspace(tmp-<8hex>)
- └── snapshots/ # Agent State 版本快照
+ ├── scratchpad/ # temp files, one subdirectory per Session id (e.g. pasted images)
+ ├── shared_env/ # shared interpreter/tool environments (virtualenvs, pipx,
+ │ # caches) the Agent creates on demand — a system prompt
+ │ # convention, not a path the code creates, so tooling is
+ │ # installed once for any task; project dependencies stay
+ │ # in the project
+ ├── workspaces/ # temporary Workspaces (tmp-<8hex>)
+ └── snapshots/ # Agent State version snapshots
```
-配置文件的字段详见[配置参考](/configuration)。
+各配置文件的字段见[配置参考](/configuration)。
## Trace 设计
-Trace 是 append-only 的 JSON Lines 文件,每行一个 OmniMessage 信封(协议见 [OmniMessage 协议](/omni-message))。历史事件只追加、从不原地修改。
+Trace 是只追加的 JSON Lines 文件,每行是一个 OmniMessage 信封,详见 [OmniMessage 协议](/omni-message)。历史只追加,从不原地修改。
-- 一个 Trace 文件对应一份完整的模型上下文。上下文压缩产生新的上下文段时,写入器轮转到 `_002`、`_003`……新文件,索引递增。
-- 记录的消息:`session_meta`、完整的 `model_msg`、全部 `event_msg`。
-- 不记录的消息:流式 `partial_*` 分片(片段结束后由生产方补写完整消息);带 `origin` 标记的嵌套消息——子 Agent 的消息写入子 Session 自己的 Trace,父 Trace 只在派生位置保留一个 `subagent` 指针事件,记录子 Session id。
-- `request_begin` 与 `request_end(status)` 成对出现,界定一轮 Request;回放以 `request_end.status === "completed"` 作为该轮已提交的判据。
-- 追加在写入器内部串行执行:并发生产者(模型流、并行工具执行)的记录严格逐条落盘,每条都是一行完整内容——base64 图片 Data URL 之类的多 MB 大记录不会被并发追加撕裂,文件轮转也不会切断任何记录。
-- 每条记录以单次 `write(2)` 追加(不用 `fs.appendFile`——它会把超过 512 KiB 的负载拆成多次底层写入),因此进程异常退出至多截断最后一条记录,不会把某条记录从中间撕开。Session 恢复续写既有文件前会探测文件尾:若上次异常退出留下了残行(末尾不是换行符),下一条记录会先补换行再落盘,残行不会吞掉后续记录。
+- 一个 Trace 文件对应一个完整的模型上下文。压缩产生新的上下文段时,写入器切换到新文件,索引依次递增:`_002`、`_003`……
+- 记录的内容:`session_meta`、完整的 `model_msg`,以及所有 `event_msg`。
+- 不记录的内容:
+ - 流式的 `partial_*` 片段。片段结束后,由生产方追加完整消息。
+ - 带 `origin` 标记的嵌套消息。子 Agent 的消息写入子 Session 自己的 Trace。父 Trace 只在派生子 Agent 的位置保留一条 `subagent` 指针事件,记录子 Session 的 id。
+- `request_begin` 与 `request_end(status)` 成对出现,界定一个 Request。重放时以 `request_end.status === "completed"` 判定该轮是否已提交。
+- 追加在写入器内部串行执行。并发生产者(模型流、并行的工具执行)写出的记录严格一条接一条落盘,每条都是一整行、中间不断开。数 MB 的记录(比如 base64 图片的 Data URL)绝不会因并发追加而撕裂;文件轮转也绝不会把一条记录切成两半。
+- 每条记录都用一次 `write(2)` 追加,不用 `fs.appendFile`:后者会把超过 512 KiB 的负载拆成多次底层写入。因此进程异常退出最多截断最后一条记录,绝不会从中间撕开一条。
+- Session 恢复继续写入已有文件之前,写入器会先探测文件尾部。如果上一次崩溃留下了断行(结尾没有换行符),下一条记录前会先补一个换行符,断行就不会吞掉之后追加的记录。
实现见 `packages/core/src/trace/writer.ts`。
-一条 Trace 的开头(示意,每行一个 OmniMessage 信封):
+### Trace 开头示例
+
+下面是一个示意性的 Trace 开头,每行一个 OmniMessage 信封。注意顺序:
+
+- 用户输入先写入,之后才是与它一起发送的 `request_begin`。
+- 首次运行时,工具集以 `tool_list_ready` 事件跟在输入之后;如果配置了 MCP Server,在这之前还有一对 `mcp_connect_begin` / `mcp_connect_end`。`session_meta` 不携带工具定义。
```jsonl
-{"timestamp":"2026-07-18T03:10:22.531Z","type":"session_meta","payload":{"session_id":"session-2026-07-18-11-10-22-3f8a1c2d","provider":"deepseek","model_id":"deepseek-v4-pro","model_context_window":1000000,"system_prompt":"…","tools":[…],"agent_state":"/home/u/.penguin/data/default_project/agents/default_agent/agent_state","workspace":"/home/u/work"}}
+{"timestamp":"2026-07-18T03:10:22.531Z","type":"session_meta","payload":{"session_id":"session-2026-07-18-11-10-22-3f8a1c2d","provider":"deepseek","model_id":"deepseek-v4-pro","model_context_window":1000000,"system_prompt":"…","agent_state":"/home/u/.penguin/data/default_project/agents/default_agent/agent_state","workspace":"/home/u/work"}}
+{"timestamp":"…","type":"model_msg","payload":{"type":"text","role":"user","text":"Create hello.txt"}}
+{"timestamp":"…","type":"event_msg","payload":{"type":"tool_list_ready","tools":[…]}}
{"timestamp":"…","type":"event_msg","payload":{"type":"request_begin"}}
-{"timestamp":"…","type":"model_msg","payload":{"type":"text","role":"user","text":"创建 hello.txt"}}
-{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call","role":"assistant","name":"exec_command","arguments":"{\"cmd\":\"printf hi > hello.txt\"}","tool_call_id":"call_0"}}
+{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call","role":"assistant","name":"exec_command","arguments":"{\"cmd\":\"printf hi > hello.txt\"}","tool_call_id":"call_0","stop_reason":"completed"}}
{"timestamp":"…","type":"event_msg","payload":{"type":"approval_decision","decision":"allow","tool_call_id":"call_0"}}
-{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call_output","role":"user","output":"[no output]","tool_call_id":"call_0"}}
-{"timestamp":"…","type":"event_msg","payload":{"type":"request_end","status":"completed"}}
{"timestamp":"…","type":"event_msg","payload":{"type":"token_usage","session":{…},"request":{…}}}
+{"timestamp":"…","type":"event_msg","payload":{"type":"request_end","status":"completed"}}
+{"timestamp":"…","type":"model_msg","payload":{"type":"tool_call_output","role":"user","output":"[no output]","tool_call_id":"call_0","stop_reason":"completed"}}
```
-工具输出超过 `maxOutputLength` 时,Trace 与 Web/CLI、模型一样只记录有界头部、截断提示和绝对 Session recovery 路径,不重复保存归档正文。该路径会暴露宿主的数据根目录布局;未经脱敏的 recovery 文件位于该 Session 的 scratchpad,因此路径跨 Task 和 Session 恢复保持有效。用户明确删除 Session 时,现有删除路径会连同 scratchpad 和 recovery 文件一起清理。因而 Trace 重放既忠实恢复「模型当时看到了什么」,也为后续追问保留可用指针。
+### 截断的工具输出
+
+工具输出超过 `maxOutputLength` 时,Trace 记录的是模型、Web App 和 CLI 看到的内容:保留的开头部分、截断标记,以及恢复文件在 Session 中的绝对路径。归档文本不会在 Trace 里再存一份。
+
+这条路径会暴露宿主的数据根目录布局。它跨 Task、跨 Session 恢复始终有效:未经脱敏的恢复文件就存放在该 Session 的 scratchpad 里,而删除 Session 会把 scratchpad 和恢复文件一并删除。因此重放 Trace 之后,既还原了模型看到的内容,也留下一个可用的指针,方便后续追问。
## Session 恢复
-Trace 是恢复的唯一事实来源,没有独立的会话数据库需要与之对齐。`resumeSession` 的流程:
+Trace 是恢复的唯一事实来源,不存在需要保持同步的独立 Session 数据库。`resumeSession` 的工作流程如下:
+
+1. 找到这个 Session 索引最大的 Trace 文件。
+2. 从文件里的 `session_meta` 读取运行时配置:
+ - 模型和 Workspace,二者在 Session 的整个生命周期内不可变;
+ - 该上下文开启时使用的系统提示词。
+3. 把已提交的历史重放进一个全新的 LLM 上下文。
+4. 重建补发内容(未送达的工具输出、中断标记),以及轮次和 Token 计数器。
+5. 继续向同一个 Trace 文件追加。
+
+> [!NOTE]
+> 思考等级不记录在 `session_meta` 里,恢复时重新确定:先看 Session 是否钉住了等级,其次是 Agent 配置,最后是 Project 默认值。
+
+### 前提与保证
+
+恢复要求 Workspace 仍然存在,并且模型仍然配置在 Project 中。
+
+恢复保证结构上的合法性:
+
+- 只重放已提交的轮次,`tool_call` / `tool_call_output` 配对保持完整。
+- 不完整的模型输出(思考、文本)允许丢失。
+
+### 损坏的文件
+
+- 容忍并忽略进程异常退出留下的末尾截断行。
+- 文件中间的损坏行(例如在写入器实现追加串行化之前就已损坏的文件里)直接跳过,并在 stderr 输出诊断信息。所有能解析的记录都会保留。
+
+见 `packages/core/src/trace/resume.ts`。
-1. 定位该 Session 索引最大的 Trace 文件;
-2. 从文件内的 `session_meta` 读取运行配置——模型与 Workspace(二者在 Session 生命周期内不可变)以及该上下文开启时的系统提示词与思考等级;
-3. 将已提交的历史回放进一份全新的 LLM 上下文;
-4. 重建 carry-over(未送达的工具输出、中断标记)与轮数、Token 计数器;
-5. 继续追加写入同一个 Trace 文件。
+### 压缩完成之后
-恢复的前提是 Workspace 与模型仍然存在。恢复保证的是结构合法性:只回放已提交的轮次,`tool_call` 与 `tool_call_output` 配对完整;未完成的模型输出(thinking、文本)允许丢失。异常退出留下的截断末行会被容忍并忽略;文件中间的损坏行(如写入器追加串行化之前受损的存量文件)会被跳过并在 stderr 给出诊断,其余可解析的记录全部保留。实现见 `packages/core/src/trace/resume.ts`。
+如果最新的 Trace 文件以一次已完成的压缩结尾,这个上下文已整体关闭,恢复时从一个空上下文开始。
-特殊情形:若最新 Trace 文件以一次完成的压缩收尾,则该上下文已整体关闭——恢复从空上下文开始;summarize 模式下会重建 `[context_summary]` 摘要,前置到恢复后第一轮输入中(旧 Trace 中早期的尖括号 `<summary>` 形式仍可识别)。这个空上下文与压缩开启的上下文一样开启:按当前 Agent State 整体装配——提示词、工具集、vault 与运行参数——而不是沿用已关闭文件里记录的提示词(见[上下文压缩](/agent-loop))。未关闭的上下文则相反:提示词沿用该文件记录的原文,工具、Environment 与 vault 只能取自当前 Agent State——Trace 不记录可执行配置。
+summarize 模式下,恢复后会重建 `[context_summary]`,并把它加在恢复后的第一条输入之前。使用早期尖括号 `<summary>` 形式的旧 Trace 仍然能够识别。
+
+这个空上下文的开启方式与压缩开启的上下文相同:整体按当前 Agent State 组装(提示词、工具集、vault 和运行设置),而不是沿用已关闭文件里记录的提示词。见[上下文压缩](/agent-loop)。
+
+尚未关闭的上下文则不同:它沿用所在文件记录的提示词。工具、Environment 和 vault 只能来自当前 Agent State,因为 Trace 不记录任何可执行配置。
## 模型切换(/model)
-Web 的 `/model` 命令按 `/agent` 交接的方式换模型:选中模型只是在输入框暂存,发送时才用普通的会话创建接口在同一 Agent 下新建一个 Session(选定新模型,**沿用源会话的 Workspace**,文件因此保持可达),首条消息以 `[model_switch_from]` 源块开头——携带源会话 id、其最新 Trace 文件的绝对路径、Workspace 与原模型二元组,用户输入的剩余文字紧随其后。历史**不注入**新上下文:部分模型回放历史时要求 thinking 与 `fidelity` 逐字一致,跨模型注入不可行——模型需要早前上下文时按路径自行读取源 Trace 文件(JSONL,每行一个消息信封)。源会话与其 Trace 不受任何影响。
+在 Web App 中,`/model` 命令用与 `/agent` 交接相同的方式切换模型:
+
+1. 选择模型后,先暂存在输入框中。
+2. 发送时,通过普通的 Session 创建 API 在同一个 Agent 下创建新 Session。新 Session 使用所选模型和来源 Session 的 Workspace,因此文件仍然可以访问。
+3. 第一条消息以 `[model_switch_from]` 来源块开头,后面跟着用户输入的内容。这个块记录来源 Session 的 id、它最新 Trace 文件的绝对路径、Workspace,以及原模型的成对引用。
+
+历史不会注入新上下文。有些模型在重放历史时要求思考负载和 `fidelity` 逐字节一致,这一点无法跨模型满足。所以模型需要更早的上下文时,会自行读取来源 Trace 文件(JSONL,每行一个消息信封);见[字段保真](#字段保真)。来源 Session 和它的 Trace 保持原样。命令的用法见[切换模型](/chat#切换模型)。
## 字段保真
-内容消息携带的不透明 Provider 保真负载 `fidelity`(思考签名、phase 分段标记、加密推理等)在 Trace 中原样保存、原样回传——部分模型在历史回放时要求该负载逐字一致,任何转写都会破坏兼容性。这也是 Trace 直接存储 OmniMessage 信封而非二次加工格式的原因之一。
+每条内容消息都携带一个不透明的供应商 `fidelity` 负载:思考签名、阶段标签、加密的推理内容等数据。Trace 原样保存这个负载,也原样发回。
+
+- 有些模型要求重放历史时逐字节一致。
+- 任何改写都会破坏兼容性。
+
+Trace 直接存储原始 OmniMessage 信封而不采用后处理格式,这是原因之一。
## 可观测性
-每一次审批决策(`approval_decision`)、中断(`abort`)、压缩(`compaction_begin` / `compaction_end`)与 `token_usage` 都作为事件落入 Trace。Web 的 Trace 视图与用量、成本统计均由这同一份数据派生,不存在第二事实来源,计价口径也相同:按 Project 当前的模型价格、以每次请求自己的时间戳判定分时段档位,因此一个 Trace 文件的逐轮成本之和,就是对话页顶部与成本中心为同一批请求给出的数字;见 [Web App 指南](/web-app)。审批机制本身见[工具与审批](/tools)。Trace 文件还可以在部署之间迁移:在对话的 Trace 面板中可将选中的文件导出(按原样下载为 JSONL),在系统设置的「常规」页可导入到某个 Agent 下——若该 Agent 已存在同名 Session 则导入被拒绝,因此导入文件总是成为一个新 Session 的 001 号文件。
+每一次审批决策、中止、压缩和 Token 用量都会以事件形式写入 Trace:
+
+| 情形 | 事件 |
+| --- | --- |
+| 审批决策 | `approval_decision` |
+| 中止 | `abort` |
+| 压缩 | `compaction_begin` / `compaction_end` |
+| Token 用量 | `token_usage` |
+
+Web App 的 Trace 视图和用量、成本统计都来自这份数据,不存在第二个事实来源。
+
+两者的计价规则也相同:按 Project 当前为该模型设置的价格,并按每个请求自身时间戳所处的时段档位计费。因此,一个 Trace 文件中各轮成本加起来,等于对话头部和成本中心为同一批请求显示的金额。见[对话](/chat)和[成本中心](/usage)。
+
+审批机制本身见[工具与审批](/tools)。
+
+### 跨部署迁移 Trace 文件
+
+- **导出:** 在对话的 Trace 面板中,**导出**会把选中的文件原样下载为 JSONL。
+- **导入:** 在[系统设置](/settings#导入-trace) → **通用**中,**导入 Trace** 会把文件添加到你选择的 Project 和 Agent,成为一个新对话。文件最大 14 MB。
+
+如果文件的 session id 已在本安装的任何位置存在,导入即失败,因此导入的文件总是成为新 Session 的 001 号文件。
diff --git a/packages/docs/content/settings.en.md b/packages/docs/content/settings.en.md
new file mode 100644
index 00000000..a204b3e4
--- /dev/null
+++ b/packages/docs/content/settings.en.md
@@ -0,0 +1,242 @@
+---
+title: Settings
+description: Manage your profile, preferences and password, and, as an admin, users, the proxy, upload limits and company mode.
+---
+
+**System settings** is one dialog for the settings that belong to neither a Project nor an agent: your profile, your interface preferences and password, and, for an admin, the server's users, proxy, upload limits and company mode.
+
+- Your own settings: [Profile](#profile), [General](#general), [Appearance](#appearance) and [Account](#account).
+- Server settings, for admins: [Users](#users), [Proxy options](#proxy-options), [Upload limits](#upload-limits) and [Company mode](#company-mode).
+
+## Open System settings
+
+1. At the bottom of the sidebar, select your user row, or your avatar when the sidebar is collapsed. The account menu opens.
+2. Select **System settings**.
+
+## How the dialog is organized
+
+The dialog shows a rail of pages on the left. Each page is a list of rows, with the title on the left and the control on the right. On a narrow screen the rail becomes a horizontal strip above the page.
+
+The rail is grouped into **Personal** and **Server**:
+
+| Page | Group | Who sees it |
+| --- | --- | --- |
+| [Profile](#profile) | Personal | Everyone |
+| [General](#general) | Personal | Everyone |
+| [Appearance](#appearance) | Personal | Everyone |
+| [Account](#account) | Personal | Only where a password exists to change |
+| [Users](#users) | Server | Admin only, and not in the desktop app |
+| [Proxy options](#proxy-options) | Server | Admin only |
+| [Upload limits](#upload-limits) | Server | Admin only |
+| [Company mode](#company-mode) | Server | Admin only |
+
+Personal preferences apply the moment they are touched. There is no Save button and nothing to lose by closing the dialog. The nickname on the Profile page is the one exception: typed text needs a commit, and its **Save** sits beside the field rather than under the page.
+
+Where your personal preferences are stored:
+
+- In this browser: language, currency, notifications, theme, terminal theme, font size, accent, the shortcuts launcher, and tool short names.
+- With your account on the server: your profile and your personal Company mode switch.
+
+The Server pages are admin-only and server-global. A non-admin sees neither those entries nor any hint that they exist: they are left with the Personal pages alone, and the rail draws no group headings at all.
+
+In the desktop app the **Users** page is absent, because the server runs single-user. The desktop app's own window also has no **Account** page: it signs in through the shell's token and holds no password to change. A browser signed into the same server with a password keeps the page.
+
+A "?" beside a row's title opens that row's explanation. A "?" beside a page heading explains the whole page.
+
+Checking for updates is not a page here. See [Updates](/updates).
+
+## Profile
+
+The **Profile** page holds your **Avatar** and **Nickname**. It is personal and appears in every session, including the desktop app's own window, because neither field needs a password to change.
+
+The page has no footer. Every control writes when it is used, and the button that writes a value stands next to that value.
+
+Both fields start unset. Until you set them, your account shows your user id and a letter tile on the sidebar's bottom user row, on the collapsed rail's avatar, and at the head of the account menu they open.
+
+Once set, your avatar and nickname replace that pair in all three places. Your user id stays visible under the nickname at the head of the account menu. The nickname also shows under the id in the **Users** list.
+
+### Change your avatar
+
+**Before you begin**
+
+- An image in PNG, JPEG, or WebP format.
+
+1. On the **Profile** page, select **Change avatar**.
+2. Choose a PNG, JPEG, or WebP image.
+
+The avatar applies at once. It is centre-cropped to a square and re-encoded at 128×128.
+
+To put the letter tile back, select **Restore default** beside **Change avatar**.
+
+### Change your nickname
+
+1. On the **Profile** page, in **Nickname**, enter a nickname of 1–32 characters.
+2. Select **Save**.
+
+The limit counts characters, so a Chinese name may be 32 characters. Saving a blank nickname clears it.
+
+**Restore default**, next to **Save**, puts your nickname back to its default, which is your user id. Both buttons write on click, and each is disabled when it would write what is already stored.
+
+## General
+
+The **General** page is personal.
+
+| Setting | Options | What it does |
+| --- | --- | --- |
+| **Language** | English / 中文 / System | System follows the browser. |
+| **Currency** | USD $ / CNY ¥ | The display currency for prices. Storage is always USD. Conversion happens only at the edge of the screen. |
+| **Task completion notifications** | On / Off (off by default) | Shows a system notification when a Task finishes while the window is hidden or unfocused. Clicking the notification opens that Session. |
+| **Company mode** | On / Off (on by default) | Shown only while an admin has turned company mode on for the server. Off hides your own **Development** / **Company** switch and nothing else; organizations keep running. See [Company mode](/company-mode). |
+| **Import Trace** | — | Turns a Trace file into a conversation. The row is there only if you own a Project. See [Import a Trace](#import-a-trace). |
+
+> [!NOTE]
+> Turning on **Task completion notifications** asks the system for permission on the spot. The system asks only once: after a refusal the switch stays off with a hint, and the only way back is the system's own notification settings. A browser without system notifications shows the switch disabled.
+
+### Import a Trace
+
+**Import Trace** turns a `.jsonl` Trace file into a conversation of an agent.
+
+**Before you begin**
+
+- A `.jsonl` Trace exported from another install, at most 14MB.
+- You must be an owner of the destination Project.
+
+You choose both the destination Project and the destination agent. The agent is asked for because a Trace file cannot name a local agent of its own. The Project is asked for because this dialog does not show which Project is open, which also means a Trace can go to a Project other than the open one. The picker lists only the Projects you own, since importing is an owner's action; with none owned, the row is absent.
+
+1. On the **General** page, in **Import Trace**, select the destination Project. It defaults to the open Project when you own it, and otherwise to the first Project you own.
+2. Select the destination agent. It defaults to the open Project's `default_agent`.
+3. Select **Choose file** and pick your `.jsonl` file. The import starts at once.
+
+The Trace becomes a new conversation of that agent. An import is refused when that agent already has a Session with the same id.
+
+Exporting is the other direction of the same road. It lives with the file it downloads, in a conversation's Trace panel.
+
+## Appearance
+
+The **Appearance** page is personal.
+
+| Setting | Options | What it does |
+| --- | --- | --- |
+| **Theme** | Light / Dark / System | The interface theme. |
+| **Terminal theme** | App / Light / Dark | The terminal panel keeps its own light or dark and follows the app theme by default. Pin it to Light or Dark to decouple the two, for prompts and TUIs tuned to one screen. |
+| **Font size** | S / M / L | The interface font size. |
+| **Accent** | Neutral, Blue, Green, Violet, Rose or Amber | The interface accent color. |
+| **Shortcuts launcher** | On / Off | The round button floating on the conversation's right edge that fans out shortcuts to the workbench's panels and the terminal. The fan's **Hide launcher** entry does the same. |
+| **Tool short names** | On / Off | Tool cards in a conversation name built-in tools by a short alias (`read_file` reads as "read"). Every other tool, MCP tools included, and the Trace viewer keep the tool's own name. Hovering a short name shows it. |
+| **Tray icon** | On / Off (on by default) | Desktop app only. See below. |
+
+About **Tray icon**: the desktop app keeps an icon in the system tray: the Windows notification area, the macOS menu bar, or the Linux tray. It stays there for as long as the app runs. Click the icon to come back to the window. Right-click it to start a new Session or quit.
+
+Turning it off removes the icon at once, with no restart. Closing the window then no longer hides it there: the app stays in the Dock on macOS, and quits on Windows and Linux.
+
+## Account
+
+The **Account** page holds the **Change password** action.
+
+The page exists only where a password exists to change. The desktop app's own window signs in through the shell's one-shot token and never sees a password, so it has no **Account** page. A browser signed into the same server with a password keeps the page.
+
+> [!NOTE]
+> A session signed in through the first-login link can set a password without entering the current one, because that account has never had a password anyone saw.
+
+### Change your password
+
+1. On the **Account** page, select **Change password**.
+2. In **Current password**, enter your current password. This field is not shown after a first-login link sign-in.
+3. In **New password**, enter the new password (at least 8 characters).
+4. In **Confirm new password**, enter it again.
+5. Select **Save**.
+
+## Users
+
+The **Users** page lists the server's users. It is admin-only, and it is absent from the desktop app, where the server runs single-user.
+
+From the page you add users, reset passwords, and delete users.
+
+### Add a user
+
+1. On the **Users** page, select **Add user**.
+2. Enter a **Username** (2–32 characters: a lowercase letter first, then lowercase letters, digits and underscores) and an **Initial password** (at least 8 characters).
+3. Select **Create**.
+
+The new user gets a default Project named `<userId>-default_project`. A user who is still on an initial password carries an **initial password** badge.
+
+### Reset a user's password
+
+1. On the **Users** page, find the user and select **Reset password**.
+2. Enter a new **Initial password** and select **Save**.
+
+The reset signs the user out of every sign-in session. They must sign in again with the new password.
+
+### Delete a user
+
+> [!WARNING]
+> Deleting a user also deletes every Project they own, data directories included. It cannot be undone.
+
+1. On the **Users** page, find the user and select **Delete**.
+2. In the dialog, select **Delete**, then **Confirm**.
+
+Users with the Admin role have no delete action, and the server refuses to delete the built-in admin.
+
+## Proxy options
+
+The **Proxy options** page is admin-only and server-global. It controls which outbound traffic goes through a proxy.
+
+| Setting | Default | What it covers |
+| --- | --- | --- |
+| **Application uses the proxy** | On | The server's own outbound traffic: LLM requests, the update check, image fetches. |
+| **Agent environment uses the proxy** | On | Agent command subprocess environments. |
+| **Proxy address** | Empty | Optional, and shared by both switches. Empty means follow the proxy environment variables. |
+
+**Proxy address** accepts any proxy URL undici's dispatcher takes: `http://`, `https://`, `socks5://`, or `socks://`, credentials allowed. A bare `host[:port]` is also accepted and stored normalized to `http://…`. Anything else is refused with the reason shown under the input.
+
+Nothing is written until **Save**. Save applies the whole form in one PUT, so a rejected address writes none of it. A save rebuilds the outbound dispatcher and takes effect on new connections, with no restart. Loopback always goes direct.
+
+### Set a proxy and test it
+
+**Before you begin**
+
+- The address of your proxy, in one of the accepted formats above.
+
+1. On the **Proxy options** page, in **Proxy address**, enter your proxy address. Leave the field empty to follow the proxy environment variables.
+2. Toggle **Application uses the proxy** to send the server's own outbound traffic through the proxy. It is on by default.
+3. Toggle **Agent environment uses the proxy** to put the proxy into agent command subprocess environments. It is on by default.
+4. Select **Save**. If the address is invalid, nothing is written and the reason appears under the input.
+5. Below **Save**, select **Test** to run the **Reachability test**.
+
+The test measures this server's own outbound hop to the model providers. It lists its targets before it runs: the model-list endpoints of OpenAI, Anthropic, Gemini, DeepSeek, Z.ai and BigModel. **Test** then sends each target one credential-free GET, and results appear one by one as they arrive. Each target waits at most five seconds.
+
+- Any HTTP answer counts as **Reachable**, 401 and 403 included, because a refused credential still proves that DNS, TCP and TLS all completed. A reachable target shows the time it took.
+- A failure is named: Timed out, DNS lookup failed, Connection refused, TLS handshake failed, or Unreachable.
+
+> [!NOTE]
+> The test measures the saved settings, because only a save rebuilds the outbound dispatcher. If you edited the address, save it before testing.
+
+## Upload limits
+
+The **Upload limits** page is admin-only and server-global. It sets two sizes, in whole MB:
+
+| Field | Default | Allowed range |
+| --- | --- | --- |
+| **Max attachment size (MB)** | 100MB | 1–200MB |
+| **Max total per message (MB)** | 120MB | 1–200MB |
+
+The total may not sit below the per-file cap, because that combination would make a legal single attachment unsendable. A value outside the range, such as "100GB" typed into a MB field as 102400, is refused with the reason shown under the input rather than accepted. Validation precedes every write: one bad field in a PUT leaves the other fields untouched too.
+
+### Change the upload limits
+
+1. On the **Upload limits** page, in **Max attachment size (MB)**, enter a whole number of MB between 1 and 200.
+2. In **Max total per message (MB)**, enter a whole number of MB between 1 and 200, and not below the per-file cap.
+3. Select **Save**.
+
+Saving takes effect immediately, with no restart: the attachment validators and the request body cap both read the setting per request.
+
+## Company mode
+
+The **Company mode** page is admin-only and server-global. It holds the **Enable company mode** master switch, off until an admin turns it on here.
+
+The switch applies the moment it is flipped. There is no Save button.
+
+Turning it off stops the organization scheduler and every organization route, and hides the mode switch for everyone. Organizations on disk are untouched. Turning it back on backfills no missed trigger.
+
+> [!NOTE]
+> Company mode is a beta. See [Company mode](/company-mode).
diff --git a/packages/docs/content/settings.zh.md b/packages/docs/content/settings.zh.md
new file mode 100644
index 00000000..8254e796
--- /dev/null
+++ b/packages/docs/content/settings.zh.md
@@ -0,0 +1,242 @@
+---
+title: 系统设置
+description: 管理个人资料、偏好设置和密码;管理员还可以管理用户、代理、上传限制和公司模式。
+---
+
+**系统设置**把不属于 Project 也不属于 Agent 的设置集中在一个对话框里:你的个人资料、界面偏好和密码;管理员还能在这里管理服务器的用户、代理、上传限制和公司模式。
+
+- 个人设置:[个人资料](#个人资料)、[通用](#通用)、[外观](#外观)和[账户](#账户)。
+- 服务器设置,仅管理员:[用户管理](#用户管理)、[代理选项](#代理选项)、[上传限制](#上传限制)和[公司模式](#公司模式)。
+
+## 打开系统设置
+
+1. 在侧边栏底部点击你的用户行;侧边栏收起时,点击你的头像。账户菜单随即打开。
+2. 选择**系统设置**。
+
+## 对话框的结构
+
+对话框左侧是一列页面导航,每个页面由若干行设置项组成,标题在左,控件在右。窄屏上,这列导航会变成页面上方的一条横向滚动栏。
+
+导航分为**个人**和**服务器**两组:
+
+| 页面 | 分组 | 谁能看到 |
+| --- | --- | --- |
+| [个人资料](#个人资料) | 个人 | 所有人 |
+| [通用](#通用) | 个人 | 所有人 |
+| [外观](#外观) | 个人 | 所有人 |
+| [账户](#账户) | 个人 | 仅在有密码可改时出现 |
+| [用户管理](#用户管理) | 服务器 | 仅管理员,桌面应用中没有 |
+| [代理选项](#代理选项) | 服务器 | 仅管理员 |
+| [上传限制](#上传限制) | 服务器 | 仅管理员 |
+| [公司模式](#公司模式) | 服务器 | 仅管理员 |
+
+个人偏好改动即生效,没有保存按钮,关掉对话框也不会丢失什么。唯一的例外是个人资料页的昵称:输入的文字需要显式提交,它的**保存**按钮就在输入框旁边,不在页面底部。
+
+个人偏好的存储位置:
+
+- 保存在当前浏览器:语言、币种、任务完成通知、主题、终端主题、字号、主题色、快捷方式悬浮球和工具短名。
+- 随账户保存在服务器:个人资料,以及你个人的公司模式开关。
+
+服务器组的页面仅管理员可见,作用于整台服务器。非管理员既看不到这些条目,也无从得知它们存在:他们只能看到个人组的几页,导航也不再显示分组标题。
+
+桌面应用里没有**用户管理**页,因为这时服务器是单用户的。桌面应用自己的窗口也没有**账户**页:它通过 shell 的 token 登录,没有密码可改;用密码登录同一台服务器的浏览器仍有这一页。
+
+设置项标题旁的「?」可以查看这一项的说明,页面标题旁的「?」则说明整个页面。
+
+检查更新不在这个对话框里,见[更新 PenguinHarness](/updates)。
+
+## 个人资料
+
+**个人资料**页包含你的**头像**和**昵称**。它属于个人设置,在任何登录方式下都有,包括桌面应用自己的窗口,因为这两项都不需要密码就能修改。
+
+这一页没有底栏:每个控件在使用时立即写入,负责写入的按钮就在对应的值旁边。
+
+两项一开始都未设置。设置之前,侧边栏底部的用户行、收起后侧栏上的头像,以及从这两处打开的账户菜单顶部,都显示你的用户名和首字母头像。
+
+设置之后,这三处都换成你的头像和昵称;账户菜单顶部仍会在昵称下方显示用户名。昵称还会显示在**用户管理**列表中用户名的下方。
+
+### 更换头像
+
+**开始之前**
+
+- 一张 PNG、JPEG 或 WebP 格式的图片。
+
+1. 在**个人资料**页选择**更换头像**。
+2. 选择一张 PNG、JPEG 或 WebP 图片。
+
+头像立即生效。图片会按中心裁成正方形,重新编码为 128×128。
+
+要换回首字母头像,选择**更换头像**旁边的**恢复默认**。
+
+### 修改昵称
+
+1. 在**个人资料**页的**昵称**里输入 1–32 个字符的昵称。
+2. 选择**保存**。
+
+长度按字符计算,因此中文昵称也可以写满 32 个字。保存空白昵称即清除昵称。
+
+**保存**旁边的**恢复默认**把昵称恢复为默认值,即你的用户名。两个按钮都是点击即写入;要写入的值与已保存的值相同时,按钮不可用。
+
+## 通用
+
+**通用**页是个人设置。
+
+| 设置 | 选项 | 作用 |
+| --- | --- | --- |
+| **语言** | English / 中文 / 跟随系统 | 「跟随系统」表示跟随浏览器。 |
+| **币种** | 美元 $ / 人民币 ¥ | 价格显示所用的币种。数据始终以美元存储,换算只发生在显示层。 |
+| **任务完成通知** | 开 / 关(默认关闭) | 窗口隐藏或失去焦点时 Task 结束,会弹出系统通知,点击即回到该 Session。 |
+| **公司模式** | 开 / 关(默认开启) | 只在管理员为服务器开启公司模式后出现。关闭只隐藏你自己的**开发** / **公司**切换,别的都不影响,组织照常运转。见[公司模式](/company-mode)。 |
+| **导入 Trace** | — | 把 Trace 文件导入为一段对话。只有你拥有至少一个 Project 时才会出现这一行。见[导入 Trace](#导入-trace)。 |
+
+> [!NOTE]
+> 打开**任务完成通知**时会当场向系统申请通知权限。系统只问一次:被拒绝后开关保持关闭并显示提示,只能到系统的通知设置里改回来。浏览器不支持系统通知时,开关不可用。
+
+### 导入 Trace
+
+**导入 Trace** 把 `.jsonl` 格式的 Trace 文件导入为某个 Agent 的一段对话。
+
+**开始之前**
+
+- 一个从其他部署导出的 `.jsonl` Trace 文件,不超过 14MB。
+- 你是目标 Project 的 owner。
+
+目标 Project 和目标 Agent 都要自己选:Agent 要选,是因为 Trace 文件本身无法指明本机的哪个 Agent;Project 要选,是因为这个对话框里看不出当前打开的是哪个 Project,这也意味着 Trace 可以导入到当前打开的 Project 之外。下拉框只列出你自己拥有的 Project,因为导入是 owner 的操作;一个都没有时,这一行不出现。
+
+1. 在**通用**页的**导入 Trace** 一行选择目标 Project:你拥有当前打开的 Project 时默认选它,否则默认选你拥有的第一个 Project。
+2. 选择目标 Agent,默认是该 Project 的 `default_agent`。
+3. 点击**选择文件**,选中 `.jsonl` 文件,导入随即开始。
+
+Trace 会成为该 Agent 的一段新对话。如果该 Agent 下已有相同 id 的 Session,导入会被拒绝。
+
+导出是反方向的操作,入口和要下载的文件在一起,位于对话的轨迹观测面板中。
+
+## 外观
+
+**外观**页是个人设置。
+
+| 设置 | 选项 | 作用 |
+| --- | --- | --- |
+| **主题** | 浅色 / 深色 / 跟随系统 | 界面主题。 |
+| **终端主题** | 跟随主题 / 浅色 / 深色 | 终端面板有自己的明暗配色,默认跟随应用主题。固定为浅色或深色即与应用主题脱钩,适合只针对一种底色调校过的命令行提示符和 TUI。 |
+| **字号** | 小 / 中 / 大 | 界面字号。 |
+| **主题色** | 灰白、蓝、绿、紫、红、橙 | 界面的主题色。 |
+| **快捷方式悬浮球** | 开 / 关 | 浮在对话区右缘的圆形按钮,展开后是通往工作台各面板和终端的快捷方式。关掉它与点击展开项里的**隐藏悬浮球**效果相同。 |
+| **工具短名** | 开 / 关 | 对话里的工具卡片用短名称呼内置工具(`read_file` 显示为「读取」)。其余工具(含 MCP 工具)和轨迹观测始终显示工具原名,悬停短名也能看到原名。 |
+| **托盘图标** | 开 / 关(默认开启) | 仅桌面应用。见下文。 |
+
+关于**托盘图标**:桌面应用运行期间,会在系统托盘(Windows 的通知区域、macOS 的菜单栏、Linux 的托盘)里常驻一个图标。点击图标回到窗口,右键可以开新会话或退出。
+
+关掉后图标立即消失,无需重启。此后关闭窗口不再收进托盘:macOS 上应用留在 Dock 中,Windows 和 Linux 上则直接退出。
+
+## 账户
+
+**账户**页提供**修改密码**操作。
+
+只有存在可修改的密码时才有这一页。桌面应用自己的窗口用 shell 的一次性 token 登录,从来没有密码,所以没有**账户**页;用密码登录同一台服务器的浏览器仍有这一页。
+
+> [!NOTE]
+> 通过首次登录链接登录时,设置密码不需要输入当前密码,因为这个账户此前的密码从来没有人见过。
+
+### 修改密码
+
+1. 在**账户**页选择**修改密码**。
+2. 在**当前密码**里输入当前密码。通过首次登录链接登录后,这个字段不会显示。
+3. 在**新密码**里输入新密码(至少 8 个字符)。
+4. 在**确认新密码**里再输入一遍。
+5. 选择**保存**。
+
+## 用户管理
+
+**用户管理**页列出服务器上的所有用户。仅管理员可见;桌面应用里的服务器是单用户的,没有这一页。
+
+在这里可以新增用户、重置密码和删除用户。
+
+### 新增用户
+
+1. 在**用户管理**页选择**新增用户**。
+2. 输入**用户名**(2–32 个字符:以小写字母开头,后面只能用小写字母、数字和下划线)和**初始密码**(至少 8 个字符)。
+3. 选择**创建**。
+
+新用户会得到一个名为 `<userId>-default_project` 的默认 Project。仍在使用初始密码的用户会带有「初始密码」徽标。
+
+### 重置用户密码
+
+1. 在**用户管理**页找到用户,选择**重置密码**。
+2. 输入新的**初始密码**,选择**保存**。
+
+重置密码会让该用户的所有登录会话失效,之后须用新密码重新登录。
+
+### 删除用户
+
+> [!WARNING]
+> 删除用户会一并删除其名下的全部 Project,包括数据目录,且不可恢复。
+
+1. 在**用户管理**页找到用户,选择**删除**。
+2. 在对话框中选择**删除**,再选择**确认**。
+
+管理员角色的用户没有删除按钮,服务器也会拒绝删除内置的 admin。
+
+## 代理选项
+
+**代理选项**页仅管理员可见,作用于整台服务器,决定哪些出站流量走代理。
+
+| 设置 | 默认值 | 覆盖范围 |
+| --- | --- | --- |
+| **应用程序使用代理** | 开 | 服务器自身的出站流量:LLM 请求、更新检查、图片抓取。 |
+| **Agent 环境使用代理** | 开 | Agent 命令子进程的环境。 |
+| **代理地址** | 空 | 可选,两个开关共用。留空表示跟随代理环境变量。 |
+
+**代理地址**接受 undici dispatcher 支持的任何代理 URL:`http://`、`https://`、`socks5://` 或 `socks://`,可以带凭据。裸的 `host[:port]` 也可以,存储时会规范化为 `http://…`。其他输入一律拒绝,原因显示在输入框下方。
+
+点击**保存**之前不会写入任何内容。保存时整个表单通过一次 PUT 提交,所以地址被拒时其余各项也不会写入。保存后出站 dispatcher 随即重建,对新建立的连接生效,无需重启。回环地址始终直连。
+
+### 设置并测试代理
+
+**开始之前**
+
+- 你的代理地址,使用上文支持的任意一种格式。
+
+1. 在**代理选项**页的**代理地址**中填入代理地址;留空则跟随代理环境变量。
+2. 打开**应用程序使用代理**,让服务器自身的出站流量走代理。默认已开启。
+3. 打开 **Agent 环境使用代理**,让 Agent 命令子进程的环境也使用代理。默认已开启。
+4. 选择**保存**。地址无效时不会写入任何内容,原因显示在输入框下方。
+5. 在**保存**下方选择**测速**,运行**连通性测速**。
+
+连通性测速测量的是本服务器出站到各模型供应商这一跳。运行前页面会先列出目标:OpenAI、Anthropic、Gemini、DeepSeek、Z.ai 和 BigModel 的模型列表地址。点击**测速**后,向每个目标各发一次不带凭据的 GET 请求,结果先到先显示,每个目标最多等待 5 秒。
+
+- 只要收到 HTTP 响应就算**已连通**,401、403 也算,因为凭据被拒恰好说明域名解析、TCP 连接和 TLS 握手都已走通。已连通的目标会显示耗时。
+- 失败会给出具体原因:连接超时、域名解析失败、连接被拒绝、TLS 握手失败或无法连接。
+
+> [!NOTE]
+> 测速用的是已保存的设置,因为只有保存才会重建出站 dispatcher。如果你改过地址,请先保存再测速。
+
+## 上传限制
+
+**上传限制**页仅管理员可见,作用于整台服务器,用来设置两个以整数 MB 计的大小:
+
+| 字段 | 默认值 | 允许范围 |
+| --- | --- | --- |
+| **单个附件上限(MB)** | 100MB | 1–200MB |
+| **单条消息附件合计上限(MB)** | 120MB | 1–200MB |
+
+合计上限不能低于单个附件上限,否则一个本身合法的附件会发不出去。超出范围的值会被拒绝,原因显示在输入框下方,例如想设「100GB」而在 MB 字段里填了 102400。校验先于写入:一次 PUT 里只要有一个字段不合法,其他字段也都不会写入。
+
+### 修改上传限制
+
+1. 在**上传限制**页的「单个附件上限(MB)」里输入 1 到 200 之间的整数。
+2. 在「单条消息附件合计上限(MB)」里输入 1 到 200 之间的整数,且不能低于单个附件上限。
+3. 选择**保存**。
+
+保存立即生效,无需重启:附件校验和请求体上限都在每次请求时读取这项设置。
+
+## 公司模式
+
+**公司模式**页仅管理员可见,作用于整台服务器。页面上只有**启用公司模式**这一个总开关,默认关闭,需由管理员在这里打开。
+
+开关一拨即生效,没有保存按钮。
+
+关闭后,组织调度器和全部组织路由随之停用,所有人的模式切换也会隐藏。磁盘上的组织不受影响;重新打开后,错过的触发不会补发。
+
+> [!NOTE]
+> 公司模式是内测功能。见[公司模式](/company-mode)。
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index 988f5670..546b3168 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -1,11 +1,217 @@
---
title: Skills & Plugins
-description: Plugins package skills (SKILL.md directories, metadata up front, body on demand) and session hooks (scripts the loop consults) — installed into an Agent's state from one library, versioned by date.
+description: Browse plugins, install Skills and hook packages on an agent, add server plugins to a Project, use Skills in a chat, and write your own.
---
-## Plugins
+A **Skill** is a set of reusable instructions that an agent reads when a task calls for it. A **hook package** is a set of scripts that the harness runs at fixed points of the agent loop. A **plugin** bundles Skills, a hook package, or both. The built-in plugins make up the plugin library, which the Web App's **Plugins** page lists together with [server plugins](#server-plugins), plugins that extend the server rather than an agent.
-The built-in library is a set of **plugins**. A plugin is a directory with a `plugin.json` manifest and the content it ships: **skills** — reusable instructions the model reads on demand — and/or a **hook package** — scripts the harness runs at the loop's hook points (see [The Agent Loop](/agent-loop#stop-hooks)). Installing a plugin puts its skills under `agent_state/skills/` and its hook package under `agent_state/hooks/`, two first-class parts of the Agent State that the rest of this page describes.
+- **Looking for new abilities?** See [Browse plugins](#browse-plugins) and [Install a plugin on an agent](#install-a-plugin-on-an-agent).
+- **An update is waiting?** See [Update installed plugins](#update-installed-plugins).
+- **Want the agent to use a specific Skill?** See [Use a Skill in a chat](#use-a-skill-in-a-chat).
+- **Managing one agent's Skills and hooks?** See [Manage an agent's Skills](#manage-an-agents-skills) and [Hook packages](#hook-packages).
+- **Adding a sandbox backend or another server plugin?** See [Server plugins](#server-plugins).
+- **Writing your own Skill?** See [Write a Skill](#write-a-skill).
+- **Looking for file formats and internals?** See [How it works](#how-it-works).
+
+## Browse plugins
+
+1. In the sidebar, select **Plugins**.
+2. Browse the lists. **Installed plugins** comes first and starts folded; select its header to unfold it. It holds the plugin library, followed by the server plugins the current Project asks for. **Available** lists the server plugins the Project can still add.
+3. To narrow the lists, type in the search box, or pick options in the filter column beside them: **Categories**, **Contains** and **Status**. **Clear filters** clears the picks and the search box. Both lists unfold while a search or filter is active.
+4. Select a library plugin's card to open its details.
+
+Each card shows the plugin's name, a short description, and a line in the form `v<version> · updated N days ago · used by N agents`. The agent count covers the agents in the current Project that have any part of the plugin installed. The tags below that line give the plugin's category (Office Productivity, Software Development, AI App Development, Agent Company or Other), **built in**, and how many Skills and hook packages it ships.
+
+The details show the full description, the hook points the plugin's hook package runs at, and a file browser. The tree on the left has one folder per Skill, with its `SKILL.md` first and its reference files after it, and a **Hooks** folder for the hook scripts. The preview on the right shows the selected file.
+
+The buttons on the right of a card:
+
+| Button | When it appears | What it does |
+| --- | --- | --- |
+| **Manage installs** | Always | Installs the plugin on an agent, or uninstalls it. |
+| **Quick start** | The plugin ships at least one Skill | Opens a new chat draft that uses the Skill. It is available only when the current agent has one of the plugin's Skills installed. |
+| Update | An agent's install is behind the library | Updates those installs. See [Update installed plugins](#update-installed-plugins). |
+
+## Install a plugin on an agent
+
+1. On the **Plugins** page, select **Manage installs** on the plugin's card. The dialog lists every agent in the current Project.
+2. Next to the agent, select **Install**.
+
+The whole plugin is installed: all of its Skills and its hook package. New conversations pick it up right away; running ones pick it up after their next compaction.
+
+To uninstall a plugin, point at **Installed** next to the agent, select **Uninstall**, and confirm. Uninstalling deletes the installed Skill and hook files, including any local edits.
+
+Any Project member can install, update and uninstall plugins.
+
+Other ways to install:
+
+- When you create an agent, pick plugins in the **Plugins** field of the **Create agent** dialog. See [Agents](/agents).
+- The built-in agent `default_agent` gets the whole library when it is initialized, except plugins marked `preinstall: false`. The [Built-in library](#built-in-library) table notes which plugins are not preinstalled.
+- To install a Skill or hook package from outside the library, import it on the agent's settings page. See [Import a Skill](#import-a-skill) and [Import a hook package](#import-a-hook-package).
+
+## Update installed plugins
+
+New versions of the built-in plugins arrive with PenguinHarness updates. An agent keeps its installed copy until you update it. When an install is behind the library, you see:
+
+- a red dot on **Plugins** in the sidebar;
+- a notice at the top of the **Plugins** page, "Changes detected: N to upgrade", with **Update now** and **Dismiss**;
+- an update button on the plugin's card, and an **Update** button next to the agent in **Manage installs**.
+
+To update:
+
+1. Choose what to update:
+ - To update every outdated plugin, select **Update now** in the notice.
+ - To update one plugin on every agent, select the update button on its card.
+ - To update one plugin on one agent, select **Update** next to the agent in **Manage installs**.
+2. Review what the update will touch, then select **Update**.
+
+> [!WARNING]
+> Updating reinstalls the library copy over each agent's installed Skill and hook files. Any local edits are lost, so export a backup first if you need them. See [Manage an agent's Skills](#manage-an-agents-skills).
+
+**Dismiss** hides the notice and the sidebar dot until the library version changes again. The update buttons on the cards stay.
+
+## Use a Skill in a chat
+
+An agent sees the name and description of every installed Skill, and reads a Skill's full instructions when a task calls for it. To make sure it uses a particular Skill:
+
+1. In the message box, select **Skills**, then select one or more Skills. You can also type `/` followed by the Skill's name to select it.
+2. Type your task and send the message.
+
+The selected Skills appear as chips above the text, and the sent message shows "Using skill: *name*". If you send the Skills without any text, the message becomes "use the *name* skill". When a message names a Skill but gives no task, the agent asks what you need before it starts.
+
+The **Skills** menu lists only the Skills installed on the current agent, and it is unavailable while a Task is running.
+
+**Quick start** on a plugin's card does the same in one step: it opens a new chat draft with the Skill selected and "use the *name* skill" filled in, without sending it.
+
+## Manage an agent's Skills
+
+To see the Skills installed on one agent, open **Agents**, select the agent, and open the **Skills** tab.
+
+- Each row shows a Skill's name, short description and version, with two actions: **Export** downloads the Skill as a zip file, and **Uninstall** deletes its directory.
+- **Enable skills** controls whether the agent's system prompt lists the installed Skills. With it off, the agent is not told which Skills exist, but Skills you select in a chat still work.
+- **Skills prompt** is the text that introduces the Skill list in the system prompt. Its `{{SKILL_METADATA}}` placeholder becomes one line per installed Skill.
+
+The Skills tab has no update action and cannot add plugins from the library. Update and install plugins on the **Plugins** page.
+
+### Import a Skill
+
+You can import a Skill from outside the library in two ways. The first is recommended, because the agent reads and reviews the Skill before installing it.
+
+To import it through a chat:
+
+1. On the **Skills** tab, select **Import skill**.
+2. In **Skill source**, enter a web page, a GitHub repository or directory, a local path, or an install command from another ecosystem, such as `npx skills add <name>`.
+3. Select **Open a new chat**. A new chat opens with the prompt filled in. You can also select **Copy prompt** to use the prompt elsewhere.
+4. Send the message. The agent reads the source in full, checks that it is safe, and installs the Skill. If the `skill-porting` Skill is installed, the agent follows its process.
+
+To upload a zip file:
+
+1. On the **Skills** tab, select **Import skill**.
+2. Under **Upload a skill zip**, select **Choose zip file**. The zip must hold `SKILL.md` at its root, or exactly one top-level directory that contains `SKILL.md`.
+3. If a Skill with the same name is already installed, confirm with **Overwrite**. Overwriting replaces all of its files.
+
+A zip file can be up to 14 MB, with at most 200 files, 5 MB per file and 20 MB in total after unpacking.
+
+## Hook packages
+
+A hook package runs scripts at the agent loop's [hook points](/agent-loop#stop-hooks): when you send a message, before a tool call, and when a Task ends. For example, the `goal` plugin's hook package drives [goal mode](/goal-mode). Hook packages usually come with a plugin from the library.
+
+To manage one agent's hook packages, open **Agents**, select the agent, and open the **Hooks** tab.
+
+- **Enable hooks** turns hooks on or off for the whole agent, not one package at a time. With it on, every Session the agent starts runs all installed hook packages. With it off, new Sessions run no hooks, and the packages stay installed. The change takes effect from the next turn; a Task that is already running keeps the setting it started with. Only the Project owner can change this switch.
+- Each row shows a package's name, the hook points it runs at, its description and version, with **Export** and **Uninstall**.
+
+### Import a hook package
+
+To import it through a chat:
+
+1. On the **Hooks** tab, select **Import hook**.
+2. In **Hook source**, enter a URL, a GitHub repository, a local path, a description of the hook you want, or another tool's hook configuration, such as the `hooks` block of a Claude Code `settings.json`.
+3. Select **Open a new chat**, or **Copy prompt**.
+4. Send the message. The agent reads the source, reviews every script, and installs the package on this agent.
+
+To upload a zip file:
+
+1. On the **Hooks** tab, select **Import hook**.
+2. Under **Upload a hook package zip**, select **Choose zip file**. The zip must hold `hooks.json` and the scripts at its root, or in exactly one top-level directory. Every command in `hooks.json` must name a file inside the zip.
+3. If a package with the same name is already installed, confirm with **Overwrite**.
+
+> [!WARNING]
+> An imported hook package takes effect at once. While the agent has hooks on, its scripts run on this machine at every hook point, so import only packages you trust.
+
+## Server plugins
+
+A server plugin extends the server itself rather than an agent: it is an npm package of server modules, such as a sandbox backend. A Project asks for the server plugins it needs, and the server runs every plugin that any of its Projects asks for, so what a plugin contributes is available to every Project.
+
+On the **Plugins** page, a server plugin's row shows its package name, description, version and status, with tags for its categories, **built in** when it ships with PenguinHarness, and its keywords. Select a row to open the plugin's page, with its license, authors, links and documentation. A plugin the registry has no entry for has no page.
+
+To add a server plugin to the current Project:
+
+1. Under **Available**, select **Install** on the plugin's row.
+2. Confirm. Adding or removing a server plugin stops the agent runs in progress in every Project.
+
+To remove one, select **Remove** on its row under **Installed plugins**, and confirm. The plugin leaves the Project's list; nothing is deleted from disk.
+
+Only admins see **Install** and **Remove**. Only plugins that ship with PenguinHarness can be added, so nothing is downloaded. A change applies without restarting the server: the server rebuilds its business surface around the new list, which is why runs in progress stop. Afterwards the row's status reads **running**, **restart to load** when the server could not apply the change without a restart, or **failed to load** with the reason.
+
+The list is the `[plugins]` table of the Project's config; see [Configuration Reference](/configuration#plugins). For the routes, see [Server API](/server-api#plugin-registry-and-project-plugins), and for how the server loads plugins, see [Server Boot and Subsystems](/server-boot#re-assembly).
+
+## Write a Skill
+
+A Skill is a directory under the agent's `agent_state/skills/` that contains a `SKILL.md` file and any other files the `SKILL.md` refers to.
+
+1. Create the directory `agent_state/skills/<name>/`. The directory name is the Skill's name and must match `^[A-Za-z0-9_-]+$`.
+2. In the directory, create `SKILL.md`: a frontmatter block with `name` and `description`, followed by the instructions. See the example below.
+3. Add any other files the `SKILL.md` refers to, such as a `reference/` directory it links to.
+
+```md
+---
+name: my-skill
+description: One-line English description injected into the system prompt.
+---
+
+# My Skill
+
+Concrete steps, boundaries and acceptance criteria...
+```
+
+The agent picks up the Skill the next time its system prompt is assembled. A directory without a `SKILL.md` is not a Skill. Because every read goes straight to the files, you can also edit an installed Skill in place.
+
+A Skill has no icon of its own. An installed Skill or hook package shows the icon of the plugin it came from. One with no plugin icon, such as a Skill you wrote yourself, shows a book for a Skill or a hook for a hook package.
+
+### Improve Skills over time
+
+An agent can rewrite its own `SKILL.md` as part of a Task. Combined with Benchmark evaluation and optimization, this closes the improvement loop; see [Self-Improvement](/self-improvement). When you change a Skill, set `version` to today's date with the next sequence number.
+
+Long Tasks can also feed their lessons back. With the `continual-learning` plugin installed, when a Task ends after more than 30 turns, its stop hook hands a condensed excerpt of the Task to a background subagent. The subagent folds the lasting findings into the relevant `SKILL.md` files; see [The Agent Loop](/agent-loop#stop-hooks).
+
+## Built-in library
+
+The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins/index.ts`; the library directory is the source of truth as plugins are added):
+
+| Category | Plugin | Purpose |
+| --- | --- | --- |
+| Office Productivity | `data-analysis` | Complete data-analysis tasks with bounded evidence inspection, explicit answer-changing decisions, native artifact handling and final output verification |
+| | `use-firecrawl` | Web search and page scraping into clean markdown via the Firecrawl API |
+| | `use-bento-slides` | Author and edit Bento presentations: single-file `.bento.html` decks whose document is JSON, mapping material to charts, morph transitions and state slides |
+| | `humanizer` | Strip AI-writing tells from prose in any language and rewrite it into the register of books, newspapers and encyclopedias (not preinstalled: install from the library when needed) |
+| | `goal` | The stop hook behind [goal mode](/goal-mode): keeps the Session working toward an objective until it is complete, blocked, or out of Token budget (preinstalled) |
+| | `continual-learning` | When a Task ends after more than 30 turns, hands its condensed excerpt to a background subagent that folds the durable findings into the agent's Skills (not preinstalled) |
+| Software Development | `software-development` | Software development end to end, with two Skills: `software-engineering` (investigate, implement and validate with minimal scope) and `web-design` (the Penguin visual language for generated web UIs) |
+| | `use-claude-code` | Run Claude Code on a remote host over SSH: a persistent expect session, headless `-p` with the stdin fix, a tmux-driven interactive TUI and multi-turn continuity (not preinstalled: install from the library when needed) |
+| AI App Development | `agent-development` | Agent development on PenguinHarness, with four Skills: `penguin-sdk` (build agent/AI/RAG apps on the SDK), `unified-llm-api` (call model APIs through `@prismshadow/agenthub`), `penguin-config` (manage model keys, defaults and Vault secrets) and `penguin-orchestration` (drive agents, Sessions, costs and schedules from a shell) |
+| | `model-development` | Model development on your own hardware, with three Skills: `llamafactory` (fine-tune), `ollama` (run local models) and `vllm` (serve behind an OpenAI-compatible endpoint) |
+| | `skill-porting` | Port Skills from external sources (plugin marketplaces, skills.sh registries, GitHub repos or local folders) into the agent after review and normalization |
+| | `agent-tuning` | The tuning loop as four Skills: `agent-initialization` (set an agent up from a requirement), `benchmark-design` (design and calibrate a capability Benchmark), `agent-evaluation` (execute and score one isolated case) and `agent-optimization` (improve the agent from measured results) |
+| Agent Company | `agent-company` | The whole toolkit of [company mode](/company-mode), with seven Skills: `company-setup` (create an organization with the user: one question at a time, a summary to confirm, then `penguin org create`; it never hires or files tickets), `company-employee` (the protocol every desk and ticket Session follows: trigger blocks, the ticket board, blocking, asking the board before heavy or irreversible work, channel etiquette, budgets), `company-ceo` (mission to tickets, hiring, Workspace partitioning, review, reporting to the board), `company-hr` (calendar coverage, hiring and offboarding, evaluation), `company-finance` (budgets, the daily audit, alerts and pauses), `company-research` (a research organization's authors and reviewers: freeze the evaluation harness and the metric, run the experiment loop inside a resource envelope the board approved, keep only what improves the metric, and put every claim through a reviewer who tries to break it) and `company-mirror` (a company of digital twins: one twin per real colleague, bound to that colleague's bot, relaying instead of filing tickets). Not preinstalled: the organization installs it when it creates the CEO and hires employees, and an agent that should be able to create an organization installs it from the library |
+
+## How it works
+
+This section describes the file formats, naming and versioning rules, loading and installation behind the tasks above.
+
+### Plugin file format
+
+A plugin is a directory with a `plugin.json` manifest and the content it ships:
```text
plugins/<plugin>/
@@ -15,56 +221,43 @@ plugins/<plugin>/
└── hooks/*.mjs # at most one hook package: plain Node scripts
```
-`plugin.json`:
+`plugin.json` fields:
| Field | Meaning |
| --- | --- |
| `description` / `description_zh` | One-line description (English required) |
| `short_description` / `short_description_zh` | Card labels (optional; the full description stands in) |
-| `version` | `YYYY.MM.DD.N` — the date plus a sequence number for that day |
-| `category` | One of `office-productivity`, `software-development`, `ai-app-development`, `agent-company`; missing or unknown lands in "Other" |
-| `preinstall` | Optional; `false` keeps the plugin out of `default_agent`'s preinstalled set — install it manually from the library |
+| `version` | `YYYY.MM.DD.N`: the date plus a sequence number for that day |
+| `category` | One of `office-productivity`, `software-development`, `ai-app-development`, `agent-company`; a missing or unknown category lands in "Other" |
+| `preinstall` | Optional; `false` keeps the plugin out of `default_agent`'s preinstalled set, so it is installed only manually from the library |
| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | The hook package's commands per [hook point](/agent-loop#stop-hooks): `[{ "command": "stop.mjs", "timeout": 60 }]`, paths relative to `hooks/`, timeout in seconds |
-The plugin name is its directory name (`^[A-Za-z0-9_-]+$`); a plugin built around someone else's product carries a `use-` prefix (`use-firecrawl`), so the name says what it is for rather than claiming the product. Versions are compared by date, then by sequence number, so `2026.08.29.10` follows `2026.08.29.9`; the manifest's version is the version of everything the plugin ships, and is distinct from the package's npm version (which follows the release). There is no other version scheme.
+### Plugin naming and versioning
-Every plugin is its own npm package — `@penguinharness/<name>`, `plugins/<name>/` in the repo. The loader lives in `@prismshadow/penguin-core`: it reads the plugin names off the host package's dependency list and resolves each package through Node (the desktop app declares the same packages as dependencies, which its installer packs). At runtime the plugin files are the source of truth for library content, read on every call.
+- The plugin name is its directory name and must match `^[A-Za-z0-9_-]+$`.
+- A plugin built around someone else's product carries a `use-` prefix (`use-firecrawl`), so the name says what it is for rather than claiming the product.
+- Versions are compared by date, then by sequence number: `2026.08.29.10` follows `2026.08.29.9`.
+- The manifest's `version` is the version of everything the plugin ships. It is separate from the package's npm version, which follows the release. There is no other version scheme.
+- Every plugin is its own npm package, `@penguinharness/<name>`, at `plugins/<name>/` in the repository. The loader in `@prismshadow/penguin-core` reads the plugin names from the host package's dependency list and resolves each package through Node. The desktop app declares the same packages as dependencies, and its installer packs them. At runtime the plugin files are the source of truth for library content and are read on every call.
-## Anatomy of a Skill
+### Skill file format
-A Skill is a directory containing a `SKILL.md` and any other files the `SKILL.md` references (for example a `reference/` subtree it links to). Skills carry no icon of their own — the icon belongs to the plugin (`icon.svg` beside `plugin.json`), and an installed skill or hook package shows the icon of the plugin it came from; one with no icon (a user-authored skill, say) shows the uniform mark of its kind instead — the book for a skill, the hook for a hook package. The directory name is the authoritative skill name and must match `^[A-Za-z0-9_-]+$`; a `name` in the frontmatter is overridden by it.
+A Skill's directory name is its authoritative name and must match `^[A-Za-z0-9_-]+$`; it overrides any `name` in the frontmatter.
-A library `SKILL.md`'s frontmatter carries only two fields — everything else lives in `plugin.json`:
+A library `SKILL.md` has only two frontmatter fields. Everything else lives in `plugin.json`.
| Field | Meaning |
| --- | --- |
| `name` | Skill name, matching the directory name |
| `description` | English one-liner injected into the system prompt |
-```md
----
-name: my-skill
-description: One-line English description injected into the system prompt.
----
-
-# My Skill
-
-Concrete steps, boundaries and acceptance criteria...
-```
-
-The **installed** copy is self-describing: at load time the library regenerates each skill's frontmatter with the plugin's `short_description`, `short_description_zh` and `version` stamped in (the way an installed hook package's `hooks.json` is generated from the manifest), and that is what gets written into `agent_state/skills/`. Update checks read the installed frontmatter's `version`; the UI reads its short descriptions. Parsing is tolerant: only `key: value` scalar lines inside the first `---` block are recognized, and a `version` that is neither `YYYY.MM.DD.N` nor the legacy `YYYY-MM-DD.N` an older installed copy carries reads as empty — older than any library version, so the library's copy counts as an update.
-
-## Progressive loading
+The installed copy describes itself. At load time the library regenerates each Skill's frontmatter with the plugin's `short_description`, `short_description_zh` and `version` added, the same way an installed hook package's `hooks.json` is generated from the manifest, and writes that into `agent_state/skills/`. Update checks read the installed frontmatter's `version`, and the Web App reads its short descriptions.
-Skills follow an "index first, body on demand" design: the system prompt injects only each installed Skill's metadata (name + description) through the `{{SKILL_METADATA}}` placeholder, and instructs the model to read the matching `SKILL.md` in full via the shell before following it. There is no dedicated skill tool — reading the body is just one `read_file` or shell call (see [Tools & Approval](/tools)).
+Parsing is tolerant: only `key: value` scalar lines inside the first `---` block count. A `version` that is neither `YYYY.MM.DD.N` nor the legacy `YYYY-MM-DD.N` of an older installed copy reads as empty. An empty version is older than any library version, so the library's copy counts as an update.
-Chat can also pin skills explicitly: the message then starts with a `[use_skills]` block listing the skill names (the earlier `<use_skills>` form is still recognized when re-rendering old Traces).
+### Hook package manifest
-If a message only names a skill without a concrete task, the model is instructed to ask what is needed before starting.
-
-## Hook packages
-
-A hook package is the plugin's `hooks/` directory installed as `agent_state/hooks/<plugin>/`, with a generated `hooks.json` beside the scripts — the manifest's identity fields (`name`, `description`, `description_zh`, `version`) plus one command list per hook point:
+An installed hook package is the plugin's `hooks/` directory, installed as `agent_state/hooks/<plugin>/` with a generated `hooks.json` beside the scripts. The manifest holds the plugin's identity fields (`name`, `description`, `description_zh`, `version`) and one command list per hook point:
```json
{
@@ -78,39 +271,25 @@ A hook package is the plugin's `hooks/` directory installed as `agent_state/hook
}
```
-Installed is active: every top-level Session of the Agent consults its installed hook packages at the loop's hook points (a Session already running keeps the set it was built with; the server rebuilds an Agent's cached runtimes on the next idle access after a hook package is installed or removed, or after the switch below is flipped). Hooks are switched as a whole, not one package at a time: `hooks.enabled` in `system_config.yaml` (absent means on) is flipped by the Hooks tab's switch (Project owner only), and with it off a Session created from then on assembles no hooks at all while every package stays on disk. The same tab exports an installed package as a zip and imports one back — `hooks.json` and the scripts at the zip root, or in exactly one top-level directory; every command the manifest lists must name a file inside the archive — or hands the import to an agent, which reads the source and reviews the scripts before installing. The scripts are plain Node with builtins only — they run wherever the harness runs, as subprocesses with JSON on stdin and a JSON answer on stdout; the contract is on [The Agent Loop](/agent-loop#stop-hooks). A hook package's other scripts are the host's to call by convention: the goal plugin's `start.mjs` is what the server runs when a user starts a goal ([Goal Mode](/goal-mode)).
+The scripts are plain Node that uses only built-in modules, so they run wherever the harness runs. Each runs as a subprocess that reads JSON on stdin and writes a JSON answer to stdout; [The Agent Loop](/agent-loop#stop-hooks) describes the contract. Every top-level Session of the agent consults the installed hook packages at the loop's hook points. The `hooks.enabled` key in the agent's `system_config.yaml` holds the **Enable hooks** switch; when the key is absent, hooks are on.
-## Installation and storage
+A hook package's other scripts are for the host to call by convention. For example, the `goal` plugin's `start.mjs` is what the server runs when a user starts a goal; see [Goal Mode](/goal-mode).
-Installed Skills live under `agent_state/skills/<name>/`, hook packages under `agent_state/hooks/<name>/`. The files are the source of truth: every read goes straight to disk with no cache, which makes Skills naturally editable.
+### Progressive loading
-- The built-in Agent `default_agent` gets the whole library installed at initialization, except plugins marked `preinstall: false` — those are only ever installed manually;
-- other Agents install on demand — through the Web UI's plugin library page, or via the SDK;
-- installing a skill writes its installable `SKILL.md` (the frontmatter regenerated with the plugin's metadata, see above), the plugin's `icon.svg`, and any other files in the skill directory (subdirectories preserved) alongside it (a user-authored or imported skill may include its own `icon.svg`, which is copied instead); installing a hook package writes `hooks.json`, the plugin's `icon.svg` and every file under the plugin's `hooks/`. Each install replaces the whole directory, so reinstalling drops files a newer version no longer ships — reinstalling is how an installed copy is updated, and the Agents page flags a plugin whose installed skill or hook package is behind the library.
+Skills load in two steps: the index first, the body on demand.
-## Built-in library
+- The system prompt's `{{SKILLS}}` placeholder expands to the **Skills prompt**, whose `{{SKILL_METADATA}}` placeholder lists each installed Skill's name and description. Nothing is injected when **Enable skills** is off or the template has no `{{SKILLS}}` placeholder.
+- The prompt tells the model to read the matching `SKILL.md` in full before it follows the Skill. There is no dedicated Skill tool: reading the body is one `read_file` or shell call; see [Tools & Approval](/tools).
+- When you select Skills in a chat, the message starts with a `[use_skills]` block that lists their names. The earlier `<use_skills>` form is still recognized when old Traces are displayed.
-The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins/index.ts`; the library directory is the source of truth as plugins are added):
+### Installation and storage
-| Category | Plugin | Purpose |
-| --- | --- | --- |
-| Office Productivity | `data-analysis` | Complete data-analysis tasks with bounded evidence inspection, explicit answer-changing decisions, native artifact handling and final output verification |
-| | `use-firecrawl` | Web search and page scraping into clean markdown via the Firecrawl API |
-| | `use-bento-slides` | Author and edit Bento presentations: single-file `.bento.html` decks whose document is JSON, mapping material to charts, morph transitions and state slides |
-| | `humanizer` | Strip AI-writing tells from prose in any language and rewrite it into the register of books, newspapers and encyclopedias (not preinstalled: install from the library when needed) |
-| | `goal` | The stop hook behind [goal mode](/goal-mode): keeps the session working toward an objective until it is complete, blocked, or out of token budget (preinstalled) |
-| | `continual-learning` | When a task ends after more than 30 turns, hands its condensed excerpt to a background subagent that folds the durable findings into the agent's skills (not preinstalled) |
-| Software Development | `software-development` | Software development end to end — two skills: `software-engineering` (investigate, implement and validate with minimal scope) and `web-design` (the Penguin visual language for generated web UIs) |
-| | `use-claude-code` | Run Claude Code on a remote host over SSH — a persistent expect session, headless `-p` with the stdin fix, a tmux-driven interactive TUI and multi-turn continuity (not preinstalled: install from the library when needed) |
-| AI App Development | `agent-development` | Agent development on PenguinHarness — four skills: `penguin-sdk` (build agent/AI/RAG apps on the SDK), `unified-llm-api` (call model APIs through `@prismshadow/agenthub`), `penguin-config` (manage model keys, defaults and Vault secrets) and `penguin-orchestration` (drive agents, sessions, costs and schedules from a shell) |
-| | `model-development` | Model development on your own hardware — three skills: `llamafactory` (fine-tune), `ollama` (run local models) and `vllm` (serve behind an OpenAI-compatible endpoint) |
-| | `skill-porting` | Port skills from external sources — plugin marketplaces, skills.sh registries, GitHub repos or local folders — into the agent after review and normalization |
-| | `agent-tuning` | The tuning loop as four skills: `agent-initialization` (set an agent up from a requirement), `benchmark-design` (design and calibrate a capability Benchmark), `agent-evaluation` (execute and score one isolated Case) and `agent-optimization` (improve the agent from measured results) |
-| Agent Company | `agent-company` | The whole toolkit of [company mode](/company-mode) — seven skills: `company-setup` (create an organization with the user: one question at a time, a summary to confirm, then `penguin org create` — it never hires or files tickets), `company-employee` (the protocol every desk and ticket session follows: trigger blocks, the ticket board, blocking, asking the board before heavy or irreversible work, channel etiquette, budgets), `company-ceo` (mission to tickets, hiring, workspace partitioning, review, reporting to the board), `company-hr` (calendar coverage, hiring and offboarding, evaluation), `company-finance` (budgets, the daily audit, alerts and pauses), `company-research` (a research organization's authors and reviewers: fix the harness and the metric, run the experiment loop inside a resource envelope the board approved, keep only improvements, and put every claim through a reviewer who tries to break it) and `company-mirror` (a company of digital twins: one twin per real colleague, bound to that colleague's bot, relaying instead of filing tickets) (not preinstalled: the organization installs it when it creates the CEO and hires employees, and an Agent that should be able to create one installs it from the library) |
-
-## Writing and optimizing Skills
-
-- Manual install: create a directory under `agent_state/skills/<name>/` and write a `SKILL.md`; the system scans `skills/` when assembling the system prompt and injects the metadata. A directory without a `SKILL.md` does not count as a Skill.
-- Uninstalling deletes the whole `skills/<name>/` (or `hooks/<name>/`) directory and is idempotent.
-- An Agent can rewrite its own SKILL.md as part of a task — combined with Benchmark evaluation and optimization this closes the improvement loop, see [Self-Improvement](/self-improvement). Bump `version` to today's date with the next sequence number when you do.
-- Long tasks can feed back on their own: with the `continual-learning` plugin installed, a task that ends after more than 30 turns has its stop hook hand a condensed excerpt of that task to a background subagent, which folds the durable findings into the relevant SKILL.md files — see [The Agent Loop](/agent-loop#stop-hooks).
+Installed Skills live under `agent_state/skills/<name>/`, and hook packages under `agent_state/hooks/<name>/`. The files are the source of truth: every read goes straight to disk with no cache.
+
+- Installing a Skill writes its installable `SKILL.md` (with the regenerated frontmatter), the plugin's `icon.svg`, and the other files in the Skill directory, keeping subdirectories. A Skill you write or import may include its own `icon.svg`, which is copied instead.
+- Installing a hook package writes `hooks.json`, the plugin's `icon.svg`, and every file under the plugin's `hooks/`.
+- Each install replaces the whole directory, so reinstalling drops files a newer version no longer ships. Reinstalling is how an installed copy is updated.
+- Uninstalling deletes the whole `skills/<name>/` or `hooks/<name>/` directory.
+- A running Session keeps the hook packages it was built with. After a hook package is installed or removed, or the **Enable hooks** switch changes, the server rebuilds the agent's cached runtimes the next time they are idle.
+- Besides the Web App, plugins can be installed through the SDK.
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index 4f58c601..e3bfc573 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -1,45 +1,168 @@
---
title: 技能与插件
-description: 插件打包 Skill(目录加 SKILL.md,元数据先行、正文按需读取)与会话钩子(循环在固定点执行的脚本)——同一个库装进 Agent State,版本按日期编号。
+description: 浏览插件,为 Agent 安装 Skill 和钩子包,为 Project 添加服务端插件,在对话中使用 Skill,编写自己的 Skill。
---
-## 插件
+**Skill** 是一组可复用的指令,Agent 在任务用得上时才去读取。**钩子包**是一组脚本,由 harness 在 Agent 循环的固定节点运行。**插件**可以包含 Skill、钩子包,或两者都有。全部内置插件组成插件库,列在 Web App 的**插件市场**页面上;同一页面还列出[服务端插件](#服务端插件),这类插件扩展的是服务器,而不是 Agent。
-内置库由一组**插件**组成。一个插件就是一个目录:一份 `plugin.json` 清单,加上它携带的内容——**Skill**(模型按需读取的可复用指令)和/或一个**钩子包**(harness 在循环固定点上运行的脚本,见[运行循环](/agent-loop#stop-hook))。安装插件即把它的 Skill 放进 `agent_state/skills/`、钩子包放进 `agent_state/hooks/`——Agent State 里并列的两个一等成员,本页其余部分分别介绍。
+- **想给 Agent 添加新能力?** 见[浏览插件](#浏览插件)和[在 Agent 上安装插件](#在-agent-上安装插件)。
+- **有更新可装?** 见[更新已安装的插件](#更新已安装的插件)。
+- **想让 Agent 用上指定的 Skill?** 见[在对话中使用 Skill](#在对话中使用-skill)。
+- **要管理某个 Agent 的 Skill 和钩子?** 见[管理 Agent 的 Skill](#管理-agent-的-skill) 和[钩子包](#钩子包)。
+- **要添加沙箱后端或其他服务端插件?** 见[服务端插件](#服务端插件)。
+- **想自己写 Skill?** 见[编写 Skill](#编写-skill)。
+- **想了解文件格式和内部机制?** 见[工作原理](#工作原理)。
-```text
-plugins/<plugin>/
-├── plugin.json # 清单——插件唯一的元数据载体
-├── icon.svg # 插件图标(每个内置插件都有)
-├── skills/<name>/SKILL.md # 零个或多个 Skill(reference/… 随行)
-└── hooks/*.mjs # 至多一个钩子包:纯 Node 脚本
-```
+## 浏览插件
-`plugin.json`:
+1. 在侧边栏选择**插件市场**。
+2. 浏览列表。**已安装的插件**排在最前,默认折叠,点击标题即可展开。其中先是插件库,然后是当前 Project 要求的服务端插件。**可安装**列出 Project 还可以添加的服务端插件。
+3. 要缩小范围,可以在搜索框中输入,或在列表旁的筛选栏中勾选选项:**分类**、**包含**和**状态**。**清除筛选**会清空已选的选项和搜索框。有搜索词或筛选条件时,两个列表都会展开。
+4. 点击插件库插件的卡片打开详情。
-| 字段 | 说明 |
-| --- | --- |
-| `description` / `description_zh` | 单行描述(英文必填) |
-| `short_description` / `short_description_zh` | 卡片短标签(可选;缺省显示完整描述) |
-| `version` | `YYYY.MM.DD.N`——日期加当日序号 |
-| `category` | `office-productivity`、`software-development`、`ai-app-development`、`agent-company` 之一;缺失或未知归入「其他」 |
-| `preinstall` | 可选;`false` 表示不进入 `default_agent` 的预装集合,仅可从插件库手动安装 |
-| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | 钩子包在各[钩子点](/agent-loop#stop-hook)的命令:`[{ "command": "stop.mjs", "timeout": 60 }]`,路径相对 `hooks/`,超时以秒计 |
+每张卡片显示插件名称、简短描述,以及一行形如 `v<版本> · N 天前更新 · N 个 Agent 在用` 的信息。其中的 Agent 数量,统计的是当前 Project 里装了这个插件任意部分的 Agent。这一行下方的标签依次标出插件的分类(办公效率、软件开发、AI 应用开发、Agent 公司或其他)、**内置**,以及插件包含的 Skill 和钩子包数量。
-插件名即目录名(`^[A-Za-z0-9_-]+$`);围绕他人产品构建的插件带 `use-` 前缀(如 `use-firecrawl`),名字说明用途而不冒用产品名。版本先比日期、再比序号,因此 `2026.08.29.10` 排在 `2026.08.29.9` 之后;清单里的版本就是插件携带的一切内容的版本,与该包的 npm 版本(跟随发行版本)是两回事。没有别的版本方案。
+详情里有完整描述、插件的钩子包在哪些钩子点运行,以及一个文件浏览器。左侧目录树中,每个 Skill 对应一个文件夹,`SKILL.md` 排在最前,参考文件跟在后面;另有一个**钩子**文件夹存放钩子脚本。右侧预览区显示选中的文件。
-每个插件都是独立的 npm 包——`@penguinharness/<name>`,仓库内位于 `plugins/<name>/`。loader 在 `@prismshadow/penguin-core` 里:从宿主包的依赖清单读出插件名,再逐包经 Node 解析(desktop 应用把同样的包声明为依赖,随安装包一并打包)。运行时库内容的事实源仍是插件文件本身,每次调用直接读取。
+卡片右侧的按钮:
-## Skill 的形态
+| 按钮 | 出现时机 | 作用 |
+| --- | --- | --- |
+| **管理安装** | 始终显示 | 把插件安装到 Agent 上,或者卸载。 |
+| **快捷调用** | 插件至少包含一个 Skill | 打开一个使用该 Skill 的新对话草稿。只有当前 Agent 装了这个插件的某个 Skill 时才可用。 |
+| 更新 | 有 Agent 上的安装落后于插件库 | 更新这些安装,见[更新已安装的插件](#更新已安装的插件)。 |
-一个 Skill 就是一个目录:内含一份 `SKILL.md`,以及它引用的其他文件(例如链接到的 `reference/` 子目录)。Skill 本身不带图标——图标属于插件(`plugin.json` 同级的 `icon.svg`),已装 Skill 与钩子包显示的是所属插件的图标;没有图标的(例如用户自建的 Skill)显示该类事物的统一图形——Skill 是书本,钩子包是钩子。目录名即权威的 Skill 名,须匹配 `^[A-Za-z0-9_-]+$`;frontmatter 中的 `name` 以目录名为准。
+## 在 Agent 上安装插件
-库内 `SKILL.md` 的 frontmatter 只有两个字段——其余全部放在 `plugin.json`:
+1. 在**插件市场**页面,点击插件卡片上的**管理安装**。对话框会列出当前 Project 里的所有 Agent。
+2. 在 Agent 旁边点击**安装**。
-| 字段 | 说明 |
-| --- | --- |
-| `name` | Skill 名,与目录名一致 |
-| `description` | 英文单行描述,注入系统 Prompt |
+安装的是整个插件:包括全部 Skill 和钩子包。新对话立即生效;正在运行的对话在下一次压缩后生效。
+
+卸载插件:把鼠标移到 Agent 旁的**已安装**上,点击**卸载**并确认。卸载会删除已安装的 Skill 和钩子文件,包括本地做过的修改。
+
+任何 Project 成员都可以安装、更新和卸载插件。
+
+其他安装方式:
+
+- 创建 Agent 时,在**创建 Agent** 对话框的**插件**字段里选择插件,见[智能体](/agents)。
+- 内置 Agent `default_agent` 初始化时会装上整个插件库,标记了 `preinstall: false` 的插件除外。[内置插件库](#内置插件库)的表格注明了哪些插件不预装。
+- 插件库之外的 Skill 或钩子包,可以在 Agent 的设置页导入,见[导入 Skill](#导入-skill) 和[导入钩子包](#导入钩子包)。
+
+## 更新已安装的插件
+
+内置插件的新版本随 PenguinHarness 更新一起发布。在你更新之前,Agent 会一直保留已安装的副本。当某个安装落后于插件库时,你会看到:
+
+- 侧边栏**插件市场**上出现红点;
+- **插件市场**页面顶部出现「检测到变更:N 个可升级」提示,带**现在升级**和**忽略**按钮;
+- 插件卡片上出现更新按钮,**管理安装**里 Agent 旁边出现**更新**按钮。
+
+更新方法:
+
+1. 选择更新范围:
+ - 更新所有落后的插件:点击提示里的**现在升级**。
+ - 更新某个插件在所有 Agent 上的安装:点击它卡片上的更新按钮。
+ - 更新某个插件在某个 Agent 上的安装:在**管理安装**里点击 Agent 旁的**更新**。
+2. 确认更新会涉及的范围,然后点击**更新**。
+
+> [!WARNING]
+> 更新会用插件库里的副本重装每个 Agent 上已安装的 Skill 和钩子文件,本地修改会全部丢失。需要保留的话,先导出备份,见[管理 Agent 的 Skill](#管理-agent-的-skill)。
+
+**忽略**会隐藏提示和侧边栏红点,直到插件库版本再次变化。卡片上的更新按钮仍然保留。
+
+## 在对话中使用 Skill
+
+Agent 能看到每个已安装 Skill 的名称和描述,任务需要时才读取 Skill 的完整指令。要确保 Agent 使用某个指定 Skill:
+
+1. 在消息输入框点击**技能**,然后选择一个或多个 Skill。也可以输入 `/` 加 Skill 名称来选择。
+2. 输入任务内容,发送消息。
+
+选中的 Skill 以标签形式显示在文本上方,发出的消息会显示「使用技能:*name*」。如果只发送 Skill 不带任何文字,消息会变成「使用 *name* 技能」。消息提到某个 Skill 却没有给出任务时,Agent 会先询问你需要什么,再开始执行。
+
+**技能**菜单只列出当前 Agent 上已安装的 Skill,Task 运行期间不可用。
+
+插件卡片上的**快捷调用**一步就能做到同样的事:打开一个新对话草稿,选好 Skill 并填入「使用 *name* 技能」,但不会发送。
+
+## 管理 Agent 的 Skill
+
+要查看某个 Agent 上安装的 Skill,打开**智能体**,选中这个 Agent,然后打开**技能**标签页。
+
+- 每行显示一个 Skill 的名称、简短描述和版本,附两个操作:**打包导出**把 Skill 下载为 zip 文件,**卸载**删除 Skill 目录。
+- **启用技能**控制系统提示词中是否列出已安装的 Skill。关闭后,Agent 不知道存在哪些 Skill,但你在对话中选中的 Skill 仍然生效。
+- **技能提示词**是系统提示词里介绍 Skill 列表的一段文字。其中的 `{{SKILL_METADATA}}` 占位符会展开为每个已安装 Skill 一行。
+
+**技能**标签页没有更新操作,也不能从插件库添加插件。更新和安装插件请前往**插件市场**页面。
+
+### 导入 Skill
+
+导入插件库之外的 Skill 有两种方式。推荐第一种:Agent 会先读取并审查 Skill,然后再安装。
+
+通过对话导入:
+
+1. 在**技能**标签页点击**导入技能**。
+2. 在**技能来源**中填入网页、GitHub 仓库或目录、本地路径,或者其他生态的安装命令,例如 `npx skills add <name>`。
+3. 点击**打开新对话**。新对话打开后,Prompt 已经填好。也可以点击**复制 Prompt**,拿到别处使用。
+4. 发送消息。Agent 会完整读取来源,检查是否安全,然后安装 Skill。如果安装了 `skill-porting` Skill,Agent 会按它的流程操作。
+
+通过上传 zip 文件导入:
+
+1. 在**技能**标签页点击**导入技能**。
+2. 在**上传技能 zip 包**下点击**选择 zip 文件**。zip 包的根目录下必须有 `SKILL.md`,或者有且仅有一个包含 `SKILL.md` 的顶层目录。
+3. 如果已安装同名 Skill,点击**覆盖安装**确认。覆盖安装会替换全部文件。
+
+zip 文件最大 14 MB,最多 200 个文件;解压后单个文件不超过 5 MB,总量不超过 20 MB。
+
+## 钩子包
+
+钩子包在 Agent 循环的[钩子点](/agent-loop#stop-hook)运行脚本:你发送消息时、工具调用之前,以及 Task 结束时。比如[目标模式](/goal-mode)就由 `goal` 插件的钩子包驱动。钩子包通常随插件库里的插件一起安装。
+
+要管理某个 Agent 的钩子包,打开**智能体**,选中这个 Agent,然后打开**钩子**标签页。
+
+- **启用钩子**是整个 Agent 的钩子总开关,不能按包单独开关。开启时,这个 Agent 启动的每个 Session 都会运行全部已安装的钩子包;关闭时,新 Session 不运行任何钩子,已安装的包仍然保留。改动从下一轮开始生效,已经在运行的 Task 沿用它开始时的设置。只有 Project owner 能改这个开关。
+- 每行显示包的名称、运行的钩子点、描述和版本,附**打包导出**和**卸载**两个操作。
+
+### 导入钩子包
+
+通过对话导入:
+
+1. 在**钩子**标签页点击**导入钩子**。
+2. 在**钩子来源**中填入 URL、GitHub 仓库、本地路径、描述你想要的钩子的一段文字,或者其他工具的钩子配置,例如 Claude Code `settings.json` 里的 `hooks` 块。
+3. 点击**打开新对话**或**复制 Prompt**。
+4. 发送消息。Agent 会读取来源,审查每个脚本,然后把包安装到这个 Agent 上。
+
+通过上传 zip 文件导入:
+
+1. 在**钩子**标签页点击**导入钩子**。
+2. 在 **上传钩子包 zip** 下方点击**选择 zip 文件**。zip 包的根目录下,或唯一一个顶层目录里,必须有 `hooks.json` 和脚本文件。`hooks.json` 里的每个命令都必须指向 zip 包内的文件。
+3. 如果已安装同名包,点击**覆盖安装**确认。
+
+> [!WARNING]
+> 导入的钩子包立即生效。只要 Agent 开着钩子,这些脚本就会在本机的每个钩子点运行,请只导入你信任的包。
+
+## 服务端插件
+
+服务端插件扩展的是服务器本身,而不是 Agent:它是一个由服务端模块组成的 npm 包,例如沙箱后端。每个 Project 声明自己需要的服务端插件,服务器运行任一 Project 要求的全部插件,因此插件提供的能力对所有 Project 都可用。
+
+在**插件市场**页面上,服务端插件的一行显示包名、描述、版本和状态,标签标出它的分类、随 PenguinHarness 发布时的**内置**,以及关键词。点击这一行打开插件页面,查看许可证、作者、链接和说明文档。市场里没有条目的插件没有页面。
+
+为当前 Project 添加服务端插件:
+
+1. 在**可安装**下,点击插件那一行的**安装**。
+2. 确认。添加或移除服务端插件会中止所有 Project 中正在进行的 Agent 运行。
+
+移除插件:在**已安装的插件**下点击它那一行的**移除**,然后确认。插件会从 Project 的列表中去掉,磁盘上的文件不会被删除。
+
+只有管理员能看到**安装**和**移除**。只能添加随 PenguinHarness 发布的插件,因此不会下载任何东西。改动无需重启服务器即可生效:服务器围绕新列表重建业务面,所以正在进行的运行会被中止。之后,这一行的状态显示为**运行中**;服务器无法免重启应用改动时显示**待重启**;加载失败时显示**加载失败**并附上原因。
+
+列表就是 Project 配置中的 `[plugins]` 表,见[配置参考](/configuration#插件)。路由见 [Server API](/server-api#插件注册表与-project-插件),服务器如何加载插件见 [Server 启动与子系统](/server-boot#重组)。
+
+## 编写 Skill
+
+一个 Skill 就是一个目录,位于 Agent 的 `agent_state/skills/` 下,里面有 `SKILL.md` 文件,以及 `SKILL.md` 引用的其他文件。
+
+1. 创建目录 `agent_state/skills/<name>/`。目录名就是 Skill 名称,必须匹配 `^[A-Za-z0-9_-]+$`。
+2. 在目录里创建 `SKILL.md`:先写一个包含 `name` 和 `description` 的 frontmatter 块,后面写正文指令。示例如下。
+3. 添加 `SKILL.md` 引用的其他文件,比如它链接到的 `reference/` 目录。
```md
---
@@ -49,22 +172,92 @@ description: One-line English description injected into the system prompt.
# My Skill
-具体的步骤、边界与验收标准……
+Concrete steps, boundaries and acceptance criteria...
```
-**已安装**的副本是自描述的:库在读取时把插件的 `short_description`、`short_description_zh` 与 `version` 盖章进各 Skill 的 frontmatter 重新生成(如同已装钩子包的 `hooks.json` 由清单生成),写进 `agent_state/skills/` 的就是这份内容。更新检查读已装 frontmatter 的 `version`,UI 读它的短标签。解析是容错的:只识别首个 `---` 块内的 `key: value` 标量行;`version` 既不是 `YYYY.MM.DD.N`、也不是旧副本里的旧写法 `YYYY-MM-DD.N` 时读作空——比库里任何版本都旧,于是库内副本算作可更新。
+下次组装系统提示词时,Agent 就会加载这个 Skill。没有 `SKILL.md` 的目录不算 Skill。由于每次读取都直接访问文件,你也可以就地修改已安装的 Skill。
-## 渐进式加载
+Skill 自身没有图标。已安装的 Skill 或钩子包显示来源插件的图标。没有插件图标时(比如你自己写的 Skill),Skill 显示书本图标,钩子包显示钩子图标。
-Skill 采用「先索引、后正文」的设计:系统 Prompt 经 `{{SKILL_METADATA}}` 占位符只注入每个已安装 Skill 的元数据(name + description),并指示模型在任务匹配某个 Skill 时,先用 Shell 完整读取对应的 `SKILL.md`,再遵循执行。系统不设专门的 Skill 工具,读取正文就是一次 `read_file` 或 Shell 调用(见 [工具与审批](/tools))。
+### 持续改进 Skill
-对话中也可以显式指定 Skill:此时消息以 `[use_skills]` 块开头,列出要使用的 Skill 名(重新渲染旧 Trace 时仍识别早期的 `<use_skills>` 形式)。
+Agent 可以在 Task 中重写自己的 `SKILL.md`。结合 Benchmark 评估和优化,这就形成了完整的改进闭环;参见[自我进化](/self-improvement)。修改 Skill 时,把 `version` 设为当天的日期加下一个序号。
-若消息只点名 Skill 而没有给出具体任务,模型会先询问需求再开始。
+长 Task 也能把经验沉淀回来。装上 `continual-learning` 插件后,一个 Task 运行超过 30 轮才结束时,插件的 stop 钩子会把这个 Task 的精简摘录交给一个后台子 Agent,由它把有长期价值的发现写进相关的 `SKILL.md` 文件,见 [Agent 循环](/agent-loop#stop-hook)。
-## 钩子包
+## 内置插件库
-钩子包就是插件的 `hooks/` 目录,安装为 `agent_state/hooks/<plugin>/`,脚本旁边生成一份 `hooks.json`——清单的身份字段(`name`、`description`、`description_zh`、`version`)加上每个钩子点各一份命令清单:
+内置插件按分类列出(`PLUGIN_CATEGORIES` 定义于 `packages/core/src/plugins/index.ts`;插件会陆续增加,以插件库目录为准):
+
+| 分类 | 插件 | 用途 |
+| --- | --- | --- |
+| 办公效率 | `data-analysis` | 完成数据分析任务:有限度地检查证据,明确决定是否修改答案,原生处理产出文件,并核验最终输出 |
+| | `use-firecrawl` | 通过 Firecrawl API 搜索网页、抓取页面,输出干净的 markdown |
+| | `use-bento-slides` | 创建和编辑 Bento 演示文稿:单文件 `.bento.html` 幻灯片,文件内容为 JSON,支持素材到图表的映射、morph 过渡和状态幻灯片 |
+| | `humanizer` | 去除任何语言文字中的 AI 写作痕迹,改写成书籍、报纸和百科全书的语体(不预装:需要时从插件库安装) |
+| | `goal` | [目标模式](/goal-mode)背后的 stop 钩子:让 Session 持续朝着目标推进,直到完成、受阻或 Token 预算耗尽(预装) |
+| | `continual-learning` | Task 运行超过 30 轮才结束时,把 Task 的精简摘录交给后台子 Agent,由它把有长期价值的发现沉淀到 Agent 的 Skill 中(不预装) |
+| 软件开发 | `software-development` | 端到端的软件开发,包含两个 Skill:`software-engineering`(在最小范围内调查、实现和验证)和 `web-design`(生成 Web UI 用的 Penguin 视觉语言) |
+| | `use-claude-code` | 通过 SSH 在远程主机上运行 Claude Code:持久 expect 会话、带 stdin 修复的无头 `-p` 模式、tmux 驱动的交互式 TUI,以及多轮连续性(不预装:需要时从插件库安装) |
+| AI 应用开发 | `agent-development` | PenguinHarness 上的 Agent 开发,包含四个 Skill:`penguin-sdk`(基于 SDK 构建 Agent/AI/RAG 应用)、`unified-llm-api`(通过 `@prismshadow/agenthub` 调用模型 API)、`penguin-config`(管理模型密钥、默认值和 Vault 机密)和 `penguin-orchestration`(在 shell 里驱动 Agent、Session、成本和定时任务) |
+| | `model-development` | 在自己的硬件上做模型开发,包含三个 Skill:`llamafactory`(微调)、`ollama`(运行本地模型)和 `vllm`(在 OpenAI 兼容端点后面提供服务) |
+| | `skill-porting` | 把外部来源(插件市场、skills.sh 注册表、GitHub 仓库或本地文件夹)的 Skill 经审查和规范化后移植到 Agent |
+| | `agent-tuning` | 用四个 Skill 构成调优闭环:`agent-initialization`(根据需求搭建 Agent)、`benchmark-design`(设计和校准能力 Benchmark)、`agent-evaluation`(隔离执行单个题目并打分)和 `agent-optimization`(根据实测结果改进 Agent) |
+| Agent 公司 | `agent-company` | [公司模式](/company-mode)的完整工具包,包含七个 Skill:`company-setup`(与用户一起创建组织:一次问一个问题、给出摘要供确认,然后执行 `penguin org create`;从不招聘,也不提交工单)、`company-employee`(每个工位 Session 和工单 Session 都要遵循的协议:触发块、工单看板、阻塞、重负载或不可逆的工作先向董事会请示、频道礼仪、预算)、`company-ceo`(把使命拆解为工单、招聘、划分 Workspace、审查、向董事会汇报)、`company-hr`(日历排班、招聘与离职、评估)、`company-finance`(预算、每日审计、告警与暂停)、`company-research`(科研组织的作者与审稿人:先固定评测脚本与指标,在董事会批准的资源额度内跑实验循环、只保留能提升指标的改动,每个结论都交给一个设法推翻它的审稿人)和 `company-mirror`(数字分身公司:每位真实同事对应一个分身,绑定到这位同事的机器人,只传话、不开工单)。不预装:组织在创建 CEO、招聘员工时会安装它;需要能创建组织的 Agent 则从插件库安装 |
+
+## 工作原理
+
+本节介绍上文各项操作背后的文件格式、命名和版本规则,以及加载与安装机制。
+
+### 插件文件格式
+
+插件是一个目录,包含一份 `plugin.json` 清单和插件发布的内容:
+
+```text
+plugins/<plugin>/
+├── plugin.json # manifest — the plugin's single metadata holder
+├── icon.svg # the plugin's icon (every built-in plugin ships one)
+├── skills/<name>/SKILL.md # zero or more skills (reference/… alongside)
+└── hooks/*.mjs # at most one hook package: plain Node scripts
+```
+
+`plugin.json` 字段:
+
+| 字段 | 含义 |
+| --- | --- |
+| `description` / `description_zh` | 一行描述(英文必填) |
+| `short_description` / `short_description_zh` | 卡片上显示的简短文案(可选;不填则使用完整描述) |
+| `version` | `YYYY.MM.DD.N`:日期加当天的序号 |
+| `category` | `office-productivity`、`software-development`、`ai-app-development`、`agent-company` 之一;缺失或未知的分类归入「其他」 |
+| `preinstall` | 可选;设为 `false` 的插件不进入 `default_agent` 的预装集合,只能从插件库手动安装 |
+| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | 钩子包在各个[钩子点](/agent-loop#stop-hook)运行的命令:`[{ "command": "stop.mjs", "timeout": 60 }]`,路径以 `hooks/` 为起点,timeout 单位为秒 |
+
+### 插件命名与版本
+
+- 插件名就是目录名,必须匹配 `^[A-Za-z0-9_-]+$`。
+- 围绕他人产品打造的插件带 `use-` 前缀(如 `use-firecrawl`),名称只表明用途,而不冒充产品本身。
+- 版本先按日期比较,再按序号比较:`2026.08.29.10` 排在 `2026.08.29.9` 之后。
+- 清单里的 `version` 是插件所含全部内容的版本,与 npm 包版本相互独立;npm 版本跟随产品发布。除此之外没有其他版本方案。
+- 每个插件都是一个独立的 npm 包 `@penguinharness/<name>`,位于仓库的 `plugins/<name>/`。`@prismshadow/penguin-core` 中的加载器从宿主包的依赖列表读取插件名,并通过 Node 解析各个包。桌面应用把同样的包声明为依赖,安装器会将它们打包。运行时,插件文件就是插件库内容的唯一事实来源,每次调用都直接读取。
+
+### Skill 文件格式
+
+Skill 的目录名是权威名称,必须匹配 `^[A-Za-z0-9_-]+$`,并覆盖 frontmatter 中的任何 `name`。
+
+插件库中的 `SKILL.md` 只有两个 frontmatter 字段,其余信息都在 `plugin.json` 里。
+
+| 字段 | 含义 |
+| --- | --- |
+| `name` | Skill 名称,与目录名一致 |
+| `description` | 注入系统提示词的英文单行描述 |
+
+已安装的副本自带描述。加载时,插件库会重新生成每个 Skill 的 frontmatter,加上插件的 `short_description`、`short_description_zh` 和 `version`,然后写入 `agent_state/skills/`,做法与已安装钩子包的 `hooks.json` 由清单生成时一致。更新检查读取安装副本 frontmatter 里的 `version`,Web App 则读取其中的简短描述。
+
+解析很宽容:只有第一个 `---` 块里的 `key: value` 标量行才算数。`version` 既不是 `YYYY.MM.DD.N`、也不是旧版安装副本使用的 `YYYY-MM-DD.N` 时,就按空值处理。空版本比任何插件库版本都旧,所以插件库里的副本算作可用的更新。
+
+### 钩子包清单
+
+安装后的钩子包就是插件的 `hooks/` 目录,安装为 `agent_state/hooks/<plugin>/`,脚本旁边附带一份生成的 `hooks.json`。清单保存插件的标识字段(`name`、`description`、`description_zh`、`version`),以及每个钩子点各自的命令列表:
```json
{
@@ -78,39 +271,25 @@ Skill 采用「先索引、后正文」的设计:系统 Prompt 经 `{{SKILL_ME
}
```
-装了即生效:Agent 的每个顶层 Session 都会在循环的钩子点上咨询已安装的钩子包(正在运行的 Session 保持构建时的那套;安装或卸载钩子包、以及下述开关变动后,服务端会在该 Agent 已缓存的运行时下次空闲访问时重建它们)。钩子的启停是整体的,不按单个包:`system_config.yaml` 的 `hooks.enabled`(缺省即启用)由 Hooks 标签页的开关(仅 Project owner)写入,关闭后新建的 Session 不组装任何钩子,已安装的包仍全部留在磁盘上。同一标签页可以把已装钩子包打包导出为 zip、再把这样的 zip 导入回来——`hooks.json` 与脚本在 zip 根目录,或在唯一的顶层目录内;清单列出的每条命令都必须指向压缩包内的文件——也可以把导入交给 Agent,由它通读来源、审查脚本后再安装。脚本是只用内置模块的纯 Node——harness 跑在哪它就跑在哪,以子进程方式运行,stdin 进 JSON、stdout 出 JSON 回答;契约见[运行循环](/agent-loop#stop-hook)。钩子包里的其他脚本由宿主按约定调用:goal 插件的 `start.mjs` 就是用户发起目标时服务端运行的那个([目标模式](/goal-mode))。
+脚本是只用内置模块的纯 Node 代码,harness 能运行的地方它们就能运行。每个脚本以子进程方式运行:从 stdin 读取 JSON,向 stdout 写回 JSON 应答;[Agent 循环](/agent-loop#stop-hook)描述了这套约定。Agent 的每个顶层 Session 都会在循环的各个钩子点查询已安装的钩子包。**启用钩子**开关保存在 Agent 的 `system_config.yaml` 的 `hooks.enabled` 键里;这个键不存在时,钩子处于开启状态。
-## 安装与存放
+钩子包的其他脚本供宿主按约定调用。例如,用户发起目标时,服务端运行的就是 `goal` 插件的 `start.mjs`;参见[目标模式](/goal-mode)。
-已安装的 Skill 位于 `agent_state/skills/<name>/`,钩子包位于 `agent_state/hooks/<name>/`。文件即事实源:每次读取直接读文件、不设缓存,因此 Skill 天然可编辑。
+### 渐进加载
-- 内置 Agent `default_agent` 在初始化时安装完整插件库(标记 `preinstall: false` 的插件除外,仅手动安装);
-- 其他 Agent 按需安装:经 Web 界面的插件库页,或经 SDK;
-- 安装 Skill 即写入它的可安装 `SKILL.md`(frontmatter 已按插件元数据重新生成,见上)、插件的 `icon.svg`,以及目录内其他文件(保留子目录)(用户自建或导入的 Skill 可自带 `icon.svg`,此时拷贝的是它自己的);安装钩子包即写入 `hooks.json`、插件的 `icon.svg` 与插件 `hooks/` 下的全部文件。每次安装整目录替换,因此重装会丢弃新版本不再携带的文件——重装就是更新已装副本的方式,Agent 列表页会标出已装 Skill 或钩子包落后于库的插件。
+Skill 分两步加载:先加载索引,正文按需读取。
-## 内置插件库
+- 系统提示词里的 `{{SKILLS}}` 占位符展开为**技能提示词**,其中的 `{{SKILL_METADATA}}` 占位符列出每个已安装 Skill 的名称和描述。**启用技能**关闭、或模板中没有 `{{SKILLS}}` 占位符时,什么都不注入。
+- 提示词要求模型先完整读取对应的 `SKILL.md`,再遵循 Skill。这里没有专门的 Skill 工具:读正文就是一次 `read_file` 或 shell 调用;参见[工具与审批](/tools)。
+- 在对话中选中 Skill 后,消息会以 `[use_skills]` 块开头,列出这些 Skill 的名称。显示旧 Trace 时,仍然识别早期的 `<use_skills>` 写法。
-内置插件按分类列出(分类清单是 `packages/core/src/plugins/index.ts` 的 `PLUGIN_CATEGORIES`;新增插件以库目录为准):
+### 安装与存储
-| 分类 | 插件 | 用途 |
-| --- | --- | --- |
-| 办公效率 | `data-analysis` | 完成数据分析任务:有界的证据检视、显式的改答案决策、原生工件处理与最终输出核验 |
-| | `use-firecrawl` | 经 Firecrawl API 做网页搜索与抓取,输出干净的 markdown |
-| | `use-bento-slides` | 编写与编辑 Bento 演示文稿:单文件 `.bento.html`,文档即 JSON,素材映射到图表、morph 转场与状态页 |
-| | `humanizer` | 剥除任意语言散文中的 AI 写作痕迹,改写为书籍、报刊与百科的语体(不预装:需要时从库安装) |
-| | `goal` | [目标模式](/goal-mode)背后的 stop hook:让会话持续朝目标工作,直到完成、受阻或 token 预算耗尽(预装) |
-| | `continual-learning` | 单个任务结束时轮次超过 30,就把该任务的浓缩摘录交给一个后台子会话,由它把值得沉淀的发现写进 Agent 的 Skill(不预装) |
-| 软件开发 | `software-development` | 端到端的软件开发——两个 Skill:`software-engineering`(最小范围的调查、实现与验证)与 `web-design`(生成网页的 Penguin 视觉规范) |
-| | `use-claude-code` | 经 SSH 在远程主机上运行 Claude Code——持久 expect 会话、headless `-p`、tmux 驱动的交互式 TUI 与多轮延续(不预装:需要时从库安装) |
-| AI 应用开发 | `agent-development` | 基于 PenguinHarness 的智能体开发——四个 Skill:`penguin-sdk`(用 SDK 构建智能体/AI/RAG 应用)、`unified-llm-api`(经 `@prismshadow/agenthub` 调用模型 API)、`penguin-config`(管理模型密钥、默认模型与 Vault 机密)、`penguin-orchestration`(在 shell 里编排智能体、会话、成本与定时任务) |
-| | `model-development` | 在自己的硬件上做模型开发——三个 Skill:`llamafactory`(微调)、`ollama`(运行本地模型)、`vllm`(以 OpenAI 兼容端点部署服务) |
-| | `skill-porting` | 从外部来源移植 Skill——插件市场、skills.sh 注册表、GitHub 仓库或本地目录——经审阅与规范化后装入 Agent |
-| | `agent-tuning` | 调优闭环的四个 Skill:`agent-initialization`(依据需求初始化 Agent)、`benchmark-design`(设计并校准能力 Benchmark)、`agent-evaluation`(隔离执行并评分单个 Case)、`agent-optimization`(根据测得结果改进 Agent) |
-| Agent 公司 | `agent-company` | [公司模式](/company-mode)的整套工具箱——七个 Skill:`company-setup`(与用户一起创建组织:一次只问一个问题,确认摘要后执行 `penguin org create`;它自己不招募、不建工单)、`company-employee`(每个工位会话与工单会话都遵循的协议:触发块、工单看板、阻塞、重负载或不可逆的事先向董事会请示、频道礼仪、预算)、`company-ceo`(使命拆解为工单、招募、划分工作区、审核、向董事会汇报)、`company-hr`(保证日程有安排、招募与离任、评估)、`company-finance`(预算、每日巡检、告警与暂停处置)、`company-research`(科研组织的作者与审稿人:先固定评测与指标,在董事会批准的资源额度内跑实验循环、只保留有提升的改动,每个结论都交给一个设法推翻它的审稿人)、`company-mirror`(数字分身公司:为每位现实同事建一个分身、绑定到他的机器人、只传话不开工单)(不预装:组织创建 CEO 与招募员工时自行安装;想让某个 Agent 能创建组织,从技能库装上它即可) |
-
-## 编写与优化
-
-- 手工安装:在 `agent_state/skills/<name>/` 下建目录并写入 `SKILL.md` 即可,系统组装系统 Prompt 时扫描 `skills/` 注入元数据;没有 `SKILL.md` 的目录不计为 Skill。
-- 卸载即删除整个 `skills/<name>/`(或 `hooks/<name>/`)目录,操作幂等。
-- Agent 可以在任务中直接改写自己的 SKILL.md——配合 Benchmark 评测与优化形成闭环,见 [自我进化](/self-improvement)。改完把 `version` 记成当天日期加下一个序号。
-- 长任务可以自己回流:装上 `continual-learning` 插件后,某个任务结束时轮次超过 30,它的 stop hook 就把该任务的浓缩摘录交给一个后台子 Session,由它把值得沉淀的发现写进相关 SKILL.md——见[运行循环](/agent-loop#stop-hook)。
+已安装的 Skill 存放在 `agent_state/skills/<name>/` 下,钩子包存放在 `agent_state/hooks/<name>/` 下。文件就是唯一事实来源:每次读取都直接访问磁盘,没有缓存。
+
+- 安装 Skill 时,会写入可安装版的 `SKILL.md`(含重新生成的 frontmatter)、插件的 `icon.svg`,以及 Skill 目录里的其他文件,子目录结构保持不变。自己编写或导入的 Skill 可以自带 `icon.svg`,这时复制的是 Skill 自带的图标。
+- 安装钩子包时,会写入 `hooks.json`、插件的 `icon.svg`,以及插件 `hooks/` 目录下的所有文件。
+- 每次安装都会整体替换目录,所以重新安装会清掉新版本不再包含的文件。已安装的副本就是靠重新安装来更新的。
+- 卸载会删除整个 `skills/<name>/` 或 `hooks/<name>/` 目录。
+- 运行中的 Session 沿用创建时加载的钩子包。安装或卸载钩子包、或者**启用钩子**开关变动之后,服务端会在 Agent 缓存的运行时下次空闲时重建它们。
+- 除 Web App 外,插件也可以通过 SDK 安装。
diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.md
index 1d24a989..8e59f5e9 100644
--- a/packages/docs/content/tools.en.md
+++ b/packages/docs/content/tools.en.md
@@ -1,11 +1,11 @@
---
title: Tools & Approval
-description: The deliberately minimal built-in toolset, its execution contract with centralized close-out, and per-call approval audited in the Trace.
+description: How the built-in tools run under one execution contract, how each call is approved and audited in the Trace, and how MCP servers join them.
---
-## Design
+PenguinHarness ships a deliberately minimal built-in toolset. Dedicated file tools (`read_file` / `edit_file` / `write_file`) cover precise reading and editing, because line-numbered output and exact-string replacement beat quoting `sed` one-liners. The shell (`exec_command`) remains the general-purpose fallback for everything else: running programs, searching, installing dependencies. Every tool that remains earns the schema Tokens it costs.
-PenguinHarness ships a deliberately minimal built-in toolset: dedicated file tools (`read_file` / `edit_file` / `write_file`) cover precise reading and editing — line-numbered output and exact-string replacement beat quoting `sed` one-liners — while the shell (`exec_command`) remains the general-purpose fallback for everything else: running programs, searching, installing dependencies. Every tool that remains earns its schema tokens.
+The Environment runs every tool call through one shared contract and handles the close-out centrally. This page covers that contract first, then the per-tool configuration, the 7 built-in tools and their background behavior, the per-call approval recorded in the Trace, and how to customize the toolset and add MCP servers.
## Execution contract
@@ -15,6 +15,7 @@ Every built-in tool implements the same `BuiltinTool` interface (`packages/core/
interface BuiltinTool {
name: string;
definition: ToolDefinitionConfig;
+ detachable?: boolean; // has a background form a running call can be moved to (exec_command, run_subagent)
execute(
args: Record<string, unknown>,
ctx: ToolExecutionContext,
@@ -25,6 +26,7 @@ interface ToolExecutionContext {
workspaceDir: string;
toolCallId: string;
signal?: AbortSignal;
+ detachSignal?: AbortSignal; // fires when the host asks this call to continue as a background task
approve?: ApproveFn; // forwarded to tools that spawn child Sessions (approval inheritance)
}
@@ -35,25 +37,57 @@ interface ToolResult {
}
```
-A tool only yields incremental `partial_tool_call_output` deltas; the Environment handles the close-out centrally:
+A tool only yields incremental `partial_tool_call_output` deltas. The Environment handles the close-out centrally:
- streaming framing (start / stop) and `tool_call_id` threading;
-- timeout merging, and head+tail-window truncation once output exceeds `maxOutputLength` (default 16000 characters): the budget splits in half, the head window streams live, and the last tail window arrives at finalization after a `[output truncated: kept first H and last T of C chars]` marker — the total C tells the model whether the recovery file is worth reading; output that ends past the head window but within the budget is flushed verbatim at finalization instead, with no marker;
-- stop_reason priority: user interrupt > timeout > tool throw > tool self-report;
-- never-empty output (`[no output]` is substituted when a tool produced nothing);
-- `note` (e.g. the exit code) and images are appended outside the output budget, so the terminal marker survives even when long output is cut.
+- timeouts, and head-and-tail truncation once output exceeds `maxOutputLength` (default 16000 characters);
+- `stop_reason` priority: user interrupt > timeout > tool throw > tool self-report. A timeout or a throw ends the call as `fatal`;
+- never-empty output: `[no output]` is substituted when a call produced no text and no note;
+- `note` (for example the exit code) and images are appended outside the output budget, so the terminal marker survives even when long output is cut.
-Tools and the Environment never throw into the engine: errors collapse into `tool_call_output` messages the model can read and react to. A call whose arguments do not fit the tool ends as `fatal` with a correction guide as its whole output: the fault, the argument names received with unknown ones called out, the tool's parameters restated from its schema, and the shape of a correct call — enough to repair the call from the output alone. See the [OmniMessage Protocol](/omni-message) for message structure.
+Truncation splits the budget in half. The head window streams live. At finalization, the Environment emits a `[output truncated: kept first H and last T of C chars]` marker followed by the tail window. The total `C` tells the model whether the [recovery file](#recovering-oversized-output) is worth reading. Output that ends past the head window but within the budget is flushed verbatim at finalization instead, with no marker.
+
+Tools and the Environment never throw into the engine. Errors become `tool_call_output` messages the model can read and react to. A call whose arguments do not fit the tool ends as `fatal`, and its whole output is a correction guide:
+
+- the fault;
+- the argument names received, with unknown ones called out;
+- the tool's parameters, restated from its schema;
+- the shape of a correct call.
+
+That is enough to repair the call from the output alone. For message structure, see the [OmniMessage Protocol](/omni-message).
### Recovering oversized output
-When tool text in an Agent Session exceeds `maxOutputLength`, the model and Web/CLI still receive the same head and tail windows, counting truncation marker, and terminal marker, and the streaming invariant that user-visible output equals model-visible output does not change. Environment also appends a short archive status/path note outside that visible-output cap and saves a Session-owned recovery file. The file is exact within the per-call archive budget and otherwise contains bounded head/tail windows. This is the complete text **received by Environment**: a producer such as a command or subagent session may already have replaced overflow with an `[..., N chars of earlier output dropped ...]` marker in its own bounded unread buffer, and the downstream archive cannot recover text lost before that point.
+When tool text in an agent Session exceeds `maxOutputLength`, the model, the Web App and the CLI still receive the same head and tail windows, the counting truncation marker and the terminal marker. The streaming invariant that user-visible output equals model-visible output does not change.
+
+Beyond that visible cap, the Environment appends a short archive status or path note and saves a recovery file owned by the Session. The file holds the exact text within the per-call archive budget, and bounded head and tail windows beyond it. It is the complete text **received by the Environment**: a producer such as a command or subagent session may already have replaced overflow in its own bounded unread buffer with a `[... N chars of earlier output dropped ...]` marker, and the archive cannot recover text lost before that point.
+
+The agent reads ordinary multiline archives with the existing `read_file` (`offset` / `limit`). For byte tails or very long lines, it builds a targeted shell command such as `rg` or `tail`; there is no dedicated retrieval tool.
+
+The note carries a plain absolute path, always the last element inside the bracket. On Windows the path uses forward slashes: `exec_command` runs through (Git) Bash and Node's fs APIs accept them, so one spelling works in JSON tool arguments and shell commands alike. POSIX paths pass through unchanged, and Session paths are ordinary absolute paths (never `\\?\`-prefixed), so swapping the separator loses nothing. As with any path, quote it in shell commands when it contains spaces.
+
+The same spelling rule covers every path core composes for the model:
-The Agent can inspect ordinary multiline archives with the existing `read_file` (`offset` / `limit`). For byte tails or very long lines, it must construct a targeted shell command such as `rg` / `tail`; no dedicated retrieval tool is added. The note carries a plain absolute path, always the last element inside the bracket. On Windows it is written with forward slashes: `exec_command` runs through (Git) Bash and Node's fs APIs accept them, so one spelling works in JSON tool arguments and shell commands alike; POSIX paths pass through unchanged, and Session paths are ordinary absolute paths (never `\\?\`-prefixed), so the separator swap is lossless. As with any path, quote it inside shell commands when it contains spaces. The same spelling rule covers every path core composes for the model — the system prompt's App Data Dir / CWD lines, `[attached image/file: …]` lines and the goal-file line (`modelVisiblePath` in the SDK).
+- the system prompt's App Data Dir / CWD lines;
+- `[attached image/file: …]` lines;
+- the goal-file line (`modelVisiblePath` in the SDK).
-Recovery files live under the Session's `scratchpad/<session-id>/truncated-tool-output/`, are created only after actual truncation, and use private permissions where the platform supports them. One call stores at most 8 MiB (the production byte limit is one byte lower so `read_file` remains below its 8 MiB scan cap); larger output keeps bounded head/tail windows in the file with an explicit middle-gap marker. The limit is per call only: a Session has no aggregate archive byte or file-count quota, and concurrent captures independently retain up to one call's budget. Files remain readable across Tasks, runtime disposal, and Session resume until explicit Session deletion removes the entire scratchpad; no separate archive cleanup lifecycle is added.
+| Property | Recovery file behavior |
+| --- | --- |
+| Location | `scratchpad/<session-id>/truncated-tool-output/`, under the Session |
+| Creation | Only after actual truncation |
+| Permissions | Private where the platform supports them |
+| Per-call size | At most 8 MiB; the production byte limit is one byte lower so `read_file` stays below its 8 MiB scan cap |
+| Larger output | Bounded head and tail windows with an explicit middle-gap marker |
+| Quota | Per call only: a Session has no total byte or file-count quota, and concurrent captures each keep up to one call's budget |
+| Lifetime | Readable across Tasks, runtime disposal and Session resume, until explicit Session deletion removes the whole scratchpad; there is no separate archive cleanup |
+
+> [!WARNING]
+> Recovery files contain the unredacted tool text the Environment received. If a tool accidentally reads credentials or other sensitive data, the local copy on disk grows from the visible windows to the archive budget.
-Recovery files contain the unredacted tool text received by Environment. Accidentally reading credentials or other sensitive data can therefore increase local at-rest retention from the visible windows to the archive budget. Trace does not duplicate those bytes, but it records the same absolute Session path shown to the model and Web/CLI, exposing the host's data-root layout. Archive-write failure never changes the original tool's `stop_reason`; the visible note and stderr warning carry only a short error code (and stderr's tool name), not the path or raw error message.
+The Trace does not duplicate those bytes. It does record the same absolute Session path shown to the model, the Web App and the CLI, which exposes the host's data-root layout.
+
+A failed archive write never changes the original tool's `stop_reason`. The visible note and the stderr warning carry only a short error code (plus the tool name on stderr), never the path or the raw error message.
## Configuration fields
@@ -65,39 +99,53 @@ Each tool is described by one `ToolDefinitionConfig`:
| `description` | Tool description handed to the model |
| `parameters` | JSON Schema of the arguments |
| `permission` | `"r"` read-only / `"rw"` read-write |
-| `forModel` | `"vision"` / `"text-only"`: selected by the Session model's class; omitted = available to all models (no built-in entry sets it — `read_file` serves both classes) |
+| `forModel` | `"vision"` / `"text-only"`: selected by the Session model's class. Omitted means available to all models. No built-in entry sets it, because `read_file` serves both classes |
| `timeoutMs` | Per-call timeout (ms), default 120000; `<=0` disables |
| `maxOutputLength` | Output length cap (characters); `<=0` disables |
-| `call_description` | Per-tool toggle for the `description` call argument declared in `parameters` (required while on); missing = kept, `false` filters it and its `required` entry out of the schema at assembly |
+| `call_description` | Per-tool switch for the `description` call argument declared in `parameters` (required while on). Missing means kept; `false` removes the property and its `required` entry from the schema at assembly |
## Built-in tools
-There are 7 built-in tools (assembled via `packages/core/src/environment/tools/registry.ts`):
+There are 7 built-in tools, assembled through `packages/core/src/environment/tools/registry.ts`:
| Tool | Permission | Timeout (ms) | Purpose |
| --- | --- | --- | --- |
-| `exec_command` | rw | 120000 | Run a shell command in the Workspace via `bash -lc`, streaming stdout/stderr |
+| `exec_command` | rw | 120000 | Run a shell command in the Workspace (through `bash -lc` where bash exists), streaming stdout/stderr |
| `input_command` | rw | 120000 | Drive a command session by `process_id`: write stdin, send Ctrl-C, poll output, or terminate it (`kill: true`) |
-| `read_file` | r | 60000 | Read a text file as a line-numbered (`cat -n`) window paged by offset/limit, or an image (path or URL) as image content — described in text by the `vision_model` for a text-only model |
-| `edit_file` | rw | 30000 | Exact-string replacement in an existing file, echoing a verification snippet |
+| `read_file` | r | 60000 | Read a text file as a line-numbered (`cat -n`) window paged by offset/limit, or an image (path or URL) as image content; for a text-only model, the `vision_model` describes the image in text |
+| `edit_file` | rw | 30000 | Replace an exact string in an existing file, echoing a diff of the change |
| `write_file` | rw | 30000 | Create or overwrite a whole file, creating parent directories as needed |
-| `run_subagent` | rw | 600000 | Delegate a self-contained subtask to a child Agent in the same Workspace |
+| `run_subagent` | rw | 600000 | Delegate a self-contained subtask to a child agent in the same Workspace |
| `input_subagent` | rw | 600000 | Poll a background subagent, steer it mid-run, stop its current run, or continue it with a follow-up prompt |
-Note that an existing agent's persisted `tools.builtin` list is frozen as written (the settings UI edits rows but adds none): agents created before this toolset do not pick up newer tools (e.g. the file tools) or newer arguments (`run_in_background`, `kill`, `abort`) automatically — and entries for since-removed tools (`kill_command`, `kill_subagent`, `read_image`, `describe_image`) simply stop assembling: a model calling them gets the standard unknown-tool failure. A stored `read_file` entry from before it read images keeps its old description and timeout (the implementation behind it already reads images) — hand-edit the agent's `system_config.yaml` (copy the entries from the default definitions in `packages/core/src/state/default-config.ts`) or run the kernel update from the agent's settings page to adopt the current definitions.
+An existing agent's stored `tools.builtin` list stays exactly as written; the settings UI edits rows but adds none. As a result:
+
+- Agents created before this toolset do not pick up newer tools (for example the file tools) or newer arguments (`run_in_background`, `kill`, `abort`) automatically.
+- Entries for removed tools (`kill_command`, `kill_subagent`, `read_image`, `describe_image`) simply stop being assembled. A model that calls one gets the standard unknown-tool failure.
+- A stored `read_file` entry from before it read images keeps its old description and timeout, although the implementation behind it already reads images.
+
+To adopt the current definitions, edit the agent's `system_config.yaml` by hand, copying the entries from the defaults in `packages/core/src/state/default-config.ts`. **Update kernel** on the agent's settings page rewrites the list only while the **Tools** tab is absent or still an unedited old default; **Restore default configuration** always does, but resets the whole config. See [Kernel updates](/configuration#kernel-updates).
### Call descriptions
-The command/subagent tools (`exec_command`, `input_command`, `run_subagent`, `input_subagent`) take a `description` argument: one model-written sentence about what the call is doing, shown by the CLI and Web UI while the call runs. The argument is declared as a normal `description` property in each entry's `parameters` in `system_config.yaml` (tool schemas live entirely in the editable config), and it is **required** there — a tool that offers the argument always gets one, so the frontends can pick a call's display form from the schema instead of guessing while the arguments stream; the model is also asked to emit it first. The per-entry `call_description` field toggles the whole thing — missing = kept, `call_description: false` filters the property (and its `required` entry) out of the schema at assembly time (in-memory only, the YAML is never rewritten). The file tools don't take it — their `file_path` argument is self-describing.
+The command and subagent tools (`exec_command`, `input_command`, `run_subagent`, `input_subagent`) take a `description` argument: one model-written sentence about what the call is doing, which the CLI and the Web App show while the call runs.
+
+The argument is declared as a normal `description` property in each entry's `parameters` in `system_config.yaml`, because tool schemas live entirely in the editable config. It is **required** there, so a tool that offers the argument always gets one. The frontends can then choose a call's display form from the schema instead of guessing while the arguments stream, and the model is asked to emit the argument first.
+
+The per-entry `call_description` field switches the whole feature. Missing means kept; `call_description: false` removes the property and its `required` entry from the schema at assembly time. This happens in memory only; the YAML is never rewritten.
+
+The file tools do not take the argument, because their `file_path` already says what the call is about.
### Command sessions
-`exec_command` waits in the foreground first; if the command outruns `yield_time_ms` it moves to the background and the call returns the output so far plus a `process_id`, driven from then on by `input_command`. With `run_in_background: true` it skips the foreground window entirely: the call returns the `process_id` immediately, and when the process exits its result arrives as an automatic user message (see [Background completion reports](#background-completion-reports)). `input_command` with `kill: true` terminates a session either way — a process is a real OS object that IS destroyed, so termination is a parameter of the access tool rather than a tool of its own:
+`exec_command` waits in the foreground first. If the command outlasts `yield_time_ms`, it moves to the background, and the call returns the output so far plus a `process_id`; from then on `input_command` drives it. With `run_in_background: true`, `exec_command` skips the foreground window: the call returns the `process_id` at once, and when the process exits, its result arrives as an automatic user message (see [Background completion reports](#background-completion-reports)).
+
+`input_command` with `kill: true` terminates a session started either way. A process is a real OS object that does get destroyed, so termination is a parameter of the access tool rather than a tool of its own:
```text
exec_command(cmd)
├─ finishes within the foreground window (yield_time_ms, default 60000)
- │ ──► full output + exit code
+ │ ──► full output (+ an exit-code or signal note when it failed)
├─ still running ──► backgrounds, returns output so far + process_id
│ │
│ input_command(process_id[, chars]) ──► write stdin / send Ctrl-C / poll
@@ -107,6 +155,8 @@ exec_command(cmd)
input_command(process_id, kill: true) ──► SIGTERM the process group (SIGKILL after a grace period)
```
+A command that exits cleanly adds no note. A non-zero exit adds `[exit code: N]` and a signal adds `[terminated by signal S]`; both end the call as `fatal`.
+
The tools' arguments (explicit keys):
```ts
@@ -129,13 +179,29 @@ The tools' arguments (explicit keys):
}
```
-On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the foreground command. On Windows there is no console signal delivery to a piped child process, so Ctrl-C degrades to a hard kill of the whole command session tree (`taskkill /t /f`) — the foreground command and every child it started terminate, instead of the foreground command being interrupted.
+**Shell.** Commands run through `bash -lc` wherever a bash exists, and the system prompt tells the model which shell is active. `PENGUIN_SHELL` (an executable name or path) overrides the choice on every platform. Otherwise the shell is picked in this order:
+
+- On POSIX: `bash` on PATH, then the usual absolute bash locations, then the `$SHELL` login shell, then `sh`.
+- On Windows: a `bash` on PATH that is not the WSL launcher (for example Git for Windows), then the bundled MinGit bash, then `pwsh`, then `powershell`.
+
+**Ctrl-C.** On POSIX, Ctrl-C sends `SIGINT` to the session's process group, which interrupts the foreground command. Windows cannot deliver a console signal to a piped child process, so Ctrl-C becomes a hard kill of the whole command session tree (`taskkill /t /f`): the foreground command and every child it started terminate, instead of only the foreground command being interrupted.
### File tools
-`read_file` / `edit_file` / `write_file` run with the user's full permissions, same as the shell tool; relative paths resolve against the Workspace and absolute paths are allowed. A symlinked path is followed to the file it names — reads, edits and writes all land on that file, and the link stays a link. They are non-streaming (a single final output) and never throw — failures come back as explanatory text with `stop_reason: failed`. `edit_file` and `write_file` serialize per file within the server process, keyed by the file's real path — a symlink and its target are one file — so parallel edits of one file are applied one after another, and an `old_string` an earlier edit removed fails to match instead of overwriting it; writes from other processes are outside that lock.
+`read_file` / `edit_file` / `write_file` run with the user's full permissions, like the shell tool. Relative paths resolve against the Workspace, and absolute paths are allowed. A symlinked path is followed to the file it names: reads, edits and writes all land on that file, and the link stays a link. `read_file` refuses the secret stores `.vault.toml` and `.project_config.toml`, matched by file name in any directory and after following symlinks.
+
+The file tools return a single final output rather than a stream, with one exception: for a text-only model, `read_file` streams the vision model's description of an image. They never throw. Failures come back as explanatory text with `stop_reason: fatal`.
+
+`edit_file` and `write_file` serialize per file within the server process, keyed by the file's real path, so a symlink and its target count as one file. Parallel edits of one file are applied one after another, and an `old_string` that an earlier edit removed fails to match instead of overwriting it. Writes from other processes are outside this lock.
-`read_file` reads images as well as text. A png/jpeg/gif/webp file up to 5MB — recognized by its magic number, then by its extension — or an http(s) URL in `file_path` (a URL is only ever an image source; the response content-type is consulted first) takes the image branch, and what comes back depends on the Session model's vision flag: a model that accepts images gets the image itself as image content (the text output is a one-line `image/png, 123.4 kB`), while a text-only model gets the Project's configured `vision_model` answering `prompt` (default: a detailed description), streamed as the tool's text output — the image never enters that Session's history. Without a `vision_model`, an image read on a text-only Session fails with an explanation asking the user to pick one in the model settings. See [Models & Providers](/models). The branch is decided by the `VisionDescriberService` the SDK injects into the Environment for text-only Sessions only, so one config entry (no `forModel`) serves both model classes.
+`read_file` reads images as well as text. The image branch takes a png, jpeg, gif or webp file up to 5MB, recognized by its magic number and then by its extension, or an http(s) URL in `file_path`. A URL is only ever an image source, and the response's content-type is checked first.
+
+What comes back depends on the Session model's vision flag:
+
+- A model that accepts images gets the image itself as image content, and the text output is one line such as `image/png, 123.4 kB`.
+- A text-only model gets the Project's `vision_model` answering `prompt` (by default, a detailed description), streamed as the tool's text output. The image never enters that Session's history. Without a `vision_model`, reading an image in a text-only Session fails with an explanation asking the user to pick one in the model settings. See [Models & Providers](/models).
+
+The branch is decided by the `VisionDescriberService` that the SDK injects into the Environment for text-only Sessions only, so one config entry (without `forModel`) serves both model classes.
```ts
// read_file — cat -n style output (line number, tab, content) for text; overlong single lines
@@ -171,9 +237,31 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the
### Subagents
-`run_subagent` hands a subtask you can fully specify in one prompt to a child Agent, with the same two-phase shape: after the foreground window (default 300000ms) it moves to the background with a `subagent_id`, driven by `input_subagent`; the child's pending approvals surface while the poll waits. `input_subagent` covers four gestures: an empty `prompt` polls; a `prompt` sent while the child **runs** is injected mid-run as a steering message (the same mechanism as a user interjecting into the main session — delivered as a `[user_steering]` message at the child's next step, recorded in the child's Trace with sender `parent_agent`); a `prompt` sent while it is idle continues the same session with a follow-up round; and `abort: true` stops the child's **current run only** — the session survives for steering and follow-ups, and combined with a `prompt` it interrupts and redirects. The model-facing output of every `input_subagent` access is the child's **most recent complete reply** — an idempotent “what it last said” snapshot rather than an incremental drain. With `run_in_background: true` the launch returns the `subagent_id` immediately and every model-initiated round's completion arrives as an automatic user message (panel-started and explicitly aborted rounds stay silent; see [Background completion reports](#background-completion-reports)). There is **no kill for subagents**: like the main agent, a subagent session is never destroyed — releasing an idle one only frees its slot, and a released `subagent_id` **revives automatically** when messaged again (the model's access and the panel's share the same resume path).
+`run_subagent` hands a subtask you can fully specify in one prompt to a child agent. It has the same two-phase shape as a command: after the foreground window (default 300000ms) the child moves to the background with a `subagent_id`, and `input_subagent` drives it from there. The child's pending approvals surface while a poll waits.
+
+`input_subagent` covers four actions:
+
+1. An empty `prompt` polls.
+2. A `prompt` sent while the child **runs** is injected mid-run as a steering message. This is the same mechanism as a user interjecting in the main session: the message arrives as `[user_steering]` at the child's next step and is recorded in the child's Trace with sender `parent_agent`.
+3. A `prompt` sent while the child is idle continues the same session with a follow-up round.
+4. `abort: true` stops the child's **current run only**. The session survives for steering and follow-ups; combined with a `prompt`, it interrupts and redirects.
+
+Every `input_subagent` call returns the child's **most recent complete reply** to the model: an idempotent snapshot of what it last said, not an incremental drain.
-The Web App's subagents panel drives a selected child with the **same composer as the main conversation** (its subagent variant): the text body, skills and slash skill commands, a thinking-level picker (pins the child Session, effective from its next model context), the context ring (the child's own usage), the locked-model badge, and the approval-mode selector — which edits the parent session's mode, the one child approvals are actually judged by. A message is simply a user input on the child, whatever its state: steering while it runs, a follow-up round while it is idle, and a **revival** when the session was already released — the server resumes the child session (its own history, model and Workspace) and re-manages it, so the conversation just continues. The action button's stop face aborts only the child's current run. Everything converges on the same core channel as `input_subagent`, and the panel's running marks follow the server's live child states rather than the transcript.
+With `run_in_background: true`, the launch returns the `subagent_id` immediately, and the completion of every round the model started arrives as an automatic user message. Rounds started from the panel and rounds ended by an explicit abort stay silent (see [Background completion reports](#background-completion-reports)).
+
+There is **no kill for subagents**. Like the main agent's session, a subagent session is never destroyed. Releasing an idle one only frees its slot, and a released `subagent_id` **revives automatically** when it is messaged again; the model and the panel share the same resume path.
+
+The Web App's subagents panel drives a selected child with the **same composer as the main conversation**, in its subagent variant:
+
+- the message body;
+- Skills and slash Skill commands;
+- a thinking-level picker, which pins the child Session from its next LLM request;
+- the context ring, showing the child's own usage;
+- the locked-model badge;
+- the approval-mode selector, which edits the parent Session's mode, since that is the mode child approvals are judged by.
+
+A message is a user input to the child, whatever its state: steering while it runs, a follow-up round while it is idle, and a **revival** when the session was already released. To revive a child, the server resumes the child Session (its own history, model and Workspace) and manages it again, so the conversation simply continues. The action button's stop face aborts only the child's current run. All of this goes through the same core channel as `input_subagent`, and the panel's running marks follow the server's live child states rather than the transcript.
```ts
// run_subagent
@@ -200,30 +288,54 @@ The Web App's subagents panel drives a selected child with the **same composer a
```
- Depth is capped at 1: a subagent cannot spawn another subagent.
-- The child Session follows the parent Session — its model (unless `model_id`/`provider` pick another), thinking level (unless `thinking_level` picks another — lower for cheap mechanical subtasks, higher for hard analysis), and Workspace — never the Project defaults.
-- The child Session inherits the parent Agent's approval callback, so the approval mode follows the parent.
-- The child Session gets its own Trace, linked from the parent by a `subagent` pointer event; child messages stream back into the parent flow tagged with `origin`. See [Sessions & Traces](/sessions-and-traces).
+- The child Session follows the parent Session, never the Project defaults: its model (unless `model_id` / `provider` pick another) and its Workspace.
+- The thinking level also follows the parent unless `thinking_level` picks one (lower for cheap mechanical subtasks, higher for hard analysis). The child inherits the parent Session's level from creation, or else the level the parent's current context opened with. A level set on the parent Session mid-conversation is not passed down.
+- The child Session inherits the parent agent's approval callback, so the approval mode follows the parent.
+- The child Session gets its own Trace, linked from the parent by a `subagent` pointer event. Child messages stream back into the parent's flow tagged with `origin`. See [Sessions & Traces](/sessions-and-traces).
### Background completion reports
-A task launched with `run_in_background: true`, and a running call the user moved to the background from its row in the Web App, both report their completion as a **user message injected by the harness** — the model does not need to poll. A call the user moved there says so in its own result: the note tells the model to leave the work alone — no polling, no input — and to move on to other work or end the turn, because the user sent it to the background precisely so the model would not follow it up; the completion arrives on its own. The message opens with a `[background_task_done]` marker block (kind, id, status, one-line detail) followed by what ran and the tail of its yet-undelivered output (capped at 4000 characters; the Web App collapses the block into a one-line notice). Its `text` payload carries `sender: "harness"`, distinguishing it from human input in the Trace (see [OmniMessage](/omni-message)).
+A task launched with `run_in_background: true`, and a running call the user [moved to the background](/chat#send-a-tool-call-to-the-background) from its card in the Web App, both report their completion as a **user message injected by the harness**. The model does not need to poll.
+
+A call the user moved to the background says so in its own result. The note tells the model to leave the work alone (no polling, no input) and to move on to other work or end the turn. The user moved it precisely so the model would not follow it up, and the completion arrives on its own.
+
+The message opens with a `[background_task_done]` marker block (kind, id, status and a one-line detail), followed by what ran and the output, capped at 4000 characters: for a command, the tail of its not-yet-delivered output; for a subagent, the end of the child's latest complete reply. The Web App shows the block as a collapsible notice. The message's `text` payload carries `sender: "harness"`, which distinguishes it from human input in the Trace (see [OmniMessage](/omni-message)).
+
+When the report is delivered depends on the Session:
-Delivery: while a Task is running, the report rides the next turn boundary — a final reply already streaming does not lose it, the Task simply continues for one more turn to react. While the Session is idle, the hosting server starts a new Task carrying the report (SDK embedders subscribe via `Session.onBackgroundNotice` / `takeBackgroundNotices`, or get it prepended to the next run). A command terminated through `input_command`'s `kill` sends no report — that call's own result already carries the outcome — and neither does a subagent round ended by an explicit `abort` (the aborter reads the outcome directly). Reports cover **model-initiated rounds only** — the `run_in_background` launch and `input_subagent` follow-ups; a round the user starts from the subagents panel is their own conversation with the child and sends no report (its answer text stays in the model-facing buffer for the next poll).
+- **A Task is running:** the report rides the next turn boundary. A final reply that is already streaming does not lose it; the Task continues for one more turn to react.
+- **The Session is idle:** the hosting server starts a new Task that carries the report. SDK embedders subscribe through `Session.onBackgroundNotice` / `takeBackgroundNotices`, or get the report prepended to the next run.
-A stop is reported, but not as a failure. A command ended on purpose reports `status: stopped` — the user's **Stop** button in the Web App's process list, a stop signal that arrived from outside (`SIGTERM`/`SIGINT`/`SIGHUP`: a Ctrl-C in a terminal sharing its process group, a `pkill`, a supervisor shutting a dev server down), or a stop the harness itself forced (a capacity eviction, an idle reap) — and its marker block says in as many words that nobody should restart it unasked. The conversation does need to hear that the dev server it started is down; worded `failed` it reads like a crash instead, and the reasonable response to a crashed dev server is to start it again, undoing the stop somebody just asked for. `failed` stays for outcomes nobody asked for: a spawn error, a non-zero exit, a hard kill or a fault signal (an OOM kill, a segfault).
+No report is sent for:
-A background subagent's lifecycle is decoupled from the call that launched it: its abort scope is its own (a per-run `abort` ends a round; the session itself leaves only with the parent Session, and even a capacity-released one can be revived), its messages stream to the frontend live through the launching Session (same origin-tagged channel a foreground window relays), and its tool approvals resolve through the launching call's own approval callback as a standing sink — so an `allow-all` launch runs unattended, and a failure still ends in a `status: failed` report rather than a child parked forever.
+- a command terminated through `input_command`'s `kill`, because that call's own result already carries the outcome;
+- a subagent round ended by an explicit `abort`, because the caller that aborted it reads the outcome directly;
+- a round the user starts from the subagents panel, which is the user's own conversation with the child. Its answer text stays in the model-facing buffer for the next poll. Reports cover **model-initiated rounds only**: the `run_in_background` launch and `input_subagent` follow-ups.
+
+**Stopped is not failed.** A command ended on purpose reports `status: stopped`, and its marker block says plainly that nobody should restart it unasked. Deliberate stops are:
+
+- the user's **Stop** button in the Web App's process list;
+- a stop signal from outside (`SIGTERM` / `SIGINT` / `SIGHUP`), such as a Ctrl-C in a terminal sharing the process group, a `pkill`, or a supervisor shutting a dev server down;
+- a stop the harness forced itself, such as a capacity eviction or an idle reap.
+
+The conversation does need to hear that the dev server it started is down. Worded as `failed`, that would read like a crash, and the reasonable response to a crashed dev server is to start it again, undoing the stop somebody just asked for. `failed` stays for outcomes nobody asked for: a spawn error, a non-zero exit, a hard kill, or a fault signal such as an OOM kill or a segfault.
+
+A background subagent's lifecycle is independent of the call that launched it:
+
+- **Aborting:** its abort scope is its own. A per-run `abort` ends a round; the session itself ends only with the parent Session, and even one released for capacity can be revived.
+- **Messages:** they stream live to the frontend through the launching Session, on the same origin-tagged channel a foreground window uses.
+- **Approvals:** they resolve through the launching call's own approval callback, which stays attached. An `allow-all` launch therefore runs unattended, and a failure still ends in a `status: failed` report rather than a child waiting forever.
### Background session caps
| Session type | Cap | Eviction |
| --- | --- | --- |
-| Command sessions | 64 | When full, exited sessions are evicted first, then idle ones by LRU |
-| Subagent sessions | 8 | Only completed ones are evicted; running subagents never — with no room, spawning is rejected |
+| Command sessions | 64 | When full, an exited session is evicted first; otherwise the least recently used session is killed and evicted |
+| Subagent sessions | 8 | Only completed sessions are evicted, never a running one; when there is no room, spawning is rejected |
## Approval
-Every complete `tool_call` triggers exactly one approval decision:
+Every complete `tool_call` gets exactly one approval decision:
```ts
type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto
@@ -232,17 +344,29 @@ type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDec
| Surface | Behavior |
| --- | --- |
-| SDK | Pass `approve` per `session.run`; with none injected the engine denies by default (conservative — nothing gets approved unattended) |
-| CLI | `--approve` takes four modes: allow-all (default) / deny-all / read-only / always-ask; read-only auto-approves `permission: "r"` tools and defers the rest to a human |
-| Web / Server | The same four modes, set per Session; the mode is re-read from the DB on every decision (edits apply at once), while a tool's `r`/`rw` comes from the running context's toolset — permission edits apply at the next rotation (compaction); manual decisions arrive via the API |
+| SDK | Pass `approve` to each `session.run`. With none injected, the engine denies everything by default, so nothing is approved unattended |
+| CLI | `--approve` takes four modes: `allow-all` (default), `deny-all`, `read-only`, `always-ask`. `read-only` auto-approves `permission: "r"` tools and leaves the rest to a person. The flag sets the approval mode of the server Session the CLI drives; without it, a CLI running inside an agent's command inherits the calling Session's mode |
+| Web / Server | The same four modes, set per Session. The mode is re-read from the database on every decision, so a change applies at once. A tool's `r` / `rw` comes from the running context's toolset, so a permission change applies at the next rotation (compaction). Manual decisions arrive through the API |
+
+Installed pre-tool-use hooks are consulted before the approval callback. A hook's `deny` refuses the call without asking, and its `allow` approves without asking, except that the [command policy](/configuration#command-policy) still vetoes an allowed call it matches. See [Pre-tool-use hooks](/agent-loop#pre-tool-use-hooks).
+
+A refused call gets a synthetic `aborted` `tool_call_output` for the model to react to. The wording names the decider:
+
+| Decider | Output |
+| --- | --- |
+| A person or approval mode (`deny`) | `Tool call denied by user.` |
+| The command policy (`forbidden`) | `Tool call denied by policy.` |
+| A pre-tool-use hook | `Tool call denied by the <hook> hook[: <reason>].` |
+
+A policy hit therefore never reads as a person cancelling. See [ApproveFn](/interfaces#approvefn). Every decision is written to the Trace as an `approval_decision` event, with a policy veto recorded as `forbidden`, which makes the Trace a complete audit record. Approval happens in the tool-execution phase of the [agent loop](/agent-loop).
-A deny produces a synthetic `aborted` `tool_call_output` for the model to react to — `Tool call denied by user.`, or `Tool call denied by policy.` when the [command policy](/configuration#command-policy) denied it, so a policy hit never reads as a person cancelling. See [ApproveFn](/interfaces#approvefn). Every decision is written to the Trace as an `approval_decision` event — a policy veto recorded as `forbidden` — forming a complete audit record. Approval happens in the tool-execution phase of the [Agent Loop](/agent-loop).
+**Subagent approvals.** Ending the parent's task never auto-denies a child's approval. The server attaches a session-lifetime fallback approval sink to every Session it runs, CLI-driven Sessions included. It escalates to the user any child approval that has no active poll window and no background-launch sink, even while the parent Session sits idle. When a parent task ends or is stopped, only the **main** Session's pending approvals are resolved. A child approval tagged with `origin` stays pending, with its card on screen, until the user decides. An SDK embedder that never calls `Session.setSubagentApprovalFallback` keeps the poll-window-only behavior: the child's requests wait until a `run_subagent` or `input_subagent` call is active.
-A subagent child's approval is never auto-denied by the parent's task ending. On the Web server, a session-lifetime fallback approval sink escalates any child approval that has no active poll window and no background-launch standing sink straight to the user (the parent session sitting idle included), and a parent task ending or being stopped converges only the **main** session's pending approvals — an origin-tagged child approval stays pending, and its card stays on screen, until the user decides. Hosts that attach no such sink (the CLI) keep the poll-window-only semantics: the child's requests queue until a `run_subagent` / `input_subagent` call is active.
+## Customizing the toolset
-## Custom tools & MCP
+The `tools.builtin` array in `system_config.yaml` declares the toolset, with entries of the same `ToolDefinitionConfig` shape. It **replaces the defaults wholesale; it is not merged with them**. Omit the section to keep the full default toolset. Once you write it, the default list is gone, and every tool you keep needs its complete definition, including the `parameters` JSON Schema, because a tool's schema comes entirely from config.
-The `tools.builtin` array in `system_config.yaml` declares the toolset with entries of the same `ToolDefinitionConfig` shape. The semantics are **wholesale replacement, not merging**: omit the section entirely to keep the full default toolset; once written, the default list is replaced and every tool you keep must carry its complete definition (including the `parameters` JSON Schema — a tool's schema comes entirely from config). `tools.mcpServers` carries the MCP Server configuration, covered in the next section. See also [Configuration](/configuration).
+`tools.mcpServers` holds the MCP Server configuration, covered in the next section. See also [Configuration](/configuration).
```yaml
tools:
@@ -262,15 +386,26 @@ tools:
mcpServers: []
```
-### MCP Servers
+## MCP Servers
-Each `tools.mcpServers` entry is `{ name, config }`: `name` is restricted to letters/digits/`_`/`-` (it becomes the tool-name prefix), and `config` describes the transport. Three transports are supported:
+Each `tools.mcpServers` entry is `{ name, config }`. `name` becomes the tool-name prefix: it must start with a letter or digit and contain only letters, digits, `_` and `-`, and a duplicate name is skipped. `config` describes the transport. Three transports are supported:
-- `stdio` — a local process (`command` / `args` / `env` / `cwd`). The process environment is the SDK's safe inherited defaults plus the entry's `env` (later wins); the Agent vault is **not** injected into MCP Server processes (unlike command subprocesses) — a variable a Server needs must be listed explicitly in the entry's `env`. `cwd` defaults to the Session's Workspace.
-- `http` — Streamable HTTP, the current spec's remote transport (`url` / `headers`).
-- `sse` — the legacy HTTP+SSE transport, kept for servers that have not migrated (`url` / `headers`).
+- `stdio`: a local process (`command` / `args` / `env` / `cwd`). The process environment is the SDK's safe inherited defaults plus the entry's `env`, with `env` winning. Unlike command subprocesses, MCP Server processes do **not** receive the agent's Vault: list any variable a Server needs in the entry's `env`. `cwd` defaults to the Session's Workspace.
+- `http`: Streamable HTTP, the current spec's remote transport (`url` / `headers`).
+- `sse`: the legacy HTTP+SSE transport, kept for servers that have not migrated (`url` / `headers`).
-The `transport` field may be omitted: an entry with `command` infers `stdio`, one with `url` infers `http`; `sse` must always be explicit. All three share the optional `connectTimeoutMs` (connect + tool-discovery budget, default 10000), `timeoutMs` / `maxOutputLength` (execution bounds applied to every tool of that Server; Environment defaults when unset) and `permission` (`auto` / `r` / `rw`, default `auto` — see the permission bullet below). `headers` are attached to every HTTP request to that Server (SSE stream included), so they can carry auth headers such as `Authorization`.
+The `transport` field may be omitted: an entry with `command` infers `stdio`, and one with `url` infers `http`. `sse` must always be explicit.
+
+All three transports share these optional fields:
+
+| Field | Meaning |
+| --- | --- |
+| `connectTimeoutMs` | Budget for connecting and discovering tools, default 10000 |
+| `timeoutMs` | Execution timeout for every tool of that Server; the Environment default when unset |
+| `maxOutputLength` | Output cap for every tool of that Server; the Environment default when unset |
+| `permission` | `auto` / `r` / `rw`, default `auto`; see [Permission mapping](#permission-mapping) |
+
+`connectTimeoutMs`, `timeoutMs` and `maxOutputLength` must be positive numbers here; an entry with a value of 0 or less is invalid. `headers` are attached to every HTTP request to that Server, SSE stream included, so they can carry auth headers such as `Authorization`.
```yaml
tools:
@@ -287,11 +422,26 @@ tools:
permission: r # auto (default) | r | rw
```
-Behavior:
+### Connection and discovery
+
+- Connecting is **lazy**. Creating a Session returns at once; the first `run()` connects all Servers in parallel and discovers their tools once.
+- The wait streams as one `mcp_connect_begin` / `mcp_connect_end` pair: frontends show a connecting status, and the end event carries the overall status plus per-Server results. The full tool definitions follow as a `tool_list_ready` event (see [OmniMessage](/omni-message)). In the Trace, all three land after the run's input, inside the new turn.
+- Aborting during the connect **cancels** the attempt, and the next `run()` connects again.
+- The discovered tools are a snapshot for the model context: `tools/list_changed` notifications are ignored. When a compaction opens the next context, a Server whose entry is unchanged keeps its live connection and tools. Removed or changed Servers are closed, and new, changed or previously failed ones connect again. The connect event pair appears only when some Server needs connecting, while `tool_list_ready` is always emitted (see [Compaction](/agent-loop)).
+- An unreachable Server or an invalid entry only produces a warning on stderr and is skipped. **The Session is never blocked.**
+- Discovered tools join the flat tool namespace as `mcp__<server>__<tool>`. A tool whose full name is not a valid LLM tool name (letters, digits, `_` and `-`, at most 128 characters) or that the Server lists twice is skipped with a warning. The rest go through the same [execution contract](#execution-contract) (timeout, truncation, interruption) and [approval](#approval) flow as built-in tools.
+
+### Permission mapping
+
+- Under the default `permission: auto`, a tool the Server annotates with `readOnlyHint: true` is `r`, which the `read-only` approval mode auto-approves. Everything else is `rw`: annotations are untrusted hints, so the default leans restrictive.
+- Setting the entry's `permission` to `r` or `rw` overrides the annotation for **every** tool of that Server. This is the way to handle the many Servers that never set `readOnlyHint` and so land on `rw` entirely.
+- `permission` fixes the level each of the Server's tools reports, and exactly one approval mode reads that level. Under `read-only`, an `r` tool is auto-approved and an `rw` tool needs manual confirmation. `allow-all`, `deny-all` and `always-ask` never consult it, so marking an entry `rw` adds no prompt in those modes.
+- Beyond that, the key does nothing. It does not sandbox the Server or restrict what its tools do when they run. It is never sent to the Server or checked against it, and the Server keeps whatever capabilities its transport gives it. Marking a Server `r` when it can in fact write removes the confirmation `read-only` would have asked for.
+
+### Results and teardown
-- Connecting is **lazy**: Session creation returns instantly, and the first `run()` connects all Servers in parallel and discovers tools once — the wait streams as one `mcp_connect_begin` / `mcp_connect_end` pair (frontends show a connecting status; the end carries the overall status plus per-Server results), and the full tool definitions follow as a `tool_list_ready` event (see [OmniMessage](/omni-message)); in the Trace all three land after the run's input, inside the new turn. Aborting mid-connect **cancels** the attempt — the next `run()` reconnects. The result is a snapshot for the model context: `tools/list_changed` notifications are ignored, and when a compaction opens the next context the Servers reconnect from the then-current config, bracketed by the same event pair (see [Compaction](/agent-loop)). An unreachable Server or invalid entry only produces a stderr warning and is skipped — **the session is never blocked**.
-- Discovered tools join the flat tool namespace as `mcp__<server>__<tool>` and go through the same [execution contract](#execution-contract) (timeout, truncation, interruption) and [approval](#approval) flow as builtin tools.
-- Permission mapping: under the default `permission: auto`, a tool the Server annotates `readOnlyHint: true` is `r` (auto-approved by the read-only approval mode); everything else is `rw` — annotations are untrusted hints, so the default takes the restrictive direction. Setting the entry's `permission` to `r` or `rw` overrides the annotation for **every** tool of that Server, which is the way in for the many Servers that never set `readOnlyHint` and so land on `rw` wholesale.
-- What `permission` is: it fixes the level each of that Server's tools reports, and exactly one approval mode reads that level. Under `read-only` an `r` tool is auto-approved and an `rw` tool needs manual confirmation; `allow-all`, `deny-all` and `always-ask` never consult it, so marking an entry `rw` adds no prompt there. Beyond that the key does nothing: it does not sandbox the Server, does not restrict what its tools do when they run, is never sent to or verified against the Server, and the Server keeps whatever capabilities its transport gives it. Marking a Server `r` that can in fact write removes the confirmation `read-only` would have asked for.
-- Result mapping: text blocks concatenate into the output text; image blocks ride along as images (data URLs); audio and binary resources collapse to placeholder lines; a result with only `structuredContent` is serialized as JSON; a Server-reported `isError` lands as `stop_reason: "failed"` with the Server's error text as the content.
-- Session teardown (`Environment.dispose`) closes every MCP client; stdio child processes exit with it.
+- Text blocks are joined into the output text, and image blocks ride along as images (data URLs).
+- Audio and binary resources become placeholder lines; a text resource contributes its text; a `resource_link` becomes `[resource: <uri>]` plus its description; an unknown block type becomes `[unsupported content type: <type>]`.
+- When the joined text is empty, `structuredContent` is serialized as JSON.
+- A Server-reported `isError` ends the call with `stop_reason: "fatal"`, and the Server's error text as the content (`[tool reported an error with no message]` when it sent none).
+- Session teardown (`Environment.dispose`) closes every MCP client, and stdio child processes exit with it.
diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.md
index 083ac79b..936d6260 100644
--- a/packages/docs/content/tools.zh.md
+++ b/packages/docs/content/tools.zh.md
@@ -1,20 +1,21 @@
---
title: 工具与审批
-description: 极简内置工具集的设计与执行契约、Environment 统一收尾规则,以及逐调用审批与 Trace 审计。
+description: 内置工具如何运行在同一套执行契约之下,每次调用如何经过审批、在 Trace 中留下审计记录,以及 MCP Server 如何接入。
---
-## 设计取向
+PenguinHarness 刻意只提供一套极简的内置工具集。专用文件工具(`read_file` / `edit_file` / `write_file`)负责精确的读取和编辑,因为带行号的输出和精确字符串替换,比手写 `sed` 单行命令更可靠。Shell(`exec_command`)则是其他一切的通用兜底:运行程序、搜索、安装依赖。留下来的每个工具,都配得上它在 schema 上占用的 Token。
-PenguinHarness 刻意维持一个极小的内置工具集:文件的精确读取与编辑交给专门的文件工具(`read_file` / `edit_file` / `write_file`)——带行号的输出与精确字符串替换比拼 `sed` 命令更可靠;Shell(`exec_command`)仍是通用兜底接口,负责运行程序、搜索、装依赖等其余一切。保留下来的每个工具都对得起它占用的 schema Token。
+Environment 让每一次工具调用都走同一套共享契约,并集中处理收尾。本页先讲这套契约,之后依次介绍:各工具的配置字段、7 个内置工具和它们的后台行为、记录在 Trace 中的逐次调用审批,以及如何自定义工具集、添加 MCP Server。
## 执行契约
-所有内置工具实现同一个 `BuiltinTool` 接口(`packages/core/src/environment/tools/types.ts`):
+每个内置工具都实现同一个 `BuiltinTool` 接口(`packages/core/src/environment/tools/types.ts`):
```ts
interface BuiltinTool {
name: string;
definition: ToolDefinitionConfig;
+ detachable?: boolean; // has a background form a running call can be moved to (exec_command, run_subagent)
execute(
args: Record<string, unknown>,
ctx: ToolExecutionContext,
@@ -25,248 +26,386 @@ interface ToolExecutionContext {
workspaceDir: string;
toolCallId: string;
signal?: AbortSignal;
- approve?: ApproveFn; // 供需要派生子 Session 的工具转发(审批继承)
+ detachSignal?: AbortSignal; // fires when the host asks this call to continue as a background task
+ approve?: ApproveFn; // forwarded to tools that spawn child Sessions (approval inheritance)
}
interface ToolResult {
- stopReason?: StopReason; // 工具自报终态(优先级最低,见下)
- note?: string; // 追加在输出预算之外的终止标记(如退出码)
- images?: string[]; // data URL 图像,附加在文本输出之后
+ stopReason?: StopReason; // the tool's self-reported terminal state (lowest priority, see below)
+ note?: string; // terminal marker appended outside the output budget (e.g. exit code)
+ images?: string[]; // data-URL images, appended after the text output
}
```
-工具本身只需 yield 增量的 `partial_tool_call_output`,收尾由 Environment 集中处理:
+工具本身只产出 `partial_tool_call_output` 增量,收尾由 Environment 集中处理:
-- 流式分帧(start / stop)与 `tool_call_id` 贯穿;
-- 超时归并;输出超过 `maxOutputLength`(默认 16000 字符)时按头尾双窗截断:预算对半开,头窗照常流式转发,尾窗在收尾时随 `[output truncated: kept first H and last T of C chars]` 标记补出——总量 C 供模型判断是否值得读 recovery 文件;超出头窗但未超预算的输出则在收尾时原样补出、不加标记;
-- stop_reason 按优先级归并:用户中断 > 超时 > 工具抛错 > 工具自报;
-- 输出永不为空:没有任何输出时补 `[no output]`;
-- `note`(如退出码)与图像附加在输出预算之外,长输出被截断时终止标记不会丢失。
+- 流式分帧(start / stop),以及 `tool_call_id` 的全程传递;
+- 超时控制,以及输出超过 `maxOutputLength`(默认 16000 字符)后只保留头部和尾部的截断;
+- `stop_reason` 的优先级:用户中断 > 超时 > 工具抛错 > 工具自报。超时或抛错都会让调用以 `fatal` 结束;
+- 输出永不为空:调用既没有产出文本也没有 note 时,用 `[no output]` 代替;
+- `note`(例如退出码)和图片不计入输出预算、直接追加在末尾,因此截断长输出也不会丢掉终止标记。
-工具与 Environment 从不向引擎抛异常:错误一律折叠为 `tool_call_output` 消息,交给模型阅读并调整下一步。参数不合工具定义的调用以 `fatal` 收尾,整段输出即一份纠错指引:出错之处、实际收到的参数名(点出 schema 未声明的名字)、按 schema 重述的全部参数,以及一次正确调用的形态——仅凭这段输出就能改对再发。消息结构见 [OmniMessage 协议](/omni-message)。
+截断时预算一分为二,头部窗口实时流出。收尾时,Environment 会发出 `[output truncated: kept first H and last T of C chars]` 标记,随后跟上尾部窗口。这个总数 `C` 能帮模型判断[恢复文件](#过长输出恢复)值不值得读。如果输出超过头部窗口、但在预算之内结束,收尾时会原样刷出,不加标记。
+
+工具和 Environment 都不会向引擎抛异常。错误会转成模型能读懂、能据此作出反应的 `tool_call_output` 消息。参数不符合工具要求的调用会以 `fatal` 结束,全部输出就是一份纠错指南:
+
+- 错在哪里;
+- 实际收到的参数名,并指出哪些是未知的;
+- 从 schema 复述出来的工具参数;
+- 一次正确调用应有的结构。
+
+只凭这份输出,就足以修好这次调用。消息结构见 [OmniMessage 协议](/omni-message)。
### 过长输出恢复
-Agent Session 中的工具文本超过 `maxOutputLength` 时,模型与 Web/CLI 仍收到相同的头尾窗口、带计数的截断标记与终止标记,「用户所见 = 模型所见」的流式契约也保持不变。Environment 还会在该可见输出上限之外追加一条简短的归档状态/路径 note,并保存归该 Session 所有的 recovery 文件:单次归档预算内保存完整文本,超出预算则保存有界头尾。这里的「完整」特指 **Environment 实际收到的文本**:命令或子 Agent Session 等生产者可能已在自身的有界未读缓冲区中用 `[..., N chars of earlier output dropped ...]` 标记替换溢出内容,下游归档无法恢复在此之前已经丢失的原文。
+Agent Session 中的工具文本超过 `maxOutputLength` 时,模型、Web App 和 CLI 收到的仍是同样的头部和尾部窗口、带计数的截断标记和终止标记。「用户可见输出等于模型可见输出」这条流式不变量保持不变。
+
+在这个可见上限之外,Environment 会追加一条简短的归档状态或路径 note,并保存一份归 Session 所有的恢复文件。文件里保存单次调用归档预算内的精确原文,超出部分则是限定大小的头部和尾部窗口。它是 Environment **收到的完整文本**:命令会话或子 Agent 会话这类生产者,可能已经在自己有限的未读缓冲区里,把溢出内容替换成了 `[... N chars of earlier output dropped ...]` 标记,在那之前丢失的文本,归档无法找回。
+
+普通的多行归档,Agent 用现成的 `read_file`(`offset` / `limit`)读取。要读字节尾部或超长行,它会构造针对性的 shell 命令,比如 `rg` 或 `tail`;没有专门的取回工具。
+
+note 里带一个普通绝对路径,总是括号内的最后一个元素。在 Windows 上路径使用正斜杠:`exec_command` 经 Git Bash 运行,Node 的 fs API 也接受正斜杠,所以同一种写法在 JSON 工具参数和 shell 命令里都能用。POSIX 路径原样保留,Session 路径本来就是普通绝对路径(从不带 `\\?\` 前缀),因此更换分隔符不会丢失任何内容。和其他路径一样,里面有空格时,在 shell 命令中要加引号。
+
+core 为模型拼出的每一条路径都遵循同一写法规则:
-普通多行归档可用现有 `read_file`(`offset` / `limit`)查看;若要读取字节级尾部或超长单行,Agent 必须自行构造定向的 `rg` / `tail` 等 Shell 命令,不新增专用读取工具。note 中的路径是普通绝对路径,恒为括号内最后一个元素。Windows 上统一写成正斜杠:`exec_command` 经 (Git) Bash 执行、Node 的 fs API 也接受正斜杠,同一拼写在 JSON 工具参数与 Shell 命令中通用;POSIX 路径原样透传,且 Session 路径都是普通绝对路径(不会带 `\\?\` 前缀),分隔符替换无损。含空格的路径在 Shell 命令中照常引用即可。同一拼写规则覆盖 core 产出给模型的全部路径——系统提示词的 App Data Dir / CWD 行、`[attached image/file: …]` 行与 Goal file 行(SDK 中的 `modelVisiblePath`)。
+- 系统提示词中的 App Data Dir / CWD 行;
+- `[attached image/file: …]` 行;
+- 目标模式的 goal 文件行(SDK 里的 `modelVisiblePath`)。
-Recovery 文件位于该 Session 的 `scratchpad/<session-id>/truncated-tool-output/`,仅在确实发生截断时创建;平台支持时使用仅当前用户可读写的私有权限。单次调用最多保存 8 MiB(生产字节上限少 1 byte,以保持低于 `read_file` 的 8 MiB 扫描上限);更大的输出在文件中保留有界头尾并写明中间被截。该限制仅针对单次调用:一个 Session 没有归档总字节数或文件数配额,并发捕获也各自最多保留一份单调用预算。文件跨 Task、运行时释放和 Session 恢复保持可读,直到用户明确删除 Session 时由现有路径连同整个 scratchpad 一起移除;不新增单独的归档清理生命周期。
+| 属性 | 恢复文件的行为 |
+| --- | --- |
+| 位置 | `scratchpad/<session-id>/truncated-tool-output/`,位于 Session 之下 |
+| 创建 | 只在实际发生截断后才创建 |
+| 权限 | 平台支持时设为私有 |
+| 单次调用大小 | 最多 8 MiB;生产环境的字节上限还要再低 1 字节,保证 `read_file` 始终低于 8 MiB 的扫描上限 |
+| 更大的输出 | 限定大小的头部和尾部窗口,中间带有明确的缺口标记 |
+| 配额 | 只按单次调用计:Session 没有总字节数或文件数配额;并发捕获时,每次捕获各自最多保留一次调用的预算 |
+| 生命周期 | 跨 Task、运行时销毁和 Session 恢复都可读,直到显式删除 Session 才随整个 scratchpad 一起移除;归档没有单独的清理机制 |
+
+> [!WARNING]
+> 恢复文件里是 Environment 收到的未经脱敏的工具文本。如果工具不小心读到凭据或其他敏感数据,磁盘上的本地副本会从可见窗口扩大到整个归档预算。
-Recovery 文件保存 Environment 收到的未经脱敏的工具文本。误读凭据或其他敏感数据会使本地静态留存量从可见窗口扩大到归档预算。Trace 不重复保存这些正文,但会记录模型与 Web/CLI 看到的同一个绝对 Session 路径,因此会暴露宿主的数据根目录布局。归档写入失败不改变原工具的 `stop_reason`;双方可见的 note 与 stderr 警告只携带简短错误码(stderr 另含工具名),不携带路径或原始错误消息。
+Trace 不会再存一份这些内容,但会记录展示给模型、Web App 和 CLI 的同一个绝对 Session 路径,这会暴露宿主的数据根目录布局。
+
+归档写入失败不会改变原工具的 `stop_reason`。可见 note 和 stderr 警告只带一个简短的错误码(stderr 上另有工具名),从不带路径,也不带原始错误信息。
## 配置字段
-每个工具由一条 `ToolDefinitionConfig` 描述:
+每个工具由一个 `ToolDefinitionConfig` 描述:
-| 字段 | 说明 |
+| 字段 | 含义 |
| --- | --- |
-| `name` | 工具名,对应模型产出的 `tool_call.name` |
-| `description` | 提供给模型的工具说明 |
-| `parameters` | 参数 JSON Schema |
+| `name` | 工具名,与模型的 `tool_call.name` 对应 |
+| `description` | 交给模型的工具描述 |
+| `parameters` | 参数的 JSON Schema |
| `permission` | `"r"` 只读 / `"rw"` 读写 |
-| `forModel` | `"vision"` / `"text-only"`:按 Session 模型类别装配;缺省对所有模型可用(内置条目均不设——`read_file` 同时服务两类模型) |
-| `timeoutMs` | 单次调用超时(ms),默认 120000;`<=0` 关闭 |
-| `maxOutputLength` | 输出长度上限(字符);`<=0` 关闭 |
-| `call_description` | 条目级开关:控制 `parameters` 中声明的 `description` 调用参数(开启时为必填);缺省保留,`false` 时装配阶段将其连同 `required` 项从 schema 滤除 |
+| `forModel` | `"vision"` / `"text-only"`:按 Session 模型的类别选用。省略表示对所有模型可用。没有内置条目设置它,因为 `read_file` 要同时服务两类模型 |
+| `timeoutMs` | 单次调用超时(毫秒),默认 120000;`<=0` 表示禁用 |
+| `maxOutputLength` | 输出长度上限(字符);`<=0` 表示禁用 |
+| `call_description` | 针对 `parameters` 中声明的 `description` 调用参数的逐工具开关(开启时必填)。缺省表示保留;`false` 则在组装时从 schema 中移除这个属性和它的 `required` 条目 |
## 内置工具
-共 7 个内置工具(装配入口 `packages/core/src/environment/tools/registry.ts`):
+内置工具共 7 个,通过 `packages/core/src/environment/tools/registry.ts` 组装:
-| 工具 | 权限 | 超时(ms) | 用途 |
+| 工具 | 权限 | 超时(ms) | 用途 |
| --- | --- | --- | --- |
-| `exec_command` | rw | 120000 | 在 Workspace 内以 `bash -lc` 运行命令,流式返回 stdout/stderr |
-| `input_command` | rw | 120000 | 按 `process_id` 驱动命令会话:写 stdin、发 Ctrl-C、轮询输出,或终止(`kill: true`) |
-| `read_file` | r | 60000 | 按 `cat -n` 风格带行号读取文本文件(以 offset/limit 分页),或读取图片(路径或 URL)作为图像内容返回——text-only 模型则由 `vision_model` 代读为文字 |
-| `edit_file` | rw | 30000 | 对既有文件做精确字符串替换,回显校验片段 |
-| `write_file` | rw | 30000 | 新建或整体覆写文件,按需创建父目录 |
-| `run_subagent` | rw | 600000 | 把自包含子任务委派给同 Workspace 的子 Agent |
-| `input_subagent` | rw | 600000 | 轮询后台 Subagent、运行中插话、停止其当前轮,或在其空闲时追加后续 Prompt |
+| `exec_command` | rw | 120000 | 在 Workspace 中执行 shell 命令(有 bash 的环境通过 `bash -lc` 执行),流式输出 stdout/stderr |
+| `input_command` | rw | 120000 | 通过 `process_id` 操控命令会话:写入 stdin、发送 Ctrl-C、轮询输出,或终止会话(`kill: true`) |
+| `read_file` | r | 60000 | 读取文本文件,返回带行号(`cat -n`)的窗口,按 offset/limit 分页;或读取图片(路径或 URL)返回图片内容;对纯文本模型,由 `vision_model` 用文字描述图片 |
+| `edit_file` | rw | 30000 | 在已有文件中精确替换字符串,并回显变更的 diff |
+| `write_file` | rw | 30000 | 创建或覆盖整个文件,必要时自动创建父目录 |
+| `run_subagent` | rw | 600000 | 把一个自包含的子任务委托给同一 Workspace 中的子 Agent |
+| `input_subagent` | rw | 600000 | 轮询后台子 Agent、在运行中向它插话、停止它当前这次运行,或用后续 Prompt 继续对话 |
+
+已有 Agent 保存的 `tools.builtin` 列表与写入时完全一致;设置界面可以编辑条目,但不会新增。因此:
-注意:既有 Agent 已落盘的 `tools.builtin` 列表按原样冻结(设置页只能编辑行、不能增行):较早创建的 Agent 不会自动获得后来新增的工具(如文件工具)与新增参数(`run_in_background`、`kill`、`abort`),已移除工具(`kill_command`、`kill_subagent`、`read_image`、`describe_image`)的存量条目则不再装配——模型按旧名调用得到标准的未知工具报错;读图之前落盘的 `read_file` 条目保留旧描述与旧超时(其背后的实现已能读图)。采纳当前定义需手工编辑该 Agent 的 `system_config.yaml`(可从 `packages/core/src/state/default-config.ts` 的默认定义复制),或走「更新内核」。
+- 在这套工具集出现之前创建的 Agent,不会自动获得后续新增的工具(例如文件工具)和新增的参数(`run_in_background`、`kill`、`abort`)。
+- 已删除工具(`kill_command`、`kill_subagent`、`read_image`、`describe_image`)的条目不再参与组装。模型调用这类工具,会得到标准的未知工具错误。
+- 在 `read_file` 支持图片之前保存的条目,仍保留旧的描述和超时,尽管背后的实现已经能读取图片。
+
+要采用当前的定义,需要手动编辑 Agent 的 `system_config.yaml`,并从 `packages/core/src/state/default-config.ts` 的默认配置中复制相应条目。Agent 设置页上的**更新内核**只有在 **工具** 标签页不存在、或仍是未经编辑的旧默认值时才会重写这份列表;**还原为默认配置**则会始终重写,但会把整个配置一并重置。见[内核更新](/configuration#内核更新)。
### 调用描述
-命令 / Subagent 类工具(`exec_command`、`input_command`、`run_subagent`、`input_subagent`)带 `description` 参数:由模型写一句"本次调用在做什么",CLI 与 Web 在调用运行期间展示给用户。该参数作为普通的 `description` 属性直接写在各条目的 `parameters` 中(工具 schema 完全存于可编辑配置),并且是**必填**的——提供该参数的工具每次调用都会带上它,前端据 schema 即可确定这次调用的展示形态,无需在参数流式过程中猜测;同时要求模型最先输出它。整个参数由条目级 `call_description` 字段控制——缺省保留,写 `call_description: false` 时装配阶段将该属性连同其 `required` 项一起从 schema 中滤除(仅内存内,不改写 YAML)。文件工具不带此参数——其 `file_path` 参数本身已说明用途。
+命令类和子 Agent 类工具(`exec_command`、`input_command`、`run_subagent`、`input_subagent`)都接受一个 `description` 参数:由模型撰写的一句话,说明这次调用正在做什么,CLI 和 Web App 会在调用执行期间显示这句话。
+
+这个参数在 `system_config.yaml` 中声明为每个条目 `parameters` 里的一个普通 `description` 属性,因为工具 schema 完全存放在可编辑的配置里。它在配置中是 **必填** 的,因此凡提供这个参数的工具,模型总会给出值。前端可以从 schema 直接确定调用的展示形式,而不必在参数流式传来的过程中猜测;同时要求模型最先输出这个参数。
+
+每个条目的 `call_description` 字段控制整个功能。字段缺省表示保留;`call_description: false` 会在组装时从 schema 中移除这个属性及其 `required` 条目。这个变更只发生在内存里,YAML 文件本身不会改动。
+
+文件工具不接受这个参数,因为它们的 `file_path` 已经说明了调用在做什么。
### 命令会话
-`exec_command` 先在前台等待;命令超过 `yield_time_ms` 仍未结束时转入后台,返回已有输出和一个 `process_id`,之后用 `input_command` 驱动。传 `run_in_background: true` 则完全跳过前台窗口:调用立即返回 `process_id`,进程退出时其结果以自动 user message 送达(见[后台完成回报](#后台完成回报))。两种方式启动的会话都可用 `input_command` 的 `kill: true` 终止——进程是真实的 OS 对象、确会销毁,终止因此是访问工具的一个参数而非独立工具:
+`exec_command` 先在前台等待。如果命令在 `yield_time_ms` 内没有结束,就转入后台,调用返回目前的输出和一个 `process_id`;此后由 `input_command` 操控。设置 `run_in_background: true` 后,`exec_command` 跳过前台等待:调用立即返回 `process_id`;进程退出时,结果会以一条自动用户消息的形式送达(参见[后台完成回报](#后台完成回报))。
+
+带 `kill: true` 的 `input_command` 可以终止以任一方式启动的会话。进程是真实的操作系统对象,终止就是真的销毁,因此「终止」是访问工具的一个参数,而不是一个独立的工具:
```text
exec_command(cmd)
- ├─ 前台窗口(yield_time_ms,默认 60000)内结束 ──► 完整输出 + 退出码
- ├─ 未结束 ──► 转入后台,返回已有输出 + process_id
+ ├─ finishes within the foreground window (yield_time_ms, default 60000)
+ │ ──► full output (+ an exit-code or signal note when it failed)
+ ├─ still running ──► backgrounds, returns output so far + process_id
│ │
- │ input_command(process_id[, chars]) ──► 写 stdin / 发 Ctrl-C / 轮询
- │ └─ 循环驱动,直至命令退出
- └─ run_in_background: true ──► 立即返回 process_id
- └─ 退出时:完成回报以 user message 送达
- input_command(process_id, kill: true) ──► 对进程组 SIGTERM(宽限后 SIGKILL)
+ │ input_command(process_id[, chars]) ──► write stdin / send Ctrl-C / poll
+ │ └─ loop until the command exits
+ └─ run_in_background: true ──► returns process_id immediately
+ └─ on exit: completion report arrives as a user message
+ input_command(process_id, kill: true) ──► SIGTERM the process group (SIGKILL after a grace period)
```
-各工具的参数(明确键名):
+正常退出的命令不附加任何注记。非零退出会附加 `[exit code: N]`,因信号终止会附加 `[terminated by signal S]`;两种情况都以 `fatal` 结束调用。
+
+工具参数(显式键):
```ts
// exec_command
{
- cmd: string; // 必填:要执行的 shell 命令(也接受别名 `command`;schema 只声明 `cmd`)
- workdir?: string; // 工作目录;缺省为 Workspace 根,相对路径按其解析
- yield_time_ms?: number; // 前台等待时长;默认 60000,最小 250,上限受工具超时约束
- run_in_background?: boolean; // true = 立即返回 process_id;完成回报以 user message 送达
- description: string; // 开关开启时必填:一句话说明,最先输出,调用运行期间展示给用户
+ cmd: string; // required: the shell command to run (also accepted as `command`; the schema names only `cmd`)
+ workdir?: string; // working directory; defaults to the Workspace root, relative paths resolve against it
+ yield_time_ms?: number; // foreground wait; default 60000, minimum 250, capped below the tool timeout
+ run_in_background?: boolean; // true = return process_id immediately; completion arrives as a user message
+ description: string; // required while call_description is on: one sentence shown to the user while the call runs, emitted first
}
// input_command
{
- process_id: string; // 必填:exec_command 返回的命令会话 id
- chars?: string; // 写入 stdin 的字符;单独发送 "\u0003" 传递 Ctrl-C;缺省仅轮询
- yield_time_ms?: number; // 等待时长;有写入默认 250,空轮询默认 110000(一次轮询等完多数构建;想快速查看可传更小值)
- description: string; // 开关开启时必填
+ process_id: string; // required: the command-session id returned by exec_command
+ chars?: string; // characters for stdin; send "\u0003" alone to deliver Ctrl-C; empty = poll only
+ kill?: boolean; // true = terminate: kill the whole process group, return undelivered output, remove the session
+ yield_time_ms?: number; // wait; defaults 250 for writes, 110000 for empty polls (one poll waits out most builds; pass a smaller value to peek)
+ description: string; // required while call_description is on
}
-
```
-POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Windows 无法向管道子进程投递控制台信号,Ctrl-C 因此退化为整棵命令会话进程树的强杀(`taskkill /t /f`)——前台命令及其启动的所有子进程一并终止,而不是仅中断前台命令。
+**Shell:** 只要有 bash,命令就通过 `bash -lc` 执行,系统提示词会告诉模型当前使用的是哪个 shell。`PENGUIN_SHELL`(可执行文件名或路径)在所有平台上都能覆盖这个选择。否则按以下顺序挑选 shell:
+
+- POSIX 上:先找 PATH 中的 `bash`,再找常见的 bash 绝对路径,然后是 `$SHELL` 登录 shell,最后是 `sh`。
+- Windows 上:先找 PATH 中非 WSL 启动器的 `bash`(例如 Git for Windows),然后是内置的 MinGit bash,然后是 `pwsh`,最后是 `powershell`。
+
+**Ctrl-C:** 在 POSIX 上,Ctrl-C 向会话的进程组发送 `SIGINT`,中断前台命令。Windows 无法向通过管道连接的子进程发送控制台信号,因此 Ctrl-C 在这里变成硬杀整个命令会话树(`taskkill /t /f`):前台命令及其启动的所有子进程一并终止,而不只是中断前台命令。
### 文件工具
-`read_file` / `edit_file` / `write_file` 与 Shell 工具一样以用户完整权限运行:相对路径按 Workspace 解析,也接受绝对路径。软链接路径会被解析到它指向的文件——读取、编辑、写入都落在该文件上,链接本身仍然是链接。三者均为非流式(一次性输出最终结果),从不抛异常——失败以解释性文本收尾,`stop_reason` 为 `failed`。`edit_file` 与 `write_file` 在服务端进程内按文件串行,以文件的真实路径为键——软链接与它指向的文件算同一个文件——因此对同一文件的并行编辑会被逐个应用,先前编辑已删去的 `old_string` 会匹配失败而不是覆盖它;其他进程的写入不在这把锁的覆盖范围内。
+`read_file` / `edit_file` / `write_file` 与 shell 工具一样,以用户的完整权限运行。相对路径以 Workspace 为基准解析,也允许绝对路径。符号链接会解析到它指向的文件:读取、编辑和写入都作用于目标文件,链接本身仍是链接。`read_file` 拒绝读取机密存储 `.vault.toml` 和 `.project_config.toml`:无论文件位于哪个目录、路径是否经过符号链接,都按文件名匹配。
+
+文件工具返回单个最终输出,而不是流式输出;唯一的例外是:对纯文本模型,`read_file` 会流式返回视觉模型对图片的描述。这些工具从不抛出异常。失败时以解释性文字返回,并带有 `stop_reason: fatal`。
-`read_file` 也读图片。png/jpeg/gif/webp 文件(不超过 5MB,先按魔数、再按扩展名识别)或 `file_path` 里的 http(s) URL(URL 只作图片来源,优先看响应的 content-type)走读图分支,返回什么取决于 Session 模型的 vision 标记:接受图片的模型拿到图片本身作为图像内容(文本输出只有一行 `image/png, 123.4 kB`);text-only 模型拿到的是 Project 配置的 `vision_model` 对 `prompt`(缺省为详细描述)的回答,以流式文本作为工具输出——图片不进入该 Session 的历史。未配置 `vision_model` 时,text-only Session 的读图以解释性错误失败,请用户到模型设置中选一个。见 [模型与 Provider](/models)。分支由 SDK 仅为 text-only Session 注入 Environment 的 `VisionDescriberService` 决定,因此同一条配置条目(不带 `forModel`)同时服务两类模型。
+`edit_file` 和 `write_file` 在服务器进程内按文件串行执行,串行键取文件的真实路径,因此符号链接与其目标算作同一个文件。并行编辑同一文件时,会依次应用各次修改;如果前一次编辑已经移除了某个 `old_string`,后续编辑将匹配失败,而不是覆盖前面的修改。其他进程的写入不受这把锁约束。
+
+`read_file` 除文本外还能读取图片。图片分支接受不超过 5MB 的 png、jpeg、gif 或 webp 文件(先按魔数识别,再按扩展名识别),也接受 `file_path` 中给出的 http(s) URL。URL 只能用作图片来源,且会先检查响应的 content-type。
+
+返回什么取决于 Session 模型的 vision 标志:
+
+- 支持图片的模型会直接拿到图片内容,文字输出只有一行,例如 `image/png, 123.4 kB`。
+- 纯文本模型则由 Project 的 `vision_model` 回答 `prompt`(默认是一段详细描述),以工具文字输出的形式流式返回。图片本身不会进入这个 Session 的历史。未配置 `vision_model` 时,在纯文本 Session 中读取图片会失败,并提示用户到模型设置中选择一个。参见[模型与供应商](/models)。
+
+走哪个分支由 `VisionDescriberService` 决定;SDK 只在纯文本 Session 时才向 Environment 注入它,因此一条配置(不带 `forModel`)即可同时服务两类模型。
```ts
-// read_file — 文本文件按 cat -n 风格输出(行号、制表符、内容);超长单行会被截断,
-// 不是受支持图片的二进制内容(含 NUL 字节)被拒绝并提示改用 Shell。图片(或 http(s) URL)
-// 则返回图像内容或文字描述,并忽略 offset/limit。
+// read_file — cat -n style output (line number, tab, content) for text; overlong single lines
+// are truncated, and binary content that is no supported image (NUL bytes) is rejected with
+// advice to use the shell. An image (or an http(s) URL) returns image content or a text
+// description instead, and ignores offset/limit.
{
- file_path: string; // 必填:绝对路径,或相对 Workspace 的路径;图片亦可为 http(s) URL
- offset?: number; // 起始行号(1 起);默认 1
- limit?: number; // 最多返回的行数;默认 2000——未读完时尾部注记提示续读
- prompt?: string; // 对图片的提问,text-only 模型时由 vision_model 回答;缺省为详细描述
+ file_path: string; // required: absolute, or relative to the Workspace; an http(s) URL for an image
+ offset?: number; // 1-based line to start from; default 1
+ limit?: number; // max lines returned; default 2000 — a trailing note points at the continuation
+ prompt?: string; // a question about an image, answered by the vision_model for a text-only model; default: a detailed description
}
-// edit_file — 文件必须已存在;old_string 必须恰好出现一次(或设 replace_all);
-// 成功时回显 "Replaced N occurrence(s)" 及改动区域的 git 风格 unified diff
-// (每个替换点一个 hunk,相邻替换点合并;replace_all 大量命中时截断为少量 hunk
-// 并附 "…and N more replacements" 注记)。
+// edit_file — the file must exist; old_string must occur exactly once (or set replace_all);
+// success echoes "Replaced N occurrence(s)" plus a git-style unified diff of the changed
+// regions (one hunk per site, nearby sites merged; replace_all storms are capped at a few
+// hunks plus an "…and N more replacements" note).
{
- file_path: string; // 必填
- old_string: string; // 必填:要替换的原文,须与文件内容(含空白/缩进)完全一致
- new_string: string; // 必填:替换文本,须与 old_string 不同
- replace_all?: boolean; // 替换全部出现处;默认 false
+ file_path: string; // required
+ old_string: string; // required: exact text to replace, including whitespace/indentation
+ new_string: string; // required: must differ from old_string
+ replace_all?: boolean; // replace every occurrence; default false
}
-// write_file — 按需创建父目录;报告 "Created" 或 "Overwrote" 及行数/字节数。
-// 覆写时还会附上与旧内容的小型 unified diff;改动过大时改为一行 +X/−Y 摘要。
+// write_file — creates parent directories as needed; reports "Created" vs "Overwrote" with
+// lines/bytes. An overwrite also shows a small unified diff against the previous content,
+// or a one-line +X/−Y summary when the change is large.
{
- file_path: string; // 必填
- content: string; // 必填:完整文件内容;空字符串创建空文件
+ file_path: string; // required
+ content: string; // required: full file content; an empty string creates an empty file
}
```
-### Subagent
+### 子 Agent
+
+`run_subagent` 把一个能用单条 Prompt 完整描述的子任务交给子 Agent。它的两阶段流程与命令一致:前台窗口期(默认 300000ms)过后,子 Agent 转入后台并获得一个 `subagent_id`,之后由 `input_subagent` 操控。轮询等待期间,子 Agent 待审批的请求也会一并呈现。
+
+`input_subagent` 覆盖四种操作:
-`run_subagent` 把一段能一次说清的子任务交给子 Agent 执行,同样是两段式:前台窗口(默认 300000ms)过后转入后台并返回 `subagent_id`,由 `input_subagent` 驱动;子 Agent 的待审批项会在轮询等待期间浮出。`input_subagent` 覆盖四种手势:`prompt` 为空仅轮询;子会话**运行中**发 `prompt` 即中途插话(与用户对主会话的运行中 steering 同一机制——在子会话下一步以 `[user_steering]` 消息送达,写入子 Trace、sender 记为 `parent_agent`);空闲时发 `prompt` 即在同一会话上续跑一轮;`abort: true` 只停止子会话**当前这一轮**——会话保留、可继续插话或续跑,与 `prompt` 同给即打断并改道。`input_subagent` 每次访问的模型面输出是子会话**最近一条完整回复**——「它最后说了什么」的幂等快照,而非增量排空。传 `run_in_background: true` 则启动即返回 `subagent_id`,模型发起的每轮完成都以自动 user message 送达(面板发起的轮与被显式 abort 的轮不回报;见[后台完成回报](#后台完成回报))。**Subagent 没有 kill**:与主 Agent 一样,子会话永不销毁——释放空闲会话只是腾出并发额度,已释放的 `subagent_id` 在再次收到消息时**自动复活**(模型访问与面板走同一条 resume 路径)。
+1. `prompt` 为空表示轮询。
+2. 子 Agent **运行中**时发送的 `prompt`,会在运行途中注入一条插话消息。这与用户在主会话中插话是同一机制:消息会在子 Agent 的下一步以 `[user_steering]` 到达,记入子 Agent 的 Trace 时发送者标记为 `parent_agent`。
+3. 子 Agent 空闲时发送的 `prompt`,会在同一 Session 中开启一轮后续对话。
+4. `abort: true` 只停止子 Agent **当前这次运行**。Session 保留下来,仍可插话和继续对话;配合 `prompt` 使用,则中断当前运行并把它引向新的方向。
-Web App 的智能体面板用**与主对话相同的 composer**(子会话变体)驱动选中的子会话:正文、技能与 slash 技能命令、思考等级选择器(钉在子会话上,从其下一个模型上下文生效)、上下文圆环(子会话自身用量)、锁定模型徽标,以及审批模式选择——它读写的是父会话的模式,子会话审批本就按其判定。发消息就是对子会话的一次用户输入,无论其状态如何:运行中即插话,空闲即续跑一轮,会话已被释放则**复活**——服务端按 resume 口径恢复该子 Session(沿用其历史、模型与 Workspace)并重新纳管,对话直接继续。操作按钮的停止面只中止子会话当前这一轮。这一切与 `input_subagent` 收敛到 core 的同一通道;面板的运行标识以服务端实况为准,不再从对话文本推断。
+每次 `input_subagent` 调用都会向模型返回子 Agent **最近一次完整回复**:这是对它上一次发言的幂等快照,而不是增量式的逐段取回。
+
+设置 `run_in_background: true` 后,启动调用立即返回 `subagent_id`;模型发起的每一轮结束时,都会以一条自动用户消息送达完成通知。从面板启动的轮次、以及经显式 abort 结束的轮次则保持静默(参见[后台完成回报](#后台完成回报))。
+
+子 Agent **没有对应的 kill 操作**。与主 Agent 的 Session 一样,子 Agent 的 Session 永不销毁。释放一个空闲 Session 只是腾出它的槽位;已释放的 `subagent_id` 再次收到消息时会**自动复活**,模型和面板共用同一条恢复路径。
+
+Web App 的子 Agent 面板用**与主对话相同的输入框**(子 Agent 变体)操控选中的子 Agent,包含:
+
+- 消息正文;
+- Skill 和斜杠 Skill 命令;
+- 思考等级选择器,从子 Session 的下一次 LLM 请求起固定它的思考等级;
+- 上下文环,显示子 Agent 自身的用量;
+- 模型锁定徽标;
+- 审批模式选择器,修改的是父 Session 的模式,因为子 Agent 的审批正是按这个模式判定。
+
+无论子 Agent 处于什么状态,消息都是发给它的用户输入:运行中就是插话,空闲时就是一轮后续对话,Session 已释放时就是**复活**。复活子 Agent 时,服务器会恢复子 Session(连同它自己的历史、模型和 Workspace)并重新接管,对话就这样继续下去。操作按钮的停止形态只中止子 Agent 当前这次运行。这一切都通过与 `input_subagent` 相同的核心通道完成;面板上的运行中标记跟随的是服务器端子 Agent 的实时状态,而不是对话记录。
```ts
// run_subagent
{
- prompt: string; // 必填:完整的子任务(含全部上下文与期望的最终产出)
- agent_id?: string; // 子 Agent;缺省复用当前 Agent
- model_id?: string; // 子 Session 模型,须与 provider 成对给出;两者都缺省时继承父 Session 的模型
- provider?: string; // model_id 所属的 provider 组;给出 model_id 时必填
- thinking_level?: string; // "low" | "medium" | "high" | "xhigh" | "max";缺省继承父 Session 的思考等级
- yield_time_ms?: number; // 前台等待时长;默认 300000
- run_in_background?: boolean; // true = 立即返回 subagent_id;完成回报以 user message 送达
- description: string; // 开关开启时必填
+ prompt: string; // required: the complete subtask (all context + the exact final output expected)
+ agent_id?: string; // the child Agent; defaults to the current Agent
+ model_id?: string; // the child Session's model, paired with provider; omit both to inherit the parent Session's model
+ provider?: string; // the provider group model_id belongs to; required whenever model_id is given
+ thinking_level?: string; // "low" | "medium" | "high" | "xhigh" | "max"; omit to inherit the parent Session's level
+ yield_time_ms?: number; // foreground wait; default 300000
+ run_in_background?: boolean; // true = return subagent_id immediately; completion arrives as a user message
+ description: string; // required while call_description is on
}
// input_subagent
{
- subagent_id: string; // 必填:run_subagent 返回的后台 Subagent id
- prompt?: string; // 运行中即插话(steering);空闲时即续跑一轮;缺省仅轮询
- abort?: boolean; // 停止子会话当前这一轮(会话保留,被中止的轮不发完成回报);与 prompt 同给即打断并改道
- yield_time_ms?: number; // 等待时长;有追加默认 300000,空轮询默认 10000
- description: string; // 开关开启时必填
+ subagent_id: string; // required: the background Subagent id returned by run_subagent
+ prompt?: string; // steering interjection while the child runs; a follow-up round while it is idle; empty = poll only
+ abort?: boolean; // stop the child's CURRENT run (session kept; the aborted round sends no completion report); with a prompt: interrupt and redirect
+ yield_time_ms?: number; // wait; defaults 300000 with a prompt, 10000 for empty polls
+ description: string; // required while call_description is on
}
```
-- 深度上限为 1:Subagent 不能再派生 Subagent。
-- 子 Session 跟随父 Session:模型(除非以 `model_id`/`provider` 显式指定)、thinking level(除非以 `thinking_level` 显式指定——机械性子任务可调低,深度分析可调高)与 Workspace 均继承父级,而非 Project 默认值。
-- 子 Session 继承父 Agent 的审批回调,审批模式随父生效。
-- 子 Session 拥有独立 Trace,父 Trace 以 `subagent` 指针事件链接;子消息带 `origin` 标记回流到父级消息流。见 [Session 与 Trace](/sessions-and-traces)。
+- 深度上限为 1:子 Agent 不能再派生另一个子 Agent。
+- 子 Session 跟随父 Session,而不是 Project 的默认值:模型(除非 `model_id` / `provider` 另有指定)和 Workspace 都取自父 Session。
+- 思考等级同样跟随父 Session,除非 `thinking_level` 另有指定(成本低的机械性子任务用低等级,困难的分析用高等级)。子 Session 从创建起就继承父 Session 的等级;父 Session 没有显式设置时,继承的则是它当前上下文开启时的等级。父 Session 在对话中途设置的等级不会向下传递。
+- 子 Session 继承父 Agent 的审批回调,因此审批模式跟随父 Session。
+- 子 Session 拥有自己的 Trace,父 Session 通过一个 `subagent` 指针事件与它关联。子 Agent 的消息带 `origin` 标签流回父 Session 的消息流。参见 [Session 与 Trace](/sessions-and-traces)。
### 后台完成回报
-以 `run_in_background: true` 启动的任务,以及用户在 Web App 的工具调用行上转入后台的调用,都在结束时以**Harness 注入的 user message** 回报完成——模型无需轮询。被用户转入后台的调用,其工具结果里的说明会把这一点写明:让它自己跑,不要轮询、不要发输入,先去做别的事或结束本轮——用户把它转入后台正是为了不让模型跟进;完成时自会送回。消息以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符;Web App 将标记块折叠为一行提示)。其 `text` payload 带 `sender: "harness"`,在 Trace 中与真人输入相区分(见 [OmniMessage](/omni-message))。
+用 `run_in_background: true` 启动的任务,以及用户在 Web App 中从调用卡片[转入后台](/chat#把工具调用转入后台)的运行中调用,完成时都会以一条**由 harness 注入的用户消息**报告。模型无需轮询。
+
+用户转入后台的调用,会在自己的结果里说明这一点。这条提示告诉模型不要再过问这项工作(不要轮询、不要输入),转去做别的工作或结束本轮。用户把它转入后台,正是为了让模型别再跟进;完成通知会自行送达。
+
+消息以一个 `[background_task_done]` 标记块开头(包含 kind、id、status 和一行细节),随后是执行的内容和输出,上限 4000 字符:命令取尚未送达输出的末尾;子 Agent 则取它最近一次完整回复的结尾。Web App 把这个块显示为可折叠的通知。消息的 `text` 载荷带有 `sender: "harness"`,在 Trace 中以此与真人输入区分(参见 [OmniMessage](/omni-message))。
+
+报告何时送达取决于 Session 的状态:
+
+- **Task 正在运行:** 报告搭乘下一个轮次边界送达。已经在流式输出的最终回复不会错过它;Task 会再多走一轮来作出反应。
+- **Session 空闲:** 托管服务器会启动一个新 Task 来承载报告。SDK 嵌入方可以通过 `Session.onBackgroundNotice` / `takeBackgroundNotices` 订阅,或者让报告前置到下一次运行的开头。
+
+以下情况不发送报告:
+
+- 通过 `input_command` 的 `kill` 终止的命令:那次调用自身的结果已经说明了结局;
+- 经显式 `abort` 结束的子 Agent 轮次:发起 abort 的调用方会直接读到结局;
+- 用户从子 Agent 面板发起的轮次:这是用户与子 Agent 自己的对话。回答文本会留在面向模型的缓冲区里,供下一次轮询使用。报告只覆盖**模型发起的轮次**:`run_in_background` 启动的运行,以及 `input_subagent` 的后续轮次。
+
+**停止不等于失败。** 有意终止的命令报告 `status: stopped`,标记块里会直白地写明:没人要求就不要重启它。有意为之的停止包括:
+
+- 用户在 Web App 进程列表里按下**停止**按钮;
+- 外部发来的停止信号(`SIGTERM` / `SIGINT` / `SIGHUP`),例如在同一进程组的终端里按 Ctrl-C、执行 `pkill`,或 supervisor 关闭开发服务器;
+- harness 自己强制执行的停止,例如容量驱逐或空闲回收。
-送达时机:Task 进行中时,回报搭乘下一个 turn 边界——即使最终回复已在流式输出,Task 也会为回应它再延续一个 turn。Session 空闲时,托管 Server 自动以该回报发起新 Task(SDK 嵌入方可订阅 `Session.onBackgroundNotice` / `takeBackgroundNotices`,否则回报并入下一次 run 的输入)。经 `input_command` 的 `kill` 终止的命令不发回报——该调用自身的结果已说明结局;被显式 `abort` 结束的子会话轮同样不发(打断者当场读到结局)。回报只覆盖**模型自己发起的轮**——`run_in_background` 的启动轮与 `input_subagent` 的续跑轮;用户从智能体面板发起的轮是用户与子会话自己的对话,不发回报(该轮答案文本留在模型面缓冲,下次轮询照常取得)。
+对话确实需要知道:它启动的开发服务器已经停了。如果写成 `failed`,读起来就像一次崩溃,而对崩溃的开发服务器,合理的反应是重新启动,这恰恰推翻了刚刚有人要求的停止。`failed` 只留给无人要求的结果:spawn 错误、非零退出、硬杀,以及 OOM kill、segfault 这类故障信号。
-停止照样回报,只是不算失败。被人主动结束的命令回报 `status: stopped`——用户在 Web App 进程列表按下的「停止」、从外部递来的停止信号(`SIGTERM`/`SIGINT`/`SIGHUP`:同进程组终端里的 Ctrl-C、`pkill`、停掉 dev server 的管理进程),以及 Harness 自己强制的停止(容量淘汰、空闲回收)——其标记块直白地告知模型:无人要求就不要重启它。对话确实需要知道自己启动的 dev server 已经不在了;但若措辞为 `failed`,它读起来就像崩溃,而面对崩溃的 dev server,模型合理的反应正是把它重新拉起来,把别人刚做的停止撤销。`failed` 留给无人要求的结局:spawn 错误、非零退出、硬杀与故障信号(OOM 杀进程、段错误)。
+后台子 Agent 的生命周期独立于启动它的调用:
-后台 Subagent 的生命周期与发起它的调用解耦:中止范围只属于它自己(逐轮 `abort` 只结束一轮;会话只随父 Session 终结,容量释放的也可复活),其消息经发起 Session 实时流向前端(与前台窗口转发同一条 origin 通道),工具审批经发起调用自身的审批回调作为常驻 sink 解决——`allow-all` 下即发即忘可全程无人值守,失败也以 `status: failed` 的回报收尾,而不是子会话永久卡住。
+- **中止:** 中止范围属于它自己。针对单次运行的 `abort` 只结束一轮;Session 本身只在父 Session 结束时才结束,即便曾因容量压力释放过,也仍可复活。
+- **消息:** 通过发起它的 Session 实时流式传到前端,走的是与前台窗口相同的带 origin 标签的通道。
+- **审批:** 由发起调用自己的审批回调处理,回调会一直挂载。因此 `allow-all` 方式启动的子 Agent 可以无人值守运行;即使失败,也会以 `status: failed` 报告收尾,而不是让子 Agent 无限期等待。
### 后台会话上限
-| 会话类型 | 上限 | 淘汰策略 |
+| Session 类型 | 上限 | 驱逐策略 |
| --- | --- | --- |
-| 命令会话 | 64 | 满时优先淘汰已退出者,否则对空闲会话按 LRU 淘汰 |
-| Subagent 会话 | 8 | 只淘汰已完成者;运行中的从不淘汰,无空位则拒绝派生 |
+| 命令会话 | 64 | 满员时优先驱逐已退出的会话;否则终止并驱逐最近最少使用的会话 |
+| 子 Agent 会话 | 8 | 只驱逐已完成的会话,绝不驱逐运行中的会话;没有空间时直接拒绝创建 |
## 审批
-每个完整的 `tool_call` 触发且只触发一次审批决策:
+每个完整的 `tool_call` 都恰好对应一次审批决策:
```ts
-type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = 命令策略的拦截
+type ApprovalDecision = "allow" | "deny" | "forbidden"; // "forbidden" = the command policy's veto
type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
```
-| 使用面 | 行为 |
+| 入口 | 行为 |
| --- | --- |
-| SDK | 每次 `session.run` 传入 `approve` 回调;未注入时引擎默认全部拒绝(保守策略,避免无人值守下误放行) |
-| CLI | `--approve` 四种模式:allow-all(默认)/ deny-all / read-only / always-ask;read-only 自动放行 `permission: "r"` 的工具,其余转人工 |
-| Web / Server | 同样四种模式,按 Session 设置;每次决策前从数据库重读审批模式(修改即刻生效);工具的 `r`/`rw` 取自运行中上下文的工具集——权限修改在下一次轮换(压缩)生效;人工决策经 API 送达 |
+| SDK | 每次调用 `session.run` 时传入 `approve`。若不注入,引擎默认拒绝所有调用,因此无人值守时不会有任何操作获得批准 |
+| CLI | `--approve` 有四种模式:`allow-all`(默认)、`deny-all`、`read-only`、`always-ask`。`read-only` 自动批准 `permission: "r"` 的工具,其余交给人工处理。这个标志设置 CLI 所驱动的服务器端 Session 的审批模式;不设置时,运行在 Agent 命令里的 CLI 会继承调用方 Session 的模式 |
+| Web / Server | 同样四种模式,按 Session 各自设置。每次决策都从数据库重新读取模式,因此改动立即生效。工具的 `r` / `rw` 取自运行上下文的工具集,因此权限改动在下一次轮换(压缩)时生效。人工决策通过 API 传入 |
-deny 会合成一条 `aborted` 的 `tool_call_output` 供模型据此调整策略——`Tool call denied by user.`,被[命令策略](/configuration#沙箱安全策略)拒绝时为 `Tool call denied by policy.`,策略命中因此不会被读成「有人取消了」。见 [ApproveFn](/interfaces#approvefn)。每次决策都以 `approval_decision` 事件写入 Trace(策略拦截即记 `forbidden`),构成完整的审计记录。审批发生在 [Agent 运行循环](/agent-loop) 的工具执行阶段。
+已安装的 pre-tool-use 钩子先于审批回调生效。钩子返回 `deny` 会直接拒绝调用,返回 `allow` 会直接批准,两者都不询问;但[命令策略](/configuration#命令策略)依然会否决它所匹配的调用,哪怕钩子已经放行。参见 [Pre-tool-use 钩子](/agent-loop#pre-tool-use-hook)。
-子会话的审批不会因父任务结束而被自动拒绝。Web 服务端为每个会话运行时挂一个**会话生命周期的兜底审批出口**:没有活跃轮询窗口、也没有后台启动常驻出口的子会话审批请求直接上报用户(父会话空闲时亦然);父任务结束或被停止时只收敛**主会话**自身的未决审批——带 origin 的子会话审批保持待决、审批卡持续显示,直到用户决定。未挂兜底出口的宿主(CLI)保持旧口径:子会话请求排队,等 `run_subagent` / `input_subagent` 调用活跃时透传。
+被拒绝的调用会收到一条合成的 `aborted` `tool_call_output`,供模型据此作出反应。文案会指明决策方:
-## 自定义与 MCP
+| 决策方 | 输出 |
+| --- | --- |
+| 人工或审批模式(`deny`) | `Tool call denied by user.` |
+| 命令策略(`forbidden`) | `Tool call denied by policy.` |
+| pre-tool-use 钩子 | `Tool call denied by the <hook> hook[: <reason>].` |
+
+因此,命中策略绝不会在文案上显得像人工取消。参见 [ApproveFn](/interfaces#approvefn)。每次决策都会以 `approval_decision` 事件写入 Trace,策略否决记录为 `forbidden`,因此 Trace 就是一份完整的审计记录。审批发生在 [Agent 运行循环](/agent-loop)的工具执行阶段。
+
+**子 Agent 审批。** 父任务结束时,绝不会自动拒绝子 Agent 的审批。服务器会为它运行的每个 Session(包括 CLI 驱动的 Session)挂上一个与 Session 同生命周期的兜底审批出口。子 Agent 的审批请求只要既没有活跃的轮询窗口,也没有后台启动时挂上的出口,就会直接上报给用户,父 Session 空闲时也一样。父任务结束或停止时,只处理**主** Session 的待审批请求;带 `origin` 标记的子 Agent 审批会一直待定,卡片也一直留在屏幕上,直到用户作出决定。从不调用 `Session.setSubagentApprovalFallback` 的 SDK 嵌入方仍然只在轮询窗口内审批:子 Agent 的请求会一直等到 `run_subagent` 或 `input_subagent` 调用处于活跃状态。
+
+## 自定义工具集
-`system_config.yaml` 的 `tools.builtin` 数组以 `ToolDefinitionConfig` 同构条目声明工具集。注意语义是**整体替换而非合并**:整段省略时使用完整默认工具集;一旦写出,默认列表即被替换,要保留的每个工具都必须携带完整定义(含 `parameters` JSON Schema——工具的参数 schema 完全来自配置)。`tools.mcpServers` 承载 MCP Server 配置,见下节。另见 [配置参考](/configuration)。
+`system_config.yaml` 中的 `tools.builtin` 数组声明工具集,每一项都采用相同的 `ToolDefinitionConfig` 结构。它**整体替换默认工具集,而不是与默认值合并**。省略这一节,即保留完整的默认工具集;一旦写了这一节,默认列表就不复存在,保留的每个工具都必须给出完整定义,包括 `parameters` 的 JSON Schema,因为工具的 schema 完全来自配置。
+
+`tools.mcpServers` 存放 MCP Server 的配置,下一节详细介绍。另见[配置参考](/configuration)。
```yaml
tools:
- # 写出 builtin 即整体替换默认工具集(此例刻意只保留一个最小工具集)。
+ # Writing builtin replaces the default toolset wholesale (this example deliberately
+ # keeps a minimal single-tool set).
builtin:
- name: exec_command
description: Run a shell command in the workspace.
permission: rw
- # 可选的条目级开关:false 时从 schema 滤除 parameters.properties 里声明的
- # description 调用参数(缺省保留)。
+ # Optional per-tool toggle: false filters the `description` call argument
+ # (declared in parameters.properties) out of the schema (missing = kept).
call_description: false
timeoutMs: 120000
maxOutputLength: 16000
- # parameters: 必须携带完整 JSON Schema(默认定义见
- # packages/core/src/state/default-config.ts),此处从略。
+ # parameters: the complete JSON Schema is required (see the default definition
+ # in packages/core/src/state/default-config.ts); elided here.
mcpServers: []
```
-### MCP Server
+## MCP Server
+
+`tools.mcpServers` 的每一项都是 `{ name, config }`。`name` 会成为工具名的前缀:必须以字母或数字开头,且只能包含字母、数字、`_` 和 `-`;名称重复的条目直接跳过。`config` 描述传输方式,支持三种:
-`tools.mcpServers` 的每个条目是 `{ name, config }`:`name` 限字母/数字/`_`/`-`(作为工具名前缀),`config` 描述 transport,支持三种:
+- `stdio`:本地进程(`command` / `args` / `env` / `cwd`)。进程环境变量由 SDK 的安全继承默认值和条目的 `env` 合并而成,`env` 优先。与命令子进程不同,MCP Server 进程**不会**拿到 Agent 的 Vault:Server 需要的任何变量都要列在条目的 `env` 里。`cwd` 默认为当前 Session 的 Workspace。
+- `http`:Streamable HTTP,当前规范的远程传输方式(`url` / `headers`)。
+- `sse`:旧式 HTTP+SSE 传输方式,为尚未迁移的 Server 保留(`url` / `headers`)。
-- `stdio`——本地进程(`command` / `args` / `env` / `cwd`)。进程环境为 SDK 安全继承环境叠加条目 `env`(后者覆盖前者);Agent vault **不**注入 MCP Server 进程(与命令子进程不同)——Server 需要的变量须在条目 `env` 中显式列出。`cwd` 缺省为本次 Session 的 Workspace。
-- `http`——Streamable HTTP,当前规范的远程 transport(`url` / `headers`)。
-- `sse`——旧版 HTTP+SSE,仅为未迁移的服务保留(`url` / `headers`)。
+`transport` 字段可以省略:有 `command` 的条目推断为 `stdio`,有 `url` 的条目推断为 `http`。`sse` 必须始终显式声明。
-`transport` 字段可省略:有 `command` 推断为 `stdio`、有 `url` 推断为 `http`;`sse` 必须显式。三种 transport 共享可选的 `connectTimeoutMs`(连接 + 工具发现预算,默认 10000)、`timeoutMs` / `maxOutputLength`(作用于该 Server 全部工具的执行约束,缺省用 Environment 默认值)与 `permission`(`auto` / `r` / `rw`,缺省 `auto`,见下方权限条目)。`headers` 附加到该 Server 的每个 HTTP 请求(含 SSE 流),可承载 `Authorization` 等认证头。
+三种传输方式共享以下可选字段:
+
+| 字段 | 含义 |
+| --- | --- |
+| `connectTimeoutMs` | 连接与工具发现的时间预算,默认 10000 |
+| `timeoutMs` | 这个 Server 每个工具的执行超时;未设置时使用 Environment 默认值 |
+| `maxOutputLength` | 这个 Server 每个工具的输出上限;未设置时使用 Environment 默认值 |
+| `permission` | `auto` / `r` / `rw`,默认 `auto`;见[权限映射](#权限映射) |
+
+这里的 `connectTimeoutMs`、`timeoutMs` 和 `maxOutputLength` 必须是正数,取值小于等于 0 的条目无效。`headers` 会附加到发往这个 Server 的每一个 HTTP 请求上,SSE 流也不例外,因此可以携带 `Authorization` 这类认证头。
```yaml
tools:
@@ -280,14 +419,29 @@ tools:
transport: http
url: https://mcp.linear.app/mcp
headers: { Authorization: "Bearer ..." }
- permission: r # auto(缺省)| r | rw
+ permission: r # auto (default) | r | rw
```
-行为口径:
+### 连接与工具发现
+
+- 连接是**惰性**的。创建 Session 立即返回;第一次 `run()` 会并行连接所有 Server,并一次性完成工具发现。
+- 这段等待以一对 `mcp_connect_begin` / `mcp_connect_end` 事件流式发出:前端据此显示「连接中」状态,结束事件携带总体状态和每个 Server 的结果。完整的工具定义随后以 `tool_list_ready` 事件发出(见 [OmniMessage](/omni-message))。在 Trace 中,这三个事件都落在这次运行的输入之后,属于新的一轮。
+- 连接期间中断会**取消**这次尝试,下一次 `run()` 会重新连接。
+- 发现的工具是模型上下文的一份快照:`tools/list_changed` 通知一律忽略。压缩开启下一个上下文时,配置条目未变的 Server 保留现有连接和工具;已移除或已变更的 Server 会断开连接,新增、变更或此前连接失败的 Server 会重新连接。连接事件对只在有 Server 需要连接时才出现,而 `tool_list_ready` 总是会发出(见[上下文压缩](/agent-loop))。
+- Server 连不上或条目无效时,只会在 stderr 上输出一条警告并跳过。**Session 绝不会因此阻塞。**
+- 发现的工具以 `mcp__<server>__<tool>` 的形式加入扁平的工具命名空间。全名不符合 LLM 工具名规范(字母、数字、`_` 和 `-`,最多 128 个字符),或者 Server 重复列出的工具,会跳过并给出警告。其余工具与内置工具一样,走相同的[执行契约](#执行契约)(超时、截断、中断)和[审批](#审批)流程。
+
+### 权限映射
+
+- 默认的 `permission: auto` 下,Server 标注为 `readOnlyHint: true` 的工具视为 `r`,`read-only` 审批模式会自动批准这类工具;其余一律视为 `rw`:标注只是不可信的提示,所以默认从严。
+- 把条目的 `permission` 设为 `r` 或 `rw`,会覆盖这个 Server **所有**工具的标注。许多 Server 从不设置 `readOnlyHint`,全部工具因此落在 `rw` 上,设置这个字段正是处理这类 Server 的办法。
+- `permission` 固定这个 Server 每个工具上报的等级,而读取这个等级的审批模式有且只有一个。`read-only` 模式下,`r` 工具自动批准,`rw` 工具需要人工确认。`allow-all`、`deny-all` 和 `always-ask` 从不参考这个等级,所以在这三种模式下,把条目标成 `rw` 不会增加任何提示。
+- 除此之外,这个键不起任何作用。它不会给 Server 加沙箱,也不限制其工具运行时的实际行为;它既不发送给 Server,也不与 Server 做比对,Server 保留传输层赋予它的全部能力。把实际能写入的 Server 标成 `r`,等于让 `read-only` 模式失去本应弹出的确认。
+
+### 结果与关闭
-- 连接是**懒加载**的:Session 创建即时返回,首个 `run()` 开始时才并行连接全部 Server 并做一次工具发现——连接期间流式发出一对 `mcp_connect_begin` / `mcp_connect_end` 事件(前端显示连接状态;end 带总体 status 与逐 Server 结果),完成后以 `tool_list_ready` 事件下发完整工具定义(见 [OmniMessage](/omni-message));这三条消息在 Trace 中写在本轮输入之后,归属新轮次。运行中打断即**取消**本次连接,下次 `run()` 重新连接。发现结果是当前模型上下文内的快照:`tools/list_changed` 通知被忽略;压缩开启下一个上下文时,Server 按当时的配置重新连接,同样以这对事件框定(见[上下文压缩](/agent-loop))。连接失败或条目非法只产生 stderr 警告并跳过该 Server,**不阻塞会话**。
-- 发现的工具以 `mcp__<server>__<tool>` 进入统一工具命名空间,与内置工具走同一条[执行契约](#执行契约)(超时、截断、打断)与[审批](#审批)流程。
-- 权限映射:缺省的 `permission: auto` 下,Server 注解 `readOnlyHint: true` 的工具为 `r`(read-only 审批模式自动放行),其余一律 `rw`——注解是未受信 hint,缺省取限制方向。把条目的 `permission` 设为 `r` 或 `rw`,则该 Server 的**全部**工具一律按此取值,覆盖注解——大量 Server 从不设置 `readOnlyHint`、因而整体落到 `rw`,这个字段就是为它们准备的。
-- `permission` 的边界:它固定该 Server 每个工具对外报出的等级,而读这个等级的审批模式只有一个。`read-only` 下 `r` 工具自动放行、`rw` 工具需人工确认;`allow-all` / `deny-all` / `always-ask` 根本不查询它,标成 `rw` 的条目在这些模式下也不会多出一次审批。除此之外该字段什么都不做:不为 Server 提供沙箱,不限制其工具运行时的行为,不会发给 Server、也不向 Server 核验,Server 依旧拥有其 transport 赋予的全部能力。把一个实际能写的 Server 标为 `r`,撤掉的就是 `read-only` 本会索要的那次确认。
-- 结果映射:text 块拼接为输出文本;image 块作为图片(data URL)随输出附带;audio 与二进制 resource 折叠为占位行;仅有 `structuredContent` 时将其序列化为 JSON;Server 报 `isError` 时落实为 `stop_reason: "failed"`,内容即 Server 给出的错误说明。
-- Session 结束(`Environment.dispose`)关闭全部 MCP 客户端,stdio 子进程一并退出。
+- 文本块合并进输出文本,图片块以图片形式附带(data URL)。
+- 音频和二进制资源变成占位行;文本资源贡献自身的文本;`resource_link` 变成 `[resource: <uri>]` 加上其描述;未知块类型变成 `[unsupported content type: <type>]`。
+- 合并后的文本为空时,`structuredContent` 序列化为 JSON。
+- Server 报告 `isError` 时,调用以 `stop_reason: "fatal"` 结束,内容为 Server 的错误文本;若 Server 未发送错误文本,则为 `[tool reported an error with no message]`。
+- Session 结束时(`Environment.dispose`)会关闭所有 MCP 客户端,stdio 子进程也随之退出。
diff --git a/packages/docs/content/updates.en.md b/packages/docs/content/updates.en.md
new file mode 100644
index 00000000..b5a34322
--- /dev/null
+++ b/packages/docs/content/updates.en.md
@@ -0,0 +1,112 @@
+---
+title: Update PenguinHarness
+description: Check which version you are running, and update the desktop app, a CLI install, or a Docker deployment.
+---
+
+Check which version of PenguinHarness you are running, and update it in the way that matches your install.
+
+- **Which version is running?** See [Check the running version](#check-the-running-version).
+- **Updating from the browser?** See [Update from the Web App](#update-from-the-web-app).
+- **Using the desktop app?** See [Update the desktop app](#update-the-desktop-app).
+- **Installed the CLI?** See [Update a CLI install](#update-a-cli-install).
+- **Running in Docker?** See [Update a Docker deployment](#update-a-docker-deployment).
+- **Don't want update checks?** See [Turn off the update check](#turn-off-the-update-check).
+
+## Check the running version
+
+In the Web App:
+
+- The new-chat page shows the running version on a version line such as `vX.Y.Z · Last updated Jul 26`. The release workflow stamps the date into the build, so it is shown without any network access. Dev builds and releases from before the stamping, v0.1.2 and earlier, show no date.
+- In the sidebar user menu, the update row directly under **System settings** shows the running version, muted, on its right.
+
+In a terminal:
+
+- `penguin -v`, the same as `penguin version`, prints the running build's one-line identity, and `penguin version --json` prints the full build info. See [penguin version](/cli#penguin-version).
+- `penguin update --check` reports the installed and the latest versions and changes nothing.
+
+## Update from the Web App
+
+Updating works the way an app updater does, from one dialog.
+
+### Open the update dialog
+
+Two entries open the dialog:
+
+- The update row directly under **System settings** in the sidebar user menu. The row says where things stand: **Check for updates**, **Checking…**, **New version vX available**, **Downloading vX 42%** or **Restart to update to vX**. Whatever it says, it opens the dialog.
+- The small superscript on the new-chat page's version line. It reads **New version available** when a release is offered, **Downloading update** while a download runs, and **Restart to update** once the download is ready.
+
+### Run the update
+
+1. Open the update dialog. If nothing is known yet, it checks for a new release. The app also checks GitHub once per page load, and a check you start from the dialog skips the cached result.
+2. When a newer release is available, the dialog offers it with a **Release notes** link. Nothing is downloaded until you continue.
+3. Click **Download and update**. A progress bar follows the download.
+4. To keep working, click **Continue in background**. This closes the dialog without cancelling anything: the update row keeps showing the percentage, and once the release is ready, a dot appears on the user button and a toast announces it.
+5. Click **Restart and update** to finish.
+
+> [!NOTE]
+> Non-admins can read the release notes but cannot run the update.
+
+If the download fails, the dialog shows the update command's own output and offers **Retry**. An install that cannot update itself, such as a source checkout, an unrecognized layout, or Windows, says why in the dialog.
+
+### What happens on a server
+
+- The download is `penguin update` running in the background, and the progress bar reads the installer's own progress. The data directory is not touched.
+- The restart is real when the service runs under `penguin web` or `penguin server`, which supervise it: the service comes back on the new release, and the page reloads by itself.
+- When the service was started some other way, the dialog tells you to restart it by hand instead.
+
+## Update the desktop app
+
+In the desktop app, the same dialog drives the app's own updater. It does so only in the app's own window, where the server release never appears.
+
+The app checks for releases on its own schedule but never downloads on its own. A release it finds shows up as the dot on the user button and in the update row. To install it:
+
+1. Open the update dialog.
+2. Click **Download and update**. The percentage is the updater's real progress.
+3. Click **Restart and update**. The app restarts into the downloaded build.
+
+The app's native **Check for Updates…** menu item offers the same download-then-restart steps in native dialogs.
+
+> [!NOTE]
+> A browser signed in with a password to the same desktop-mode server gets no update entry at all. It can neither read that machine's updater state nor restart the app's window, and it cannot run the CLI self-update on that server either.
+
+Two forms of the app cannot replace themselves, and the dialog says so: a Linux install owned by the system package manager (`.deb`), which you update through the package manager, and a development run. The [Desktop app](/quickstart-desktop) page covers the installers.
+
+### The bundled `penguin` command
+
+The `penguin` command that the desktop app installs comes from the same build as the app, so updating the app updates the command. Running `penguin update` with that command changes nothing: it explains that the command is replaced when the app updates, and points you to the application menu.
+
+## Update a CLI install
+
+`penguin update` upgrades an install in place, with the mechanism it was installed with:
+
+```bash
+penguin update --check # report versions only
+penguin update # upgrade to the latest release, after confirming
+```
+
+| Install type | What `penguin update` does |
+| --- | --- |
+| Tarball install (`install.sh`) | Re-runs the official installer |
+| Global npm/pnpm/yarn/bun install | Runs that package manager's global install |
+| Source checkout | Refuses; update it with `git pull` and a rebuild |
+
+`--release <tag>` targets a specific release, and `-y` skips the confirmation. The data root is never touched.
+
+> [!NOTE]
+> On Windows, `penguin update` does not upgrade in place and tells you what to run instead. To upgrade an install made with the Windows installer, run the installer again.
+
+Running the install script again also upgrades an install; its files are swapped atomically. See [penguin update](/cli#penguin-update) for every option and the download source rules, and the [Installation reference](/quickstart-cli#installation-reference) for the installers.
+
+## Update a Docker deployment
+
+Pull a newer tag and recreate the container. The data root is on the volume and carries over:
+
+```bash
+docker compose pull && docker compose up -d
+```
+
+Updating from inside the container is not supported. See [Upgrade the container](/quickstart-docker#upgrade-the-container) for the details.
+
+## Turn off the update check
+
+Set `PENGUIN_UPDATE_CHECK=off` to turn off the automatic release check. That is all it turns off: model requests, an enabled remote-control connection, provider key authorization and the proxy test still reach the network. With the check off, the update dialog says **Update checks are disabled (PENGUIN_UPDATE_CHECK=off)**. See the [Configuration Reference](/configuration#environment-variables).
diff --git a/packages/docs/content/updates.zh.md b/packages/docs/content/updates.zh.md
new file mode 100644
index 00000000..bf257df2
--- /dev/null
+++ b/packages/docs/content/updates.zh.md
@@ -0,0 +1,112 @@
+---
+title: 更新 PenguinHarness
+description: 查看正在运行的版本,并更新桌面应用、CLI 安装或 Docker 部署。
+---
+
+查看正在运行的 PenguinHarness 版本,并按你的安装方式完成更新。
+
+- **想确认当前版本?** 见[查看当前版本](#查看当前版本)。
+- **在浏览器里更新?** 见[通过 Web App 更新](#通过-web-app-更新)。
+- **用的是桌面应用?** 见[更新桌面应用](#更新桌面应用)。
+- **装的是 CLI?** 见[更新 CLI 安装](#更新-cli-安装)。
+- **在 Docker 里运行?** 见[更新 Docker 部署](#更新-docker-部署)。
+- **不想检查更新?** 见[关闭更新检查](#关闭更新检查)。
+
+## 查看当前版本
+
+在 Web App 里:
+
+- 新对话页的版本行会显示正在运行的版本,形如 `vX.Y.Z · 最近更新日期 7月26日`。日期由发布流程在构建时写入,所以不联网也能显示。开发构建,以及引入日期写入之前的发布版(v0.1.2 及更早)没有日期。
+- 在侧边栏的用户菜单里,紧贴**系统设置**下方的更新行会在右侧以浅色显示当前运行的版本。
+
+在终端里:
+
+- `penguin -v` 与 `penguin version` 相同,输出当前构建的单行标识;`penguin version --json` 输出完整的构建信息。见 [penguin version](/cli#penguin-version)。
+- `penguin update --check` 报告已安装的版本和最新版本,不做任何改动。
+
+## 通过 Web App 更新
+
+更新的交互和常见的应用更新器一样,集中在一个弹窗里完成。
+
+### 打开更新弹窗
+
+有两个入口可以打开更新弹窗:
+
+- 侧边栏用户菜单里紧贴**系统设置**下方的更新行。这一行会显示更新到了哪一步:**检查更新**、**检查中…**、**新版本 vX 可用**、**正在下载 vX 42%** 或**重启以更新到 vX**。无论显示哪种状态,点击都会打开弹窗。
+- 新对话页版本行上的小上标。有新版本时显示**有新版本可用**,下载中显示**正在下载更新**,下载就绪后显示**重启以更新**。
+
+### 执行更新
+
+1. 打开更新弹窗。如果还不知道有没有新版本,弹窗会先检查一次。应用每次加载页面时也会向 GitHub 查询一次,而从弹窗发起的检查会绕过缓存的结果。
+2. 有新版本时,弹窗会列出它,并附上**更新说明**链接。在你继续之前,不会下载任何内容。
+3. 点击**下载并更新**,进度条会跟随下载进度。
+4. 如果想继续做别的事,点击**放到后台**。弹窗会关闭,但不会取消任何操作:更新行继续显示下载百分比;新版本就绪后,用户按钮上会出现圆点,并弹出一条提示。
+5. 点击**重启并更新**,完成更新。
+
+> [!NOTE]
+> 非管理员可以查看更新说明,但不能执行更新。
+
+下载失败时,弹窗会显示更新命令自己的输出,并提供**重试**。无法自更新的安装方式,例如源码检出、无法识别的目录布局或 Windows,会在弹窗里说明原因。
+
+### 服务端上的更新过程
+
+- 下载就是在后台运行 `penguin update`,进度条读取的是安装器自己的进度。数据目录不受影响。
+- 服务由 `penguin web` 或 `penguin server` 托管时,重启是真实发生的:服务会以新版本重新运行,页面自动刷新。
+- 用其他方式启动的服务,弹窗会提示你手动重启。
+
+## 更新桌面应用
+
+在桌面应用里,同一个弹窗驱动的是应用自带的更新器。这只发生在应用自己的窗口里,服务端的版本不会在那里出现。
+
+应用会按自己的节奏检查新版本,但从不自行下载。查到的新版本会显示为用户按钮上的圆点,并出现在更新行里。安装步骤如下:
+
+1. 打开更新弹窗。
+2. 点击**下载并更新**。显示的百分比就是更新器的真实进度。
+3. 点击**重启并更新**。应用会重启,并运行已下载的新版本。
+
+应用的原生菜单项 **Check for Updates…** 也会在原生对话框里提供同样的「先下载、再重启」两步。
+
+> [!NOTE]
+> 用密码登录同一台桌面模式服务端的浏览器,完全看不到更新入口:它既读不到那台机器的更新器状态,也无法重启应用窗口,更不能在那台服务端上运行 CLI 自更新。
+
+有两种形态的应用无法替换自身,弹窗会说明这一点:一种是由系统包管理器管理的 Linux 安装(`.deb`),需要通过包管理器更新;另一种是开发运行。安装包的说明见[桌面应用](/quickstart-desktop)页面。
+
+### 应用自带的 `penguin` 命令
+
+桌面应用安装的 `penguin` 命令与应用来自同一次构建,所以更新应用时命令也会随之更新。用这个命令运行 `penguin update` 不会改动任何东西:它会说明这个命令会随应用更新一起替换,并提示你到应用菜单里检查更新。
+
+## 更新 CLI 安装
+
+`penguin update` 会按当初的安装方式原地升级:
+
+```bash
+penguin update --check # report versions only
+penguin update # upgrade to the latest release, after confirming
+```
+
+| 安装方式 | `penguin update` 的做法 |
+| --- | --- |
+| 压缩包安装(`install.sh`) | 重新运行官方安装脚本 |
+| npm/pnpm/yarn/bun 全局安装 | 执行对应包管理器的全局安装 |
+| 源码检出 | 拒绝执行,请用 `git pull` 更新并重新构建 |
+
+`--release <tag>` 可以指定某个发布版,`-y` 跳过确认。数据目录始终保持不变。
+
+> [!NOTE]
+> 在 Windows 上,`penguin update` 不会原地升级,而是告诉你应该运行什么。用 Windows 安装器装的,重新运行安装器即可升级。
+
+重新运行安装脚本同样可以升级,文件以原子方式替换。全部选项和下载来源规则见 [penguin update](/cli#penguin-update),安装器的说明见[安装参考](/quickstart-cli#安装参考)。
+
+## 更新 Docker 部署
+
+拉取新的镜像 tag,然后重建容器。数据目录在数据卷上,会原样保留:
+
+```bash
+docker compose pull && docker compose up -d
+```
+
+不支持在容器内部更新,详见[升级容器](/quickstart-docker#升级容器)。
+
+## 关闭更新检查
+
+设置 `PENGUIN_UPDATE_CHECK=off` 可以关闭自动的版本检查。它只关掉这一项:模型请求、已启用的远程控制连接、Key 授权和代理测试照常联网。关闭后,更新弹窗会显示**更新检查已关闭(PENGUIN_UPDATE_CHECK=off)**。见[配置参考](/configuration#环境变量)。
diff --git a/packages/docs/content/usage.en.md b/packages/docs/content/usage.en.md
new file mode 100644
index 00000000..9bfb00b0
--- /dev/null
+++ b/packages/docs/content/usage.en.md
@@ -0,0 +1,78 @@
+---
+title: Cost Center
+description: Track Token usage, cost, and server errors by agent, model, and time range.
+---
+
+The Cost Center shows how many Tokens your agents use, what those requests cost, and which requests failed. To open it, select **Cost Center** in the sidebar. The page, headed **Costs & usage**, lives at `/usage`.
+
+- To narrow what the page shows, see [Filter by agent, model, and time range](#filter-by-agent-model-and-time-range).
+- For totals, see [Read the summary cards](#read-the-summary-cards).
+- For trends over time, see [Read the charts](#read-the-charts) and [Gaps in the charts](#gaps-in-the-charts).
+- For failed requests, see [Review and clear server errors](#review-and-clear-server-errors).
+
+## Filter by agent, model, and time range
+
+At the top of the page, choose an agent (**All agents** by default), a model (**All models** by default), and a date range: **Last hour**, **Last 24 hours**, **Last 7 days** (the default), **Last 30 days**, **Last 90 days**, or **Custom**, which adds a start and an end date.
+
+The range also sets the chart precision, so there is no separate precision control:
+
+| Date range | Chart precision |
+| --- | --- |
+| Last hour | Per minute |
+| Last 24 hours | Hourly |
+| Last 7, 30 or 90 days | Daily |
+| Custom | Daily up to 92 days, weekly up to 190 days, monthly beyond that |
+
+The same range and agent filter decide which rows the server error panel lists, and which rows its **Clear** deletes.
+
+## Read the summary cards
+
+Three cards show totals: **Today**, **Last 7 days**, and **Total** for the selected date range. All three follow the agent and model filters. Each card lists the Tokens, the number of requests and the cost.
+
+Prices are shown in the display currency you choose under [System settings › General](/settings#general). Only models with configured pricing count toward cost. When some records have no price, an asterisk appears beside **Cost** and a note at the bottom of the page says so.
+
+## Read the charts
+
+Four charts show the selected range as time series:
+
+| Chart | What it draws |
+| --- | --- |
+| **Requests & success rate by agent** | Each bucket's requests as one stacked bar, a segment per agent, on the left axis. Each agent's success rate is its own dashed line on a right-hand 0–100% axis, drawn above the bars. |
+| **Requests & success rate by model** | The same, per model. |
+| **Token trend** | Three-segment stacked bars, with a dashed cache-hit-rate line in front. |
+| **Cost trend** | A line with points over a filled area. |
+
+The two requests charts name the four busiest agents or models. The rest fold into one neutral series whose label says how many it holds, such as "Other (3)"; a single leftover keeps its own name.
+
+Every chart responds to the pointer the same way:
+
+- Hover a column to see that bucket's figures in a bubble.
+- Hover one bar segment to single it out.
+- Hover a line to single that line out.
+- In a requests chart, hover an agent or model in the legend to highlight its bars and line together.
+
+## Gaps in the charts
+
+A dash in the hover table means there is no rate for that bucket: no requests, every request aborted, or no cache traffic. A bucket in which nothing at all was recorded is left out of every chart, and a break mark shows the skip.
+
+## Review and clear server errors
+
+The **Errors** panel at the bottom of the page shows the errors the server recorded:
+
+- Summary figures: **Total**, **Unexpected**, **Expected** and the **Most common** error code.
+- A table of errors with their time, **Source · code**, **Type** and **Message**. Click a message to expand its full text. The table shows 10 rows a page and pages with **Newer** and **Older** instead of scrolling.
+
+The model filter does not apply to this panel.
+
+When unexpected errors were recorded in the last 7 days, a dot marks **Cost Center** in the sidebar and a notice under the page title counts them. Select **Mark as read** to dismiss both; they come back only when a newer error arrives.
+
+### Clear error records
+
+**Before you begin:** only a Project owner can clear errors.
+
+1. Set the date range and the agent filter to the rows you want to delete.
+2. In the **Errors** panel, select **Clear**. It appears only when the panel lists errors and, for a custom range, both dates are set.
+3. Check the confirmation. It names a preset range the way the picker does, such as "in the last 7 days", and a custom range by its dates.
+4. Confirm. The deletion cannot be undone.
+
+When an admin clears errors, the deletion also removes the unattributed error rows that only admins can see.
diff --git a/packages/docs/content/usage.zh.md b/packages/docs/content/usage.zh.md
new file mode 100644
index 00000000..77a21854
--- /dev/null
+++ b/packages/docs/content/usage.zh.md
@@ -0,0 +1,78 @@
+---
+title: 成本中心
+description: 按 Agent、模型和时间范围查看 Token 用量、成本与服务器异常。
+---
+
+成本中心展示各个 Agent 用了多少 Token、这些请求花了多少钱,以及哪些请求失败了。在侧边栏选择**成本中心**即可打开,页面标题为**成本与统计**,地址是 `/usage`。
+
+- 想缩小页面的统计范围,见[按 Agent、模型和时间范围筛选](#按-agent模型和时间范围筛选)。
+- 想看汇总数字,见[查看汇总卡片](#查看汇总卡片)。
+- 想看随时间的变化,见[查看图表](#查看图表)和[图表中的空档](#图表中的空档)。
+- 想排查失败的请求,见[查看并清空服务器异常](#查看并清空服务器异常)。
+
+## 按 Agent、模型和时间范围筛选
+
+在页面顶部选择 Agent(默认**全部 Agent**)、模型(默认**全部模型**)和日期范围:**最近一小时**、**最近一天**、**近 7 天**(默认)、**近 30 天**、**近 90 天**或**自定义**。选择**自定义**后会多出起始和结束两个日期。
+
+日期范围同时决定图表的精度,因此没有单独的精度设置:
+
+| 日期范围 | 图表精度 |
+| --- | --- |
+| 最近一小时 | 按分钟 |
+| 最近一天 | 按小时 |
+| 近 7、30 或 90 天 | 按天 |
+| 自定义 | 92 天以内按天,190 天以内按周,更长按月 |
+
+异常面板列出哪些记录、**清空**删除哪些记录,也由同一组日期范围和 Agent 筛选决定。
+
+## 查看汇总卡片
+
+三张卡片分别汇总**今日**、**近 7 天**和**累计**的数据,其中**累计**统计的是所选日期范围。三张卡片都受 Agent 和模型筛选影响,每张列出 Token 用量、请求数和成本。
+
+价格按你在[系统设置 › 通用](/settings#通用)中选择的币种显示。只有配置了价格的模型才计入成本;部分记录没有价格时,**成本**旁会出现星号,页面底部也有一行说明。
+
+## 查看图表
+
+四张图表以时间序列展示所选范围:
+
+| 图表 | 画的是什么 |
+| --- | --- |
+| **各 Agent 请求与成功率** | 每个时间桶的请求数画成一根堆叠柱,每个 Agent 一段,对应左轴。每个 Agent 的成功率各是一条虚线,对应右侧 0–100% 的轴,画在柱子上方。 |
+| **各模型请求与成功率** | 同上,按模型拆分。 |
+| **Token 变化** | 分三段的堆叠柱,前面叠一条缓存命中率虚线。 |
+| **成本变化** | 带数据点的折线,下方填充面积。 |
+
+两张请求图只为请求最多的四个 Agent 或模型单独命名,其余的合并成一条中性色序列,标签写明合并了几个,例如「其他 3 项」;如果只剩一个,则保留它自己的名字。
+
+每张图表的悬停方式都一样:
+
+- 悬停在某一列上,气泡里显示这个时间桶的数字。
+- 悬停在某段柱子上,单独突出这一段。
+- 悬停在某条线上,单独突出这条线。
+- 在请求图的图例里悬停某个 Agent 或模型,同时突出它的柱段和折线。
+
+## 图表中的空档
+
+悬停表格里的短横线表示这个时间桶没有比率:没有发出请求、请求全部中止,或者没有缓存流量。什么都没记录的时间桶不会出现在任何图表里,跳过的位置用断轴标记标出。
+
+## 查看并清空服务器异常
+
+页面底部的**异常**面板展示服务器记录的异常:
+
+- 汇总数字:**总数**、**未预期**、**预期内**和**最常见**的错误码。
+- 异常明细表:时间、**来源 · 错误码**、**类型**和**消息**。点击消息可展开全文。每页 10 条,用**较新**和**更早**翻页,不滚动。
+
+模型筛选对这个面板不起作用。
+
+最近 7 天内记录到未预期异常时,侧边栏的**成本中心**旁会出现一个圆点,页面标题下方也会提示异常条数。选择**标记为已读**,圆点和提示一起消失,直到有更新的异常出现。
+
+### 清空异常记录
+
+**开始之前**:只有 Project owner 可以清空异常。
+
+1. 设置日期范围和 Agent 筛选,让面板列出要删除的记录。
+2. 在**异常**面板中选择**清空**。只有面板列出了异常时才有这个按钮;自定义范围还要填好起止两个日期。
+3. 核对确认框。预设范围按选择器里的叫法写出,例如「近 7 天内」;自定义范围写出起止日期。
+4. 确认删除。此操作不可恢复。
+
+管理员清空时,还会一并删除只有管理员能看到的未归属异常记录。
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index b5ef4772..45d19386 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -1,217 +1,216 @@
---
-title: Web App Guide
-description: A page-by-page guide to the Web App — login, chat, Agent management, models, usage, and traces.
+title: Web App
+description: Sign in to the Web App, find your way around, manage Projects and members, and run the app in production.
---
-PenguinHarness ships with a ready-to-use Web App: multi-user login, streaming chat, Agent configuration, model and usage management all happen in the browser. This guide walks through the app page by page. For installation and first launch, see the [Quickstart](/quickstart).
+PenguinHarness ships with a Web App: multi-user sign-in, streaming chat, agent configuration, and model and usage management all happen in the browser. The desktop app shows the same interface in its own window. This page is the overview; each part of the app has its own guide. For installation and first launch, see the [Quickstart](/quickstart).
-## Source layout
+- To sign in for the first time, see [Open the Web App and sign in](#open-the-web-app-and-sign-in).
+- To find your way around, see [The app layout](#the-app-layout).
+- To set up a Project or its members, see [Projects and members](#projects-and-members).
+- To let an agent fill in a form for you, see [Create with AI or manually](#create-with-ai-or-manually).
+- To run the app for a team, see [Production deployment](#production-deployment).
-```text
-packages/web/src
-├── api/ # fetch wrapper · one function per API (DTOs type-only from @prismshadow/penguin-server/api) · SSE wrapper
-├── state/ # auth / project / sessions / theme / locale contexts
-├── lib/omni/ # OmniMessage stream → view-model reducer; connect-first + dedup stream controller
-├── components/ # ui primitives (modal / drawer / select …) and the app layout
-└── features/ # chat / agents / skills / models / usage / traces / benchmark / admin pages
-```
+## Open the Web App and sign in
-## Startup and Login
+Start the service from a terminal:
```bash
penguin web
-# open http://127.0.0.1:7364
+# opens http://localhost:7364
```
-The initial account is `admin`, and it starts with no password of its own: the server prints a first-login link in a framed notice on every start until one is set, and opening that link signs the browser in to set it. The link stays usable — and identical — until the password exists. There is no self-registration: accounts are created by an admin on the user-management page, and every new user automatically gets an independent initial Project named `<userId>-default_project`. While the initial password is still in use, a banner prompts the user to change it. A forgotten password is reset by the admin on the user-management page; a forgotten **admin** password is reset offline with `penguin server reset-admin-password` (server stopped), which returns the account to the unclaimed state and brings the first-login link back.
-
-Logins persist for 30 days with sliding renewal; an admin password reset invalidates all of that user's login sessions.
-
-The interface language (中文 / English / system) and theme (light / dark / system) can be switched at any time.
-
-## Chat (/chat)
+`penguin web` starts the service, waits until it is ready, prints the URL, and opens your browser. Add `--no-open` to skip opening the browser. `penguin server` starts the same service without opening a browser. See [penguin server / penguin web](/cli#penguin-server-penguin-web).
-### Creating a Conversation
+> [!NOTE]
+> On a local-only server, the app lives at `localhost`. The `127.0.0.1` address is reserved for previews of files the agent writes, and forwards you to `localhost`.
-A new conversation starts as a draft: pick the Agent, the Workspace (via a server-side directory browser), the approval mode, the model, and the thinking level before sending the first message. The Session is created on first send, and from then on its model and Workspace are locked. Switching the thinking level or the model in the draft makes the switched-to value the new default: the level is written back to the selected Agent's `model.thinking_level` immediately, and the picked model carries over as the next conversation's default. Inside an active session the thinking level belongs to the session: the composer's picker starts out showing the Agent config's level and auto-follows it until touched (sends omit the level, so config edits keep taking effect); a pick is **stored on the Session itself**, so it survives a page reload and shows up in another tab, applies to every later run of that conversation — a later Agent-config edit no longer moves it — and is still never written back to the Agent config. Changing the level mid-chat asks first, because switching mid-conversation lowers the prompt-cache hit rate and raises cost — the dialog offers three choices: **Compact, then switch** (recommended — it compacts the context exactly like `/compact` and applies the level once that compaction ends; a compaction that fails or is aborted still applies the level, with a notice that it did not finish), **Switch anyway** (applies immediately), and Cancel (keeps the current level). A compaction can only start on an idle conversation, so while a task is running the first choice is disabled with a note explaining why, and the other two stay available. A conversation with no messages yet, a re-pick of the displayed level, or a switch right after a successful compaction applies directly without asking; the model stays locked per session — the `/model` command switches models the way the `/agent` handoff does: picking a model stages it as a chip in the composer, and **sending** opens a new session for the same Agent on the picked model, keeping the current Workspace, whose first message carries a `[model_switch_from]` source block (source session id, Trace file path, previous model) followed by whatever the composer held (an interface-language auto-line when empty). In the new session that block collapses into a "switched model" banner linking back to the source conversation, and the model reads the source Trace file itself when it needs the earlier history.
+### Sign in for the first time
-There are four approval modes: `allow-all`, `deny-all`, `read-only` (only read-only tools pass), and `always-ask`. See [Tools and Approvals](/tools).
+The initial account is `admin`, and it starts with no password of its own. Until you set one, the server prints a first-login link in a framed notice on every start. Opening the link signs your browser in.
-Below the composer the draft page files example prompts into folders, exactly one of them open at a time; clicking a row fills the composer with that prompt and sends nothing, so it can be read and edited before Send. The last folder, **My shortcuts**, is your own: **New shortcut** opens an editor already holding whatever is in the composer, with its first line suggested as the name, and saving files it under that folder — a saved shortcut is a name plus a prompt, pins no Skills, and is stored per user on the server, so it follows you to another browser or machine. Rows carry edit and delete, the folder header counts `used/limit`, and the **New shortcut** row disappears once 3 are saved (a name is at most 40 characters, a prompt at most 4000) — the cap is what keeps this folder the same height as a built-in one, with no scrollbar of its own.
+1. Start the server with `penguin web`.
+2. Find the framed notice in the server output. It contains the first-login link.
+3. Open the link in your browser. You are signed in as `admin`.
+4. Set a password: select **Change now** on the banner that appears, or go to **System settings** › **Account**. This first session needs no current password.
-### The Conversation List
+> [!NOTE]
+> The link can be opened again. It lasts 30 days, or until a password is set. A restart prints a new link and the old one stops working. A link that no longer works lands on the login page with an explanation.
-The sidebar's conversation list groups by Workspace or by Agent. Under Workspace grouping, the directories the system makes for itself — the temporary Workspace a conversation gets when none is chosen, and the isolated Test Workspace an evaluation creates for each Case × Run, both directly under the Agent's own `workspaces/` directory — fold into one **Temporary workspaces** group instead of each standing alone; a directory you pick yourself always has its own group. Grouping and sort order are switched in the **List options** menu (the sliders icon in the section header), where each option carries its own icon: a folder for Workspace grouping, the Agent glyph for Agent grouping, a clock for most-recent order, and up/down arrows for the drag-reordered manual order.
+The desktop app does not print the notice. The server also skips it while a password pinned with `PENGUIN_SEED_ADMIN_PASSWORD` still works. For how these mechanisms are secured, see [Security](/security).
-A row's actions come at two levels:
+### Accounts
-- **Hovering** a row replaces the trailing last-active time with two icon buttons — archive and delete. They are reachable from the keyboard too: tabbing onto either one reveals it;
-- **Right-clicking** a row opens the full menu at the pointer: pin, rename, remote control, archive, copy Session ID, delete. A **long press** on touch and **Shift+F10** on the keyboard open the same menu, since neither hover nor a secondary click exists there. Escape, a click elsewhere, or scrolling the list dismisses it; the browser's own context menu is taken over on conversation rows only, and stays as usual everywhere else on the page.
+The login page asks for a **Username** and a **Password**, and has language and theme switches in its corner.
-Beside a row's title sit its status marks: a turning hourglass while the Session runs (a squeezing bar while it compacts), a green dot once a run finished that you have not looked at yet, and a small green activity trace while the Session still owns **background tasks** — commands running on past their yield window and background subagents mid-round. Its tooltip counts them ("2 background tasks"). The mark is independent of the others: an idle conversation whose dev server is still up keeps it, and it disappears the moment the last task ends, pushed live without a refresh.
+There is no self-registration. An admin creates accounts on the **Users** page of System settings. Every new user automatically gets an independent initial Project named `<userId>-default_project`.
-Below a group's active rows stand its collapsed folders — Subagents, Scheduled, Evaluations and Archived — each loading its rows only once it is opened. **Evaluations** holds the conversations the Evaluation Center's **Use → Evaluate / Optimize** opens and the Test Sessions the evaluation Skill launches for every Case × Run, so an evaluation no longer floods the tested agent's list. A group with no active conversation of its own — only rows inside its folders, which is what an evaluation's per-case Workspaces and an agent that has only ever run evaluations look like — is collapsed by default and sorted after the other groups of its mode (pinned groups excepted), its header dimmed and counting the folded rows; open it once and it stays open for that Project. Pinning is offered only in the active list — the folders leave it out — and a pinned conversation sorts to the top of its group. The choice is remembered per Project in the browser.
+While the initial password is still in use, a banner prompts the user to change it, with a **Change now** link. Closing the banner hides it for good.
-An expanded folder reveals ten conversations at a time, the window the active list above it already uses: **Show N more chats** reveals ten more per click — rows already in memory first, and a page is fetched from the server only when they run short, so a fetch that returns more than a page leaves the extra rows in memory rather than on screen. As soon as the folder shows more than those first ten a **Show less** row stands beside the reveal row and folds it back to them; the reveal row itself disappears once the folder's whole share is on screen.
+After five failed sign-in attempts, the server makes you wait. The wait starts at one second and doubles, up to a minute.
-### Streaming Rendering
+### Passwords
-- Model text renders token by token; thinking blocks are collapsible;
-- Tool cards expand to show arguments and output, with a live timer while running; a call made with `run_in_background` carries the same activity trace as the conversation list, right of its duration ("Runs in the background") — the call returns at once, and the mark says its work did not; a card heads itself with a short name for the built-in tools (`read_file` reads as "read"), keeping the tool's own name in the tooltip, and the **Tool short names** switch on the Appearance settings page turns that off — every other tool, MCP tools included, always reads as itself;
-- A context compaction leaves a row whose title doubles as its status, the work-group header's Running/Done idiom: Compacting while it runs and Compacted once it settles (Clearing/Cleared for a discard), with its wall time; while a summarize runs the row is open: its thinking section appears once the request's thinking arrives, and its result section only after that thinking finishes, when the first summary text lands — each closed by default, each with its own wall time — and the row closes itself again once the compaction settles, leaving the one line; a failed compaction keeps the bare mode word (Compaction, or Clear) over a one-line reason instead;
-- Subagents leave a full-width row in the stream, styled like the other collapsed step rows (agent avatar, name, short session id, running spinner, and an amber dot while one of their tool calls awaits approval); clicking it opens the agents side panel — a call graph of that row's Task on top (each node shows its elapsed time; click a node to switch) and the selected child's live conversation below — the child's own user prompts included — where nested tool cards and approvals work exactly as in the main chat. Panel visibility is task-scoped: sending a message that starts a new task closes it by default (entering a session starts closed too), and it comes back when you open it yourself or — on desktop — when the current task spawns a subagent (one auto-open per task; a manual close holds until the next task; never over an open files panel). Opening the panel from the toolbar, or switching sessions, shows the latest Task's graph; a row on an older turn brings back that turn's graph. The agents panel and the Workspace files panel never show together — opening one closes the other. Context compaction and the first-run MCP connect show a unified step row (the work-group header shell, sticky title bar included — running/success/failure only swap the icon and the one-line detail, with the wall time on the result; the MCP row leads with the discovered-tool count and names unavailable servers, and expands into one group per server — status, tool count and that server's connect time — each opening into its tool list or the failure detail);
-- After each Task, a stats line shows tokens, TPS, elapsed time, cost, copy, and a **Fork** action to the right of copy. Fork asks for confirmation first — it duplicates the conversation into a new chat — and only then opens a new Session at that completed assistant reply with the same Agent, model, Workspace, approval mode, and retained transcript. Forks from different replies in one source chat share an increasing, language-neutral title sequence (`Source title (1)`, `Source title (2)`). Its Trace and scratchpad are independent snapshots: local images/files keep rendering even after the source chat is deleted;
-- Opening a conversation loads its latest 50 turns; scrolling near the top backfills 50 more with your reading position held in place, the beginning of the conversation is marked once nothing older remains, and a failed backfill offers a retry. Turn numbering and the header statistics continue from the cumulative values the server sends with the window, so they match a full load.
+A forgotten password is reset by the admin on the **Users** page, with **Reset password**.
-### Header Stats and the Details Card
+A forgotten **admin** password is reset offline:
-The toolbar's right edge shows the Session's cumulative stats (tokens, cost, elapsed time); clicking them opens the details card — model, Session id (with a copy button beside it), Workspace, creation time and per-line statistics. The elapsed line carries its two components in parentheses, `Elapsed 10.3s (API 5s, tools 5.3s)`: time inside model requests with the human approval wait deducted, and tool wall time as the union of the tool executions, so tools running in parallel count once. They are two measurements of that span rather than a split of it — a background tool overlaps the model's decoding, while approval waits and harness overhead belong to neither — so they may exceed or fall short of the total, and neither is derived from it. Below those: Right of the elapsed time, while the conversation still owns background tasks, a small pill shows their count — the same figure the conversation list's mark carries. Below those:
+**Before you begin**
-- **Processes** — background processes the conversation started (`exec_command`s promoted past their yield window), one row each with the command, start time and pid — plus, on running rows, a link to the service the process serves when one was detected (the last local URL its output printed, else a listen-port probe of its process group). Running rows carry a **Stop** button (kills the whole process group and drops the row) — the conversation is told the process is down, as **stopped** rather than failed, so the model knows the dev server is gone without reading it as a crash to restart; exited rows keep their "exited" label and carry a **Remove** button that deletes the entry from the list. Removal is immediate and final: the entry leaves the runtime registry together with the output captured from that process, so afterwards the model can no longer be asked to read it — keep the row until you are done with its output.
+- The server is stopped.
-Copy buttons across the app confirm at the button itself: the copy icon flips to a check mark for a moment (no "Copied" text label).
+1. Run `penguin server reset-admin-password`.
+2. Start the server again.
+3. Open the first-login link from the framed notice, and set a new password.
-### Input and Shortcuts
+The command gives the admin account a new random password that nobody sees, and ends every admin session. The next start prints the first-login link again.
-- Enter sends, Shift+Enter inserts a newline, and images can be pasted — an image placed inline in the conversation is capped at 20MB, separately from file attachments and not raised along with them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every session resume, whereas an attachment is only ever read from disk by path;
-- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, and by default ≤ 100MB each and 120MB in total — an admin can change both sizes under **System settings → Upload limits**, see below; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection, and the message names the limit actually in force); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;
-- Files can also be **dragged onto the chat area** — the conversation and the composer, on the chat page and the draft page alike: while a file drag is over that region a "Drop files to attach" overlay covers it (it hides as soon as the drag moves off; dragging text or anything that isn't a file is ignored), and releasing attaches the whole batch to the composer — images join the pasted-image pipeline, everything else becomes file attachments, with the same type and size validation and the same errors as the "+" menu. Dropping works while a Task is running too (the attachments then send per the mid-run send mode below); goal mode takes dropped images but refuses files with a notice. Only the chat area attaches: dropping a file on the sidebar, the top bar, the other docked panels or any page without a composer attaches nothing and shows nothing — it is simply ignored, instead of the browser navigating away to the dropped file (the Files panel is the one other drop target, and it uploads — see below);
-- Typing `/` opens the slash menu: trigger context compaction (`/compact`), hand the conversation over to another Agent (`/agent`), switch the model (`/model`) — both switch commands appear in an active session only, since a draft has nothing to switch and picks its Agent and model up front — or toggle installed Skills — chosen Skills are sent along with the message in a `[use_skills]` block;
-- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced. Each queued hint line — an undelivered steering message or a queued follow-up — ends in a **recall** control (a curved-back arrow, "Recall") that withdraws the message back into the input box (attachments included) for editing and resending; a steering message that already reached the model can no longer be recalled. When the run ends before a steering message was delivered — pressing Stop while a tool is still running is the usual way — you do not have to reach for that control: the message returns to the input box on its own, attachments and all, ready to edit and send again, so an interrupt never eats what you had already typed;
-- **Goal mode** (the "+" menu, or `/goal`) turns the draft into an objective the system loops Tasks against. Attached images ride along and are always sent as scratchpad paths (a goal objective is re-injected as text every round — see [Goal mode](/goal-mode)); text is still required, since a picture alone states no objective, and file attachments are refused. Round 1's bubble shows the attachments in full, later rounds collapse them into a chip that expands on click;
-- `/agent` and `/model` stage their pick instead of acting on it: the chosen Agent or model becomes a chip above the text body and nothing is sent yet, so you keep typing — Enter/Send is what hands the conversation over (a new chat for that Agent) or forks it onto the chosen model, carrying the text along; with an empty composer a default message is filled in, and the chip's × cancels. Both chips are cached with the draft, so they survive a reload or a trip to another conversation together with the text. A model fork additionally waits for the Session to be idle — it continues from the Session's Trace, which a running turn or a compaction is still writing — and a line above the composer says so while it waits;
-- The toolbar's right side carries a **context ring**: a single-colour gauge of how full the context is, measured against the point compaction fires (the Agent's `compaction.max_context_length`, capped by what the model window leaves room for), amber past 80% and red past 95%. Clicking it opens the **context panel** — the used/threshold figures, a bar that runs to the model's full window split into the six things the context is made of (system prompt, tool definitions, user messages, model messages, tool requests, tool results), with "Max context N" naming that scale underneath it, and a Top 5 of the tools, or of the files the file tools touched, switched by a pair of text buttons on the heading line and listing file names alone with the full path on hover. The dashed cutter on that bar is where compaction fires, and it is draggable: drag it (or focus it and use the arrow keys — Shift for a coarser step) and releasing asks to confirm the new threshold in a dialog whose number you can still edit. The stretch of the bar past the cutter is hatched — room the model has but compaction fires before the Session can use — and moves with the value while you drag. Bar segments and legend rows are clickable: a click pins the highlight until you click it again or pick another. The legend rows are buttons, so the pin is reachable by keyboard, and a pinned row keeps a ring that hover alone does not draw. Confirming writes it to the Agent and it applies to this conversation immediately, mid-run included;
-- When human approval is required, tool calls show inline allow/deny buttons in the message stream; the approval mode can be changed mid-Session;
-- While the engine waits out a reconnect backoff (≥2s), the retry line shows a live countdown to the next attempt with inline **Retry now** (skips the remaining wait) and **Give up** (the ordinary abort) controls;
-- When the model API rejects the Session's credentials (an authentication failure), the composer grays out and disables — recoverably: the Session pins only the model reference, and credentials come from the current Project config. The notice's primary button opens the Models page; saving a new API key there unlocks the composer by itself (open tabs unlock live via a `credentials_updated` event, and after a reload the composer stays unlocked because the credential update is newer than the recorded auth failure). A "Retry" button clears the state manually for another attempt (it re-arms if the key is still bad), a completed request always clears it, and "New Session" remains as the escape to a fresh draft. The disabled composer keeps its draft selectable, so a long message that failed to send can still be copied out.
-- Terminals live in the docks beside the conversation: Ctrl+` shows or hides the terminal tabs (adopting or starting a shell when none is open), and Ctrl+W, with a terminal focused, closes that terminal — the same confirm-then-kill its tab's × runs, in the dock and on the standalone `/terminal` page alike — and never reaches the shell. Browsers reserve Ctrl+W for closing the browser tab and may act on it first; the desktop app delivers it to the terminal.
+### Sign-in sessions
-### Shortcuts Launcher
+Logins persist for 30 days with sliding renewal: using the app renews the full 30 days.
-Whenever no side panel is on screen — the right panel closed on a desktop-width window, or neither panel open on a narrow one, where the two merge into a bottom sheet — a translucent round button carrying a workbench glyph floats 32px inside the right edge of the conversation, the region between the toolbar and the composer, with a short caption beneath it reading "Shortcuts", so the workbench's panels stay one click away even for someone who has never noticed the toolbar's toggle. Clicking it (or pressing Enter/Space on it) fans out one round entry per panel — agents, Workspace files, memory, Trace, messaging, and a terminal — on a tight semicircular ring around the button, opening leftward. The entries are glyphs alone; pointing at one, or focusing it, shows its name in the caption under the button, which stays centred beneath it — the room the button keeps from the edge is what holds even the longest name. The button is the other half of that readout: it draws the pointed-at entry's glyph in place of its workbench mark, and while the pointer or the keyboard focus is on the button itself it names what the next click will do — an expand mark captioned "Open" while the fan is closed, a collapse mark captioned "Close" while it stands open — a fan merely standing open with nothing pointed at leaves the button on its resting mark. Neither the button nor the entries carry a tooltip: their names are already on screen. Near the top or bottom of the conversation the arc shortens to the part that still fits. Picking an entry opens that panel — in the right side panel on a desktop-width window, in the bottom sheet on a narrow one — and the button disappears the moment the panel is open. The arc ends in a "Hide launcher" entry that puts the button away for good; a message says where it comes back from, and the **Shortcuts launcher** switch on the Appearance settings page turns it on again. Esc, a click elsewhere or scrolling folds the fan. The button drags up and down along the edge (a short press stays a click), following the pointer wherever it goes — over other controls included — and springs back onto the edge when released; it never covers the toolbar or the composer, and its position is remembered in the browser as one preference shared by every conversation. While the panel is closed and a subagent is waiting for an approval, the amber dot from the toolbar's toggle rides the button too.
+An admin password reset invalidates all of that user's login sessions. Changing your own password keeps your current session.
-### Files Panel
+**Sign out** is in the account menu and asks for confirmation first. It ends the session in this browser. Conversations that are running keep going on the server.
-The files panel shows the Workspace as a directory tree on the left and a preview of the selected file on the right. A directory lists its contents the first time it is opened; the tree takes the arrow keys (up/down move, right opens a directory or steps into it, left closes it or steps out), the selected file is highlighted, and the breadcrumbs above read out the current directory — a path, not a row of links, since the tree beside them is what navigates; when the path outgrows the toolbar its leading segments collapse into a single `…`, keeping the current directory visible and Refresh and Upload on the same row; the root segment reads `.`, and the Workspace's absolute path lives in the Session details card rather than on this toolbar. A search box above the tree filters what the tree holds: matching is on the entry's name, a match keeps its parent directories visible and open, and a directory whose own name matches is shown with its contents. The tree is lazy, so the search reaches only the directories that have been opened at least once — when nothing in them matches it says so rather than looking empty; Esc clears the box. Opening or closing a directory grows its subtree out of its row, or shrinks it back into it, over about 200ms — the rows stay on screen until the collapse finishes; with reduced motion the change is immediate. A toolbar toggle hides or shows the tree (shown by default; the choice is remembered in the browser) and slides out of and back into the panel's left edge over about 200ms, the motion the docks themselves expand and collapse with; the divider between the two panes drags to set the tree's width (arrow keys nudge it while it has focus, and the width is remembered too), and a panel too narrow for both panes falls back to one column — the tree until a file is chosen, then the preview with a Back button. Markdown and HTML preview rendered with a Source toggle, text files inline with highlighting, images inline (click to zoom), PDF embedded; anything else is offered as a download. A file whose extension says nothing about its type (a `Makefile`, a `LICENSE`) is read as text when its bytes look like text.
+> [!NOTE]
+> The desktop app signs its own window in by itself as the admin, with no password. That window has no **Sign out**, no initial-password banner, no **Account** page and no user management.
-Text files can be edited in place: **Edit** replaces the preview with a plain monospace text box — no rich editor — and **Save** (also Ctrl+S / Cmd+S) writes the file back through the same content endpoint uploads use, after the usual save confirmation; Cancel returns to the preview. A **Wrap** toggle sits beside them: off by default, so long lines scroll sideways as they would in a code editor, and the choice carries to the next file you edit. The panel asks before unsaved changes would be lost — switching to another file, closing the panel's tab, leaving the page. Collapsing or hiding the dock loses nothing: the panel stays exactly as it was, preview, tree and draft included, and comes back untouched without asking. A draft survives a Session switch too: opening the same file again reopens the editor on it. A file larger than the 256KB preview cap is shown truncated and stays read-only (saving a partial text would overwrite the whole file), and a save over the 14MB write limit is refused with a message. In the desktop app's own window a **Show in folder** button sits beside Download and opens the file's directory in the system file manager — Finder and Explorer select the file, a Linux desktop opens the directory; a browser signed into the same server, even on this machine, does not get the button, because the server cannot tell it from a remote one.
+## The app layout
-Because the Agent writes to the same Workspace, a file can change while you are editing it. It is checked whenever a turn finishes — your text is never replaced, but the editor header says **Changed on disk** as soon as it has — and a save that would land on a changed file is refused before anything is written: the panel asks whether to **Overwrite** it with your version or keep editing, and your text is kept either way.
+The sidebar on the left holds everything that is not a conversation. The rest of the window shows the page you open. Each part of the app has its own guide.
-Uploads go into the current directory (the toolbar's **Upload** button, several files at a time), or files can be **dragged from the desktop onto the panel**: a dashed frame names the directory they will land in, dropping onto a folder row uploads into that folder (the row highlights while the drag is over it), and the first uploaded file opens afterwards. Each file is limited to 14MB — oversize picks are named and skipped before anything is read — and a same-named file in the target directory is overwritten after confirmation. Download is in the preview header.
+### The sidebar
-### Scheduled Tasks Panel
+From top to bottom, the sidebar holds:
-The scheduled tasks panel lists the tasks bound to the current conversation (tasks that open a new Session each run belong to the agent and live on its settings tab), with a search box and All / Active / Paused / Completed filters. Each row shows a state glyph, the task name and a plain-language schedule line ("Every day at 08:00 · Next: tomorrow 08:00", "Every 30 minutes", "Every Monday at 09:00", "One-off · Sep 3, 10:00"); owners toggle a task with the switch on its row and edit or delete it from the row's menu. A **Suggestions** list — a daily brief, a weekly review, a follow-up reminder, an update monitor — opens the AI dialog with that request filled in. This panel is the only place a task bound to a conversation is created, and its header carries two buttons on a row of their own beneath the title — the panel's width is yours to drag, and a pair sitting beside the title clips when you make it narrow. **Create with AI** (the magic wand, open to every member) differs from the AI path elsewhere in one way: its exit is **Edit in this conversation**, prefilling this conversation's own composer rather than a new one's, because a task created from inside a conversation is bound to that conversation by default. Whether to send is still yours to decide, and pressing Send takes the same path as anything you type. **Create manually** (the hand, owners only) opens the same form as the settings tab, pinned to this Session. A conversation with a bound task that **still has a next fire time** wears an alarm clock on its row in the sidebar's session list, whichever agent it belongs to and however the list is grouped — the icon only, no count; a task switched off, past its end time, or a one-off that has already run has no next fire time and shows nothing. Saving or toggling a task reports only what happened: a scheduled task fires on the scheduler's clock, independent of any conversation's context, so a change takes effect at once. The list refreshes when the panel comes to the front, when the window regains focus, when a task fires or is queued, when a conversation turn finishes, every 30 seconds while visible, and after every change — the mark on the session row reads the same list and refreshes with it, so the two never disagree.
+- The **Development** / **Company** switch, only when company mode is available: an admin has enabled it for the server, and you have not turned it off for yourself. Company mode swaps the page entries below for an organization's pages, and the conversation list for its channels. See [Company mode](/company-mode).
+- The Project switcher, with the **Collapse sidebar** button beside it. See [Projects and members](#projects-and-members).
+- **New chat**, which opens a new conversation draft. See [Chat](/chat).
+- The page entries. The chevron under the last one folds them away:
-## Create with AI
+| Entry | What it is for | Guide |
+| --- | --- | --- |
+| **Agents** | Create agents and edit their prompt, memory, runtime, tools, Skills, hooks, Vault and scheduled tasks | [Agents](/agents) |
+| **Plugins** | Browse plugins, install their Skills and hook packages onto agents, and add server plugins to the Project | [Skills](/skills) |
+| **Models** | Configure the Project's models, providers and credentials | [Models](/models) |
+| **Cost Center** | Token usage, cost and server errors by agent, model and time range | [Cost Center](/usage) |
+| **Evaluation Center** | Benchmarks: evaluate agents and optimize them against a Benchmark | [Evaluation Center](/evaluation-center) |
-Everything the Web App creates from a form — an agent, a model group, a Benchmark, a scheduled task, a vault secret, an app, an agent import — can also be described to an agent instead. Each page offers two buttons side by side: **Create with AI** with the magic wand, and **Create manually** with the hand, so both paths are visible at once. The prompt box comes with clickable examples that fill the draft, and a folded **Full prompt** preview shows the fixed instructions that travel with what you typed, with a copy button. There is one way out, **Edit in a new conversation**: it opens a new conversation with the Project's `default_agent` (the first agent when there is none) and prefills the composer with the prompt — whether to send it is yours to decide. A prefilled prompt is not something the browser holds on to: leave the page without editing or sending it and it is dropped, so it cannot resurface in a later conversation. Type into it and it becomes an ordinary draft, kept like anything else you write.
+- The conversation list, with search and grouping by Workspace, agent or time. See [Chat](/chat).
+- Your user row at the bottom. It opens the account menu:
+ - **System settings**. See [Settings](/settings).
+ - The update row, which names where an update stands and opens the update dialog. See [Updates](/updates).
+ - **Sign out**.
-## Agent Management (/agents)
+### Notification dots
-The header carries the two buttons described under [Create with AI](#create-with-ai), and the list's call to action offers the same pair while the Project has no agent beyond `default_agent`. The dialog opens on the path you picked and stays there. **Create with AI** opens a prompt box with five examples — a jotting agent, a financial Copilot, a document RAG agent, a deep-research report agent, and the report-writing agent with the id `report-writer` that the onboarding path starts from (create it with AI, then let AI build a Benchmark for it and optimize it) — and a fixed tail that has the Project's default agent run the `agent-initialization` skill: a new agent under this Project with the id you gave or a semantic one, its AGENTS.md and name/description written, only the skills it needs copied from the plugin library, no other agent touched, and the id plus how to start a conversation reported at the end. **Create manually** opens the form: the name comes first, and **Generate with AI** beside the id field derives the agent id from the name (or the description while the name is empty) with the Project's default model; the sidebar's "new agent" button names no path and opens it too.
+A dot on a page entry means something is waiting there:
-The list page creates and deletes Agents — the create dialog can initialize the new agent from an exported Agent State snapshot package (name and description left empty keep the package's values, and plugin picking is unavailable then, since the package carries its own skills and hooks) — and clicking through opens the `/agents/:agentId` settings page, organized into tabs:
-
-| Tab | Contents |
+| Entry | What the dot means |
| --- | --- |
-| Overview | Basic info, export / import of Agent State snapshots, and restoring the default configuration (overwrites customizations, keeping only name/description) |
-| Prompt | AGENTS.md and system_prompt |
-| Memory | The Agent-level switch, then every memory grouped by scope — user memory first, then one group per Workspace, each group collapsible with add, export and import entries — with view / delete / edit-via-chat actions per row |
-| Runtime | Runtime parameters such as max_turns, model.*, compaction.* |
-| Tools | Built-in tool table (incl. per-tool call_description switches) and MCP Server management: a table plus an add/edit form whose fields follow the transport (http by default; changes save immediately; full transport validation server-side; a permission control fixes the approval level of that server's tools at `auto` / `r` / `rw`, and the table shows each server's effective level); connectivity testing mirrors the models page — a standalone button in the form probes the current entry (toast with tool count and latency), and a section-level button tests every server in turn with a result badge on each row |
-| Hooks | An **Enable hooks** switch at the top (owner only; members see the state) decides whether a Session this agent starts from now on runs its hook packages at all — with it off a new Session runs none of them and every package stays on disk. Below it, the installed hook packages (agent_state/hooks/): each row leads with the package name and the hook points it answers at right beside it (bare point names such as `stop`), the description below, then the version, export as a zip and uninstall. **Import hook** opens the skill import dialog's shape: the recommended path lets the agent import it in chat — a hook source field (a URL, a GitHub repository, a local path, a description, or another tool's hooks config) with a live preview of the prompt, where **Copy prompt** and **Open a new chat** are greyed together while the source is empty; below it, a hook package zip can be uploaded directly (asking before it overwrites an installed name). Library installs still happen on the plugin library page |
-| Vault | Environment-variable entries with masked values; **Create with AI** beside **Create manually** hands secrets to AI, which writes them with `penguin config vault set` — the dialog warns that a value typed there reaches the model provider, the conversation's Trace and the agent's own command line, so the safer prompt asks for key names only, and its examples lead with that ask |
-| Schedule | Scheduled tasks (TOML-defined): create — with AI or manually — edit, toggle, delete; suggestions stand in for an empty list |
-
-The Memory tab's switch writes immediately rather than joining the tab-level Save, so turning Memory off never drags an unrelated half-finished edit along with it. Turning it off keeps every file and the tab fully usable: it only stops Memory from entering the agent's context and from preparing directories for new Sessions. Scope groups collapse on header click, with the collapse state remembered in the browser per user × Project × Agent; each group header carries an **Add** text entry to its collapse arrow's left (the models page's group convention) — like editing, it goes through a bridge modal (a required content-or-source field plus a live prompt preview) into a new chat, where the agent organizes the content into that scope; the drafts stay deliberately minimal, since the save mechanics live in the Memory prompt. Rows are read-only on purpose, their actions icon-only like the skills tab's — **View** renders the body in a right drawer on desktop and a bottom sheet on narrow screens (the chat page panels' interaction, with half / full snap points), **Delete** confirms and also removes the file's `MEMORY.md` index lines, and **Edit** opens a bridge modal first (what to change plus a prompt preview), then jumps to a new chat with this agent; a Workspace scope's chat also pins that Workspace, so the Session reads the very index it is changing. A whole group also moves in one piece: **Export** downloads it as a JSON document (every memory plus the group's `MEMORY.md`) whose file name carries the export date and time, so repeated exports stay apart, and **Import** — owner only, mirroring the Agent State snapshot's split — reads one back. Import asks what to do with a name the group already has: keep the one that is here (the default, which loses nothing), take the file's version, or replace the whole group; either of the latter two confirms first, naming the memories that would be overwritten or deleted. Below the groups the two memory prompts (`memory.prompt` / `memory.workspace_prompt`) are edited in place, and when the prompt template carries no `{{MEMORY}}` placeholder (an agent created before Memory) it shows a hint with a one-click insert — an explicit, idempotent config write. The agent list cards' stat line also shows the memory count, deep-linking to this tab. For the storage model, see [Configuration](/configuration#memory).
+| **Agents** | Agents on an outdated kernel |
+| **Plugins** | Plugin updates |
+| **Models** | Preset models to sync (shown to owners) |
+| **Cost Center** | Unexpected errors |
-Scheduled tasks fire on a fixed period (minimum 5 minutes) and run only while the service is running.
+A dot on your avatar means a software update. Pointing at an entry names what is waiting.
-## Plugin Library (/plugins)
+### The collapsed rail and narrow windows
-Browse the plugin library by category — skills and session hooks alike — install a plugin onto an Agent (its skills and hook package together), update installs the library has moved past, or quick-invoke a skill into a chat draft. Each card carries a semantic metadata line (`v<version> · updated N days ago · used by N agents`) and opens a detail Modal: the plugin's full description and the hook points its hook package answers at, then a file browser over everything it ships — the same component the Benchmark case dialog uses, with the Workspace files panel's tree on the left, one collapsible group per skill (its SKILL.md and reference files) and one for the hook scripts, any number open at once, and a preview on the right that renders the selected file without leaving the summary or the tree.
+**Collapse sidebar** shrinks the sidebar to a narrow rail of icons: **Expand sidebar**, the company mode toggle when available, **Last conversation**, **New chat**, the page entries, and your avatar, which opens the same account menu. Pointing at an icon, or focusing it, shows its name. The choice is remembered in the browser.
-## Model Configuration (/models)
+On a narrow window, the sidebar hides behind a menu button in a top bar and opens as a drawer.
-A per-Project model table grouped by provider. Models can be added and edited: identity is the `(provider, model_id)` pair, credentials are masked, and context window, max output tokens (a per-model cap overriding the Agent's `model.max_tokens` — lower it for small-context models), pricing, the vision flag, and fast mode (off by default: faster output at the provider's premium tier — the toggle is shown only for models whose AgentHub client can serve it, and switching it on confirms the premium billing first) are configurable. A model with fast mode on is badged in the list. You can set the default model and the vision model (which reads images on behalf of session models without image input), and run a connectivity test on any entry — the test carries the dialog's current fast-mode toggle, so a rejection surfaces before saving. Only Project owners can edit. For concepts, see [Models and Providers](/models).
+### Trajectories and Machines
-The header carries the two create buttons (owner only). **Create with AI** hands a model listing page or a description of a service to the Project's default agent, which registers the models as a group through `penguin config model add`; the dialog's lead says when the **Import models** path is the faster one. **Create manually** opens the **Add group** dialog. The table reloads on every visit, so the group is there when you come back from the conversation.
+Two parts of the app have no sidebar entry.
-## Usage (/usage)
+**Trajectories** is a side panel of the chat page, not a page of its own. It shows the open conversation's Trace files, with a summary, per-turn statistics, an execution timeline, and the individual events. **Export** downloads a file. See [Chat](/chat).
-- Filters: Agent, model, and date range (trailing last hour / last 24 hours, last 7 / 30 / 90 days, or a custom pair). The range decides the precision the charts are drawn at — per minute for the last hour, hourly for the last 24 hours, daily for the calendar presets, week or month for a long custom range — so there is no separate precision control;
-- Summary cards: today / last 7 days / cumulative;
-- Charts, all time series over the selected range: requests + success rate broken down by Agent and, beside it, the same by Model (a bucket's requests stacked one segment per entity on the left axis, each entity's success rate as its own dashed line on a right 0–100% axis, drawn above the bars; the top few entities are named and the rest fold into a neutral series labelled with how many), Token trend (three-segment stacked bars with a dashed cache-hit-rate line in front), and cost trend (line + points + area). Every chart takes the same hovers: a column for its bubble, one bar segment to single that segment out, a line to single the line out. Lines are straight segments, never smoothed, all at the same stroke width. Charts fit their card and never scroll;
-- Two things a chart cannot draw. A bucket with **no rate** — an entity that made no request in it, or a bucket with no cache traffic — has its line carried across at the top of the axis so the stroke stays continuous; the hover table prints a dash there, never a percentage, and a real 0% (requests were made and all of them failed) still prints 0%. A bucket that recorded **nothing at all** is not plotted: every chart drops it and packs the rest left to right, so all four share one x axis that skips the quiet intervals and carries a break mark at each skip. Emptiness is judged per bucket, never per entity — an interval anything ran in stays, with the entities that were idle in it showing their zeros and dashes;
-- A server error panel: summary stats plus an errors table paged at a fixed page size (no scrolling). Its **Clear** (Project owner only) deletes the rows the current range and Agent filter lists — the trailing window or calendar preset the picker holds, named as such in the confirmation, or a custom range named by its dates; an admin's clear also takes the unattributed rows only admins see.
+**Machines** installs this PenguinHarness build on other hosts over ssh, choosing from the server account's `~/.ssh/config`. It is not offered in the sidebar in this release. An admin can reach it at `/machines`.
-## Evaluation Center (/benchmark)
+### Language and theme
-Every Benchmark of the Project, one card each — a Benchmark belongs to the Project, not to an agent, so the list is a flat one: the title and directory name, the description, the case and run counts, when it was last evaluated, the agents it has evaluated, a sparkline of the scoreboard, and the newest score with its change from the previous evaluation under the same label. Clicking a card, or **View**, enters that Benchmark's own page (`/benchmark/<benchmark>`) — the score chart over time, the evaluation table with per-case and per-run rows, and the case browser (the same file browser as the plugin detail: the Workspace panel's tree on the left — task materials and rubric as its two top-level folders, listed level by level — and a read-only preview on the right) — with a back button to the list. A Benchmark whose config says `status = "draft"` — the agent is still writing and calibrating it — is masked: the card dims under a notice that it is being built, **Use** and **View** are disabled, and its page shows the same notice in place of the cases and the chart; only the owner's delete icon stays live. One whose config says `status = "failed"` — its difficulty calibration never finished — is masked the same way, under a "creation failed" notice asking the user to delete the Benchmark and create it again. The mask lifts once the status is `published`. Under the title stand three separate step cards, one per step of the loop — **Create**, **Evaluate**, **Optimize** — each with its number, its title and one sentence saying where to do it: creating is the two buttons at the top right, and evaluating and optimizing are **Use** on a Benchmark followed by the matching tab. The conversations **Use** opens, and the Test Sessions an evaluation launches for every Case × Run, are filed under the session list's **Evaluations** folder.
+The interface language (English / 中文 / System) and the theme (Light / Dark / System) can be switched at any time in [System settings](/settings), and on the login page. Both are saved per browser.
-- Two buttons sit side by side at the top right, the same pair the agent's scheduled-tasks tab uses: the magic wand goes to AI, the hand to the form. **Create with AI** asks for the Test Agent and a description of the capability and scenarios; the prompt's fixed tail hands the `benchmark-design` Skill the agent id, a desired baseline score and a pilot-iteration limit, and asks for the baseline to be taken. **Create manually** is a form — title, id (which **Generate with AI** derives from the title in kebab-case), description, runs per case, and one statement plus rubric per case, with no owning agent to pick — that the server writes to disk in the layout the Skills read (`POST …/benchmarks`, owner only).
-- **Use**, on a card and in the Benchmark page's header, opens one dialog with two tabs over a single exit. **Evaluate** puts an agent on the frozen cases: the tested agent (the one the newest evaluation tested, by default), the evaluator agent (with a warning when it lacks the `agent-evaluation` Skill), the model of the evaluation conversation (the Project settings' own model picker, preset to the Project's default model), runs per case, and an optional note. Its prompt asks for the full Case × runs matrix through self-spawned `agent-evaluation` subagents, requires every result's agent, model pair and thinking level to agree, and appends exactly one labelled evaluation to `scoreboard.yaml` — the tested agent and the Benchmark are left untouched. **Optimize** is the optimizer form: the optimizer agent (warned the same way), the **agent under test**, the model of the optimizer's own conversation (the same picker, preset the same way), runs per case, a round limit, a target score (ten above that agent's baseline by default) and an optional focus; an agent with no baseline here is told to take one on the Evaluate tab first. Both tabs preview the full prompt and both end the same way, at **Edit in a new conversation**: the prompt is prefilled into the composer and sending it is yours to decide. The evaluation runtime is never picked in this dialog — Evaluate takes the tested agent's own configured model and thinking level, and Optimize reuses what the baseline recorded.
-- The chart plots time against score and draws one series per **label** — agent id, model id and thinking level — so only comparable scores share a line; a record with no label falls into a grey series. The Agent State version is deliberately not part of the label: successive versions of one agent on the same model and thinking level stay on one line, which is exactly where an improvement is supposed to become visible, and each point names the version it tested in its hover bubble. The evaluation table keeps a version column of its own, and names the agent under test in another.
-- Clicking a row of the evaluation table opens that **evaluation in a dialog**, in the same shape as the case dialog: the series label with the tested agent and the version at the top, the Score, cost and duration under it, the evaluation's own summary (its title and its body shown separately), and the per-case table, whose rows expand to the raw result of every Run with the Session it ran in. A case named in there opens the case dialog on top of it.
-- Both dialogs end in an **Ask AI** button. It opens the prompt dialog with a question already in the box — why this evaluation came out as it did, or what this case tests — the same question leading the examples so it can be brought back after trying one of the three others, and a fixed tail carrying the facts on screen: for an evaluation, the Benchmark id and directory, the time, the series label, the version, the runtime, the total and per-case scores, every run's Session id and the summary; for a case, its `statement/README.md` and `rubric/README.md` paths and how the latest evaluation's runs scored it. The agent is asked to read those files and Traces and explain what it finds — the cases are frozen and the tested agent is not the subject of the question — and the exit is the same **Edit in a new conversation**.
-- A card's actions are **Use**, **View** and — for the owner — a delete icon, which removes the directory whole after a confirmation (`DELETE …/benchmarks/:id`). The Benchmark's own page names its directory, `benchmarks/<benchmark>`, beside the title, with a button that copies the path. `/benchmark?agentId=` narrows the list to the Benchmarks that have evaluated that agent.
-- **A Benchmark's cases are frozen once it exists.** Neither the Web App nor the server API can edit a statement or a rubric after creation: changing the questions would make the scores already on the scoreboard incomparable, so asking different questions means creating a new Benchmark. The calibration AI does while writing the cases happens before the baseline is taken, and is part of creating them.
-- Every Project carries the example Benchmark, `example-benchmark`, whenever the Project has no `benchmarks/` directory: it is provisioned when the Project's `default_agent` is initialized and again the first time that agent is loaded, so a data root older than the example gets one too. Deleting the example while `benchmarks/` remains — holding other Benchmarks, or nothing — is a decision that stands; removing the whole directory asks for the example back.
+## Projects and members
-Works together with the [Self-Improvement](/self-improvement) workflow.
+A Project holds its agents, models, Benchmarks, and conversations. The Project switcher at the top of the sidebar lists the Projects you own or belong to, each with its role (`owner` or `member`), and switches between them. The same menu has **New Project** and **Project settings**.
-## System Settings
+### Create a Project
-One dialog for the settings that belong to neither a Project nor an Agent, opened from the sidebar user menu's **System settings** row: a left rail of pages, each page a list of rows — title and a one-line explanation on the left, the control on the right.
+Any signed-in user can create a Project and becomes its owner.
-The rail is grouped. **Personal** holds preferences that belong to the signed-in account and apply the moment they are touched — no Save button, nothing to lose by closing the dialog; the Profile page's nickname is the one exception, since typed text needs a commit, and its Save sits beside the field rather than under the page. **Server** holds the server-global surfaces: the settings written through `GET|PUT /api/admin/settings` and user management are admin-only — a non-admin gets neither those entries nor any hint they exist, and the APIs answer a non-admin with 403 whatever the browser rendered. A non-admin is therefore left with the Personal pages alone, and the rail draws no group headings at all. In the desktop app the user-management page is absent (the server runs single-user), and the shell's own window also has no Account page — it signs in through the shell's token and holds no password to change, while a browser signed into the same server with a password keeps it. Checking for updates is not a page here — see [Version and Updates](#version-and-updates).
+1. Open the Project switcher at the top of the sidebar.
+2. Select **New Project**.
+3. In **Display name**, enter an optional display name. If you leave it empty, the id is shown.
+4. In **Project id**, enter an id, or select **Generate with AI** beside the field to derive one from the display name. The current Project's default model writes the proposal, since a Project is not inside a Project.
+5. Select **Create**. You are now the Project's owner.
-### Profile
+The id is 2–64 characters long. It starts with a lowercase letter and uses only lowercase letters, digits, and underscores. For a user other than the admin, it starts with the username and a hyphen, and only the part after that prefix is typed.
-Personal, and present in **every** session — the desktop shell's own window included, since neither field needs a password to change. An **avatar** and a **nickname**, and the page has no footer: every control writes when it is used, and the button that writes a value stands next to that value. Choosing an image applies it at once — centre-cropped to a square and re-encoded at 128×128, as PNG or, when the PNG would pass 100 KB, as JPEG; anything still over 128 KiB is refused in the browser rather than sent for the server to reject — and **Restore default** beside it puts the letter tile back. The nickname is typed text, so it keeps an explicit **Save**, with a **Restore default** of its own next to it; both of those write on click, so the two buttons beside the field never disagree about when they act. It is 1–32 characters (counted as characters, so a Chinese name may be 32 of them), its default is the user id, and saving it blank clears it. Each button is dead when it would write what is already stored. Nothing is applied optimistically: the preview shows the stored avatar, so a write that fails leaves every surface agreeing with the server and says so inline. Both start unset, so an account that predates this page shows its user id and the letter tile until it sets them. Once set they replace that pair on the sidebar's bottom user row, on the collapsed rail's avatar and at the head of the account menu those two open — where the user id stays visible under the nickname — and the nickname also shows under the id in the **Users** list.
+> [!NOTE]
+> The Project id cannot be changed later.
-### General
+### Project settings
-Personal. **Language** (Chinese / English / follow the browser) and the **display currency** for prices (USD / CNY; storage is always USD — conversion happens only at the edge of the screen). **Show CLI sessions** (default off): 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. Stored per user. **Import Trace**: choose the destination Project and Agent, upload a `.jsonl` Trace exported from another install, and it becomes a conversation of that Agent. Both halves are asked for: the endpoint is per-Agent because a Trace file cannot name a local Agent of its own, and the Project 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 is the other direction of the same road and lives with the file it downloads, in a conversation's Trace panel.
+**Project settings** has four pages:
-### Appearance
+| Page | Contents |
+| --- | --- |
+| **General** | The display name, the **Project ID**, and **Delete Project**, which removes the Project's directory recursively and cannot be undone |
+| **Members** | Who belongs to the Project, and with what role. The owner adds an existing user by username (**Add member**) and removes members (**Remove**). Not in the desktop app. |
+| **Defaults** | **New chat defaults**: the agent, working directory, approval mode, thinking level and default model that every new chat starts with |
+| **Security policy** | Command policy rules. A command matching an enabled rule is refused, whatever the approval mode. See [Command policy](/configuration#command-policy) |
-Personal. The app **theme** (light / dark / follow the system), the **terminal theme** — the terminal panel keeps its own light/dark and by default follows the app theme; pin it light or dark to decouple the two, for prompts and TUIs tuned to one screen — the interface **font size**, and the **accent color**.
+### Roles
-### Account
+Members have two roles: `owner` and `member`. A Project has one owner, its creator. There is no role change and no ownership transfer. Being an admin grants no access to other users' Projects.
-The **Change password** action. The page exists only where a password exists to change: the desktop shell's own window signs in through the shell's one-shot token and never sees one.
+The owner alone can:
-### Users
+- Rename or delete the Project, manage its members, and change **Defaults** and **Security policy**. Members see these pages read-only.
+- Change models, Vault, and scheduled tasks.
+- Create and delete Benchmarks, delete agents, clear Cost Center errors, and set up remote control.
+- Import agent snapshots, memory, and Traces.
-Admin only, outside the desktop app: list and create users, reset passwords, and delete users (the built-in admin cannot be deleted).
+Members can still create agents and conversations, and delete conversations, Skills, hook packages, and memory files.
-### Proxy Options
+> [!NOTE]
+> `default_project` is shared with the CLI and cannot be deleted from the Web App. The last Project of an account cannot be deleted.
-Admin only, server-global. Two switches — **Application uses the proxy** (the server's own outbound traffic: LLM requests, the update check, image fetches) and **Agent environment uses the proxy** (agent command subprocess environments) — share one optional **proxy address**; empty means follow the proxy environment variables. The address accepts any proxy URL undici's dispatcher takes (`http://`, `https://`, `socks5://`, credentials allowed) or a bare `host[:port]`, which is stored normalized to `http://…`; anything else is refused with the reason under the input. Nothing is written until Save, which applies the whole form in one PUT, so a rejected address writes none of it. A save rebuilds the outbound dispatcher and takes effect on new connections with no restart; loopback always goes direct.
+## Create with AI or manually
-### Upload Limits
+Many things the Web App creates from a form can also be described to an agent instead. Those places offer two buttons side by side: **Create with AI**, with the magic wand, and **Create manually**, with the hand.
-Admin only, server-global: two sizes — the **per-file attachment cap** and the **per-message total** — both whole MB, defaulting to 100MB and 120MB. Each may be set between 1 and 200MB, and the total may not sit below the per-file cap (that combination would make a legal single attachment unsendable). A value outside the range — "100GB" typed into a MB field as 102400, say — is refused with the reason shown under the input rather than accepted. Validation precedes every write: one bad field in a PUT leaves the other fields untouched too.
+| What you can create | Where |
+| --- | --- |
+| An agent | The Agents page |
+| A model group | The Models page |
+| A Benchmark | The Evaluation Center |
+| A vault secret | An agent's Vault tab |
+| A scheduled task | An agent's Schedules tab, or a conversation's Scheduled tasks panel |
-Saving takes effect immediately, with no restart: the attachment validators and the request body cap both read the setting per request. The body cap is not configured separately but derived from the total — attachments ride the request as base64 `data:` URLs, which inflates them by 4/3, so it has to rise with them or a request whose every attachment was individually legal would die at the HTTP layer instead.
+Some of these are for Project owners only:
-Two numbers are deliberately not exposed. The per-message file **count** stays at 20: it bounds how usable the composer's chip row is, not what the server can survive — the byte budgets do that. And an inline **image** stays capped at 20MB rather than following the attachment limit up, because an image placed inline enters the conversation and the Trace, where its size is paid again on every history page and every session resume; the model side is lower still (providers commonly cap around 5MB, and `read_file` reads an image of at most 5MB), so raising it to 100MB would only trade a clear refusal for a later, more confusing failure.
+- The Models page and the Vault tab: both buttons are for owners only.
+- Scheduled tasks: **Create manually** is for owners only.
-## Version and Updates
+The prompt box comes with clickable examples that fill the draft. When the page adds fixed instructions to what you type, a folded **Full prompt** preview shows them, with **Copy prompt**.
-Updating works the way an app updater does, from one dialog. Two entries open it: the row directly under **System settings** in the sidebar user menu, and the small "New version available" superscript on the new-chat page's version line (`vX.Y.Z · Last updated Jul 26` — the date is stamped into the build by the release workflow and shown without any network access; dev builds and releases predating the stamping, v0.1.2 and earlier, have no date). The row names where things stand — "Check for updates", "Checking…", "New version vX available", "Downloading vX 42%", "Restart to update to vX" — with the running version muted on its right, and every state opens the dialog.
+There is one way out: **Edit in a new conversation**. It opens a new conversation with the Project's `default_agent`, or the first agent when there is none, and prefills the composer with the prompt. Whether to send it is yours to decide.
-The dialog walks the update through: opening it with nothing known runs a check (the app also checks GitHub once per load, and the manual check bypasses the cached result); a newer release is offered with its release-notes link and a **Download and update** button, and nothing is fetched until you press it; a progress bar follows the download, and **Continue in background** closes the dialog without cancelling anything — the row keeps showing the percentage, a dot on the user button appears once the release is ready, and a toast announces it; then **Restart and update** finishes the job. On a server the download is `penguin update` running in the background (the data directory is untouched), the bar reads the installer's own progress, and the restart is real when the service runs under `penguin web` or `penguin server`, which supervise it: the service comes back on the new release and the page reloads by itself. A service started some other way is told to restart by hand instead. Non-admins can read the release notes but cannot run the update. A failed download shows the update command's own output and offers a retry; an install that cannot update itself (a source checkout, an unrecognized layout, Windows) says why. Set `PENGUIN_UPDATE_CHECK=off` to disable the update check entirely — see the [Configuration Reference](/configuration).
+- The prompt survives a reload of that new-chat page.
+- Leave the page without editing or sending it, and the prompt is dropped. It cannot resurface in a later conversation.
+- Type into it, and it becomes an ordinary draft, kept like anything else you write.
-**In the desktop app** the same dialog drives the app's own updater — in the shell's own window only, where the server release never appears. The shell checks on its own schedule but never downloads on its own: a found release shows up as the dot and the row, the download starts from the dialog, its percentage is the updater's real progress, and **Restart and update** restarts into the downloaded build (the shell's native "Check for Updates…" menu item offers the same download-then-restart steps in native dialogs). A browser signed into the same desktop-mode server with a password gets no update entry at all: it can neither read that machine's updater state nor restart its window, and it cannot run the CLI self-update on that server either. Forms that cannot replace themselves — a Linux install owned by the system package manager (`.deb`), and a development run — say so in the dialog; the [Desktop app guide](/quickstart-desktop) covers the installers.
+The Scheduled tasks panel is the exception. Its way out is **Edit in this conversation**, which fills the current conversation's composer. See [Scheduled tasks](/schedules).
-## Projects and Members
+## Production deployment
-The sidebar provides a Project switcher and supports creating new Projects: the display name comes first, and **Generate with AI** beside the Project id field derives the id from it with the current Project's default model (a non-admin types only what follows `<username>-`). Members have two roles, owner and member: owners manage membership and exclusively edit models, Vault, and Schedules, as well as perform deletions.
+The server hosts the built SPA itself, on the same origin and with SPA fallback. A single `penguin web` or `penguin server` process is all production needs.
-## Production Deployment
+The npm package bundles the frontend build. To serve a custom static directory instead, override it with `PENGUIN_WEB_DIST`. See the [Configuration Reference](/configuration).
-The server hosts the built SPA itself (same origin, SPA fallback), so a single `penguin web` or `penguin server` process is all production needs. The npm package bundles the frontend build; to serve a custom static directory, override it with `PENGUIN_WEB_DIST` — see the [Configuration Reference](/configuration).
+The server listens on `127.0.0.1` by default, so it answers only on its own machine. Exposing it on a network, with `HOST`, belongs behind a reverse proxy that terminates TLS. See [Security](/security).
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 34b474cb..2d1812dd 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -1,216 +1,216 @@
---
-title: Web App 指南
-description: 按页面组织的 Web App 使用指南:登录、Chat、Agent 管理、模型、用量与 Trace。
+title: Web App
+description: 登录 Web App,熟悉界面布局,管理 Project 与成员,并在生产环境中运行。
---
-PenguinHarness 自带一个开箱即用的 Web App:多用户登录、流式对话、Agent 配置、模型与用量管理都在浏览器中完成。本文按页面组织,逐一介绍各页面的功能与操作。安装与首次启动见[快速开始](/quickstart)。
+PenguinHarness 自带一个 Web App:多用户登录、流式对话、Agent 配置、模型与用量管理,都在浏览器里完成。桌面应用在自己的窗口中显示的也是同一套界面。本页是总览,各个部分另有专门的指南。安装与首次启动见[快速开始](/quickstart)。
-## 目录结构
+- 第一次登录,见[打开 Web App 并登录](#打开-web-app-并登录)。
+- 熟悉界面,见[应用布局](#应用布局)。
+- 设置 Project 或管理成员,见 [Project 与成员](#project-与成员)。
+- 让 Agent 替你填写表单,见[用 AI 创建或手动创建](#用-ai-创建或手动创建)。
+- 为团队部署,见[生产环境部署](#生产环境部署)。
-```text
-packages/web/src
-├── api/ # fetch 封装 · 每个 API 一个函数(DTO type-only 来自 @prismshadow/penguin-server/api)· SSE 封装
-├── state/ # auth / project / sessions / theme / locale 五个 context
-├── lib/omni/ # OmniMessage 流 → 渲染视图模型 reducer;连接先行 + 去重的流控制器
-├── components/ # ui 原语(modal / drawer / select …)与应用布局
-└── features/ # chat / agents / skills / models / usage / traces / benchmark / admin 各页面
-```
+## 打开 Web App 并登录
-## 启动与登录
+在终端中启动服务:
```bash
penguin web
-# 打开 http://127.0.0.1:7364
+# opens http://localhost:7364
```
-初始账号为 `admin`,它一开始并没有自己的密码:在设置密码之前,每次启动服务端都会以边框提示打印一条首次登录链接,打开该链接即以登录态进入浏览器并设置密码。该链接在密码存在之前一直有效,可以重复打开。系统不开放自助注册:账号由管理员在用户管理页创建;每个新用户会自动获得一个独立的初始 Project,命名为 `<userId>-default_project`。仍在使用初始密码时,页面会以横幅提示尽快修改。用户忘记密码由管理员在用户管理页重置;**管理员**自己忘记密码时,停止服务后执行 `penguin server reset-admin-password` 离线把账号恢复成未认领状态,首次登录链接随之回来。
-
-登录状态保持 30 天(滑动续期);管理员重置密码会使该用户的全部登录会话失效。
-
-界面语言(中文 / English / 跟随系统)与主题(浅色 / 深色 / 跟随系统)可随时切换。
-
-## Chat 页面(/chat)
-
-### 新建会话
+`penguin web` 会启动服务,等它就绪后打印地址并打开浏览器;加上 `--no-open` 则不打开浏览器。`penguin server` 启动的是同一个服务,但不打开浏览器。见 [penguin server / penguin web](/cli#penguin-server-penguin-web)。
-新会话从草稿开始:先选择 Agent、Workspace(服务器端目录浏览器选取)、审批模式、模型与思考等级,再发送第一条消息。Session 在首次发送时才真正创建,此后该会话的模型与 Workspace 即被锁定。草稿里切换思考等级或模型时,切换后的值即成为新的默认:思考等级立即写回所选 Agent 的 `model.thinking_level`,所选模型则作为下一个新会话的默认延续。进行中的会话里,思考等级属于该会话:输入区拾取器初始显示 Agent 配置的档位并自动跟随(未选择时发送不携带档位,配置修改持续生效);一旦选定,该档位**存在 Session 上**——刷新页面、换一个标签页打开都保持不变,此后该会话的每次运行都用它,Agent 配置再改也不会把它带走,同时依旧不写回 Agent 配置。会话中途切换思考等级会先弹确认框,因为中途切换会降低提示词缓存命中率、增加成本——确认框提供三种选择:**压缩后切换**(推荐,等同于先执行 `/compact` 压缩上下文,压缩结束后应用新档位;压缩失败或被中断时档位照样切换,并提示压缩未成功完成)、**仍要切换**(立即生效)与取消(保持当前档位)。压缩只能在会话空闲时启动,因此任务运行期间第一项会置灰并说明原因,另外两项照常可用。会话尚无消息、重选当前显示档位、或刚完成一次成功压缩后的切换则直接生效、不弹框;模型仍在会话内锁定,改用 `/model` 命令切换模型——与 `/agent` 交接同一方式:选中模型只是在输入框暂存为一枚 chip,**发送时**才在同一 Agent 下新建一个使用所选模型、沿用当前 Workspace 的会话并跳转,其首条消息携带 `[model_switch_from]` 源块(源会话 id、Trace 文件路径、原模型),输入框中的文字随之发出(为空时发一句界面语言的自动消息);新会话中该源块折叠为一条“已切换模型”横幅,可点击回到原会话,模型需要早前历史时按路径自行读取源 Trace 文件。
+> [!NOTE]
+> 服务只监听本机地址时,应用的地址是 `localhost`。`127.0.0.1` 留给 Agent 写出的文件做预览用,访问它会被转到 `localhost`。
-审批模式共四种:`allow-all`(全部放行)、`deny-all`(全部拒绝)、`read-only`(仅放行只读工具)、`always-ask`(每次询问),详见[工具与审批](/tools)。
+### 首次登录
-草稿页在输入框下方按折叠夹陈列示例提示词,同一时刻只展开一个;点击某一行即把该提示词填入输入框,并不发送,可先阅读修改再自行发出。最后一个折叠夹「我的快捷指令」属于用户自己:点**新建快捷指令**会打开编辑框,其中已带上输入框中现有的内容,并以首行作为建议名称,保存后即归入该折叠夹——一条快捷指令由名称与提示词组成,不绑定 Skill,按用户存放在服务端,因此换浏览器、换机器都还在。每行提供编辑与删除,折叠夹标题显示「已用/上限」,存满 3 条后**新建快捷指令**行即隐藏(名称不超过 40 个字符,提示词不超过 4000 个字符)——这个上限正是为了让该折叠夹与内置折叠夹等高,不需要自己的滚动条。
+初始账号是 `admin`,一开始没有自己的密码。在设置密码之前,服务每次启动都会以带边框的提示打印一条首次登录链接,打开这条链接即可在浏览器中登录。
-### 会话列表
+1. 用 `penguin web` 启动服务。
+2. 在服务的输出里找到带边框的提示,其中有首次登录链接。
+3. 在浏览器中打开链接,即以 `admin` 身份登录。
+4. 设置密码:点击随后出现的横幅上的**去修改**,或进入**系统设置** › **账户**。这次登录后设置密码,不需要输入当前密码。
-侧边栏的会话列表按 Workspace 或 Agent 分组;按 Workspace 分组时,系统为自己建的目录——未指定 Workspace 时自动建的临时目录,以及评估为每个 Case × Run 建的独立 Test Workspace,两者都直接位于 Agent 自己的 `workspaces/` 目录下——一律并入同一个**临时工作区**分组,而不是各自成组;自己选的目录始终单独成组。分组方式与排序方式在标题栏的**列表选项**菜单(滑块图标)里切换,每个选项前带一枚对应图标:文件夹表示按 Workspace 分组、机器人表示按智能体分组、时钟表示按最近更新排序、上下箭头表示手动拖拽排序。
+> [!NOTE]
+> 链接可以重复打开,有效期 30 天,设置密码后即失效。重启服务会打印新链接,旧链接随之作废。打开已失效的链接会跳到登录页,并显示说明。
-会话行的操作分两层:
+桌面应用不会打印这条提示;用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定的密码仍然有效时,服务也不打印。这些机制如何保证安全,见[安全模型](/security)。
-- **悬停**一行时,行尾的最近活跃时间让位给两个图标按钮——归档与删除;键盘同样够得到:Tab 到其中任意一个,该按钮即显形;
-- **右键点击**一行,在指针处打开完整菜单:置顶、重命名、远程控制、归档、复制 Session ID、删除。触屏**长按**、键盘 **Shift+F10** 打开同一个菜单(触屏没有悬停,也没有右键)。按 Esc、点击别处或滚动列表都会关闭它;系统右键菜单只在会话行上被接管,页面其他位置照常。
+### 账号
-会话行标题旁是它的状态标记:Session 运行中是翻转的沙漏(压缩中是向中线合拢的压缩标),有一条你还没看过的回复时是一枚绿点,会话仍有**后台任务**——超过 yield 窗口继续运行的命令、正在跑一轮的后台子智能体——时另有一枚小小的绿色活动波形标记,悬停显示数量(「2 个后台任务」)。这枚标记与其他标记互不影响:dev server 还开着的空闲对话照样带着它,最后一项后台任务结束的那一刻它即消失,由服务端实时推送、无需刷新。
+登录页要求填写**用户名**和**密码**,页面一角有语言和主题的切换。
-每个分组的活跃会话之下是它的折叠夹——子智能体、定时任务、评估任务与已归档——各自展开时才加载其中的会话。**评估任务**收纳评估中心「使用 → 评估 / 优化」开出的对话,以及评估技能为每个 Case × Run 启动的被测会话,一次评估不会再把这些会话一股脑倒进被测 Agent 的列表。自己没有任何活跃会话、只有折叠夹里那些会话的分组——评估为每道题建的 Workspace、只跑过评估的 Agent 都是这样——默认折叠并排在同一分组方式的最后(置顶的分组除外),分组头变浅、计数为折叠会话数,点开一次后按 Project 记住。置顶只在活跃列表里出现(这些折叠夹中都没有这一项),置顶的会话排在所属分组的最前面,该状态按 Project 记在浏览器本地。
+系统不开放自助注册:账号由管理员在系统设置的**用户管理**页创建。每个新用户都会自动获得一个独立的初始 Project,名为 `<userId>-default_project`。
-展开的折叠夹一次只显示十个对话,与上方活跃列表同一口径:**展开其余 N 个对话**每次再显示十个——先显示内存里已加载的行,不够时才向服务端再取一页,因此一次取回多于一页时,多出来的行留在内存里而不落到屏幕上。折叠夹显示的行数一超过最前十条,**收起**一行便与展开行并列出现,把它折回这十条;展开行本身则在本夹份额全部显示后消失。
+仍在使用初始密码时,页面顶部会显示横幅,提醒尽快修改,并附有**去修改**链接。关闭横幅后,它就不再出现。
-### 流式渲染
+连续登录失败 5 次后,服务会要求等待:等待时间从 1 秒开始,每次翻倍,最长 1 分钟。
-- 模型文本逐 Token 渲染,思考块可折叠;
-- 工具卡片可展开查看参数与输出,执行中显示实时计时;以 `run_in_background` 发起的调用在用时右侧带与会话列表同一枚活动波形标记(「在后台运行」)——调用本身立刻返回,标记说明它的工作没有;卡片以短名称呼内置工具(`read_file` 显示为「读取」),工具本来的名字留在 tooltip 里,设置页「外观」的**工具短名**开关可关掉它——其余工具(含 MCP 工具)始终显示原名;
-- 上下文压缩在消息流中留下一行,标题兼作状态、与工作分组组头的「运行中」/「运行完毕」同一写法:按实际动作写作「压缩中」/「压缩完毕」,discard 则为「清空中」/「清空完毕」,并带用时;summarize 运行期间该行展开:压缩请求的思考一到就出现「思考」一节,「压缩结果」一节要等思考结束、第一段摘要文本抵达后才出现——两节默认折叠、各带自己的用时——压缩结束后该行自行收起,只留下这一行;失败的压缩保留裸的「压缩」或「清空」标题与一行原因;
-- 子 Agent 在消息流中只留下一条通栏行,样式与其他折叠步骤行一致(头像、名称、短会话号、运行中转圈,子会话内有待审批时带琥珀色圆点);点击打开右侧智能体面板——上方是该行所属 Task 派生关系的调用图(节点上显示运行时长,点节点切换),下方是所选子会话的实时对话(含子会话自己的用户消息),嵌套工具卡片与审批与主对话完全一致;面板的显示以任务为界:发送消息开启新任务时默认关闭(进入会话时同样默认关闭),仅在手动打开、或(桌面端)当前任务派生子智能体时重新显示(每个任务自动打开一次,任务内手动关闭后保持关闭到下个任务,且不抢占已打开的工作区面板);从工具条打开面板或切换 Session 时默认展示最新 Task 的调用图,点旧轮次的行则回看那一轮的调用图;智能体面板与工作区面板不会同时显示,打开一个即关闭另一个;上下文压缩与首次 MCP 连接以统一样式的步骤行提示(与运行分组头同款外壳,含吸顶标题栏,连接中/成功/失败仅切换图标与单行详情,结果行含耗时;MCP 行主显发现的工具数并点名不可用的 Server,展开后按 Server 分组——每组一行状态、工具数与该 Server 的连接耗时,点开组内是工具列表或失败原因);
-- 每个 Task 结束后显示统计行:Token 用量、TPS、耗时、费用、复制以及位于复制按钮右侧的**分叉**操作。分叉会先弹出确认框(该操作会把对话复制为一个新对话),确认后才在该条已完成的模型回复处新建 Session,沿用 Agent、模型、Workspace、审批模式和保留范围内的历史;同一源对话从不同回复分叉时,标题使用不依赖界面语言的编号后缀,按 `原标题 (1)`、`原标题 (2)` 递增。新旧会话的 Trace 与 scratchpad 是独立快照,即使删除源对话,本地图片和附件仍可显示;
-- 打开一个对话只加载最近 50 轮;滚动到顶部附近会自动向前续载 50 轮,阅读位置保持不动,载到开头显示「已是对话开头」,续载失败则点击重试。轮次编号与顶部统计由服务端随窗口附带的累计值接续,与整段加载一致。
+### 密码
-### 头部统计与详情卡
+用户忘记密码时,由管理员在**用户管理**页通过**重置密码**重置。
-工具行最右侧显示会话累计统计(Token、费用、用时),点击即打开详情卡——模型、Session id(旁附复制按钮)、Workspace、创建时间与逐行统计。用时一行在括号里带两个分项,形如 `用时 10.3s(API 5s,工具 5.3s)`:一项是模型请求内的时间(已扣除人工审批等待),另一项是工具的 wall time(各工具执行区间的并集,并行工具只计一次)。二者是对这段用时的两项实测,不是对它的切分——后台工具会与模型解码重叠,审批等待与 harness 开销又不属于任何一项——故其和可能大于也可能小于总用时,任一项都不由总用时减去另一项得出。其下还有一节:会话仍有后台任务时,用时右侧有一枚小胶囊显示其数量——与会话列表行上那枚标记同一个数。其下还有一节:
+**admin** 忘记密码时,需要离线重置:
-- **会话进程**——对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`),逐行显示命令、启动时间与 pid;运行中的行在检测到进程所服务的地址时,还会附上可点击的服务链接(取其输出打印的最后一个本机 URL,否则对其进程组做监听端口探测)。运行中的行带「停止」按钮(杀停整个进程组并把该行从列表移除)——对话会收到该进程已结束的回报,措辞是「已停止」而非失败,模型因此知道 dev server 没了,却不会把它读成需要重启的崩溃;已退出的行保留「已退出」标注,并带「移除」按钮,可把该条目从列表删除。移除立即生效且不可撤销:条目连同该进程已捕获的输出一起离开运行时注册表,之后无法再让模型读取那段输出——输出还有用时请先留着这一行。
+**开始之前**
-全站的复制按钮在按钮自身给出反馈:复制成功后图标短暂切换为对勾(不再显示「已复制」文字)。
+- 服务已停止。
-### 输入与快捷操作
+1. 运行 `penguin server reset-admin-password`。
+2. 重新启动服务。
+3. 打开带边框提示中的首次登录链接,设置新密码。
-- Enter 发送,Shift+Enter 换行,支持粘贴图片——嵌入对话的图片单独设有 20MB 上限,不随附件上限一起放宽:图片会进入对话与轨迹,此后每次翻阅历史、恢复会话都要重新付出它的体积,而附件只是按路径从磁盘读取;
-- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,默认单个 ≤ 100MB、合计 ≤ 120MB——两个尺寸均可由管理员在**系统设置 → 上传限制**中调整,见下文;超限的文件在读取前即被拒绝,不会先上传再报错,提示中会写出当前生效的上限),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;
-- 也可以把文件**拖拽到聊天区**上传(聊天区即对话与输入框所在区域,会话页与草稿页皆可):文件拖到该区域上方时显示覆盖该区域的「松开以添加附件」浮层(拖离即消失,拖动文本等非文件内容不触发),松开即把整批文件附加到输入框——图片走粘贴图片的同一管线,其余文件成为附件,类型与大小校验及报错与「+」菜单一致。任务运行中同样可以拖入(附件按下述运行中发送方式送出);目标模式下拖入的图片照常附加、文件会以提示拒绝。只有聊天区会把文件作为附件:把文件放到侧边栏、顶栏、其他停靠面板或任何没有输入框的页面上,既不显示浮层也不会添加附件,只是被直接忽略,同时不会让浏览器跳转打开该文件(文件面板是另一处拖放目标,它把文件上传到 Workspace,见下文);
-- 输入 `/` 打开快捷菜单:触发上下文压缩(`/compact`)、把会话交接给其他 Agent(`/agent`)、切换模型(`/model`)——两个切换命令都只在进行中的会话里提供,草稿没有可切换的对话,Agent 与模型本就在草稿页选定——或勾选已安装的 Skill——所选 Skill 会以 `[use_skills]` 块随消息发送;
-- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失)。每条排队提示——未送达的插话或排队中的跟进消息——行尾都带一枚**撤回**按钮(一个向回弯的箭头图标),可把消息(含附件)撤回到输入框编辑后重新发送;插话一旦送达模型即不可撤回。运行在插话送达之前结束时(工具跑着的时候按停止是最常见的情形)不用你动手:这条插话会自动回到输入框,附件一并还原,改完可以直接再发——打断不会吃掉已经打好的话;
-- `/agent` 与 `/model` 都是暂存而非立即生效:选中的 Agent 或模型只在文本区上方留下一枚 chip,此时不发送任何内容,可以继续输入——按 Enter / 点发送才真正交接(为该 Agent 新开一个对话)或换用所选模型继续本对话,输入的文字随之带走;正文为空时自动填入默认消息,点 chip 上的 × 即可取消。两枚 chip 都随草稿缓存,刷新页面或切到别的会话再回来时与文字一同恢复;其中切换模型还需等待会话空闲——新会话要从本会话的 Trace 接续,而运行中的一轮或压缩仍在写入——等待期间输入框上方会给出说明;
-- 工具条右侧是**上下文占用圆环**:单色圆环,标尺是压缩真正触发的那个点(Agent 的 `compaction.max_context_length`,被模型窗口留出的余地钳住),>80% 转琥珀、>95% 转红。点击展开**上下文构成面板**:`已用 / 阈值` 数字、一条以模型完整窗口为标尺的条形(已填充部分按系统提示词、工具定义、用户消息、模型消息、工具请求、工具结果六项细分,条形下方以「最大上下文 N」标出该标尺),以及工具 / 文件两份 Top 5(标题行上的一对文字按钮切换,文件视图只列出 `read_file` / `edit_file` / `write_file` 触及的文件名,完整路径悬停可见)。条形上的虚线切刀标出压缩触发点,且可以拖动——拖动它(或聚焦后用方向键,按住 Shift 步长更大),松手即弹出确认框,框内的数值仍可编辑;切刀右侧直到模型窗口的一段以斜纹虚化——这是模型还有、但压缩先触发因而暂时用不到的空间,与左侧的空余轨道分开,拖动时随待定值实时移动;条形的填充段与图例行都可点击:点击即钉住该项的高亮,再点一次或点别的项解除——图例行是按钮,钉住也可由键盘到达,钉住的那一行带一圈悬停不会画的描边;确认后写入该 Agent,并对当前这段对话立即生效,运行中也不例外;
-- 需要人工审批时,工具调用在消息流中内联显示“允许 / 拒绝”按钮;审批模式在会话中途可随时调整;
-- 引擎在重连退避等待(≥2 秒)期间,重试提示行会实时倒计时到下一次尝试,并内联提供**立即重试**(跳过剩余等待)与**放弃**(普通中断)两个按钮;
-- 模型 API 拒绝该 Session 的凭据(鉴权失败)时,输入框会置灰禁用——但可恢复:Session 锁定的只是模型引用,凭据取自当前 Project 配置。提示条的主按钮跳转到模型配置页;在那里保存新的 API key 后输入框会自动解锁(已打开的标签页经 `credentials_updated` 事件即时解锁;刷新后也保持解锁,因为凭据更新时间晚于记录的鉴权失败时间)。「重试」按钮可手动清除该状态再试一次(key 仍无效时会重新变灰),一次成功的请求总会清除该状态,「新建会话」仍作为跳到全新草稿的出口。禁用态的输入框保留草稿且可选中——发送失败的长消息仍能复制出来。
-- 终端位于对话两侧的停靠面板:Ctrl+` 显示或收起终端标签(没有打开的终端时会接管或新建一个 Shell),终端获得焦点时按 Ctrl+W 关闭该终端——与标签 × 相同,先确认、再结束 Shell,停靠面板与独立的 `/terminal` 页一致——按键不会到达 Shell。浏览器把 Ctrl+W 留给关闭浏览器标签页,可能先于页面响应;桌面应用会把它交给终端。
+这条命令会给 admin 账号换上一个没人见过的随机密码,并结束 admin 的所有登录会话。下次启动时,服务会重新打印首次登录链接。
-### 快捷方式悬浮球
+### 登录会话
-没有面板占据屏幕时——桌面宽度下右侧停靠栏收起,窄屏下两块面板合并成的底部弹层没有打开——对话区(工具行与输入框之间的区域)右缘内侧 32px 处会浮着一枚半透明圆形按钮(球面是工作台图标)、下方带一行小字「快捷方式」,让工作台的各块面板始终一步可达——即使从未注意到工具行上的开关。点击它(或在其上按 Enter / Space)会以按钮为圆心向左展开一圈紧挨着它的圆形入口——智能体、Workspace 文件、记忆、轨迹、消息软件与终端各一枚,只有图标;指到或聚焦其中一枚时,按钮下方那行小字改显示它的名称;这行小字始终居中在按钮正下方,按钮与边缘留出的距离足以容下最长的那个名称。按钮本身是这行小字的另一半:指到某个入口时,球面换成该入口自己的图标;指针或键盘焦点落在按钮自身上时,球面与小字说的是下一次点击的结果——弧收起时是展开图标与「打开」,弧展开时是收起图标与「关闭」——弧展开着但没有指向任何一项时,球面回到静止时的工作台图标。按钮与入口都不带 tooltip——名称已经写在屏幕上。按钮靠近对话区上下两端时,这段弧收窄为放得下的那一段。选中入口即打开对应面板——桌面宽度落在右侧停靠栏,窄屏落在底部弹层——面板一出现按钮就消失。弧末另有一枚「隐藏悬浮球」入口,选中即让按钮不再出现,并提示去哪儿恢复;设置页「外观」的**快捷方式悬浮球**开关可重新打开。Esc、点击别处或滚动都会收起这段弧。按钮可沿右缘上下拖动(短按仍是点击),拖动全程跟随指针——指针经过其他按钮也不会中断——松手回弹贴边;它不会盖住工具行或输入框,位置作为一条全局偏好记在浏览器里,所有对话共用。停靠栏收起期间若有子智能体等待审批,工具行开关上的琥珀色小点也会显示在这枚按钮上。
+登录状态保持 30 天,滑动续期:只要在使用,有效期就重新算满 30 天。
-### 文件面板
+管理员重置某个用户的密码后,该用户的所有登录会话立即失效;自己修改密码则不影响当前会话。
-文件面板左侧是 Workspace 的目录树,右侧是所选文件的预览。目录在首次展开时才加载内容;目录树支持方向键(上下移动、右键展开目录或进入其中、左键收起或回到上级),选中的文件高亮,工具栏的面包屑只读出当前目录的路径、不再可点——旁边就是目录树,导航交给它;路径长到工具栏放不下时,前导段折叠成一个「…」,当前目录始终可见,刷新 / 上传也不会被挤到第二行;根目录在面包屑里写作 `.`,Workspace 的绝对路径在会话详情卡片里,不在这条工具栏上。目录树上方的搜索框按条目名称过滤:命中项的上级目录一并保留并展开,名称本身命中的目录连同其内容一起显示。目录树是懒加载的,搜索只能覆盖至少展开过一次的目录——都不匹配时会明说,而不是显示成空树;按 Esc 清空搜索框。展开 / 折叠时子树以高度过渡动画展开或收起(约 200ms,折叠期间行仍可见直至收起完成;系统设为减少动态时即时)。工具栏按钮可隐藏或显示目录树(默认显示,选择记在浏览器本地),显隐时目录树以约 200ms 的宽度过渡滑出或滑入,与停靠面板展开 / 收起同款;两栏之间的分隔条可拖动调整目录树宽度(获得焦点后可用左右方向键微调,宽度同样记住);面板宽度容不下两栏时退化为单栏——先显示目录树,选中文件后换成带「返回列表」按钮的预览。Markdown 与 HTML 以渲染视图预览并可切换源码,文本文件内联高亮显示,图片内联显示(点击放大),PDF 内嵌;其余类型提示下载。扩展名看不出类型的文件(`Makefile`、`LICENSE` 之类)在内容看起来是文本时按文本处理。
+**登出**在账户菜单中,点击后会先确认。登出只结束这个浏览器里的会话,正在运行的对话会在服务端继续。
-文本文件可以就地编辑:**编辑**把预览换成纯文本的等宽文本框——没有富文本编辑器——**保存**(也可按 Ctrl+S / Cmd+S)经上传所用的同一内容写接口写回文件,保存前先弹统一的确认框;取消则回到预览。旁边还有**自动换行**开关:缺省关闭,长行像代码编辑器那样横向滚动,选择会带到下一个编辑的文件。未保存的修改在可能丢失之前都会先询问——切换到别的文件、关闭该面板的标签页、离开页面。折叠或隐藏停靠面板不会丢失任何东西:面板连同预览、目录树状态与编辑草稿原样留着,重新展开即回到原处,也不会询问。切换 Session 时草稿也会保留:再次打开同一文件即回到编辑状态。超过 256KB 预览上限的文件以截断方式显示且保持只读(把不完整的文本存回去会覆盖整个文件);超过 14MB 写入上限的保存会被拒绝并给出提示。在桌面端自己的窗口里,「下载」旁多一枚**在文件夹中显示**按钮,会在系统文件管理器里打开该文件所在目录——Finder 与资源管理器会选中该文件,Linux 桌面打开目录;用浏览器登录同一台服务端的会话——哪怕就在本机——不显示这枚按钮,服务端分不清它与远程浏览器。
+> [!NOTE]
+> 桌面应用会以 admin 身份自动登录自己的窗口,不需要密码。这个窗口里没有**登出**、没有初始密码横幅,也没有**账户**页和用户管理。
-Agent 写的是同一个 Workspace,你编辑期间文件可能被改动。每轮 Task 结束时都会检查一次——你的文本不会被替换,但编辑器标题栏会立即标出**磁盘上已变更**;若保存会落在已变更的文件上,写入前即被拒绝:面板会询问是用你的版本**仍然覆盖**,还是继续编辑,两种选择都保留你的文本。
+## 应用布局
-上传写入当前目录(工具栏的**上传**按钮,可一次多选),也可以把文件**从桌面拖到面板上**:虚线框会标出文件将落入的目录,拖到某个文件夹行上松开即上传到该文件夹(拖动经过时该行高亮),完成后自动打开第一个上传的文件。单个文件上限 14MB——超限的文件在读取前即被点名跳过——目标目录中已有同名文件时先确认再覆盖。下载按钮在预览标题栏。
+左侧的侧边栏放着对话之外的所有入口,窗口的其余部分显示当前打开的页面。各个部分都有自己的指南。
-### 定时任务面板
+### 侧边栏
-定时任务面板列出绑定到当前对话的定时任务(每次新建 Session 的任务属于 Agent,在其设置页管理),带搜索框与全部 / 生效中 / 已暂停 / 已完成筛选。每行显示状态字形、任务名与一行人话时间表(「每天 08:00 · 下次 明天 08:00」「每 30 分钟」「每周一 09:00」「一次性 · 9月3日 10:00」);owner 可用行上的开关启停任务,在行菜单里编辑或删除。**建议**区列出每日简报、每周回顾、跟进提醒、监控更新四条现成请求,点击即打开 AI 对话框并预填。绑定到对话的定时任务只在本面板创建,面板标题之下另起一行并排两枚按钮——面板宽度可以拖动,按钮若与标题同行,拖窄时会被挤裁。带魔法棒的**用 AI 创建**(所有成员可用)与别处的 AI 创建只有一点不同:它的出口是**在本对话中编辑**,把提示词预填进这段对话自己的输入框,而不是新开一个对话——因为在对话里创建的任务默认就绑定到这段对话;发不发送仍由你决定,按下发送后走的就是手输文字的同一条路。带手形的**手动创建**(仅 owner)打开与设置页相同的表单,目标锁定为本 Session。绑定了**还有下一次触发**的定时任务的对话,不论属于哪个 Agent、列表按什么分组,都会在侧栏会话列表的行上带一枚闹钟图标(悬停显示「有待触发的定时任务」):只有图标、没有数量;已停用、已过结束时间、或已经触发过的一次性任务都没有下一次触发,不出现图标。保存或启停一个任务只提示发生了什么——定时任务由调度器按时触发,与对话上下文无关,改完即时生效。列表在面板到前台、窗口重获焦点、有任务触发或排队、对话每轮结束时、可见期间每 30 秒以及每次改动后刷新——会话行上的标记读的是同一份列表,同一次刷新把面板和标记一并更新,二者不会各说各话。
+侧边栏从上到下依次是:
-## 用 AI 创建
+- **开发** / **公司**切换,只在公司模式可用时出现:管理员已为服务器启用公司模式,而你没有为自己关闭它。切换到公司模式后,下面的页面入口换成组织的页面,对话列表换成频道。见[公司模式](/company-mode)。
+- Project 切换器,旁边是**收起侧栏**按钮。见 [Project 与成员](#project-与成员)。
+- **新建对话**,打开一份新的对话草稿。见[对话](/chat)。
+- 页面入口。最后一项下方的箭头可以把这组入口折叠起来:
-Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchmark、定时任务、密钥保险柜条目、应用、Agent 导入——都可以改为向 Agent 描述。每个页面并排给出两个按钮:带魔法棒的**用 AI 创建**与带手形的**手动创建**,两条路径同时可见。提示词框自带可点击的示例,点一下即填入草稿;折叠的**完整提示词**预览展示随你的输入一起发送的固定说明,并带复制按钮。唯一的出口是**在新对话中编辑**:以 Project 的 `default_agent`(没有时取第一个 Agent)开启新对话,把提示词预填进输入框,发不发送由你决定。预填的提示词不会被浏览器留下:不作修改也不发送就离开该页面,它随即被丢弃,不会在之后的对话里再冒出来;一旦动手编辑,它就成为普通草稿,与你自己写的内容一样保留。
+| 入口 | 用途 | 指南 |
+| --- | --- | --- |
+| **智能体** | 创建 Agent,编辑它们的提示词、记忆、运行参数、工具、Skill、钩子、密钥保险柜和定时任务 | [Agent](/agents) |
+| **插件市场** | 浏览插件,把插件中的 Skill 和钩子包安装到 Agent 上,为 Project 添加服务端插件 | [Skill](/skills) |
+| **模型库** | 配置 Project 的模型、供应商和凭证 | [模型](/models) |
+| **成本中心** | 按 Agent、模型和时间范围查看 Token 用量、成本和服务器异常 | [成本中心](/usage) |
+| **评估中心** | Benchmark:评估 Agent,并以 Benchmark 为标准优化 Agent | [评估中心](/evaluation-center) |
-## Agent 管理(/agents)
+- 对话列表,可以搜索,可以按 Workspace、Agent 或时间分组。见[对话](/chat)。
+- 底部是你的用户行,点击打开账户菜单:
+ - **系统设置**,见[系统设置](/settings)。
+ - 更新行,显示更新进行到哪一步,点击打开更新对话框,见[更新 PenguinHarness](/updates)。
+ - **登出**。
-页头是[用 AI 创建](#用-ai-创建)一节所述的那两个按钮;Project 里除 `default_agent` 外还没有 Agent 时,列表末尾的空态按钮同样是这一对。弹窗按你点的那个按钮打开对应路径,并停在那里。**用 AI 创建**的提示词框带五个示例——随记智能体、金融 Copilot、文档 RAG 智能体、深度研究报告智能体,以及新手引导链(先用 AI 创建它,再让 AI 为它建 Benchmark 并优化)起点的报告写作智能体(id 为 `report-writer`)——固定尾巴让 Project 的默认 Agent 用 `agent-initialization` 技能创建:在当前 Project 下新建一个 Agent(用你给的 id,否则取语义 id),写好它的 AGENTS.md 与名称、描述,只从插件库复制它需要的技能,不动其他 Agent,最后报出 id 与开始对话的方式。**手动创建**打开表单:名称在前,id 字段旁的「用 AI 生成」以 Project 的默认模型按名称(名称留空时按描述)推导 Agent id;侧边栏那个「新建 Agent」按钮不点名路径,打开的也是它。
+### 提醒圆点
-列表页支持创建与删除 Agent——创建弹窗可选从导出的 Agent State 快照包直接初始化(名称与描述留空沿用包内值;此时技能选择不可用,包自带技能);点击进入 `/agents/:agentId` 设置页,按标签页组织:
+页面入口上出现圆点,说明那里有事情等你处理:
-| 标签页 | 内容 |
+| 入口 | 圆点的含义 |
| --- | --- |
-| Overview | 基本信息、Agent State 快照的导出 / 导入,以及还原为默认配置(覆盖自定义内容,仅保留名称与描述) |
-| Prompt | AGENTS.md 与 system_prompt |
-| Memory | Agent 级开关,以及按作用域分组的全部记忆——用户记忆在前、每个 Workspace 一组,分组可折叠并带添加、导出与导入入口——每行提供查看 / 删除 / 对话编辑 |
-| Runtime | max_turns、model.*、compaction.* 等运行参数 |
-| Tools | 内置工具表格(含条目级 call_description 开关)与 MCP Server 管理:表格 + 添加/编辑表单(默认 http,字段随 transport 切换,改动即时保存,服务端按 transport 完整校验;permission 控件把该 Server 工具的审批等级固定为 `auto` / `r` / `rw`,表格列出各 Server 的生效等级);测试连接与模型页同款——表单内独立按钮测当前条目(toast 报工具数与耗时),区块级按钮逐一测试全部 Server 并在各行显示结果徽标 |
-| Hooks | 顶部一个**启用钩子**开关(仅 owner,成员只见状态)决定该 Agent 此后新建的 Session 是否运行钩子包——关闭后新建的 Session 一个钩子都不运行,已安装的包仍全部留在磁盘上。其下是已安装的钩子包(agent_state/hooks/):每行以包名加紧随其后的钩子点胶囊(只写钩子点名,如 `stop`)开头,其下描述,行尾版本、打包导出与卸载。**导入钩子**弹窗与导入技能同款:推荐路径是让 Agent 在对话中导入——填入钩子来源(URL / GitHub 仓库 / 本地路径 / 一段描述,或其他工具的钩子配置),弹窗实时预览发送给 Agent 的 Prompt,**复制 Prompt**与**打开新对话**在来源为空时一同置灰;其下可直接上传钩子包 zip(同名已装先确认覆盖)。从插件库安装仍在插件库页完成 |
-| Vault | 环境变量条目,值以掩码显示;**手动创建**旁的**用 AI 创建**把密钥交给 AI、由它以 `penguin config vault set` 写入——弹窗如实提醒:写进提示词的值会发给模型服务商、进入对话记录(Trace),也会出现在智能体执行的命令里,更稳妥的是只让它建键名,示例即以此打头 |
-| Schedule | 定时任务(TOML 定义):创建(用 AI 创建或手动创建)、编辑、启停、删除;列表为空时展示建议 |
+| **智能体** | 有 Agent 的内核版本过旧 |
+| **插件市场** | 有插件可以更新 |
+| **模型库** | 有预置模型可以同步(仅 owner 可见) |
+| **成本中心** | 有未预期的错误 |
-Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,因此关闭记忆不会连带把别处未改完的内容一起存盘。关闭记忆也不会删除任何文件,标签页仍可正常查看与删除——只是记忆不再进入 Agent 上下文,也不再为新 Session 准备目录。作用域分组可折叠,折叠状态按「用户 × Project × Agent」记在浏览器本地;每组标题的折叠箭头左侧有**添加**文字入口(与模型页的分组约定一致)——和编辑一样经中转弹窗(必填的内容或来源 + 引导语实时预览)跳到新对话,由 agent 整理保存到该作用域;引导语刻意极简,写入规范由记忆提示词承载。记忆行有意不提供就地编辑,操作与技能页一致为纯图标按钮:**查看**在桌面端从右侧抽屉、窄屏从底部弹层(与对话页面板同一交互,半屏 / 全屏两档吸附)渲染正文;**删除**先确认,并同步清掉该文件在 `MEMORY.md` 中的索引行;**编辑**先打开中转弹窗(修改要求 + 引导语预览),再跳到与该 Agent 的新对话——Workspace 作用域的对话还会锁定对应 Workspace,让会话恰好读到它正在修改的那份索引。整组记忆也可以一次搬运:**导出**把它下载为一份 JSON 文档(这一组的全部记忆加它的 `MEMORY.md`),文件名带导出日期时间,多次导出互不覆盖;**导入**把这样一份文档读回来——与 Agent State 快照同样的分工,仅 owner 可用。导入时需要指定同名记忆的处理方式:保留现有的(缺省,不丢失任何内容)、改用文件里的版本、或整组替换;后两者会先弹出确认,逐条列出将被覆盖或删除的记忆。标签页下方可直接编辑两段记忆提示词(`memory.prompt` / `memory.workspace_prompt`);当提示词模板中没有 `{{MEMORY}}` 占位符(创建于记忆功能之前的 agent)时会给出提示并提供一键插入——显式且幂等的配置写入。Agent 列表卡片的统计行也显示记忆条数,点击直达本标签页。存储模型见[配置说明](/configuration#记忆)。
+头像上的圆点表示有软件更新。鼠标指向入口,可以看到具体在等什么。
-定时任务按固定周期触发(最短 5 分钟),且仅在服务运行期间执行。
+### 收起的侧栏与窄窗口
-## 插件库(/plugins)
+**收起侧栏**把侧边栏收成一列图标,从上到下是:**展开侧栏**、公司模式切换(可用时)、**最近一次对话**、**新建对话**、各页面入口,以及你的头像,点击头像打开的也是同一个账户菜单。鼠标指向或键盘聚焦某个图标时会显示它的名称。收起状态记在浏览器里。
-按分类浏览插件库——Skill 与会话钩子都在这里——把插件安装到指定 Agent(Skill 与钩子包一并装入)、更新落后于库的已装副本,或把某个 Skill 一键带入 Chat 草稿快速调用。每张卡片带一行语义化元信息(`v<版本> · N 天前更新 · N 个 Agent 在用`),点开即详情弹窗:插件完整描述与钩子包应答的钩子点,其下是它携带全部文件的浏览器,与 Benchmark 题目详情共用同一个文件浏览器组件(Workspace 文件面板同款文件树 + 只读预览)——左侧文件树按 Skill 分组(各自的 SKILL.md 与参考文件)、钩子脚本单独一组,可同时展开任意多组;右侧预览所选文件,摘要与文件树始终在场。
+窗口较窄时,侧边栏收进顶栏的菜单按钮里,点击后以抽屉形式展开。
-## 模型配置(/models)
+### 轨迹观测与机器
-按 Provider 分组展示当前 Project 的模型表格。支持添加与编辑模型:以 `(provider, model_id)` 为唯一标识,凭据以掩码显示,可配置上下文窗口、最大输出长度(按模型的输出上限,覆盖 Agent 的 `model.max_tokens`——小上下文模型建议调低)、定价、视觉(vision)标记与快速模式(默认关闭:进入厂商的溢价快速档位、输出更快——该开关只对 AgentHub client 支持该档位的模型显示,打开时会先确认溢价计费);开启了快速模式的模型会在列表中带角标;可设置默认模型与视觉模型(在会话模型不支持图片输入时代为读图),并对任一模型做连通性测试——测试会携带弹窗当前的快速模式开关状态,被拒时在保存前即可发现。仅 Project Owner 可编辑,概念说明见[模型与 Provider](/models)。
+应用里有两个部分没有侧边栏入口。
-页头带那两个创建按钮(仅 owner)。**用 AI 创建**把模型列表页或一段服务描述交给 Project 的默认 Agent,由它经 `penguin config model add` 把模型加为一个分组;弹窗引导语说明何时用**导入模型**更快。**手动创建**打开**新增分组**弹窗。模型表每次进入页面都重新加载,从对话回来即能看到新分组。
+**轨迹观测**是对话页的一个侧边面板,而不是独立页面。它展示当前对话的 Trace 文件,包括汇总、每轮统计、执行时间线和逐条事件,点击**导出**可以下载文件。见[对话](/chat)。
-## 用量统计(/usage)
+**机器**页通过 ssh 把当前版本的 PenguinHarness 安装到其他主机上,主机从服务器账户的 `~/.ssh/config` 中选择。这个版本的侧边栏还没有它的入口,管理员可以直接访问 `/machines`。
-- 筛选条件:Agent、模型与日期范围(最近一小时 / 最近一天滑动窗口、近 7 / 30 / 90 天、或自定义起止)。图表以何种精度绘制由范围决定——最近一小时按分钟,最近一天按小时,日历档位按天,跨度很长的自定义范围按周或按月——因此没有单独的精度控件;
-- 概览卡片:今日 / 近 7 天 / 累计用量;
-- 图表,全部按所选范围展示的时间序列:并排的「按 Agent 拆分」与「按模型拆分」的请求与成功率图(单个时间桶的请求数按对象分段堆叠、走左轴,每个对象的成功率各自成一条虚线、走右侧 0–100% 轴并绘制在柱子上方;请求数最高的若干对象具名呈现,其余折叠为一条标注了数量的中性色序列)、Token 变化(三段堆叠柱 + 前置的缓存命中率虚线)、成本变化(折线带点 + 面积)。每张图都支持同样的悬停:悬停整列看气泡、悬停单段柱突出该段、悬停折线突出该线。所有折线都是直连线段、不做平滑,线宽统一。图表自适应卡片宽度,不出现滚动条;
-- 有两种情况图画不出来。**没有比率**的桶——该对象在这个桶里一次请求都没发,或该桶没有缓存流量——折线沿坐标轴顶部横穿过去,只为让线保持连续;悬停表格在该处显示「—」而非百分比,而真正的 0%(发了请求且全部失败)仍然显示 0%。**什么都没记录**的桶一律不画:四张图都丢弃它、把其余的从左往右依次排开,因此共用同一条会跳过空闲区间的横轴,跳过处画有断轴标记。空与不空按桶判断、绝不按单个对象判断——只要有任何对象在这个区间跑过,桶就保留,当时空闲的对象在该列显示 0 与「—」;
-- 服务端错误面板:汇总统计 + 异常明细表,按固定页大小分页(不滚动)。其**清空**(仅 Project owner)删除当前范围与 Agent 筛选所列的记录——确认框按档位名点出范围(如「近 7 天内」「最近一小时内」),自定义范围才写起止日期;管理员的清空同时带走只有管理员看得到的无归属记录。
+### 语言与主题
-## 评估中心(/benchmark)
+界面语言(English / 中文 / 跟随系统)和主题(浅色 / 深色 / 跟随系统)随时可以在[系统设置](/settings)中切换,登录页上也能切换。两者都按浏览器保存。
-Project 的全部 Benchmark 平铺列出,每个 Benchmark 一张卡片——Benchmark 属于 Project 而非某个 Agent,因此页面不按 Agent 分组:标题与目录名、描述、题数与每题运行次数、最近评估时间、评测过的 Agent、评分板的分数走势小折线,以及最新分数与相对同标签上一条评估的增减。点击卡片或**查看**进入这个 Benchmark 自己的页面(`/benchmark/<benchmark>`)——以时间为横轴的分数曲线、带单题与逐次运行行的评估明细表、题目浏览器(题目浏览器与插件详情共用同一个文件浏览器:左侧是 Workspace 文件面板同款的文件树——任务材料与评分标准是它的两个顶层目录,逐级懒加载——右侧是只读预览)——页头的返回按钮回到列表。配置里 `status = "draft"` 的 Benchmark(智能体仍在出题与校准)会被遮罩:卡片变淡并覆一层「构建中」提示,**使用**与**查看**禁用,其页面正文也以同样的提示代替题目与曲线;只有 owner 的删除图标仍可用。配置里 `status = "failed"` 的 Benchmark(难度校准未能完成)同样被遮罩,提示改为「创建失败」,请用户删除后重新创建。状态改为 `published` 后遮罩解除。标题下是三张独立的步骤卡片,一步一张——**出题**、**评估**、**优化**——各写序号、标题与一句话操作说明:出题用右上角的两个创建按钮,评估与优化都是在某个 Benchmark 上按**使用**再选对应的 tab。**使用**开出的对话,以及一次评估为每个 Case × Run 启动的被测会话,都归入会话列表的**评估任务**折叠夹。
-
-- 右上并排两个按钮,与智能体设置的定时任务页是同一对:魔法棒走 AI,手掌走表单。**用 AI 创建**要求选定被测 Agent 并描述要考察的能力与场景;提示词的固定尾部把 Agent id、期望基线分与 Pilot 迭代上限交给 `benchmark-design` 技能,并要求取得基线分。**手动创建**是一张表单——标题、id(可点「用 AI 生成」按标题推导为 kebab-case)、描述、每题运行次数、每道题的题干与评分细则,不再选择所属 Agent——由服务端按技能读取的目录结构落盘(`POST …/benchmarks`,仅 owner)。
-- 卡片与 Benchmark 页面头部的**使用**打开同一个弹窗,顶部两个 tab 共用一个出口。**评估**把一个智能体放到已冻结的题目上:被测 Agent(缺省为最近一条评估的 Agent)、执行评估的 Agent(未装 `agent-evaluation` 技能时有提示)、评估会话使用的模型(与 Project 默认设置同一个模型选择器,缺省即当前 Project 的默认模型)、每题运行次数与可选说明。它的提示词要求经自调用的 `agent-evaluation` 子会话跑完整的 Case × runs 矩阵,校验每条结果的被测 Agent、成对模型与思考等级一致,并只向 `scoreboard.yaml` 追加一条带标签的评估——不动被测 Agent,也不动 Benchmark。**优化**是优化表单:执行优化的 Agent(同样会提示缺技能)、**被测 Agent**、优化会话自身使用的模型(同一个选择器、同样的缺省)、每题运行次数、最多轮数、目标分数(缺省比该 Agent 的基线高 10 分)与可选的优化重点;所选被测 Agent 在此还没有基线时,提示先到「评估」取得一条。两个 tab 都可折叠展开完整提示词,也都以同一个出口结束——**在新对话中编辑**:提示词预填进输入框,发不发送由你决定。评测 Runtime 不在这个弹窗里选——「评估」取被测 Agent 当前配置的模型与思考等级,「优化」沿用基线记录的那一套。
-- 曲线以时间为横轴、分数为纵轴,按**标签**分系列——标签为被测 Agent id、模型 id 与思考等级三者,只有同标签的分数才可比;没有标签的旧记录归入灰色系列。Agent State 版本号刻意不进标签:同一被测 Agent 在同一模型与思考等级下的历次版本连成一条线,进步正应该在这条线上看出来,版本号则标在每个点的悬停提示里。评估明细表自带一列版本号,另有一列写明被测 Agent。
-- 点击评估明细表的一行打开该次**评估详情弹窗**,形制与题目详情弹窗一致:顶部是系列标签、被测 Agent 与版本,其下为 Score、成本与耗时,再下是这次评估自己的说明(标题与正文分开展示)与单题得分表,题目行可展开逐次 run 的原始结果及其 Session id。在其中点开某道题,题目详情弹窗叠在它之上。
-- 两个弹窗的页脚都有**问 AI**:打开提示词弹窗,问题已经填好(这次评估为什么是这个结果 / 这道题考什么),示例按钮里排在最前的就是这个默认问题(试过别的示例后一键换回),后面另有三个可替换的示例,固定尾部把屏幕上的事实一并交出去——评估这一侧是 Benchmark id 与目录、评估时间、系列标签、版本、评测 Runtime、总分与逐题得分、逐次 run 的 Session id 与评估说明;题目这一侧是 `statement/README.md` 与 `rubric/README.md` 的路径,以及最近一次评估在这道题上的逐次结果。它只被要求读这些文件与 Trace 后作出解释:题目已冻结,被测 Agent 也不是这个问题的对象。出口同为**在新对话中编辑**。
-- 卡片上的动作是**使用**、**查看**,以及 owner 才有的删除图标——确认后整目录删除(`DELETE …/benchmarks/:id`)。Benchmark 自己的页面在标题旁写出它的目录 `benchmarks/<benchmark>`,并附一个复制路径的按钮。`/benchmark?agentId=` 把列表收窄为评测过该 Agent 的 Benchmark。
-- **Benchmark 创建即冻结题目。** Web App 与服务端接口都没有改题的入口:改动题干或评分细则会让记分板上已有的分数不再可比,因此要换题只能新建一个 Benchmark。AI 出题过程中的校准发生在基线确立之前,属于创建的一部分。
-- 每个 Project 都带示例 Benchmark `example-benchmark`,判定在于 Project 有没有 `benchmarks/` 目录:`default_agent` 初始化时预置,此后每次装载也会补——因此早于该示例的存量数据根在首次装载时同样得到它。`benchmarks/` 还在(无论里面有别的 Benchmark 还是空的)时删掉示例是一个会被尊重的决定;整个目录删除才会要回示例。
+## Project 与成员
-配合[自我进化](/self-improvement)工作流使用。
+一个 Project 包含它的 Agent、模型、Benchmark 和对话。侧边栏顶部的 Project 切换器列出你拥有或参与的所有 Project,并标出你在其中的角色(`owner` 或 `member`),点击即可切换。同一个菜单里还有**新建 Project** 和 **Project 设置**。
-## 系统设置
+### 创建 Project
-把既不属于 Project 也不属于 Agent 的设置收进一个弹窗,入口是侧边栏用户菜单的「系统设置」:左侧一列页面导航,右侧每页是一列设置行——左边标题加一行说明,右边控件。
+任何已登录的用户都可以创建 Project,并成为它的 owner。
-导航按组划分。**个人**组存放属于当前账号的偏好,改动即刻生效,没有保存按钮,关闭弹窗也不会丢失什么——唯一的例外是「个人资料」页的昵称,输入的文本需要一次显式提交,其「保存」按钮就挨着输入框,而不在页面底部;**服务器**组存放服务器全局的界面:经 `GET|PUT /api/admin/settings` 写入的设置与用户管理仅管理员可见——非管理员既看不到这些条目、也不会得知它们存在,无论前端渲染成什么,接口对非管理员一律返回 403。因此非管理员只会看到「个人」组的几页,此时导航不再绘制分组标题。桌面应用中没有用户管理页(服务端是单用户模式);桌面 shell 自己的窗口还没有「账户」页——它通过 shell 的一次性 token 登录,没有可修改的密码,而用密码登录同一服务器的浏览器会话仍保留该页。检查更新不是这里的一页,见[版本与更新](#版本与更新)。
+1. 打开侧边栏顶部的 Project 切换器。
+2. 选择**新建 Project**。
+3. 在**显示名**中填写显示名,可以不填,不填时显示 id。
+4. 在 **Project id** 中填写 id,也可以点输入框旁边的**用 AI 生成**,从显示名生成一个。提议由当前 Project 的默认模型写出,因为 Project 本身不在任何 Project 之内。
+5. 选择**创建**。你就是这个 Project 的 owner 了。
-### 个人资料
+id 长 2–64 个字符,以小写字母开头,只能包含小写字母、数字和下划线。admin 以外的用户创建的 id 以「用户名-」开头,输入框里只需填写这个前缀后面的部分。
-个人设置,且在**任何**会话中都存在——包括桌面 shell 自己的窗口,因为这两项都不需要密码即可修改。**头像**与**昵称**;本页没有页脚,每个控件被使用时即写入,写入某个值的按钮就挨着那个值。选中图片即刻生效——按中心裁成正方形并以 128×128 重新编码:默认 PNG,PNG 超过 100 KB 时改用 JPEG;仍超过 128 KiB 的在浏览器内即被拒绝,不会发出服务端同样会拒绝的请求——旁边的**恢复默认**把首字母头像换回来。昵称是输入的文本,因此保留显式的**保存**,并在其旁配一个自己的**恢复默认**;两者都在点击时写入,因此同一字段旁的两个按钮不会在「何时生效」上各说各话。昵称为 1–32 个字符(按字符计,因此中文昵称可以有 32 个),其默认值是用户名,保存空值即清除。当按钮要写入的正是已存储的值时,它处于禁用态。本页不做乐观更新:预览展示的是已存储的头像,因此写入失败时各处显示仍与服务端一致,并就地给出提示。两项默认都未设置,因此本页之前就存在的账号在设置之前一直显示用户名与首字母头像。设置之后,侧边栏底部用户行、收起态侧栏头像,以及由这两处打开的账户菜单顶部都换成新的头像与昵称——菜单里用户名仍显示在昵称下方——昵称同时出现在**用户管理**列表中用户名的下方。
+> [!NOTE]
+> Project id 创建后不能修改。
-### 通用
+### Project 设置
-个人设置。**语言**(中文 / English / 跟随浏览器)与价格的**显示币种**(USD / CNY;存储始终为美元,换算只发生在显示层)。**显示 CLI 会话**(默认关):关闭时会话列表只列出在 Web 端创建的 Session,直接由数据库返回;开启后会额外扫描轨迹目录,把 CLI 创建的会话一并列出。按用户存储。**导入 Trace**:选择目的地的 Project 与 Agent,上传从其他部署导出的 `.jsonl` 轨迹文件,它会成为该 Agent 的一个会话。两者都需要选择:接口按 Agent 划分,因为轨迹文件自身无法指认本机的 Agent;Project 则是因为本对话框不显示当前打开的是哪一个——这也意味着可以导入到当前打开之外的 Project。导出是同一条路的反方向,与它下载的文件待在一起,位于对话的 Trace 面板中。
+**Project 设置**包含四个页面:
-### 外观
+| 页面 | 内容 |
+| --- | --- |
+| **通用** | 显示名、**Project ID**,以及**删除 Project**(递归删除 Project 目录,不可恢复) |
+| **成员** | Project 有哪些成员、各是什么角色。owner 可以按用户名添加已有用户(**添加成员**),也可以移除成员(**移除**)。桌面应用中没有这一页。 |
+| **默认值** | **新对话默认值**:每个新对话默认使用的 Agent、工作目录、审批模式、思考等级和默认模型 |
+| **安全策略** | 命令策略规则:命中任何一条已启用规则的命令都会被拒绝,与审批模式无关。见[命令策略](/configuration#命令策略) |
-个人设置。应用**主题**(浅色 / 深色 / 跟随系统)、**终端主题**——终端面板保留自己的明暗配色,默认跟随应用主题,显式选定浅色或深色即与应用解耦,适合提示符与 TUI 只为一种屏幕调校过的场景——以及界面**字号**与**主题色**。
+### 角色
-### 账户
+成员角色分为 `owner` 和 `member` 两种。每个 Project 只有一个 owner,即它的创建者;角色不能更改,所有权也不能转移。管理员身份不会让你获得访问其他用户 Project 的权限。
-**修改密码**操作。该页只在存在可修改密码时出现:桌面 shell 自己的窗口通过 shell 的一次性 token 登录,从未见过密码。
+只有 owner 可以:
-### 用户管理
+- 重命名或删除 Project、管理成员,以及修改**默认值**和**安全策略**(member 只能查看这些页面)。
+- 修改模型、密钥保险柜和定时任务。
+- 创建和删除 Benchmark、删除 Agent、清空成本中心的异常记录、设置远程控制。
+- 导入 Agent 快照、记忆和 Trace。
-仅管理员可见、桌面应用中不出现:列出与创建用户、重置密码、删除用户(内置 admin 不可删除)。
+member 仍然可以创建 Agent 和对话,也可以删除对话、Skill、钩子包和记忆文件。
-### 代理选项
+> [!NOTE]
+> `default_project` 与 CLI 共用,不能在 Web App 中删除;一个账号的最后一个 Project 也不能删除。
-仅管理员可见、服务器全局。两个开关——**应用程序使用代理**(server 自身出网:LLM 请求、更新检查、图片抓取)与 **Agent 环境使用代理**(Agent 命令子进程环境)——共用一个可选的**代理地址**,留空即跟随代理环境变量。地址接受 undici dispatcher 认可的任意代理 URL(`http://`、`https://`、`socks5://`,可带凭据)或裸 `host[:port]`(归一化为 `http://…` 后存储),其余一律拒绝并在输入框下方给出原因。保存前不写入任何内容,保存以单次 PUT 整体提交,因此地址被拒时其余字段也不会落库。保存后重建出网 dispatcher,对新发起的连接即时生效、无需重启;回环地址始终直连。
+## 用 AI 创建或手动创建
-### 上传限制
+Web App 中很多通过表单创建的东西,也可以改为向 Agent 描述,让它来创建。这些位置并排放着两个按钮:带魔法棒的**用 AI 创建**,和带手形的**手动创建**。
-仅管理员可见、服务器全局:两个尺寸——**单个附件上限**与**单条消息附件合计上限**,均以整数 MB 填写,默认 100MB 与 120MB。两者的取值范围为 1–200MB,且合计不得低于单个上限(否则一个本身合法的附件将无法发送);超出范围的值——例如把「100GB」按 MB 填成 102400——会被服务端明确拒绝并在输入框下方给出原因,不会被接受。校验先于写入:一次 PUT 中只要有一个字段非法,其余字段也不会落库。
+| 可以创建的内容 | 位置 |
+| --- | --- |
+| Agent | 智能体页 |
+| 模型分组 | 模型库页 |
+| Benchmark | 评估中心 |
+| 密钥保险柜中的密钥 | Agent 的「密钥保险柜」标签页 |
+| 定时任务 | Agent 的「定时任务」标签页,或对话的「定时任务」面板 |
-保存即刻生效,无需重启:附件校验与请求体上限都在每次请求时读取该设置。请求体上限本身不单独配置,而是由合计上限推导——附件以 base64 `data:` URL 随请求送达,体积膨胀 4/3,因此上限必须随之上浮,否则每个附件单独合法的请求会在 HTTP 层被拒。
+其中有些只对 Project owner 开放:
-有两个数值刻意不开放:单条消息的附件**数量**上限固定为 20(它约束的是输入框的可用性,而非服务器资源),对话内嵌**图片**上限固定为 20MB。图片不随附件上限放宽是有意为之——图片进入对话与轨迹,其体积在每次翻阅历史与恢复会话时被反复付出;而且模型侧另有更低的实际限制(供应商通常约 5MB,`read_file` 读图亦为 5MB),把它放宽到 100MB 只会把一个清晰的拒绝换成更靠后、更难懂的失败。
+- 模型库页和「密钥保险柜」标签页:两个按钮都只有 owner 可用。
+- 定时任务:**手动创建**只有 owner 可用。
-## 版本与更新
+提示词输入框附带可点击的示例,点一下就会填入草稿。如果页面会在你输入的内容后面附加固定说明,下方会有一个折叠的**完整提示词**预览展示这些说明,并提供**复制提示词**。
-更新的交互和常见的应用更新器一样,集中在一个弹窗里。两个入口都打开它:侧边栏用户菜单里紧贴「系统设置」下方的那一行,以及新对话页版本行上的「有新版本可用」上标(版本行形如「vX.Y.Z · 最近更新日期 7月26日」——日期由发布流程在构建时打入,直接显示、无需联网;开发构建以及打入机制之前的发布版,v0.1.2 及以前,没有日期)。那一行会说明进行到哪一步——「检查更新」「检查中…」「新版本 vX 可用」「正在下载 vX 42%」「重启以更新到 vX」——右侧以浅色显示当前运行版本,任何状态点击都打开弹窗。
+出口只有一个:**在新对话中编辑**。它用 Project 的 `default_agent`(没有时用第一个 Agent)打开一个新对话,并把提示词预填进输入框,发不发送由你决定。
-弹窗按步骤走完更新:在一无所知时打开会先检查(应用每次加载也会向 GitHub 查一次,手动检查则绕过缓存结果);查到新版本时给出更新说明链接和「下载并更新」按钮,按下之前不会下载任何东西;下载中显示进度条,「放到后台」只是关掉弹窗、不取消下载——那一行继续显示百分比,下载就绪后用户按钮上出现圆点并弹出提示;最后「重启并更新」完成整个过程。在服务器上,下载就是后台运行的 `penguin update`(数据目录不受影响),进度条读的是安装器自己的进度;当服务由 `penguin web` 或 `penguin server` 托管时,重启是真实的——服务在新版本上回来,页面自动刷新;用其他方式启动的服务则被告知需要手动重启。非管理员可以看更新说明,但不能执行更新。下载失败会显示更新命令自己的输出并提供重试;无法自更新的安装方式(源码运行、无法识别的目录布局、Windows)会说明原因。设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭新版本检查——见[配置参考](/configuration)。
+- 刷新这个新对话页面,提示词仍在。
+- 既不编辑也不发送就离开页面,提示词会被丢弃,不会在之后的对话里再次出现。
+- 一旦在其中输入,它就成为普通草稿,和你写的其他内容一样保留。
-**在桌面应用中**同一个弹窗驱动的是应用自带的更新器——只在 shell 自身的窗口里,服务端的版本在那里完全不出现。shell 会按自己的节奏后台检查,但绝不自行下载:查到的版本以圆点和那一行的文案出现,下载从弹窗开始,百分比来自更新器的真实进度,「重启并更新」重启进已下载的版本(shell 原生菜单里的「Check for Updates…」在原生对话框里提供同样的「先下载、再重启」两步)。用密码登录同一台桌面模式服务器的浏览器完全看不到更新入口:它既读不到那台机器的更新状态,也无法重启它的窗口,更无法在那台服务器上跑 CLI 自更新。无法自我替换的形态——由系统包管理器管理的 Linux 安装(`.deb`)以及开发运行——在弹窗里说明原因;安装包本身见[桌面应用指南](/quickstart-desktop)。
+「定时任务」面板是例外:它的出口是**在本对话中编辑**,提示词会填进当前对话的输入框。见[定时任务](/schedules)。
-## Project 与成员
+## 生产环境部署
-侧边栏提供 Project 切换器,并支持创建新 Project:显示名在前,Project id 字段旁的「用 AI 生成」以当前 Project 的默认模型按显示名推导 id(非 admin 用户只填 `<用户名>-` 之后的部分)。成员分为 Owner 与 Member 两种角色:Owner 负责成员管理,并独占模型、Vault、Schedule 的编辑以及各类删除操作。
+服务端自己托管构建好的 SPA(同源、支持 SPA fallback),生产环境只需运行一个 `penguin web` 或 `penguin server` 进程。
-## 生产部署
+npm 安装包已经内置前端构建产物。如果要使用自定义的静态目录,用 `PENGUIN_WEB_DIST` 覆盖即可,见[配置参考](/configuration)。
-服务端自身托管构建好的 SPA(同源、SPA fallback),生产环境只需运行 `penguin web` 或 `penguin server` 一个进程。npm 安装包已内置前端产物;如需自定义静态目录,可用 `PENGUIN_WEB_DIST` 覆盖,见[配置参考](/configuration)。
+服务默认监听 `127.0.0.1`,只能从本机访问。如果要通过 `HOST` 让它在网络上可访问,应当放在负责 TLS 终结的反向代理之后,见[安全模型](/security)。
diff --git a/packages/docs/src/lib/nav.ts b/packages/docs/src/lib/nav.ts
index d48cb6fc..4a4b594c 100644
--- a/packages/docs/src/lib/nav.ts
+++ b/packages/docs/src/lib/nav.ts
@@ -19,7 +19,7 @@ export interface DocsPageDef {
export interface DocsSectionDef {
/** Section id — also the key into S.sections for the localized label. */
- id: "start" | "design" | "guides" | "reference";
+ id: "start" | "guides" | "advanced" | "design" | "reference";
/** Pages in display order. */
pages: DocsPageDef[];
}
@@ -38,9 +38,29 @@ export const DOCS_NAV: DocsSectionDef[] = [
slug: "quickstart",
children: ["quickstart-desktop", "quickstart-cli", "quickstart-docker", "quickstart-sdk"],
},
+ { slug: "concepts" },
+ { slug: "updates" },
],
},
- { id: "guides", pages: pages("web-app", "goal-mode", "company-mode", "self-improvement") },
+ {
+ id: "guides",
+ pages: pages(
+ "web-app",
+ "chat",
+ "files",
+ "schedules",
+ "remote-control",
+ "agents",
+ "skills",
+ "models",
+ "usage",
+ "settings",
+ ),
+ },
+ {
+ id: "advanced",
+ pages: pages("evaluation-center", "self-improvement", "goal-mode", "company-mode"),
+ },
{
id: "design",
pages: pages(
@@ -51,8 +71,6 @@ export const DOCS_NAV: DocsSectionDef[] = [
"message-flow",
"interfaces",
"tools",
- "skills",
- "models",
"sessions-and-traces",
),
},
@@ -73,26 +91,12 @@ export function sectionOf(slug: string): DocsSectionDef | undefined {
);
}
-/**
- * Pages whose successor is not the slug that follows them in the sidebar.
- *
- * The SDK route is the last of Quickstart's three, so linear order hands its reader the
- * Web App guide — a tour of the browser UI, for someone who just embedded the engine in
- * their own program. It continues into the interface contracts instead, which is also
- * where the page's own "next steps" point. Note this redirects only the forward link:
- * Core Interfaces keeps the predecessor its own position gives it.
- */
-const NEXT_OVERRIDE: Record<string, string> = {
- "quickstart-sdk": "interfaces",
-};
-
-/** Pager targets for a page: sidebar order, unless it overrides its successor. */
+/** Pager targets for a page: its neighbours in sidebar order. */
export function pagerFor(slug: string): { prev: string | null; next: string | null } {
const index = DOC_SLUGS.indexOf(slug);
if (index === -1) return { prev: null, next: null };
- const linearNext = index < DOC_SLUGS.length - 1 ? DOC_SLUGS[index + 1]! : null;
return {
prev: index > 0 ? DOC_SLUGS[index - 1]! : null,
- next: NEXT_OVERRIDE[slug] ?? linearNext,
+ next: index < DOC_SLUGS.length - 1 ? DOC_SLUGS[index + 1]! : null,
};
}
diff --git a/packages/docs/src/lib/strings-en.ts b/packages/docs/src/lib/strings-en.ts
index 2d85c557..562ad963 100644
--- a/packages/docs/src/lib/strings-en.ts
+++ b/packages/docs/src/lib/strings-en.ts
@@ -37,8 +37,9 @@ export const en: Strings = {
sections: {
start: "Get Started",
- design: "Core Design",
guides: "Guides",
+ advanced: "Advanced",
+ design: "How It Works",
reference: "Reference",
} as Record<string, string>,
diff --git a/packages/docs/src/lib/strings.ts b/packages/docs/src/lib/strings.ts
index 8bb4974c..957077cf 100644
--- a/packages/docs/src/lib/strings.ts
+++ b/packages/docs/src/lib/strings.ts
@@ -43,8 +43,9 @@ export const zh = {
sections: {
start: "开始",
- design: "核心设计",
guides: "使用指南",
+ advanced: "进阶功能",
+ design: "工作原理",
reference: "参考",
} as Record<string, string>,
diff --git a/packages/docs/test/content.test.ts b/packages/docs/test/content.test.ts
index 6df12f69..d22e3367 100644
--- a/packages/docs/test/content.test.ts
+++ b/packages/docs/test/content.test.ts
@@ -7,8 +7,13 @@
* renders two entries pointing at the same place) and a "#..." link naming no heading
* scrolls nowhere. An absolute "/..." link is handed to the router as a doc route, so a
* target that is not a slug renders nothing at all — the way "/docs/goal-mode" did,
- * carrying the deployed base path that the router already supplies. Reads the files via
- * fs so the check runs under plain node (no Vite glob).
+ * carrying the deployed base path that the router already supplies. A "/slug#anchor"
+ * link carries both halves, and the anchor half is the one that rots quietly: a heading
+ * renamed on the target page leaves the link working and the reader on the wrong part of
+ * it. Each language links its own twin, since the headings are translated. The sidebar's
+ * section labels are checked here too: `S.sections` is a Record, so a section id with no
+ * label typechecks and renders an empty heading. Reads the files via fs so the check runs
+ * under plain node (no Vite glob).
*/
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
@@ -16,6 +21,8 @@ import { describe, expect, it } from "vitest";
import { DOCS_NAV, DOC_SLUGS, pagerFor } from "../src/lib/nav";
import { parseFrontmatter } from "../src/lib/frontmatter";
import { hashTargetId } from "../src/lib/hash";
+import { en } from "../src/lib/strings-en";
+import { zh } from "../src/lib/strings";
import { extractToc } from "../src/lib/toc";
const contentDir = join(__dirname, "..", "content");
@@ -26,13 +33,25 @@ function inPageAnchors(body: string): string[] {
return [...body.matchAll(/\]\(#([^)\s]+)\)/g)].map((match) => hashTargetId(match[1]!));
}
-/** Slugs of absolute doc links, i.e. "[label](/slug)" or "[label](/slug#anchor)". */
-function docLinkSlugs(body: string): string[] {
- return [...body.matchAll(/\]\((\/[^)\s]*)\)/g)].map((match) =>
- match[1]!.split("#")[0]!.replace(/^\//, "").replace(/\/$/, ""),
- );
+/** Absolute doc links, i.e. "[label](/slug)" or "[label](/slug#anchor)", both halves resolved as the router does. */
+function docLinks(body: string): Array<{ slug: string; anchor: string | null }> {
+ return [...body.matchAll(/\]\((\/[^)\s]*)\)/g)].map((match) => {
+ const [path, hash] = match[1]!.split("#");
+ return {
+ slug: path!.replace(/^\//, "").replace(/\/$/, ""),
+ anchor: hash === undefined ? null : hashTargetId(hash),
+ };
+ });
}
+/** Heading ids of every content file, by file name. */
+const headingIds = new Map<string, Set<string>>(
+ files.map((file) => {
+ const { body } = parseFrontmatter(readFileSync(join(contentDir, file), "utf8"));
+ return [file, new Set(extractToc(body).map((entry) => entry.id))];
+ }),
+);
+
describe("docs navigation / content integrity", () => {
it("has unique slugs in DOCS_NAV", () => {
expect(new Set(DOC_SLUGS).size).toBe(DOC_SLUGS.length);
@@ -51,8 +70,13 @@ describe("docs navigation / content integrity", () => {
expect(target, `${slug} paginates ${dir} to itself`).not.toBe(slug);
}
}
- // The one page whose successor is not its sidebar neighbour (see NEXT_OVERRIDE).
- expect(pagerFor("quickstart-sdk").next).toBe("interfaces");
+ });
+
+ it("labels every navigation section in both dictionaries", () => {
+ for (const { id } of DOCS_NAV) {
+ expect(zh.sections[id], `missing zh label for the ${id} section`).toBeTruthy();
+ expect(en.sections[id], `missing en label for the ${id} section`).toBeTruthy();
+ }
});
it("provides zh and en files with a title for every navigated slug", () => {
@@ -87,7 +111,7 @@ describe("docs navigation / content integrity", () => {
it("resolves every in-page anchor link to a heading on the same page", () => {
for (const file of files) {
const { body } = parseFrontmatter(readFileSync(join(contentDir, file), "utf8"));
- const ids = new Set(extractToc(body).map((entry) => entry.id));
+ const ids = headingIds.get(file)!;
const dangling = inPageAnchors(body).filter((anchor) => !ids.has(anchor));
expect(dangling, `dangling in-page anchors in ${file}`).toEqual([]);
}
@@ -96,8 +120,22 @@ describe("docs navigation / content integrity", () => {
it("points every absolute doc link at a navigated slug", () => {
for (const file of files) {
const { body } = parseFrontmatter(readFileSync(join(contentDir, file), "utf8"));
- const dangling = docLinkSlugs(body).filter((slug) => !DOC_SLUGS.includes(slug));
+ const dangling = docLinks(body)
+ .map((link) => link.slug)
+ .filter((slug) => !DOC_SLUGS.includes(slug));
expect(dangling, `links to non-existent doc pages in ${file}`).toEqual([]);
}
});
+
+ it("resolves every cross-page anchor to a heading of the target page in the same language", () => {
+ for (const file of files) {
+ const lang = /\.(zh|en)\.md$/.exec(file)![1]!;
+ const { body } = parseFrontmatter(readFileSync(join(contentDir, file), "utf8"));
+ const dangling = docLinks(body)
+ .filter((link) => link.anchor !== null && DOC_SLUGS.includes(link.slug))
+ .filter((link) => !headingIds.get(`${link.slug}.${lang}.md`)?.has(link.anchor!))
+ .map((link) => `/${link.slug}#${link.anchor}`);
+ expect(dangling, `dangling cross-page anchors in ${file}`).toEqual([]);
+ }
+ });
});