Skip to content

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

docs: fold Installation (#303)

Myriad-Dreamin73796764008d
diff --git a/changelog/unreleased/2026-08-16-docs-quickstart-and-nav-order.md b/changelog/unreleased/2026-08-16-docs-quickstart-and-nav-order.md
new file mode 100644
index 00000000..d83ebab4
--- /dev/null
+++ b/changelog/unreleased/2026-08-16-docs-quickstart-and-nav-order.md
@@ -0,0 +1,28 @@
+# Docs: Quickstart branches into one page per route, and guides come before the design chapters
+
+- **Date:** 2026-08-16
+- **Type:** process
+- **Scope:** `docs`
+- **PR:** [#303](https://github.com/Prism-Shadow/penguin-harness/pull/303)
+
+[中文版](2026-08-16-docs-quickstart-and-nav-order.zh.md)
+
+The Installation page was folded into Quickstart, which became an overview branching into one sub-page per installation route; the sidebar gained a level of nesting to show them, and the usage guides moved ahead of the core-design chapters.
+
+## Details
+
+- Quickstart became a three-row route table (desktop app / CLI and Web App / SDK — who each is for, and whether a terminal is involved), what the three share, and the one common prerequisite. Each route then carries its own page to a first Task: `quickstart-desktop` (download page and per-platform installers, the one-time unsigned-build unblock, configuring a model, a first message from the Chat page), `quickstart-cli` (the install one-liners plus npm, `penguin web`, `penguin run`, `penguin chat`, and everything the Installation page carried as a trailing installation reference), `quickstart-sdk` (installing `@prismshadow/penguin-core` and a first program annotated line by line).
+- `DocsPageDef` gained `children`, the sidebar renders them indented under their parent, and `DOC_SLUGS` flattens each parent immediately ahead of its children so pagination follows the visible order. Nesting stops at one level.
+- `content/installation.{zh,en}.md` was deleted and the post-build step stopped emitting its route shell; the links that pointed there — both Introduction pages and the CLI package README — were retargeted at Quickstart.
+- `DOCS_NAV` moved `guides` above `design`: Start → Guides → Core Design → Reference.
+- The SDK page overrides its pagination successor to Core Interfaces rather than the Web App guide. The override is forward-only: Core Interfaces keeps the predecessor its own position gives it.
+
+## Renderer
+
+- **Tabbed code blocks** (`remark-tabs`) — a fence whose info string carries `tab="Label"` becomes a tab, and adjacent tab fences group into one switcher. Labels ride on the group as JSON rather than on each block, since `mdast-util-to-hast` applies a code node's `hProperties` to the inner `<code>`. Only the selected panel is mounted; arrow keys move between tabs over a roving tabindex.
+- **Callouts** (`remark-callout`) — a blockquote whose first line carries a `[!TYPE]` marker becomes a boxed note, a trailing `-` collapsing it and `+` opening it. Collapsing is emitted as native `<details>`/`<summary>`, so it costs no JavaScript and the body stays in the DOM for find-in-page and Copy Markdown. `markdownToSearchText` strips the marker so the type and flag stay out of the search index.
+- **Syntax highlighting** (Shiki) — the highlighter is built from `shiki/core` with only the seven grammars this site writes and the JavaScript RegExp engine rather than Oniguruma, which drops the WASM payload; everything sits behind dynamic imports (~30 kB gzip of core plus a grammar only when a page uses one), leaving the entry bundle unchanged. Both themes are baked into one render through dual-theme CSS variables, so the light/dark toggle is a CSS switch. A language with no grammar, or a highlighter that fails to load, leaves the plain `<pre>` in place, carrying the same padding and type. The grammar loaders are written out one static `import()` each, since Vite only rewrites a dynamic import it can read literally.
+
+## Checks
+
+`test/content.test.ts` gained checks that heading anchors are unique within a page, that every `[…](#anchor)` names a heading on its own page, that every `[…](/slug)` names a navigated slug, and that every page paginates to a real page other than itself. The slug check found five dead `/docs/goal-mode` links in `agent-loop`, `server-api` and `web-app.en` that carried the deployed base path the router already supplies; all five now link to `/goal-mode`.
diff --git a/changelog/unreleased/2026-08-16-docs-quickstart-and-nav-order.zh.md b/changelog/unreleased/2026-08-16-docs-quickstart-and-nav-order.zh.md
new file mode 100644
index 00000000..a826a567
--- /dev/null
+++ b/changelog/unreleased/2026-08-16-docs-quickstart-and-nav-order.zh.md
@@ -0,0 +1,28 @@
+# 文档:Quickstart 按安装路线分出子页,使用指南排到设计章节之前
+
+- **Date:** 2026-08-16
+- **Type:** process
+- **Scope:** `docs`
+- **PR:** [#303](https://github.com/Prism-Shadow/penguin-harness/pull/303)
+
+[English](2026-08-16-docs-quickstart-and-nav-order.md)
+
+Installation 页并入了 Quickstart,Quickstart 变成一个总览页,按安装路线各分出一个子页;侧边栏为此多了一层嵌套,使用指南也移到了核心设计章节之前。
+
+## 细节
+
+- Quickstart 变为一张三行的路线表(桌面应用 / 命令行与 Web 应用 / SDK——各自面向谁,以及是否涉及终端)、三条路线共通的部分,以及唯一那项共同前置要求。此后每条路线由自己的页面带读者走到第一个 Task:`quickstart-desktop`(下载页与各平台安装包、一次性的未签名构建放行、配置模型、从 Chat 页发出第一条消息)、`quickstart-cli`(安装一行命令与 npm、`penguin web`、`penguin run`、`penguin chat`,以及 Installation 页原有的全部内容作为末尾的安装参考)、`quickstart-sdk`(安装 `@prismshadow/penguin-core`,以及逐行注解的第一个程序)。
+- `DocsPageDef` 增加了 `children`,侧边栏将其缩进渲染在父项之下,`DOC_SLUGS` 把每个父项紧挨着摊平在其子项之前,使分页顺序与可见顺序一致。嵌套只做一层。
+- `content/installation.{zh,en}.md` 被删除,构建后步骤不再为其生成路由外壳;原先指向它的链接——两个语种的 Introduction 页与 CLI 包的 README——都改指 Quickstart。
+- `DOCS_NAV` 把 `guides` 移到了 `design` 之上:Start → Guides → Core Design → Reference。
+- SDK 页覆盖了自己的分页后继,指向 Core Interfaces 而非 Web 应用指南。该覆盖只作用于向前一侧:Core Interfaces 仍保留其位置本身给它的前驱。
+
+## 渲染器
+
+- **标签式代码块**(`remark-tabs`)——信息串中带 `tab="Label"` 的围栏成为一个标签页,相邻的标签围栏归为同一个切换器。标签文字以 JSON 挂在整组上而不是各个块上,因为 `mdast-util-to-hast` 会把 code 节点的 `hProperties` 施加到内层的 `<code>` 上。只有选中的面板会被挂载;方向键在 roving tabindex 上于各标签间移动。
+- **提示框**(`remark-callout`)——首行带 `[!TYPE]` 标记的引用块成为一个带框提示,末尾的 `-` 令其默认折叠,`+` 令其展开。折叠以原生 `<details>`/`<summary>` 输出,因此不耗费 JavaScript,正文也留在 DOM 中,供页内查找与 Copy Markdown 使用。`markdownToSearchText` 会剥除该标记,使类型与标志不进入搜索索引。
+- **语法高亮**(Shiki)——高亮器基于 `shiki/core` 构建,只装入本站会用到的七种语法,并使用 JavaScript RegExp 引擎而非 Oniguruma,从而完全去掉 WASM 负载;全部置于动态导入之后(core 约 30 kB gzip,语法则仅在页面用到时才加载),入口包体积不变。两套主题通过双主题 CSS 变量烘焙进同一次渲染,因此明暗切换只是一次 CSS 切换。没有对应语法、或高亮器加载失败时,原样保留纯 `<pre>`,其内边距与字体与高亮输出一致。语法加载器逐个写成静态的 `import()`,因为 Vite 只会改写它能字面读懂的动态导入。
+
+## 检查
+
+`test/content.test.ts` 新增了这样几项检查:页内标题锚点唯一、每个 `[…](#anchor)` 都指向本页某个标题、每个 `[…](/slug)` 都指向一个已被导航的 slug,以及每个页面的分页都通向一个存在且不是自身的页面。其中的 slug 检查查出了 `agent-loop`、`server-api` 与 `web-app.en` 中五个失效的 `/docs/goal-mode` 链接——它们带上了路由本身已经提供的部署基路径;五处现已改为 `/goal-mode`。
diff --git a/install.ps1 b/install.ps1
index 35ee2109..b861c0e5 100644
--- a/install.ps1
+++ b/install.ps1
@@ -27,7 +27,7 @@
# The data dir (%USERPROFILE%\.penguin\data) sits under the install home but is never touched by
# reinstall/upgrade (which only replace bin/lib/web/node/git). Upgrading = re-running this installer.
#
-# Docs: https://penguin.ooo/docs/installation
+# Docs: https://penguin.ooo/docs/quickstart-cli
param(
[string]$Version = "",
[string]$InstallDir = "",
diff --git a/install.sh b/install.sh
index 6180a408..aec85680 100644
--- a/install.sh
+++ b/install.sh
@@ -25,7 +25,7 @@
#
# The data dir (~/.penguin/data) sits under the install home but is never touched by reinstall/upgrade (which only replace bin/lib/web/node).
#
-# Docs: https://penguin.ooo/docs/installation
+# Docs: https://penguin.ooo/docs/quickstart-cli
set -eu
REPO="https://github.com/Prism-Shadow/penguin-harness"
diff --git a/packages/cli/README.md b/packages/cli/README.md
index ad0eb670..74dcd8d2 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -19,7 +19,7 @@ penguin chat --resume # resume the late
Tool calls go through an approval gate — `--approve allow-all` (default) `| deny-all | read-only | always-ask`. Data lives under `~/.penguin/data` (`PENGUIN_HOME` or `--root` override); model credentials come from the Project config or provider env vars (e.g. `DEEPSEEK_API_KEY`).
-Prefer a one-line install with a bundled Node runtime? See the [installation guide](https://penguin.ooo/docs/installation).
+Prefer a one-line install with a bundled Node runtime? See [Quickstart → CLI and Web App](https://penguin.ooo/docs/quickstart-cli).
## Documentation
diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.md
index 953a122d..2b19af38 100644
--- a/packages/docs/content/agent-loop.en.md
+++ b/packages/docs/content/agent-loop.en.md
@@ -99,7 +99,7 @@ An input image either rides the request as an image message or becomes an `[atta
| 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](/docs/goal-mode).
+Goal mode is the exception because its objective is re-injected as text every round: see [Goal mode](/goal-mode).
## Automatic reconnect
diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.md
index cea5ff3d..dc2fafaa 100644
--- a/packages/docs/content/agent-loop.zh.md
+++ b/packages/docs/content/agent-loop.zh.md
@@ -96,7 +96,7 @@ Task 运行期间,宿主可通过 `session.steer(input)` 排队一条用户消
| 插话(`steer`) | 模型不支持图片 | 投递时,即 turn 边界——入队必须保持同步,而中断时被丢弃的队列若已折叠会留下没人读的孤儿文件 |
| 目标(goal) | **总是** | 抽取 objective 之前,这样路径行才能活过每一轮的重新注入 |
-目标模式是唯一的例外,因为它的目标每轮都作为文本重新注入:见[目标模式](/docs/goal-mode)。
+目标模式是唯一的例外,因为它的目标每轮都作为文本重新注入:见[目标模式](/goal-mode)。
## 自动重连
diff --git a/packages/docs/content/introduction.en.md b/packages/docs/content/introduction.en.md
index ee43e8e4..2add6baa 100644
--- a/packages/docs/content/introduction.en.md
+++ b/packages/docs/content/introduction.en.md
@@ -45,5 +45,5 @@ The unified message protocol is called **OmniMessage** in technical writing (mar
## Next steps
-- [Install](/installation) PenguinHarness, then run your first Task with the [Quickstart](/quickstart).
+- Follow the [Quickstart](/quickstart): install PenguinHarness by whichever of the three routes fits you — desktop app, CLI, or SDK — and run your first Task.
- Start the design docs at the [Architecture](/architecture) overview to see how the pieces fit together.
diff --git a/packages/docs/content/introduction.zh.md b/packages/docs/content/introduction.zh.md
index fa8910be..592f8618 100644
--- a/packages/docs/content/introduction.zh.md
+++ b/packages/docs/content/introduction.zh.md
@@ -45,5 +45,5 @@ PenguinHarness 的能力围绕三个递进的概念展开——消息协议、SD
## 下一步
-- [安装](/installation) PenguinHarness,然后跟随[快速开始](/quickstart)跑通第一个 Task。
+- 跟随[快速开始](/quickstart):桌面端、命令行、SDK 三条路线任选其一装好 PenguinHarness,跑通第一个 Task。
- 从[架构总览](/architecture)进入设计文档,理解各组件如何协作。
diff --git a/packages/docs/content/installation.en.md b/packages/docs/content/quickstart-cli.en.md
similarity index 73%
rename from packages/docs/content/installation.en.md
rename to packages/docs/content/quickstart-cli.en.md
index 6acb1541..583ca822 100644
--- a/packages/docs/content/installation.en.md
+++ b/packages/docs/content/quickstart-cli.en.md
@@ -1,44 +1,95 @@
---
-title: Installation
-description: Install PenguinHarness via the install script, npm, or from source.
+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.
---
-## Requirements
+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.
-- 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.
+## Install
+
+Pick your platform. The first two 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
+```
+
+```powershell tab="Windows"
+irm https://penguin.ooo/install.ps1 | iex
+```
-## Script install (recommended)
+```bash tab="npm (any platform)"
+npm install -g @prismshadow/penguin-cli
+```
-On Linux / macOS:
+Verify the install:
```bash
-curl -fsSL https://penguin.ooo/install.sh | sh
+penguin -v
```
-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 below, not by `--universal`).
+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 stable entry point defaults to `PENGUIN_DOWNLOAD_SOURCE=auto`: it prefers an immutable OSS release directory only after that release has been completely uploaded and verified, then falls back to the matching GitHub Release if the metadata or download is unavailable. Set the variable to `oss` or `github` to force either source. Normal installer output names the source without printing the mirror's full URL.
+## Configure a model
-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.
+Use the Models page in the Web UI, or the CLI:
-On Windows (PowerShell):
+```bash
+penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-key sk-... --set-default
+```
-```powershell
-irm https://penguin.ooo/install.ps1 | iex
+- 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.
+
+## Start the Web App
+
+```bash
+penguin web
```
-To pin a version, set the env var first:
+The service runs at http://127.0.0.1:7364 and opens your browser (`--no-open` to skip). First login is `admin` — the server prints the initial password (of the form `penguin-1234`) in a framed notice on every start until it is changed; change it right away. `penguin server` starts the same process headless.
-```powershell
-$env:PENGUIN_VERSION = "vX.Y.Z"; irm https://penguin.ooo/install.ps1 | iex
+The [Web App Guide](/web-app) covers the interface in full.
+
+## One-shot run
+
+```bash
+penguin run -m "Create hello.txt containing Hello, Penguin"
```
-Verify the install:
+The Workspace defaults to the current directory; pass `--workspace /path` to change it. The target directory must already exist.
+
+## Interactive chat
```bash
-penguin -v
+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.
+
+The full command and option list is in the [CLI Reference](/cli).
+
+## Installation reference
+
+The three commands above cover nearly every case; the rest of the options and details follow.
+
+### Requirements
+
+- 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.
+
+### 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`).
+
+The stable entry point defaults to `PENGUIN_DOWNLOAD_SOURCE=auto`: it prefers an immutable OSS release directory only after that release has been completely uploaded and verified, then falls back to the matching GitHub Release if the metadata or download is unavailable. Set the variable to `oss` or `github` to force either source. 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 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:
+
+```powershell
+$env:PENGUIN_VERSION = "vX.Y.Z"; irm https://penguin.ooo/install.ps1 | iex
```
### Offline install
@@ -59,6 +110,18 @@ On Linux / macOS, run:
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.
+### From source
+
+Requires Node.js >= 24 and pnpm:
+
+```bash
+git clone https://github.com/Prism-Shadow/penguin-harness.git
+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`) default to a separate data root `~/.penguin/dev-data`, while the linked/installed `penguin` keeps `~/.penguin/data`; export `PENGUIN_HOME` to override.
+
### Install location and options
| Item | Details |
@@ -94,29 +157,7 @@ Script flags go after `sh -s --`, e.g. `curl -fsSL https://penguin.ooo/install.s
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.
-## npm install
-
-Requires system Node.js >= 24:
-
-```bash
-npm install -g @prismshadow/penguin-cli
-```
-
-The npm package is `@prismshadow/penguin-cli`; the installed command is `penguin`. Web UI assets ship inside the `@prismshadow/penguin-server` package, so this single install yields a working `penguin web`. This route works on every platform (including Windows) and is the alternative when the packaged zip/tarball is unsuitable.
-
-## From source
-
-Requires Node.js >= 24 and pnpm:
-
-```bash
-git clone https://github.com/Prism-Shadow/penguin-harness.git
-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`) default to a separate data root `~/.penguin/dev-data`, while the linked/installed `penguin` keeps `~/.penguin/data`; export `PENGUIN_HOME` to override.
-
-## Published npm packages
+### Published npm packages
| Package | Description |
| --- | --- |
@@ -129,5 +170,6 @@ All packages are published under the Apache-2.0 license.
## Next steps
-- [Quickstart](/quickstart): configure a model and run your first Task.
+- [Web App Guide](/web-app): use PenguinHarness from the browser.
- [CLI Reference](/cli): the full list of commands and options.
+- [SDK](/quickstart-sdk): embed the engine in your own program.
diff --git a/packages/docs/content/installation.zh.md b/packages/docs/content/quickstart-cli.zh.md
similarity index 73%
rename from packages/docs/content/installation.zh.md
rename to packages/docs/content/quickstart-cli.zh.md
index a7fd89a6..cf33c94d 100644
--- a/packages/docs/content/installation.zh.md
+++ b/packages/docs/content/quickstart-cli.zh.md
@@ -1,44 +1,95 @@
---
-title: 安装
-description: 通过安装脚本、npm 或源码安装 PenguinHarness。
+title: 命令行与 Web 应用
+description: 一行命令装出 penguin,配置模型,用 penguin web 打开浏览器界面——附完整安装参考。
---
-## 系统要求
+一行命令装出 `penguin`,再用 `penguin web` 在浏览器里打开与[桌面端应用](/quickstart-desktop)相同的界面。在线安装器自带官方 Node.js 运行时,解压即用,本机无需安装 Node。
-- Linux / macOS(x64 或 arm64):安装脚本提供内置官方 Node.js 运行时的平台压缩包,解压即用,无需本机安装 Node。
-- Windows 10 及以上(x64),PowerShell 5.1+:Windows 安装器提供内置运行时的 `penguin-win32-x64.zip`,同样无需本机安装 Node。
-- 其他平台,或通过 npm / 源码安装:需要系统 Node.js >= 24。
+## 安装
+
+选择你的平台。前两种自带 Node.js 运行时;npm 方式需要本机已有 Node.js >= 24。
+
+```bash tab="Linux / macOS"
+curl -fsSL https://penguin.ooo/install.sh | sh
+```
+
+```powershell tab="Windows"
+irm https://penguin.ooo/install.ps1 | iex
+```
-## 脚本安装(推荐)
+```bash tab="npm(任意平台)"
+npm install -g @prismshadow/penguin-cli
+```
-在 Linux / macOS 上执行:
+安装完成后验证:
```bash
-curl -fsSL https://penguin.ooo/install.sh | sh
+penguin -v
```
-脚本按平台下载 `penguin-{linux,darwin}-{x64,arm64}.tar.gz`——即标准安装包:包内封入程序负载(捆绑官方 Node.js 运行时)、负载的 SHA256 校验文件与同一个安装器。下载后先对照 Release 发布的 `.sha256` 校验外层,再校验包内封入的负载 checksum,然后才进入暂存安装。其他 POSIX 平台**不会自动回退**:脚本会退出并提示先安装 Node.js >= 24、再携带 `--universal` 重新执行,改用不含运行时的 `penguin-universal.tar.gz` 安装包(Windows 使用下方专属安装器,而不是 `--universal`)。
+离线安装、源码安装、安装目录、版本固定与 Windows 细节,见本页末尾的[安装参考](#安装参考)。
-稳定入口默认使用 `PENGUIN_DOWNLOAD_SOURCE=auto`:优先选择已完整上传并验证的 OSS 不可变版本目录;元数据或下载不可用时,回退到同一版本的 GitHub Release。也可以将该变量设为 `oss` 或 `github` 来强制指定来源。安装器只显示来源名称,不在常规输出中打印镜像的完整 URL。
+## 配置模型
-`penguin.ooo` 稳定入口每次执行时都会解析当前稳定版本。从 GitHub 或 OSS 的版本化 Release 中直接下载的独立安装脚本会写入该 Release tag,并默认安装同一版本,确保安装器与安装包格式匹配;如需覆盖,可显式设置 `PENGUIN_VERSION`(POSIX 也可使用 `--version`)。
+可以在 Web UI 的模型页完成,也可以用 CLI:
-在 Windows(PowerShell)上执行:
+```bash
+penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-key sk-... --set-default
+```
-```powershell
-irm https://penguin.ooo/install.ps1 | iex
+- 模型引用始终是 `(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
+
+```bash
+penguin web
```
-如需固定版本,先设置环境变量:
+服务运行在 http://127.0.0.1:7364 并自动打开浏览器(`--no-open` 跳过)。首次登录使用 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印,请立即修改密码。`penguin server` 启动同一进程的 headless 版本。
-```powershell
-$env:PENGUIN_VERSION = "vX.Y.Z"; irm https://penguin.ooo/install.ps1 | iex
+界面的完整说明见 [Web App 指南](/web-app)。
+
+## 单次运行
+
+```bash
+penguin run -m "创建 hello.txt,内容为 Hello, Penguin"
```
-安装完成后验证:
+Workspace 默认为当前目录,可用 `--workspace /path` 指定;目标目录必须已存在。
+
+## 交互式对话
```bash
-penguin -v
+penguin chat
+```
+
+- 每输入一行即发起一个 Task。
+- `/compact` 压缩上下文;`/clear` 开启全新 Session(原会话仍可恢复);`/exit` 或 `/quit` 退出;Ctrl-C 中断正在运行的 Task。
+- 退出时会打印 `penguin chat --resume <sessionId>` 提示,用于恢复本次 Session;`--resume` 不带 id 时恢复该 Agent 最近的 Session。
+
+完整命令与选项见 [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。
+
+### 安装脚本细节
+
+脚本按平台下载 `penguin-{linux,darwin}-{x64,arm64}.tar.gz`——即标准安装包:包内封入程序负载(捆绑官方 Node.js 运行时)、负载的 SHA256 校验文件与同一个安装器。下载后先对照 Release 发布的 `.sha256` 校验外层,再校验包内封入的负载 checksum,然后才进入暂存安装。其他 POSIX 平台**不会自动回退**:脚本会退出并提示先安装 Node.js >= 24、再携带 `--universal` 重新执行,改用不含运行时的 `penguin-universal.tar.gz` 安装包(Windows 使用专属安装器,而不是 `--universal`)。
+
+稳定入口默认使用 `PENGUIN_DOWNLOAD_SOURCE=auto`:优先选择已完整上传并验证的 OSS 不可变版本目录;元数据或下载不可用时,回退到同一版本的 GitHub Release。也可以将该变量设为 `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
```
### 离线安装
@@ -59,6 +110,18 @@ Linux / macOS 上执行:
解压后的目录同时包含安装器、程序负载(`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 之前的旧版程序压缩包均可。
+### 源码安装
+
+需要 Node.js >= 24 与 pnpm:
+
+```bash
+git clone https://github.com/Prism-Shadow/penguin-harness.git
+cd penguin-harness
+pnpm install && pnpm build
+```
+
+构建完成后,在仓库内用 `pnpm penguin <args>` 作为开发入口运行,或使用全局链接的 `penguin` 命令。开发入口(`pnpm penguin`、`pnpm dev`)默认使用独立数据根目录 `~/.penguin/dev-data`,全局链接或安装的 `penguin` 仍使用 `~/.penguin/data`;可通过环境变量 `PENGUIN_HOME` 覆盖。
+
### 安装位置与选项
| 项目 | 说明 |
@@ -94,29 +157,7 @@ Linux / macOS 上执行:
数据目录默认位于 `~/.penguin/data`(Windows 为 `%USERPROFILE%\.penguin\data`),在安装主目录之下,但安装与升级都不会改动它,可用环境变量 `PENGUIN_HOME` 覆盖。模型配置、Session 记录等在升级后均会保留。
-## npm 安装
-
-需要系统 Node.js >= 24:
-
-```bash
-npm install -g @prismshadow/penguin-cli
-```
-
-npm 包名为 `@prismshadow/penguin-cli`,安装后的命令是 `penguin`。Web UI 静态资源随 `@prismshadow/penguin-server` 包发布,因此仅执行上述命令即可直接使用 `penguin web`。该方式在所有平台(含 Windows)可用,是压缩包不适用时的替代路径。
-
-## 源码安装
-
-需要 Node.js >= 24 与 pnpm:
-
-```bash
-git clone https://github.com/Prism-Shadow/penguin-harness.git
-cd penguin-harness
-pnpm install && pnpm build
-```
-
-构建完成后,在仓库内用 `pnpm penguin <args>` 作为开发入口运行,或使用全局链接的 `penguin` 命令。开发入口(`pnpm penguin`、`pnpm dev`)默认使用独立数据根目录 `~/.penguin/dev-data`,全局链接或安装的 `penguin` 仍使用 `~/.penguin/data`;可通过环境变量 `PENGUIN_HOME` 覆盖。
-
-## 已发布的 npm 包
+### 已发布的 npm 包
| 包 | 说明 |
| --- | --- |
@@ -129,5 +170,6 @@ pnpm install && pnpm build
## 下一步
-- [快速开始](/quickstart):配置模型并运行第一个 Task。
-- [CLI 参考](/cli):完整的命令与选项列表。
+- [Web App 指南](/web-app):在浏览器中使用 PenguinHarness。
+- [CLI 参考](/cli):完整命令与选项。
+- [SDK](/quickstart-sdk):把引擎嵌进自己的程序。
diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.md
new file mode 100644
index 00000000..68fc353b
--- /dev/null
+++ b/packages/docs/content/quickstart-desktop.en.md
@@ -0,0 +1,52 @@
+---
+title: Desktop app
+description: A double-click install that opens already signed in — the route that asks the least of a terminal.
+---
+
+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. Builds are not signed yet, so macOS and Linux may each need one command the first time the system blocks the app; the box below carries it. It shares its data root with a [CLI install](/quickstart-cli), so the two can be mixed freely.
+
+## 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).
+
+| Platform | Installers |
+| --- | --- |
+| macOS 11+ | dmg (Apple Silicon / Intel) |
+| Windows 10+ | installer (.exe, x64) |
+| Linux (x64) | AppImage / deb |
+
+> [!INFO]- The system blocked the first launch? One fix per platform, once
+>
+> Current builds are unsigned, so the system may block the very first launch. Only your own platform needs anything:
+>
+> **macOS says "PenguinHarness" is damaged and can't be opened** — macOS quarantines files downloaded from the internet, and the missing signature makes that flag surface as a false "damaged" alert. Drag `PenguinHarness.app` from the dmg into the **Applications** folder, open Terminal (Launchpad → Other → Terminal), paste the command below and press Enter, then type your login password (nothing shows while you type; press Enter when done). Once it finishes, double-click the app — it now opens normally:
+>
+> ```bash
+> sudo xattr -rd com.apple.quarantine /Applications/PenguinHarness.app
+> ```
+>
+> **Windows SmartScreen says "Windows protected your PC"** — the installer is not signed yet, so SmartScreen holds the first run: click **More info**, then **Run anyway** to continue installing — first run only.
+>
+> **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):
+>
+> ```bash
+> chmod +x penguin-desktop-linux-x86_64.AppImage
+> ```
+
+## Configure a model
+
+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.
+
+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
+
+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".
+
+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).
+
+## Next steps
+
+- [Web App Guide](/web-app): every page of the interface, one by one.
+- [CLI and Web App](/quickstart-cli): if you also want the `penguin` command on the same machine.
+- [Architecture Overview](/architecture): how the pieces fit together.
diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.md
new file mode 100644
index 00000000..2c7183d6
--- /dev/null
+++ b/packages/docs/content/quickstart-desktop.zh.md
@@ -0,0 +1,52 @@
+---
+title: 桌面端应用
+description: 双击安装,打开即已登录——对终端要求最少的那条路线。
+---
+
+完整的 Web 体验打包成一个独立应用:内嵌服务端,双击打开即已登录——没有登录页,不用抄初始密码,也不必从命令行安装任何东西。目前的构建尚未签名,macOS 与 Linux 在系统拦下首次启动时各需要执行一条命令,下面的方框里写了。它与[命令行安装](/quickstart-cli)共用同一个数据目录,两者可以混用。
+
+## 下载与安装
+
+前往[下载页](https://penguin.ooo/download)获取对应平台的安装包(国内自动走 OSS 镜像加速);同样的文件也附于每个 [GitHub Release](https://github.com/Prism-Shadow/penguin-harness/releases)。
+
+| 平台 | 安装包 |
+| --- | --- |
+| macOS 11+ | dmg(Apple 芯片 / Intel) |
+| Windows 10+ | 安装程序(.exe,x64) |
+| Linux(x64) | AppImage / deb |
+
+> [!INFO]- 首次启动被系统拦下?按平台操作一次即可解除
+>
+> 当前构建暂未签名,系统可能拦截第一次启动。只需处理你自己的平台:
+>
+> **macOS 提示「PenguinHarness 已损坏,无法打开」**——macOS 会给从网络下载的文件加上隔离标记,应用未签名时会因此被误报为「已损坏」。把 `PenguinHarness.app` 从 dmg 拖入「应用程序」文件夹,打开终端(启动台 → 其他 → 终端),粘贴下面这条命令并回车,再输入开机密码(输入时屏幕不显示字符,输完回车即可);执行完成后双击即可正常打开:
+>
+> ```bash
+> sudo xattr -rd com.apple.quarantine /Applications/PenguinHarness.app
+> ```
+>
+> **Windows SmartScreen 提示「Windows 已保护你的电脑」**——安装程序暂未签名,点「更多信息」,再点「仍要运行」即可继续安装,仅首次运行需要。
+>
+> **Linux 双击 AppImage 没有反应**——浏览器下载的 AppImage 默认没有执行权限,赋权一次后即可正常启动(deb 包经包管理器安装,无此问题):
+>
+> ```bash
+> chmod +x penguin-desktop-linux-x86_64.AppImage
+> ```
+
+## 配置模型
+
+打开应用,在左侧进入**模型**页,点「添加模型」填入 Provider、模型 id 与 API key,保存后设为默认模型。
+
+模型引用始终是 `(provider, model_id)` 二元组,Provider 绝不由模型 id 推断;内置分组见[模型与 Provider](/models)。
+
+## 跑通第一个 Task
+
+回到**对话**页新建会话:先选好 Agent、Workspace(用服务器端目录浏览器选取)与审批模式,再发送第一条消息,例如「创建 hello.txt,内容为 Hello, Penguin」。
+
+工具调用会在消息流里以卡片形式内联展开,可点开查看参数与输出;审批模式选 `always-ask` 时,每次写文件都会等你点「允许」。四种审批模式的区别见[工具与审批](/tools)。
+
+## 下一步
+
+- [Web App 指南](/web-app):按页面逐一介绍界面的全部功能。
+- [命令行与 Web 应用](/quickstart-cli):想在同一台机器上再装一个 `penguin` 命令时看这里。
+- [架构总览](/architecture):了解整体设计。
diff --git a/packages/docs/content/quickstart-sdk.en.md b/packages/docs/content/quickstart-sdk.en.md
new file mode 100644
index 00000000..4e5bf50a
--- /dev/null
+++ b/packages/docs/content/quickstart-sdk.en.md
@@ -0,0 +1,55 @@
+---
+title: SDK
+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.
+
+## Install
+
+Requires Node.js >= 24:
+
+```bash
+npm install @prismshadow/penguin-core
+```
+
+## Configure a model
+
+The SDK reads the same data root as the other two routes, `~/.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.
+
+If this machine has no model configured yet, the shortest path is to install the CLI and do it once:
+
+```bash
+npm install -g @prismshadow/penguin-cli
+penguin config model add --provider deepseek --model-id deepseek-v4-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.
+
+## Your first program
+
+```ts
+import { createAgent, isCompleteModelMessage, userText } from "@prismshadow/penguin-core";
+
+const agent = await createAgent({ agentId: "default_agent" });
+const session = await agent.createSession({ workspaceDir: process.cwd() });
+
+for await (const output of session.run([userText("Create hello.txt containing hi")], {
+ approve: async () => "allow",
+})) {
+ if (isCompleteModelMessage(output) && output.payload.type === "text") {
+ console.log(output.payload.text);
+ }
+}
+```
+
+- `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).
+
+## Next steps
+
+- [Core Interfaces](/interfaces): the contracts behind `createAgent`, `Session`, LLM and Environment.
+- [The OmniMessage Protocol](/omni-message): the shape of what `session.run()` yields.
+- [The Agent Loop](/agent-loop): what happens inside a single Task.
+- [Sessions & Traces](/sessions-and-traces): how conversations and execution records are stored.
diff --git a/packages/docs/content/quickstart-sdk.zh.md b/packages/docs/content/quickstart-sdk.zh.md
new file mode 100644
index 00000000..6c0dffa8
--- /dev/null
+++ b/packages/docs/content/quickstart-sdk.zh.md
@@ -0,0 +1,55 @@
+---
+title: SDK
+description: 用 @prismshadow/penguin-core 在自己的 TypeScript 程序里创建 Agent 与 Session。
+---
+
+`@prismshadow/penguin-core` 就是 CLI 与 Server 内部使用的同一个引擎,可以直接嵌进自己的程序。
+
+## 安装
+
+需要 Node.js >= 24:
+
+```bash
+npm install @prismshadow/penguin-core
+```
+
+## 配置模型
+
+SDK 与其他两条路线读同一个数据目录 `~/.penguin/data`,所以在[桌面端应用](/quickstart-desktop)或 [CLI](/quickstart-cli) 里配好的模型,SDK 直接可用,无需重复配置。
+
+如果这台机器还没配过模型,最省事的方式是装上 CLI 配一次:
+
+```bash
+npm install -g @prismshadow/penguin-cli
+penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-key sk-... --set-default
+```
+
+也可以完全不落盘:模型条目没有内联 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";
+
+const agent = await createAgent({ agentId: "default_agent" });
+const session = await agent.createSession({ workspaceDir: process.cwd() });
+
+for await (const output of session.run([userText("Create hello.txt containing hi")], {
+ approve: async () => "allow",
+})) {
+ if (isCompleteModelMessage(output) && output.payload.type === "text") {
+ console.log(output.payload.text);
+ }
+}
+```
+
+- `createAgent` 按 agentId 载入 Agent 配置(提示词、工具、运行参数);`default_agent` 是初始化数据目录时自带的那个。
+- `session.run()` 返回一个异步迭代器,逐条产出 OmniMessage——上面的判断只挑出模型的完整文本消息,工具调用、思考块等都在同一个流里。
+- `approve` 是审批回调,返回 `"allow"` 即全部放行;四种审批模式与工具的对应关系见[工具与审批](/tools)。
+
+## 下一步
+
+- [核心接口](/interfaces):`createAgent`、`Session`、LLM 与 Environment 的接口契约。
+- [OmniMessage 协议](/omni-message):`session.run()` 产出的消息结构。
+- [Agent 运行循环](/agent-loop):一个 Task 内部经历了什么。
+- [Session 与 Trace](/sessions-and-traces):会话与执行记录如何落盘。
diff --git a/packages/docs/content/quickstart.en.md b/packages/docs/content/quickstart.en.md
index f2bfe7c5..069b4788 100644
--- a/packages/docs/content/quickstart.en.md
+++ b/packages/docs/content/quickstart.en.md
@@ -1,76 +1,32 @@
---
title: Quickstart
-description: Install PenguinHarness, configure a model, and run your first Task.
+description: Three routes — desktop app, CLI, or SDK — pick one to install PenguinHarness and run your first Task.
---
-## Install
+PenguinHarness has three 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:
-One-liner for Linux / macOS:
+| Route | Best for | Terminal needed? |
+| --- | --- | --- |
+| [Desktop app](/quickstart-desktop) | Using PenguinHarness as a product, straight away | Only if the system blocks the first launch |
+| [CLI and Web App](/quickstart-cli) | Servers and remote machines, or wanting the `penguin` command | Once, to install |
+| [SDK](/quickstart-sdk) | Embedding the engine in your own TypeScript program | Yes |
-```bash
-curl -fsSL https://penguin.ooo/install.sh | sh
-```
+If you are unsure, take the [desktop app](/quickstart-desktop): it has the fewest steps, and moving to another route later costs you nothing. Builds are not signed yet, so macOS and Linux may need one command the first time — that page carries it.
-For other options (npm, from source), see [Installation](/installation).
+## What all three share
-## Configure a model
+- **One data root**: `~/.penguin/data` (`%USERPROFILE%\.penguin\data` on Windows). Agents, model configuration and past Sessions are common to all three routes, so they 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.
-PenguinHarness ships with no built-in model credentials, so configure a model first. Use the Models page in the Web UI, or the CLI:
+## Before you start
-```bash
-penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-key sk-... --set-default
-```
+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.
-- 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.
-
-## Start the Web App
-
-```bash
-penguin web
-```
-
-The service runs at http://127.0.0.1:7364 and opens your browser (`--no-open` to skip). First login is `admin` — the server prints the initial password (of the form `penguin-1234`) in a framed notice on every start until it is changed; change it right away. `penguin server` starts the same process headless.
-
-## One-shot run
-
-```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.
-
-## Interactive chat
-
-```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.
-
-## SDK hello
-
-After installing `@prismshadow/penguin-core`:
-
-```ts
-import { createAgent, isCompleteModelMessage, userText } from "@prismshadow/penguin-core";
-
-const agent = await createAgent({ agentId: "default_agent" });
-const session = await agent.createSession({ workspaceDir: process.cwd() });
-
-for await (const output of session.run([userText("Create hello.txt containing hi")], {
- approve: async () => "allow",
-})) {
- if (isCompleteModelMessage(output) && output.payload.type === "text") {
- console.log(output.payload.text);
- }
-}
-```
+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.
## Next steps
-- [Web App Guide](/web-app): use PenguinHarness from the browser.
-- [CLI Reference](/cli): the full list of commands and options.
-- [Architecture Overview](/architecture): how the pieces fit together.
+- [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.
+- [SDK](/quickstart-sdk): create Agents and Sessions from your own program.
diff --git a/packages/docs/content/quickstart.zh.md b/packages/docs/content/quickstart.zh.md
index f14fbbca..ccd3db73 100644
--- a/packages/docs/content/quickstart.zh.md
+++ b/packages/docs/content/quickstart.zh.md
@@ -1,76 +1,32 @@
---
title: 快速开始
-description: 安装 PenguinHarness、配置模型并运行第一个 Task。
+description: 桌面端、命令行、SDK 三条路线,挑一条装好 PenguinHarness 并跑通第一个 Task。
---
-## 安装
+PenguinHarness 有三条入口,背后是同一个引擎,区别只在你以什么方式接触它。先挑一条适合自己的,各自的页面会把你一路带到第一个 Task:
-Linux / macOS 一键安装:
+| 路线 | 适合 | 需要用终端吗 |
+| --- | --- | --- |
+| [桌面端应用](/quickstart-desktop) | 想直接把 PenguinHarness 当成一个应用来用 | 仅在系统拦下首次启动时 |
+| [命令行与 Web 应用](/quickstart-cli) | 装到服务器或远程机器,或想要 `penguin` 命令 | 安装时用一次 |
+| [SDK](/quickstart-sdk) | 把引擎嵌进自己的 TypeScript 程序 | 需要 |
-```bash
-curl -fsSL https://penguin.ooo/install.sh | sh
-```
+拿不准就选[桌面端应用](/quickstart-desktop):它步骤最少,而且换到另一条路线不用重来。目前的构建尚未签名,macOS 与 Linux 首次启动时可能需要执行一条命令,那一页里写了。
-其他方式(npm、源码)见[安装](/installation)。
+## 三条路线共用什么
-## 配置模型
+- **同一个数据目录**:`~/.penguin/data`(Windows 为 `%USERPROFILE%\.penguin\data`)。Agent、模型配置与历史会话互通,所以三条路线可以随时混用——桌面端配好的模型,CLI 与 SDK 立刻就能用。
+- **同一时刻只有一个服务端**:一个数据目录只跑一个服务端进程。命令行已经用 `penguin web` 启动过实例时,桌面端应用会直接接入它,而不是再起一个。
+- **同一套界面**:桌面端应用与 `penguin web` 打开的是同一个 Web App,只是前者内嵌了服务端、免去登录。
-PenguinHarness 不内置任何模型凭据,使用前需要先配置一个模型。可以在 Web UI 的 Models 页面完成,也可以用 CLI:
+## 开始之前
-```bash
-penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-key sk-... --set-default
-```
+PenguinHarness 不内置任何模型凭据,跑第一个 Task 之前必须先配置一个模型,准备好一个 Provider 的 API Key 即可。三条路线各自的页面都包含这一步。
-- 模型引用始终是 `(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
-
-```bash
-penguin web
-```
-
-服务运行在 http://127.0.0.1:7364 并自动打开浏览器(`--no-open` 跳过)。首次登录使用 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印,请立即修改密码。`penguin server` 启动同一进程的 headless 版本。
-
-## 单次运行
-
-```bash
-penguin run -m "创建 hello.txt,内容为 Hello, Penguin"
-```
-
-Workspace 默认为当前目录,可用 `--workspace /path` 指定;目标目录必须已存在。
-
-## 交互式对话
-
-```bash
-penguin chat
-```
-
-- 每输入一行即发起一个 Task。
-- `/compact` 压缩上下文;`/clear` 开启全新 Session(原会话仍可恢复);`/exit` 或 `/quit` 退出;Ctrl-C 中断正在运行的 Task。
-- 退出时会打印 `penguin chat --resume <sessionId>` 提示,用于恢复本次 Session;`--resume` 不带 id 时恢复该 Agent 最近的 Session。
-
-## SDK 示例
-
-安装 `@prismshadow/penguin-core` 后:
-
-```ts
-import { createAgent, isCompleteModelMessage, userText } from "@prismshadow/penguin-core";
-
-const agent = await createAgent({ agentId: "default_agent" });
-const session = await agent.createSession({ workspaceDir: process.cwd() });
-
-for await (const output of session.run([userText("Create hello.txt containing hi")], {
- approve: async () => "allow",
-})) {
- if (isCompleteModelMessage(output) && output.payload.type === "text") {
- console.log(output.payload.text);
- }
-}
-```
+模型引用始终是 `(provider, model_id)` 二元组,Provider 绝不由模型 id 推断;内置分组见[模型与 Provider](/models)。
## 下一步
-- [Web App 指南](/web-app):在浏览器中使用 PenguinHarness。
-- [CLI 参考](/cli):完整命令与选项。
-- [架构总览](/architecture):了解整体设计。
+- [桌面端应用](/quickstart-desktop):双击安装,打开即已登录。
+- [命令行与 Web 应用](/quickstart-cli):一行安装 `penguin`,含完整的安装参考。
+- [SDK](/quickstart-sdk):在自己的程序里创建 Agent 与 Session。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 073f7dd4..b6b06e46 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -183,7 +183,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode
| DELETE | / | Delete the Session (along with its Traces and scratch files) |
| GET | /messages | Full OmniMessage history; while a Task runs the response also carries `live` (the in-progress stream tail, see below) |
| GET | /stream | SSE event stream (next section) |
-| POST | /tasks | Start a Task: `{input: TaskInputPart[], thinkingLevel?, 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: 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](/docs/goal-mode) |
+| POST | /tasks | Start a Task: `{input: TaskInputPart[], thinkingLevel?, 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: 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 |
| POST | /approvals/:toolCallId | Approval decision: `{decision}` is `allow` or `deny` → 204 |
| POST | /abort | Interrupt the current Task: 202 when triggered, 204 when idle |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 1c1aa2f3..cb9515d3 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -183,7 +183,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入
| DELETE | / | 删除 Session(连同 Trace 与暂存文件) |
| GET | /messages | 完整 OmniMessage 历史;Task 运行期间响应额外携带 `live`(进行中的流式尾部,见下) |
| GET | /stream | SSE 事件流(见下节) |
-| POST | /tasks | 发起 Task:`{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202。带 `queueIfBusy` 时,运行中的 Session 会把输入暂存为跟进消息(`queued: true`),空闲后按序自动作为普通 Task 发出;`task_state` 事件携带排队数。`file` 类型的输入会写入 Session scratchpad,以 `[attached file: <路径>]` 行交给模型(见下方请求体)。带 `goal: {budget?}` 时该输入转为发起目标循环:必须含非空文字(一张图说明不了目标),随行的图片一律折叠成 scratchpad 路径行写入目标文本、与模型是否支持视觉无关,而 `file` 会被拒绝——没有东西能把它折进每轮重注入的目标里——见[目标模式](/docs/goal-mode) |
+| POST | /tasks | 发起 Task:`{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202。带 `queueIfBusy` 时,运行中的 Session 会把输入暂存为跟进消息(`queued: true`),空闲后按序自动作为普通 Task 发出;`task_state` 事件携带排队数。`file` 类型的输入会写入 Session scratchpad,以 `[attached file: <路径>]` 行交给模型(见下方请求体)。带 `goal: {budget?}` 时该输入转为发起目标循环:必须含非空文字(一张图说明不了目标),随行的图片一律折叠成 scratchpad 路径行写入目标文本、与模型是否支持视觉无关,而 `file` 会被拒绝——没有东西能把它折进每轮重注入的目标里——见[目标模式](/goal-mode) |
| POST | /steer | 运行中插话:`{text, images?}` 为运行中的 Task 排队一条消息(作为独立的 `[user_steering]` 用户消息随下一轮送达,图片紧随其后)→ 202;两个字段任一非空即可成消息,都为空则 400;无 Task 运行返回 409 `not_running` |
| POST | /approvals/:toolCallId | 审批决定:`{decision}` 取 `allow` 或 `deny` → 204 |
| POST | /abort | 中断当前 Task:已触发返回 202,无任务返回 204 |
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 2a75781c..b1c576fc 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -59,7 +59,7 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to
- 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, ≤ 10MB each and 12MB in total; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection); 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;
- 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;
-- **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](/docs/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;
+- **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;
- 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;
diff --git a/packages/docs/package.json b/packages/docs/package.json
index 16a00734..dc5ace9b 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -16,7 +16,8 @@
"react-dom": "^19.1.0",
"react-markdown": "^10.1.0",
"react-router": "^8.3.0",
- "remark-gfm": "^4.0.0"
+ "remark-gfm": "^4.0.0",
+ "shiki": "^4.3.1"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.0",
diff --git a/packages/docs/src/components/code-block.tsx b/packages/docs/src/components/code-block.tsx
new file mode 100644
index 00000000..818bb20a
--- /dev/null
+++ b/packages/docs/src/components/code-block.tsx
@@ -0,0 +1,41 @@
+/**
+ * Fenced code block: the same surface for every block, holding either Shiki's highlighted
+ * markup or a plain <pre> fallback. The fallback is what renders first (and forever, for
+ * a language with no grammar), so a block is readable before the highlighter chunk lands
+ * and stays readable if it never does.
+ *
+ * The two states carry identical padding and type, so the swap on highlight does not
+ * reflow the page.
+ */
+import { useEffect, useState } from "react";
+import { highlight, isHighlightable } from "../lib/highlight";
+
+export function CodeBlock({ code, language }: { code: string; language: string }) {
+ const [html, setHtml] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!isHighlightable(language)) {
+ setHtml(null);
+ return;
+ }
+ let alive = true;
+ void highlight(code, language).then((result) => {
+ if (alive) setHtml(result);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [code, language]);
+
+ return (
+ <div className="md-code">
+ {html ? (
+ <div dangerouslySetInnerHTML={{ __html: html }} />
+ ) : (
+ <pre>
+ <code>{code}</code>
+ </pre>
+ )}
+ </div>
+ );
+}
diff --git a/packages/docs/src/components/doc-tabs.tsx b/packages/docs/src/components/doc-tabs.tsx
new file mode 100644
index 00000000..b7ba28cf
--- /dev/null
+++ b/packages/docs/src/components/doc-tabs.tsx
@@ -0,0 +1,64 @@
+/**
+ * Tabbed code group: one tab strip over the code blocks remark-tabs grouped together.
+ * Only the selected panel is mounted, so a long install page shows one command instead of
+ * three stacked ones.
+ *
+ * Labels arrive as the `data-tab` of each child, and the panels are those same children in
+ * order — the pairing comes from the document, not from a separate list that could drift.
+ * Arrow keys move between tabs, the roving tabindex keeping one stop for the whole strip.
+ */
+import { Children, useId, useRef, useState } from "react";
+import type { ReactNode } from "react";
+
+export function DocTabs({ labels, children }: { labels: string[]; children: ReactNode }) {
+ const panels = Children.toArray(children);
+ const [selected, setSelected] = useState(0);
+ // Pairing ids, so a screen reader can tell which tab owns the panel it is reading.
+ const groupId = useId();
+ const stripRef = useRef<HTMLDivElement | null>(null);
+ const active = Math.min(selected, labels.length - 1);
+
+ const move = (delta: number) => {
+ const next = (active + delta + labels.length) % labels.length;
+ setSelected(next);
+ // Follow the selection with focus, so the next arrow key continues from the new tab.
+ stripRef.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
+ };
+
+ return (
+ <div className="md-tabs-group">
+ <div className="md-tabs-strip" role="tablist" ref={stripRef}>
+ {labels.map((label, index) => (
+ <button
+ key={label}
+ type="button"
+ role="tab"
+ id={`${groupId}-tab-${index}`}
+ aria-controls={`${groupId}-panel-${index}`}
+ aria-selected={index === active}
+ tabIndex={index === active ? 0 : -1}
+ onClick={() => setSelected(index)}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowRight") {
+ event.preventDefault();
+ move(1);
+ } else if (event.key === "ArrowLeft") {
+ event.preventDefault();
+ move(-1);
+ }
+ }}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ <div
+ role="tabpanel"
+ id={`${groupId}-panel-${active}`}
+ aria-labelledby={`${groupId}-tab-${active}`}
+ >
+ {panels[active]}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/docs/src/components/sidebar.tsx b/packages/docs/src/components/sidebar.tsx
index 999fd4cd..251e0774 100644
--- a/packages/docs/src/components/sidebar.tsx
+++ b/packages/docs/src/components/sidebar.tsx
@@ -1,11 +1,13 @@
/**
* Docs sidebar: sections + page links from DOCS_NAV, titles resolved from the active
- * locale's frontmatter. Desktop: sticky column. Mobile: the layout renders it as an
- * overlay panel under the top bar; onNavigate closes that panel.
+ * locale's frontmatter. Sub-pages (a page's children) render indented under their
+ * parent. Desktop: sticky column. Mobile: the layout renders it as an overlay panel
+ * under the top bar; onNavigate closes that panel.
*/
import { Link, useLocation } from "react-router";
import { S } from "../lib/strings";
import { useLocale } from "../state/locale";
+import type { Locale } from "../state/locale";
import { DOCS_NAV, HOME_SLUG } from "../lib/nav";
import { docTitle } from "../lib/docs";
import { currentSearchShortcutLabel } from "../lib/shortcut";
@@ -41,28 +43,64 @@ export function Sidebar({
{S.sections[section.id]}
</p>
<ul className="space-y-0.5 border-l border-gray-200 dark:border-gray-800">
- {section.slugs.map((slug) => {
- const active = slug === activeSlug;
- return (
- <li key={slug}>
- <Link
- to={slug === HOME_SLUG ? "/" : `/${slug}`}
- onClick={onNavigate}
- aria-current={active ? "page" : undefined}
- className={`-ml-px block border-l py-1 pl-3 transition-colors ${
- active
- ? "border-brand-600 font-medium text-brand-700 dark:border-brand-400 dark:text-brand-300"
- : "border-transparent text-gray-600 hover:border-gray-300 hover:text-gray-900 dark:text-gray-400 dark:hover:border-gray-700 dark:hover:text-gray-100"
- }`}
- >
- {docTitle(slug, locale)}
- </Link>
- </li>
- );
- })}
+ {section.pages.map((page) => (
+ <li key={page.slug}>
+ <PageLink
+ slug={page.slug}
+ activeSlug={activeSlug}
+ locale={locale}
+ onNavigate={onNavigate}
+ />
+ {page.children && (
+ <ul className="space-y-0.5">
+ {page.children.map((child) => (
+ <li key={child}>
+ <PageLink
+ slug={child}
+ activeSlug={activeSlug}
+ locale={locale}
+ onNavigate={onNavigate}
+ nested
+ />
+ </li>
+ ))}
+ </ul>
+ )}
+ </li>
+ ))}
</ul>
</div>
))}
</nav>
);
}
+
+function PageLink({
+ slug,
+ activeSlug,
+ locale,
+ onNavigate,
+ nested = false,
+}: {
+ slug: string;
+ activeSlug: string;
+ locale: Locale;
+ onNavigate?: () => void;
+ nested?: boolean;
+}) {
+ const active = slug === activeSlug;
+ return (
+ <Link
+ to={slug === HOME_SLUG ? "/" : `/${slug}`}
+ onClick={onNavigate}
+ aria-current={active ? "page" : undefined}
+ className={`-ml-px block border-l py-1 transition-colors ${nested ? "pl-6 text-[13px]" : "pl-3"} ${
+ active
+ ? "border-brand-600 font-medium text-brand-700 dark:border-brand-400 dark:text-brand-300"
+ : "border-transparent text-gray-600 hover:border-gray-300 hover:text-gray-900 dark:text-gray-400 dark:hover:border-gray-700 dark:hover:text-gray-100"
+ }`}
+ >
+ {docTitle(slug, locale)}
+ </Link>
+ );
+}
diff --git a/packages/docs/src/lib/highlight.ts b/packages/docs/src/lib/highlight.ts
new file mode 100644
index 00000000..e4004c18
--- /dev/null
+++ b/packages/docs/src/lib/highlight.ts
@@ -0,0 +1,105 @@
+/**
+ * Syntax highlighting for fenced code blocks, via Shiki.
+ *
+ * Built from `shiki/core` with only the languages this site actually writes, and with the
+ * JavaScript RegExp engine rather than Oniguruma — that drops the WASM payload entirely,
+ * and every grammar below was checked to highlight correctly under it. The highlighter is
+ * created once, lazily, on the first code block, and each grammar is registered only when a
+ * block actually uses it: everything here lives behind a dynamic import, so the core and each
+ * grammar become their own chunks instead of weighing down the first paint.
+ *
+ * Both themes are baked into one output using Shiki's dual-theme CSS variables, so the
+ * light/dark toggle is a CSS switch (see styles.css) and never re-highlights.
+ */
+import type { HighlighterCore } from "shiki/core";
+
+/**
+ * Grammar loaders, written out one static import each: Vite only rewrites a dynamic
+ * import it can read literally, so `import(\`shiki/langs/${lang}.mjs\`)` would survive
+ * into the browser as a bare specifier and throw at runtime.
+ */
+const LOADERS = {
+ typescript: () => import("shiki/langs/typescript.mjs"),
+ shellscript: () => import("shiki/langs/shellscript.mjs"),
+ powershell: () => import("shiki/langs/powershell.mjs"),
+ yaml: () => import("shiki/langs/yaml.mjs"),
+ toml: () => import("shiki/langs/toml.mjs"),
+ markdown: () => import("shiki/langs/markdown.mjs"),
+ json: () => import("shiki/langs/json.mjs"),
+};
+
+/** Fence language -> Shiki grammar. Anything absent renders unhighlighted. */
+const GRAMMARS: Record<string, keyof typeof LOADERS> = {
+ ts: "typescript",
+ typescript: "typescript",
+ bash: "shellscript",
+ sh: "shellscript",
+ shell: "shellscript",
+ powershell: "powershell",
+ ps1: "powershell",
+ yaml: "yaml",
+ yml: "yaml",
+ toml: "toml",
+ md: "markdown",
+ markdown: "markdown",
+ json: "json",
+ // Shiki has no JSON Lines grammar; each line is JSON, so the JSON one reads correctly.
+ jsonl: "json",
+};
+
+let highlighter: Promise<HighlighterCore> | null = null;
+const grammars = new Map<keyof typeof LOADERS, Promise<void>>();
+
+function loadHighlighter(): Promise<HighlighterCore> {
+ highlighter ??= (async () => {
+ const [{ createHighlighterCore }, { createJavaScriptRegexEngine }] = await Promise.all([
+ import("shiki/core"),
+ import("shiki/engine/javascript"),
+ ]);
+ return createHighlighterCore({
+ themes: [import("shiki/themes/github-light.mjs"), import("shiki/themes/github-dark.mjs")],
+ // Grammars load per language, on the first block that needs one: starting from none
+ // is what keeps a page that only writes Bash from fetching all seven chunks.
+ langs: [],
+ engine: createJavaScriptRegexEngine(),
+ });
+ })();
+ return highlighter;
+}
+
+/** Registers a grammar once, sharing the in-flight load between blocks of the same language. */
+function loadGrammar(shiki: HighlighterCore, lang: keyof typeof LOADERS): Promise<void> {
+ let pending = grammars.get(lang);
+ if (!pending) {
+ // A failed load is not cached, so a later block can try again rather than inheriting
+ // a permanently rejected promise.
+ pending = shiki.loadLanguage(LOADERS[lang]()).catch((error: unknown) => {
+ grammars.delete(lang);
+ throw error;
+ });
+ grammars.set(lang, pending);
+ }
+ return pending;
+}
+
+/** Whether a fence language has a grammar — lets a caller skip the async path entirely. */
+export function isHighlightable(language: string): boolean {
+ return language.toLowerCase() in GRAMMARS;
+}
+
+/** Highlighted HTML for a fenced block, or null when the language has no grammar. */
+export async function highlight(code: string, language: string): Promise<string | null> {
+ const lang = GRAMMARS[language.toLowerCase()];
+ if (!lang) return null;
+ try {
+ const shiki = await loadHighlighter();
+ await loadGrammar(shiki, lang);
+ return shiki.codeToHtml(code, {
+ lang,
+ themes: { light: "github-light", dark: "github-dark" },
+ });
+ } catch {
+ // A grammar that fails to load must not blank the page: fall back to plain text.
+ return null;
+ }
+}
diff --git a/packages/docs/src/lib/nav.ts b/packages/docs/src/lib/nav.ts
index 8e3d3bd0..c0fd8d84 100644
--- a/packages/docs/src/lib/nav.ts
+++ b/packages/docs/src/lib/nav.ts
@@ -3,20 +3,47 @@
* prev/next pagination. Section labels live in the strings dictionaries (S.sections);
* page titles come from each Markdown file's frontmatter. Kept pure (no import.meta)
* so the content-integrity test can import it under plain node.
+ *
+ * A page may carry sub-pages, rendered indented under it in the sidebar: Quickstart is
+ * an overview that branches into one page per installation route. Nesting is one level
+ * deep on purpose — the sidebar shows every entry at once, and a deeper tree would need
+ * collapsing to stay readable.
*/
+export interface DocsPageDef {
+ /** Page slug; content files are content/<slug>.<zh|en>.md. */
+ slug: string;
+ /** Sub-page slugs, in display order — indented under the parent, paginated after it. */
+ children?: string[];
+}
+
export interface DocsSectionDef {
/** Section id — also the key into S.sections for the localized label. */
id: "start" | "design" | "guides" | "reference";
- /** Page slugs in display order; content files are content/<slug>.<zh|en>.md. */
- slugs: string[];
+ /** Pages in display order. */
+ pages: DocsPageDef[];
+}
+
+/** Shorthand for the common case: a run of pages that have no sub-pages. */
+function pages(...slugs: string[]): DocsPageDef[] {
+ return slugs.map((slug) => ({ slug }));
}
export const DOCS_NAV: DocsSectionDef[] = [
- { id: "start", slugs: ["introduction", "installation", "quickstart"] },
+ {
+ id: "start",
+ pages: [
+ { slug: "introduction" },
+ {
+ slug: "quickstart",
+ children: ["quickstart-desktop", "quickstart-cli", "quickstart-sdk"],
+ },
+ ],
+ },
+ { id: "guides", pages: pages("web-app", "goal-mode", "self-improvement") },
{
id: "design",
- slugs: [
+ pages: pages(
"architecture",
"omni-message",
"agent-loop",
@@ -26,18 +53,45 @@ export const DOCS_NAV: DocsSectionDef[] = [
"skills",
"models",
"sessions-and-traces",
- ],
+ ),
},
- { id: "guides", slugs: ["web-app", "goal-mode", "self-improvement"] },
- { id: "reference", slugs: ["cli", "server-api", "configuration"] },
+ { id: "reference", pages: pages("cli", "server-api", "configuration") },
];
-/** All slugs in display order (pagination order). */
-export const DOC_SLUGS: string[] = DOCS_NAV.flatMap((section) => section.slugs);
+/** All slugs in display order — each parent immediately followed by its children. */
+export const DOC_SLUGS: string[] = DOCS_NAV.flatMap((section) =>
+ section.pages.flatMap((page) => [page.slug, ...(page.children ?? [])]),
+);
/** The docs landing page ("/" renders this slug). */
export const HOME_SLUG = DOC_SLUGS[0]!;
export function sectionOf(slug: string): DocsSectionDef | undefined {
- return DOCS_NAV.find((section) => section.slugs.includes(slug));
+ return DOCS_NAV.find((section) =>
+ section.pages.some((page) => page.slug === slug || page.children?.includes(slug)),
+ );
+}
+
+/**
+ * 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. */
+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,
+ };
}
diff --git a/packages/docs/src/lib/remark-callout.ts b/packages/docs/src/lib/remark-callout.ts
new file mode 100644
index 00000000..3f19085f
--- /dev/null
+++ b/packages/docs/src/lib/remark-callout.ts
@@ -0,0 +1,85 @@
+/**
+ * Callouts: a blockquote whose first line carries a `[!TYPE]` marker becomes a boxed
+ * note instead of a quote. A trailing `-` collapses it by default and `+` renders it
+ * open; with neither, the box is a plain non-collapsible aside. The rest of that line is
+ * the title.
+ *
+ * > [!INFO]- 首次启动被系统拦下
+ * >
+ * > …ordinary Markdown, fenced code included…
+ *
+ * Collapsing is emitted as native `<details>`/`<summary>`, so it needs no JavaScript and
+ * the body stays in the DOM — the browser's find-in-page and the page's own "Copy
+ * Markdown" keep seeing it. The marker is spelled the way GitHub alerts are, which is
+ * what the repo's READMEs already use and what a reader copying the Markdown expects.
+ *
+ * Pure mdast in, mdast out — no Vite or DOM — so the transform is unit-testable.
+ */
+
+/** The subset of an mdast node this transform reads or writes. */
+export interface CalloutNode {
+ type: string;
+ value?: string;
+ children?: CalloutNode[];
+ data?: {
+ hName?: string;
+ hProperties?: Record<string, string | boolean>;
+ };
+}
+
+/** `[!TYPE]`, an optional collapse marker, then the title — matched on the first line. */
+const MARKER = /^\[!(\w+)\]([-+]?)[ \t]*(.*)$/;
+
+export function remarkCallout() {
+ return (tree: CalloutNode): void => {
+ transform(tree);
+ };
+}
+
+function transform(node: CalloutNode): void {
+ if (!node.children) return;
+ for (const child of node.children) {
+ if (child.type === "blockquote") applyCallout(child);
+ transform(child);
+ }
+}
+
+function applyCallout(quote: CalloutNode): void {
+ const paragraph = quote.children?.[0];
+ const lead = paragraph?.type === "paragraph" ? paragraph.children?.[0] : undefined;
+ if (!paragraph || lead?.type !== "text" || typeof lead.value !== "string") return;
+
+ const [firstLine = "", ...restLines] = lead.value.split("\n");
+ const marker = MARKER.exec(firstLine);
+ if (!marker) return;
+
+ const [, rawType = "", collapse = "", title = ""] = marker;
+ const type = rawType.toLowerCase();
+ const collapsible = collapse === "-" || collapse === "+";
+
+ // Drop the marker line; if it was all the node held, drop the node — and the paragraph
+ // with it when the marker line was the whole paragraph.
+ const remainder = restLines.join("\n");
+ if (remainder) {
+ lead.value = remainder;
+ } else {
+ paragraph.children = paragraph.children?.slice(1);
+ if (paragraph.children?.length === 0) quote.children = quote.children?.slice(1);
+ }
+
+ quote.children = [
+ {
+ type: "calloutTitle",
+ children: [{ type: "text", value: title.trim() || type.toUpperCase() }],
+ data: { hName: collapsible ? "summary" : "p", hProperties: { className: "callout-title" } },
+ },
+ ...(quote.children ?? []),
+ ];
+ quote.data = {
+ hName: collapsible ? "details" : "aside",
+ hProperties: {
+ className: `callout callout-${type}`,
+ ...(collapse === "+" ? { open: true } : {}),
+ },
+ };
+}
diff --git a/packages/docs/src/lib/remark-tabs.ts b/packages/docs/src/lib/remark-tabs.ts
new file mode 100644
index 00000000..7de1f862
--- /dev/null
+++ b/packages/docs/src/lib/remark-tabs.ts
@@ -0,0 +1,83 @@
+/**
+ * Tabbed code blocks: a fenced block whose info string carries `tab="Label"` becomes one
+ * tab, and adjacent tab blocks group into one switcher. Each tab holds an ordinary code
+ * block, so the language keeps driving highlighting and nothing about the code changes.
+ *
+ * ```bash tab="Linux / macOS"
+ * curl -fsSL https://penguin.ooo/install.sh | sh
+ * ```
+ *
+ * ```powershell tab="Windows"
+ * irm https://penguin.ooo/install.ps1 | iex
+ * ```
+ *
+ * The group becomes a `div.md-tabs` carrying its labels, in child order, as JSON on
+ * `data-tab-labels`. The labels ride on the group rather than on each block because
+ * mdast-util-to-hast applies a code node's hProperties to the inner `<code>` and then
+ * wraps it in a `<pre>` — a per-block attribute would sit one level below where a reader
+ * of the group's children would look for it.
+ *
+ * Pure mdast in, mdast out — no Vite or DOM — so the transform is unit-testable.
+ */
+
+/** The subset of an mdast node this transform reads or writes. */
+export interface TabNode {
+ type: string;
+ meta?: string | null;
+ children?: TabNode[];
+ data?: {
+ hName?: string;
+ hProperties?: Record<string, string>;
+ };
+}
+
+const TAB_LABEL = /(?:^|\s)tab="([^"]+)"/;
+
+export function remarkTabs() {
+ return (tree: TabNode): void => {
+ transform(tree);
+ };
+}
+
+/** The tab label of a fenced block, or undefined when it is an ordinary one. */
+export function tabLabelOf(node: TabNode): string | undefined {
+ if (node.type !== "code") return undefined;
+ return TAB_LABEL.exec(node.meta ?? "")?.[1];
+}
+
+function transform(node: TabNode): void {
+ if (!node.children) return;
+
+ const out: TabNode[] = [];
+ let run: TabNode[] = [];
+ let labels: string[] = [];
+
+ const flush = () => {
+ if (run.length === 0) return;
+ out.push({
+ type: "tabGroup",
+ children: run,
+ data: {
+ hName: "div",
+ hProperties: { className: "md-tabs", "data-tab-labels": JSON.stringify(labels) },
+ },
+ });
+ run = [];
+ labels = [];
+ };
+
+ for (const child of node.children) {
+ const label = tabLabelOf(child);
+ if (label !== undefined) {
+ run.push(child);
+ labels.push(label);
+ continue;
+ }
+ flush();
+ transform(child);
+ out.push(child);
+ }
+ flush();
+
+ node.children = out;
+}
diff --git a/packages/docs/src/lib/search.ts b/packages/docs/src/lib/search.ts
index 2ab063e1..7997326d 100644
--- a/packages/docs/src/lib/search.ts
+++ b/packages/docs/src/lib/search.ts
@@ -170,11 +170,21 @@ export function markdownToSearchText(markdown: string): string {
const protectedLines: string[] = [];
let fence = "";
let fencedCode: string[] = [];
+ let quotedFence = false;
- for (const line of lines) {
+ // A callout body is a blockquote, so its fences arrive as "> ```bash" and never match a
+ // fence opener that anchors at the line start. The prefix therefore comes off before the
+ // match, and off the body lines of a fence that opened quoted — otherwise the grammar name
+ // and the "> " markers reach the index as prose. A fence that opened unquoted keeps its
+ // lines verbatim, so a Markdown example quoting a blockquote is not rewritten.
+ const unquote = (line: string): string => line.replace(/^\s{0,3}(?:>[ \t]?)+/, "");
+
+ for (const raw of lines) {
+ const line: string = !fence || quotedFence ? unquote(raw) : raw;
const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1] ?? "";
if (!fence && marker) {
fence = marker;
+ quotedFence = line !== raw;
fencedCode = [];
continue;
}
@@ -198,7 +208,11 @@ export function markdownToSearchText(markdown: string): string {
.replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/<(https?:\/\/[^>]+)>/g, "$1")
- .replace(/^\s{0,3}(?:#{1,6}|>|[-+*]|\d+[.)])\s+/gm, "");
+ .replace(/^\s{0,3}(?:#{1,6}|>|[-+*]|\d+[.)])\s+/gm, "")
+ // Callout marker (remark-callout): the type and collapse flag are chrome, but the
+ // title following them is prose and stays indexed. Runs after the blockquote marker
+ // above has already been peeled off the line.
+ .replace(/^\[!\w+\][-+]?[ \t]*/gm, "");
return stripMarkdownTableSyntax(stripMarkdownFormatting(visibleText))
.replace(/\s+/g, " ")
diff --git a/packages/docs/src/pages/doc-page.tsx b/packages/docs/src/pages/doc-page.tsx
index 16ec612d..7c979509 100644
--- a/packages/docs/src/pages/doc-page.tsx
+++ b/packages/docs/src/pages/doc-page.tsx
@@ -5,6 +5,11 @@
* slugifier as the TOC) and the active section is tracked while scrolling — the same
* mechanics as the landing page blog. Internal links written as "/<slug>" navigate
* client-side; external links open in a new tab.
+ *
+ * Two remark plugins extend the Markdown the content may use: remark-tabs groups adjacent
+ * `tab="…"` fences into one switcher, and remark-callout turns a `[!TYPE]` blockquote into
+ * a boxed (optionally collapsed) note. Both emit plain elements carrying data attributes,
+ * which the component overrides below pick back up.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
@@ -14,11 +19,48 @@ import { Link, useParams } from "react-router";
import { S } from "../lib/strings";
import { useLocale } from "../state/locale";
import { docMarkdown, docTitle, getDoc } from "../lib/docs";
-import { DOC_SLUGS, HOME_SLUG, sectionOf } from "../lib/nav";
+import { HOME_SLUG, pagerFor, sectionOf } from "../lib/nav";
import { extractToc, slugifyHeading } from "../lib/toc";
+import { remarkCallout } from "../lib/remark-callout";
+import { remarkTabs } from "../lib/remark-tabs";
import { CopyMarkdownButton } from "../components/copy-markdown-button";
+import { CodeBlock } from "../components/code-block";
+import { DocTabs } from "../components/doc-tabs";
import { ArrowRightIcon } from "../components/icons";
+/** The hast shape the tab / code overrides read back off their rendered nodes. */
+interface HastElement {
+ type: string;
+ tagName?: string;
+ properties?: Record<string, unknown>;
+ children?: HastElement[];
+ value?: string;
+}
+
+/** Tab labels a tab group carries, in child order; empty when the value is unusable. */
+function parseTabLabels(raw: unknown): string[] {
+ if (typeof raw !== "string") return [];
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return Array.isArray(parsed) ? parsed.map(String) : [];
+ } catch {
+ return [];
+ }
+}
+
+/** Fence language and source text of a `<pre><code class="language-x">` hast node. */
+function readFencedCode(node: HastElement | undefined): { code: string; language: string } {
+ const codeEl = node?.children?.find((child) => child.tagName === "code");
+ const className = codeEl?.properties?.className;
+ const language = (Array.isArray(className) ? className : [])
+ .map(String)
+ .find((name) => name.startsWith("language-"))
+ ?.slice("language-".length);
+ const collect = (el: HastElement | undefined): string =>
+ el?.type === "text" ? (el.value ?? "") : (el?.children ?? []).map(collect).join("");
+ return { code: collect(codeEl).replace(/\n$/, ""), language: language ?? "" };
+}
+
/** Flatten react-markdown heading children to plain text for slugging. */
function nodeText(node: ReactNode): string {
if (node === null || node === undefined || typeof node === "boolean") return "";
@@ -74,10 +116,7 @@ function Toc({
function Pager({ slug }: { slug: string }) {
const { locale } = useLocale();
- const index = DOC_SLUGS.indexOf(slug);
- if (index === -1) return null;
- const prev = index > 0 ? DOC_SLUGS[index - 1]! : null;
- const next = index < DOC_SLUGS.length - 1 ? DOC_SLUGS[index + 1]! : null;
+ const { prev, next } = pagerFor(slug);
const card = (target: string, dir: "prev" | "next") => (
<Link
to={target === HOME_SLUG ? "/" : `/${target}`}
@@ -258,7 +297,7 @@ export function DocPage() {
</header>
<div className="md-body mt-6 text-[15px] text-gray-800 dark:text-gray-200">
<Markdown
- remarkPlugins={[remarkGfm]}
+ remarkPlugins={[remarkGfm, remarkTabs, remarkCallout]}
components={{
a: ({ href, children }) => <MdLink href={href}>{children}</MdLink>,
h2: ({ children }) => (
@@ -271,6 +310,25 @@ export function DocPage() {
{children}
</h3>
),
+ pre: ({ node, children }) => {
+ const { code, language } = readFencedCode(node as HastElement | undefined);
+ // Not a fenced block (no language-* class and no text): leave it alone.
+ if (!code) return <pre>{children}</pre>;
+ return <CodeBlock code={code} language={language} />;
+ },
+ div: ({ node, className, children, ...props }) => {
+ if (className !== "md-tabs") {
+ return (
+ <div className={className} {...props}>
+ {children}
+ </div>
+ );
+ }
+ const raw = (node as HastElement | undefined)?.properties?.["data-tab-labels"];
+ const labels = parseTabLabels(raw);
+ if (labels.length === 0) return <div className={className}>{children}</div>;
+ return <DocTabs labels={labels}>{children}</DocTabs>;
+ },
}}
>
{doc.body}
diff --git a/packages/docs/src/styles.css b/packages/docs/src/styles.css
index 6e474845..917aa9af 100644
--- a/packages/docs/src/styles.css
+++ b/packages/docs/src/styles.css
@@ -189,6 +189,95 @@
color: inherit;
padding: 0;
}
+
+/* Fenced blocks: .md-code owns the surface (border, radius, fill) and the inner <pre> only
+ scrolls and pads, so the plain fallback and Shiki's markup sit in an identical box and
+ the swap on highlight causes no reflow. Shiki writes its theme background as an inline
+ style, which only !important can drop — hence the reset here rather than on .md-code. */
+.md-body .md-code {
+ @apply my-2.5 overflow-hidden rounded-lg border border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-900;
+}
+.md-body .md-code pre {
+ @apply overflow-x-auto p-3 text-[13px] leading-6;
+ margin: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent !important;
+}
+/* Dark mode flips colors through Shiki's dual-theme CSS variables, so switching themes
+ never re-highlights: one render carries both palettes. */
+html.dark .md-body .shiki,
+html.dark .md-body .shiki span {
+ color: var(--shiki-dark) !important;
+ font-style: var(--shiki-dark-font-style) !important;
+ font-weight: var(--shiki-dark-font-weight) !important;
+ text-decoration: var(--shiki-dark-text-decoration) !important;
+}
+
+/* Callouts (remark-callout). A collapsible one is a <details>, so the arrow and the
+ open/closed state are the browser's; the summary carries the whole clickable row. */
+.md-body .callout {
+ @apply my-3 rounded-lg border px-3.5 py-2.5;
+}
+.md-body .callout > :first-child {
+ margin-top: 0;
+}
+.md-body .callout > :last-child {
+ margin-bottom: 0;
+}
+.md-body .callout-title {
+ @apply font-medium;
+}
+.md-body details.callout > summary {
+ @apply -mx-1 cursor-pointer list-none rounded px-1 select-none;
+}
+.md-body details.callout > summary::-webkit-details-marker {
+ display: none;
+}
+.md-body details.callout > summary::before {
+ content: "";
+ @apply mr-2 inline-block h-0 w-0 align-[0.09em] border-y-4 border-l-[6px] border-y-transparent transition-transform;
+ border-left-color: currentColor;
+}
+.md-body details.callout[open] > summary::before {
+ transform: rotate(90deg);
+}
+.md-body details.callout[open] > summary {
+ @apply mb-2;
+}
+.md-body .callout-info {
+ @apply border-brand-200 bg-brand-50/50 dark:border-brand-900 dark:bg-brand-950/40;
+}
+.md-body .callout-info .callout-title {
+ @apply text-brand-800 dark:text-brand-200;
+}
+.md-body :is(.callout-warning, .callout-caution) {
+ @apply border-amber-300 bg-amber-50/60 dark:border-amber-900 dark:bg-amber-950/30;
+}
+.md-body :is(.callout-warning, .callout-caution) .callout-title {
+ @apply text-amber-800 dark:text-amber-200;
+}
+
+/* Tabbed code groups (remark-tabs): the strip sits on the code surface, so a group reads
+ as one object rather than a row of buttons above an unrelated block. */
+.md-body .md-tabs-group {
+ @apply my-2.5 overflow-hidden rounded-lg border border-gray-200 dark:border-gray-800;
+}
+.md-body .md-tabs-strip {
+ @apply flex flex-wrap gap-1 border-b border-gray-200 bg-gray-50 px-1.5 pt-1.5 dark:border-gray-800 dark:bg-gray-900;
+}
+.md-body .md-tabs-strip button {
+ @apply cursor-pointer rounded-t-md px-2.5 py-1 text-[13px] text-gray-500 transition-colors hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100;
+ border-bottom: 2px solid transparent;
+}
+.md-body .md-tabs-strip button[aria-selected="true"] {
+ @apply border-b-brand-600 font-medium text-brand-700 dark:border-b-brand-400 dark:text-brand-300;
+}
+/* The group already draws the border and radius the block would otherwise repeat. */
+.md-body .md-tabs-group .md-code {
+ @apply my-0 rounded-none border-0;
+}
+
.md-body blockquote {
@apply border-l-2 border-gray-300 pl-3 text-gray-600 dark:border-gray-700 dark:text-gray-400;
}
diff --git a/packages/docs/test/content.test.ts b/packages/docs/test/content.test.ts
index 9d5462bb..5fbfe0a0 100644
--- a/packages/docs/test/content.test.ts
+++ b/packages/docs/test/content.test.ts
@@ -2,23 +2,58 @@
* Content integrity: the sidebar (DOCS_NAV) and the content/ directory must agree —
* every navigated slug has both zh and en files with a frontmatter title, and every
* content file belongs to the navigation (an orphan file would be unreachable).
- * Reads the files via fs so the check runs under plain node (no Vite glob).
+ * Also guards the links pages navigate each other and themselves with. Heading ids come
+ * from the heading text, so two identical headings collide into one id (the TOC then
+ * 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).
*/
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
-import { DOCS_NAV, DOC_SLUGS } from "../src/lib/nav";
+import { DOCS_NAV, DOC_SLUGS, pagerFor } from "../src/lib/nav";
import { parseFrontmatter } from "../src/lib/frontmatter";
+import { extractToc } from "../src/lib/toc";
const contentDir = join(__dirname, "..", "content");
const files = readdirSync(contentDir).filter((f) => f.endsWith(".md"));
+/** In-page targets of Markdown links, i.e. "[label](#anchor)" (percent-decoded). */
+function inPageAnchors(body: string): string[] {
+ return [...body.matchAll(/\]\(#([^)\s]+)\)/g)].map((match) => decodeURIComponent(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(/\/$/, ""),
+ );
+}
+
describe("docs navigation / content integrity", () => {
it("has unique slugs in DOCS_NAV", () => {
expect(new Set(DOC_SLUGS).size).toBe(DOC_SLUGS.length);
expect(DOCS_NAV.length).toBeGreaterThan(0);
});
+ it("paginates every page to real neighbours, and never to itself", () => {
+ for (const slug of DOC_SLUGS) {
+ const { prev, next } = pagerFor(slug);
+ for (const [dir, target] of [
+ ["prev", prev],
+ ["next", next],
+ ] as const) {
+ if (target === null) continue;
+ expect(DOC_SLUGS, `${slug} paginates ${dir} to a non-existent page`).toContain(target);
+ 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("provides zh and en files with a title for every navigated slug", () => {
for (const slug of DOC_SLUGS) {
for (const lang of ["zh", "en"] as const) {
@@ -38,4 +73,30 @@ describe("docs navigation / content integrity", () => {
expect(DOC_SLUGS, `orphan content file ${file}`).toContain(slug!);
}
});
+
+ it("gives every heading on a page its own anchor", () => {
+ for (const file of files) {
+ const { body } = parseFrontmatter(readFileSync(join(contentDir, file), "utf8"));
+ const ids = extractToc(body).map((entry) => entry.id);
+ const duplicates = [...new Set(ids.filter((id, index) => ids.indexOf(id) !== index))];
+ expect(duplicates, `colliding heading anchors in ${file}`).toEqual([]);
+ }
+ });
+
+ 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 dangling = inPageAnchors(body).filter((anchor) => !ids.has(anchor));
+ expect(dangling, `dangling in-page anchors in ${file}`).toEqual([]);
+ }
+ });
+
+ 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));
+ expect(dangling, `links to non-existent doc pages in ${file}`).toEqual([]);
+ }
+ });
});
diff --git a/packages/docs/test/highlight.test.ts b/packages/docs/test/highlight.test.ts
new file mode 100644
index 00000000..eaa5da54
--- /dev/null
+++ b/packages/docs/test/highlight.test.ts
@@ -0,0 +1,26 @@
+/**
+ * The highlighter falls back to plain text on any failure, so a broken grammar registration
+ * costs nothing visible — every page still renders, just never highlighted. These check the
+ * on-demand path end to end instead.
+ */
+import { describe, expect, it } from "vitest";
+import { highlight, isHighlightable } from "../src/lib/highlight";
+
+describe("code highlighting", () => {
+ it("registers a grammar on demand and highlights with both themes baked in", async () => {
+ const html = await highlight("sudo xattr -rd com.apple.quarantine /Applications", "bash");
+
+ expect(html).toContain("<span");
+ expect(html).toContain("--shiki-dark");
+ });
+
+ it("registers a second grammar without disturbing the first", async () => {
+ expect(await highlight("const port: number = 7376;", "ts")).toContain("<span");
+ expect(await highlight("penguin web", "shell")).toContain("<span");
+ });
+
+ it("leaves a language with no grammar unhighlighted", async () => {
+ expect(isHighlightable("cobol")).toBe(false);
+ expect(await highlight("IDENTIFICATION DIVISION.", "cobol")).toBeNull();
+ });
+});
diff --git a/packages/docs/test/remark.test.ts b/packages/docs/test/remark.test.ts
new file mode 100644
index 00000000..fe2c1806
--- /dev/null
+++ b/packages/docs/test/remark.test.ts
@@ -0,0 +1,128 @@
+/**
+ * The two Markdown extensions the content may use, tested on mdast directly: both
+ * transforms are pure tree rewrites, so nothing here needs a renderer.
+ */
+import { describe, expect, it } from "vitest";
+import { remarkCallout } from "../src/lib/remark-callout";
+import type { CalloutNode } from "../src/lib/remark-callout";
+import { remarkTabs, tabLabelOf } from "../src/lib/remark-tabs";
+import type { TabNode } from "../src/lib/remark-tabs";
+
+function quote(firstLine: string, ...rest: CalloutNode[]): CalloutNode {
+ return {
+ type: "blockquote",
+ children: [{ type: "paragraph", children: [{ type: "text", value: firstLine }] }, ...rest],
+ };
+}
+
+function runCallout(node: CalloutNode): CalloutNode {
+ const tree: CalloutNode = { type: "root", children: [node] };
+ remarkCallout()(tree);
+ return tree.children![0]!;
+}
+
+describe("remarkCallout", () => {
+ it("turns a marked blockquote into a collapsed details with a title", () => {
+ const out = runCallout(quote("[!INFO]- First launch blocked"));
+ expect(out.data?.hName).toBe("details");
+ expect(out.data?.hProperties?.className).toBe("callout callout-info");
+ expect(out.data?.hProperties?.open).toBeUndefined();
+
+ const title = out.children![0]!;
+ expect(title.data?.hName).toBe("summary");
+ expect(title.children![0]!.value).toBe("First launch blocked");
+ });
+
+ it("renders '+' open and no flag as a plain, non-collapsible box", () => {
+ expect(runCallout(quote("[!INFO]+ T")).data?.hProperties?.open).toBe(true);
+
+ const plain = runCallout(quote("[!NOTE] T"));
+ expect(plain.data?.hName).toBe("aside");
+ expect(plain.children![0]!.data?.hName).toBe("p");
+ });
+
+ it("keeps the body, and drops the paragraph the marker occupied alone", () => {
+ const out = runCallout(
+ quote("[!INFO]- T", { type: "code", children: [{ type: "text", value: "x" }] }),
+ );
+ // summary + the code block: the marker's own paragraph is gone.
+ expect(out.children!.map((child) => child.type)).toEqual(["calloutTitle", "code"]);
+ });
+
+ it("keeps text that followed the marker on later lines of the same paragraph", () => {
+ const out = runCallout(quote("[!INFO]- T\nsecond line"));
+ expect(out.children![1]!.children![0]!.value).toBe("second line");
+ });
+
+ it("falls back to the type when no title is given", () => {
+ expect(runCallout(quote("[!INFO]-")).children![0]!.children![0]!.value).toBe("INFO");
+ });
+
+ it("leaves an ordinary blockquote alone", () => {
+ const out = runCallout(quote("just a quote"));
+ expect(out.data).toBeUndefined();
+ expect(out.children![0]!.type).toBe("paragraph");
+ });
+
+ it("transforms callouts nested inside other containers", () => {
+ const tree: CalloutNode = {
+ type: "root",
+ children: [{ type: "listItem", children: [quote("[!INFO] T")] }],
+ };
+ remarkCallout()(tree);
+ expect(tree.children![0]!.children![0]!.data?.hName).toBe("aside");
+ });
+});
+
+function code(lang: string, meta: string | null): TabNode {
+ return { type: "code", meta, ...{ lang } } as TabNode;
+}
+
+function runTabs(children: TabNode[]): TabNode {
+ const tree: TabNode = { type: "root", children };
+ remarkTabs()(tree);
+ return tree;
+}
+
+describe("remarkTabs", () => {
+ it("reads the label out of the info string", () => {
+ expect(tabLabelOf(code("bash", 'tab="Linux / macOS"'))).toBe("Linux / macOS");
+ expect(tabLabelOf(code("bash", null))).toBeUndefined();
+ expect(tabLabelOf({ type: "paragraph" })).toBeUndefined();
+ });
+
+ it("groups adjacent tab blocks, carrying the labels in child order", () => {
+ const tree = runTabs([code("bash", 'tab="A"'), code("powershell", 'tab="B"')]);
+ expect(tree.children!.length).toBe(1);
+
+ const group = tree.children![0]!;
+ expect(group.type).toBe("tabGroup");
+ expect(group.data?.hProperties?.className).toBe("md-tabs");
+ expect(group.data?.hProperties?.["data-tab-labels"]).toBe('["A","B"]');
+ expect(group.children!.length).toBe(2);
+ });
+
+ it("starts a fresh label list per group", () => {
+ const tree = runTabs([code("bash", 'tab="A"'), { type: "paragraph" }, code("bash", 'tab="B"')]);
+ expect(tree.children!.map((child) => child.data?.hProperties?.["data-tab-labels"])).toEqual([
+ '["A"]',
+ undefined,
+ '["B"]',
+ ]);
+ });
+
+ it("does not join tab blocks separated by other content", () => {
+ const tree = runTabs([code("bash", 'tab="A"'), { type: "paragraph" }, code("bash", 'tab="B"')]);
+ expect(tree.children!.map((child) => child.type)).toEqual([
+ "tabGroup",
+ "paragraph",
+ "tabGroup",
+ ]);
+ });
+
+ it("leaves an ordinary fenced block untouched", () => {
+ const tree = runTabs([code("bash", null)]);
+ expect(tree.children![0]!.type).toBe("code");
+ expect(tree.children![0]!.data).toBeUndefined();
+ });
+});
diff --git a/packages/docs/test/search.test.ts b/packages/docs/test/search.test.ts
index c312d85f..e7f616dd 100644
--- a/packages/docs/test/search.test.ts
+++ b/packages/docs/test/search.test.ts
@@ -101,6 +101,28 @@ describe("docs search", () => {
);
});
+ it("keeps a fence inside a callout out of the index, grammar name and quote markers included", () => {
+ const markdown = [
+ "> [!INFO]- The system blocked the first launch?",
+ ">",
+ "> Grant it once and the app starts normally:",
+ ">",
+ "> ```bash",
+ "> chmod +x penguin-desktop-linux-x86_64.AppImage",
+ "> ```",
+ ].join("\n");
+
+ expect(markdownToSearchText(markdown)).toBe(
+ "The system blocked the first launch? Grant it once and the app starts normally: chmod +x penguin-desktop-linux-x86_64.AppImage",
+ );
+ });
+
+ it("leaves an unquoted fence's blockquote lines verbatim", () => {
+ const markdown = ["```markdown", "> a quoted line", "```"].join("\n");
+
+ expect(markdownToSearchText(markdown)).toBe("> a quoted line");
+ });
+
it("removes paired formatting without changing literal identifier punctuation", () => {
expect(
markdownToSearchText(
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index be9c8ecb..dacf7b2b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -186,6 +186,9 @@ importers:
remark-gfm:
specifier: ^4.0.0
version: 4.0.1([email protected])
+ shiki:
+ specifier: ^4.3.1
+ version: 4.3.1
devDependencies:
'@tailwindcss/vite':
specifier: ^4.1.0